Header And Logo

PostgreSQL
| The world's most advanced open source database.

analyze.c

Go to the documentation of this file.
00001 /*-------------------------------------------------------------------------
00002  *
00003  * analyze.c
00004  *    the Postgres statistics generator
00005  *
00006  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
00007  * Portions Copyright (c) 1994, Regents of the University of California
00008  *
00009  *
00010  * IDENTIFICATION
00011  *    src/backend/commands/analyze.c
00012  *
00013  *-------------------------------------------------------------------------
00014  */
00015 #include "postgres.h"
00016 
00017 #include <math.h>
00018 
00019 #include "access/multixact.h"
00020 #include "access/transam.h"
00021 #include "access/tupconvert.h"
00022 #include "access/tuptoaster.h"
00023 #include "access/visibilitymap.h"
00024 #include "access/xact.h"
00025 #include "catalog/index.h"
00026 #include "catalog/indexing.h"
00027 #include "catalog/pg_collation.h"
00028 #include "catalog/pg_inherits_fn.h"
00029 #include "catalog/pg_namespace.h"
00030 #include "commands/dbcommands.h"
00031 #include "commands/tablecmds.h"
00032 #include "commands/vacuum.h"
00033 #include "executor/executor.h"
00034 #include "foreign/fdwapi.h"
00035 #include "miscadmin.h"
00036 #include "nodes/nodeFuncs.h"
00037 #include "parser/parse_oper.h"
00038 #include "parser/parse_relation.h"
00039 #include "pgstat.h"
00040 #include "postmaster/autovacuum.h"
00041 #include "storage/bufmgr.h"
00042 #include "storage/lmgr.h"
00043 #include "storage/proc.h"
00044 #include "storage/procarray.h"
00045 #include "utils/acl.h"
00046 #include "utils/attoptcache.h"
00047 #include "utils/datum.h"
00048 #include "utils/guc.h"
00049 #include "utils/lsyscache.h"
00050 #include "utils/memutils.h"
00051 #include "utils/pg_rusage.h"
00052 #include "utils/sortsupport.h"
00053 #include "utils/syscache.h"
00054 #include "utils/timestamp.h"
00055 #include "utils/tqual.h"
00056 
00057 
00058 /* Data structure for Algorithm S from Knuth 3.4.2 */
00059 typedef struct
00060 {
00061     BlockNumber N;              /* number of blocks, known in advance */
00062     int         n;              /* desired sample size */
00063     BlockNumber t;              /* current block number */
00064     int         m;              /* blocks selected so far */
00065 } BlockSamplerData;
00066 
00067 typedef BlockSamplerData *BlockSampler;
00068 
00069 /* Per-index data for ANALYZE */
00070 typedef struct AnlIndexData
00071 {
00072     IndexInfo  *indexInfo;      /* BuildIndexInfo result */
00073     double      tupleFract;     /* fraction of rows for partial index */
00074     VacAttrStats **vacattrstats;    /* index attrs to analyze */
00075     int         attr_cnt;
00076 } AnlIndexData;
00077 
00078 
00079 /* Default statistics target (GUC parameter) */
00080 int         default_statistics_target = 100;
00081 
00082 /* A few variables that don't seem worth passing around as parameters */
00083 static MemoryContext anl_context = NULL;
00084 static BufferAccessStrategy vac_strategy;
00085 
00086 
00087 static void do_analyze_rel(Relation onerel, VacuumStmt *vacstmt,
00088                AcquireSampleRowsFunc acquirefunc, BlockNumber relpages,
00089                bool inh, int elevel);
00090 static void BlockSampler_Init(BlockSampler bs, BlockNumber nblocks,
00091                   int samplesize);
00092 static bool BlockSampler_HasMore(BlockSampler bs);
00093 static BlockNumber BlockSampler_Next(BlockSampler bs);
00094 static void compute_index_stats(Relation onerel, double totalrows,
00095                     AnlIndexData *indexdata, int nindexes,
00096                     HeapTuple *rows, int numrows,
00097                     MemoryContext col_context);
00098 static VacAttrStats *examine_attribute(Relation onerel, int attnum,
00099                   Node *index_expr);
00100 static int acquire_sample_rows(Relation onerel, int elevel,
00101                     HeapTuple *rows, int targrows,
00102                     double *totalrows, double *totaldeadrows);
00103 static int  compare_rows(const void *a, const void *b);
00104 static int acquire_inherited_sample_rows(Relation onerel, int elevel,
00105                               HeapTuple *rows, int targrows,
00106                               double *totalrows, double *totaldeadrows);
00107 static void update_attstats(Oid relid, bool inh,
00108                 int natts, VacAttrStats **vacattrstats);
00109 static Datum std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
00110 static Datum ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull);
00111 
00112 
00113 /*
00114  *  analyze_rel() -- analyze one relation
00115  */
00116 void
00117 analyze_rel(Oid relid, VacuumStmt *vacstmt, BufferAccessStrategy bstrategy)
00118 {
00119     Relation    onerel;
00120     int         elevel;
00121     AcquireSampleRowsFunc acquirefunc = NULL;
00122     BlockNumber relpages = 0;
00123 
00124     /* Select logging level */
00125     if (vacstmt->options & VACOPT_VERBOSE)
00126         elevel = INFO;
00127     else
00128         elevel = DEBUG2;
00129 
00130     /* Set up static variables */
00131     vac_strategy = bstrategy;
00132 
00133     /*
00134      * Check for user-requested abort.
00135      */
00136     CHECK_FOR_INTERRUPTS();
00137 
00138     /*
00139      * Open the relation, getting ShareUpdateExclusiveLock to ensure that two
00140      * ANALYZEs don't run on it concurrently.  (This also locks out a
00141      * concurrent VACUUM, which doesn't matter much at the moment but might
00142      * matter if we ever try to accumulate stats on dead tuples.) If the rel
00143      * has been dropped since we last saw it, we don't need to process it.
00144      */
00145     if (!(vacstmt->options & VACOPT_NOWAIT))
00146         onerel = try_relation_open(relid, ShareUpdateExclusiveLock);
00147     else if (ConditionalLockRelationOid(relid, ShareUpdateExclusiveLock))
00148         onerel = try_relation_open(relid, NoLock);
00149     else
00150     {
00151         onerel = NULL;
00152         if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
00153             ereport(LOG,
00154                     (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
00155                   errmsg("skipping analyze of \"%s\" --- lock not available",
00156                          vacstmt->relation->relname)));
00157     }
00158     if (!onerel)
00159         return;
00160 
00161     /*
00162      * Check permissions --- this should match vacuum's check!
00163      */
00164     if (!(pg_class_ownercheck(RelationGetRelid(onerel), GetUserId()) ||
00165           (pg_database_ownercheck(MyDatabaseId, GetUserId()) && !onerel->rd_rel->relisshared)))
00166     {
00167         /* No need for a WARNING if we already complained during VACUUM */
00168         if (!(vacstmt->options & VACOPT_VACUUM))
00169         {
00170             if (onerel->rd_rel->relisshared)
00171                 ereport(WARNING,
00172                  (errmsg("skipping \"%s\" --- only superuser can analyze it",
00173                          RelationGetRelationName(onerel))));
00174             else if (onerel->rd_rel->relnamespace == PG_CATALOG_NAMESPACE)
00175                 ereport(WARNING,
00176                         (errmsg("skipping \"%s\" --- only superuser or database owner can analyze it",
00177                                 RelationGetRelationName(onerel))));
00178             else
00179                 ereport(WARNING,
00180                         (errmsg("skipping \"%s\" --- only table or database owner can analyze it",
00181                                 RelationGetRelationName(onerel))));
00182         }
00183         relation_close(onerel, ShareUpdateExclusiveLock);
00184         return;
00185     }
00186 
00187     /*
00188      * Silently ignore tables that are temp tables of other backends ---
00189      * trying to analyze these is rather pointless, since their contents are
00190      * probably not up-to-date on disk.  (We don't throw a warning here; it
00191      * would just lead to chatter during a database-wide ANALYZE.)
00192      */
00193     if (RELATION_IS_OTHER_TEMP(onerel))
00194     {
00195         relation_close(onerel, ShareUpdateExclusiveLock);
00196         return;
00197     }
00198 
00199     /*
00200      * We can ANALYZE any table except pg_statistic. See update_attstats
00201      */
00202     if (RelationGetRelid(onerel) == StatisticRelationId)
00203     {
00204         relation_close(onerel, ShareUpdateExclusiveLock);
00205         return;
00206     }
00207 
00208     /*
00209      * Check that it's a plain table, materialized view, or foreign table; we
00210      * used to do this in get_rel_oids() but seems safer to check after we've
00211      * locked the relation.
00212      */
00213     if (onerel->rd_rel->relkind == RELKIND_RELATION ||
00214         onerel->rd_rel->relkind == RELKIND_MATVIEW)
00215     {
00216         /* Regular table, so we'll use the regular row acquisition function */
00217         acquirefunc = acquire_sample_rows;
00218         /* Also get regular table's size */
00219         relpages = RelationGetNumberOfBlocks(onerel);
00220     }
00221     else if (onerel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
00222     {
00223         /*
00224          * For a foreign table, call the FDW's hook function to see whether it
00225          * supports analysis.
00226          */
00227         FdwRoutine *fdwroutine;
00228         bool        ok = false;
00229 
00230         fdwroutine = GetFdwRoutineForRelation(onerel, false);
00231 
00232         if (fdwroutine->AnalyzeForeignTable != NULL)
00233             ok = fdwroutine->AnalyzeForeignTable(onerel,
00234                                                  &acquirefunc,
00235                                                  &relpages);
00236 
00237         if (!ok)
00238         {
00239             ereport(WARNING,
00240              (errmsg("skipping \"%s\" --- cannot analyze this foreign table",
00241                      RelationGetRelationName(onerel))));
00242             relation_close(onerel, ShareUpdateExclusiveLock);
00243             return;
00244         }
00245     }
00246     else
00247     {
00248         /* No need for a WARNING if we already complained during VACUUM */
00249         if (!(vacstmt->options & VACOPT_VACUUM))
00250             ereport(WARNING,
00251                     (errmsg("skipping \"%s\" --- cannot analyze non-tables or special system tables",
00252                             RelationGetRelationName(onerel))));
00253         relation_close(onerel, ShareUpdateExclusiveLock);
00254         return;
00255     }
00256 
00257     /*
00258      * OK, let's do it.  First let other backends know I'm in ANALYZE.
00259      */
00260     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
00261     MyPgXact->vacuumFlags |= PROC_IN_ANALYZE;
00262     LWLockRelease(ProcArrayLock);
00263 
00264     /*
00265      * Do the normal non-recursive ANALYZE.
00266      */
00267     do_analyze_rel(onerel, vacstmt, acquirefunc, relpages, false, elevel);
00268 
00269     /*
00270      * If there are child tables, do recursive ANALYZE.
00271      */
00272     if (onerel->rd_rel->relhassubclass)
00273         do_analyze_rel(onerel, vacstmt, acquirefunc, relpages, true, elevel);
00274 
00275     /*
00276      * Close source relation now, but keep lock so that no one deletes it
00277      * before we commit.  (If someone did, they'd fail to clean up the entries
00278      * we made in pg_statistic.  Also, releasing the lock before commit would
00279      * expose us to concurrent-update failures in update_attstats.)
00280      */
00281     relation_close(onerel, NoLock);
00282 
00283     /*
00284      * Reset my PGXACT flag.  Note: we need this here, and not in vacuum_rel,
00285      * because the vacuum flag is cleared by the end-of-xact code.
00286      */
00287     LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
00288     MyPgXact->vacuumFlags &= ~PROC_IN_ANALYZE;
00289     LWLockRelease(ProcArrayLock);
00290 }
00291 
00292 /*
00293  *  do_analyze_rel() -- analyze one relation, recursively or not
00294  *
00295  * Note that "acquirefunc" is only relevant for the non-inherited case.
00296  * If we supported foreign tables in inheritance trees,
00297  * acquire_inherited_sample_rows would need to determine the appropriate
00298  * acquirefunc for each child table.
00299  */
00300 static void
00301 do_analyze_rel(Relation onerel, VacuumStmt *vacstmt,
00302                AcquireSampleRowsFunc acquirefunc, BlockNumber relpages,
00303                bool inh, int elevel)
00304 {
00305     int         attr_cnt,
00306                 tcnt,
00307                 i,
00308                 ind;
00309     Relation   *Irel;
00310     int         nindexes;
00311     bool        hasindex;
00312     VacAttrStats **vacattrstats;
00313     AnlIndexData *indexdata;
00314     int         targrows,
00315                 numrows;
00316     double      totalrows,
00317                 totaldeadrows;
00318     HeapTuple  *rows;
00319     PGRUsage    ru0;
00320     TimestampTz starttime = 0;
00321     MemoryContext caller_context;
00322     Oid         save_userid;
00323     int         save_sec_context;
00324     int         save_nestlevel;
00325 
00326     if (inh)
00327         ereport(elevel,
00328                 (errmsg("analyzing \"%s.%s\" inheritance tree",
00329                         get_namespace_name(RelationGetNamespace(onerel)),
00330                         RelationGetRelationName(onerel))));
00331     else
00332         ereport(elevel,
00333                 (errmsg("analyzing \"%s.%s\"",
00334                         get_namespace_name(RelationGetNamespace(onerel)),
00335                         RelationGetRelationName(onerel))));
00336 
00337     /*
00338      * Set up a working context so that we can easily free whatever junk gets
00339      * created.
00340      */
00341     anl_context = AllocSetContextCreate(CurrentMemoryContext,
00342                                         "Analyze",
00343                                         ALLOCSET_DEFAULT_MINSIZE,
00344                                         ALLOCSET_DEFAULT_INITSIZE,
00345                                         ALLOCSET_DEFAULT_MAXSIZE);
00346     caller_context = MemoryContextSwitchTo(anl_context);
00347 
00348     /*
00349      * Switch to the table owner's userid, so that any index functions are run
00350      * as that user.  Also lock down security-restricted operations and
00351      * arrange to make GUC variable changes local to this command.
00352      */
00353     GetUserIdAndSecContext(&save_userid, &save_sec_context);
00354     SetUserIdAndSecContext(onerel->rd_rel->relowner,
00355                            save_sec_context | SECURITY_RESTRICTED_OPERATION);
00356     save_nestlevel = NewGUCNestLevel();
00357 
00358     /* measure elapsed time iff autovacuum logging requires it */
00359     if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
00360     {
00361         pg_rusage_init(&ru0);
00362         if (Log_autovacuum_min_duration > 0)
00363             starttime = GetCurrentTimestamp();
00364     }
00365 
00366     /*
00367      * Determine which columns to analyze
00368      *
00369      * Note that system attributes are never analyzed.
00370      */
00371     if (vacstmt->va_cols != NIL)
00372     {
00373         ListCell   *le;
00374 
00375         vacattrstats = (VacAttrStats **) palloc(list_length(vacstmt->va_cols) *
00376                                                 sizeof(VacAttrStats *));
00377         tcnt = 0;
00378         foreach(le, vacstmt->va_cols)
00379         {
00380             char       *col = strVal(lfirst(le));
00381 
00382             i = attnameAttNum(onerel, col, false);
00383             if (i == InvalidAttrNumber)
00384                 ereport(ERROR,
00385                         (errcode(ERRCODE_UNDEFINED_COLUMN),
00386                     errmsg("column \"%s\" of relation \"%s\" does not exist",
00387                            col, RelationGetRelationName(onerel))));
00388             vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
00389             if (vacattrstats[tcnt] != NULL)
00390                 tcnt++;
00391         }
00392         attr_cnt = tcnt;
00393     }
00394     else
00395     {
00396         attr_cnt = onerel->rd_att->natts;
00397         vacattrstats = (VacAttrStats **)
00398             palloc(attr_cnt * sizeof(VacAttrStats *));
00399         tcnt = 0;
00400         for (i = 1; i <= attr_cnt; i++)
00401         {
00402             vacattrstats[tcnt] = examine_attribute(onerel, i, NULL);
00403             if (vacattrstats[tcnt] != NULL)
00404                 tcnt++;
00405         }
00406         attr_cnt = tcnt;
00407     }
00408 
00409     /*
00410      * Open all indexes of the relation, and see if there are any analyzable
00411      * columns in the indexes.  We do not analyze index columns if there was
00412      * an explicit column list in the ANALYZE command, however.  If we are
00413      * doing a recursive scan, we don't want to touch the parent's indexes at
00414      * all.
00415      */
00416     if (!inh)
00417         vac_open_indexes(onerel, AccessShareLock, &nindexes, &Irel);
00418     else
00419     {
00420         Irel = NULL;
00421         nindexes = 0;
00422     }
00423     hasindex = (nindexes > 0);
00424     indexdata = NULL;
00425     if (hasindex)
00426     {
00427         indexdata = (AnlIndexData *) palloc0(nindexes * sizeof(AnlIndexData));
00428         for (ind = 0; ind < nindexes; ind++)
00429         {
00430             AnlIndexData *thisdata = &indexdata[ind];
00431             IndexInfo  *indexInfo;
00432 
00433             thisdata->indexInfo = indexInfo = BuildIndexInfo(Irel[ind]);
00434             thisdata->tupleFract = 1.0; /* fix later if partial */
00435             if (indexInfo->ii_Expressions != NIL && vacstmt->va_cols == NIL)
00436             {
00437                 ListCell   *indexpr_item = list_head(indexInfo->ii_Expressions);
00438 
00439                 thisdata->vacattrstats = (VacAttrStats **)
00440                     palloc(indexInfo->ii_NumIndexAttrs * sizeof(VacAttrStats *));
00441                 tcnt = 0;
00442                 for (i = 0; i < indexInfo->ii_NumIndexAttrs; i++)
00443                 {
00444                     int         keycol = indexInfo->ii_KeyAttrNumbers[i];
00445 
00446                     if (keycol == 0)
00447                     {
00448                         /* Found an index expression */
00449                         Node       *indexkey;
00450 
00451                         if (indexpr_item == NULL)       /* shouldn't happen */
00452                             elog(ERROR, "too few entries in indexprs list");
00453                         indexkey = (Node *) lfirst(indexpr_item);
00454                         indexpr_item = lnext(indexpr_item);
00455                         thisdata->vacattrstats[tcnt] =
00456                             examine_attribute(Irel[ind], i + 1, indexkey);
00457                         if (thisdata->vacattrstats[tcnt] != NULL)
00458                             tcnt++;
00459                     }
00460                 }
00461                 thisdata->attr_cnt = tcnt;
00462             }
00463         }
00464     }
00465 
00466     /*
00467      * Determine how many rows we need to sample, using the worst case from
00468      * all analyzable columns.  We use a lower bound of 100 rows to avoid
00469      * possible overflow in Vitter's algorithm.  (Note: that will also be the
00470      * target in the corner case where there are no analyzable columns.)
00471      */
00472     targrows = 100;
00473     for (i = 0; i < attr_cnt; i++)
00474     {
00475         if (targrows < vacattrstats[i]->minrows)
00476             targrows = vacattrstats[i]->minrows;
00477     }
00478     for (ind = 0; ind < nindexes; ind++)
00479     {
00480         AnlIndexData *thisdata = &indexdata[ind];
00481 
00482         for (i = 0; i < thisdata->attr_cnt; i++)
00483         {
00484             if (targrows < thisdata->vacattrstats[i]->minrows)
00485                 targrows = thisdata->vacattrstats[i]->minrows;
00486         }
00487     }
00488 
00489     /*
00490      * Acquire the sample rows
00491      */
00492     rows = (HeapTuple *) palloc(targrows * sizeof(HeapTuple));
00493     if (inh)
00494         numrows = acquire_inherited_sample_rows(onerel, elevel,
00495                                                 rows, targrows,
00496                                                 &totalrows, &totaldeadrows);
00497     else
00498         numrows = (*acquirefunc) (onerel, elevel,
00499                                   rows, targrows,
00500                                   &totalrows, &totaldeadrows);
00501 
00502     /*
00503      * Compute the statistics.  Temporary results during the calculations for
00504      * each column are stored in a child context.  The calc routines are
00505      * responsible to make sure that whatever they store into the VacAttrStats
00506      * structure is allocated in anl_context.
00507      */
00508     if (numrows > 0)
00509     {
00510         MemoryContext col_context,
00511                     old_context;
00512 
00513         col_context = AllocSetContextCreate(anl_context,
00514                                             "Analyze Column",
00515                                             ALLOCSET_DEFAULT_MINSIZE,
00516                                             ALLOCSET_DEFAULT_INITSIZE,
00517                                             ALLOCSET_DEFAULT_MAXSIZE);
00518         old_context = MemoryContextSwitchTo(col_context);
00519 
00520         for (i = 0; i < attr_cnt; i++)
00521         {
00522             VacAttrStats *stats = vacattrstats[i];
00523             AttributeOpts *aopt;
00524 
00525             stats->rows = rows;
00526             stats->tupDesc = onerel->rd_att;
00527             (*stats->compute_stats) (stats,
00528                                      std_fetch_func,
00529                                      numrows,
00530                                      totalrows);
00531 
00532             /*
00533              * If the appropriate flavor of the n_distinct option is
00534              * specified, override with the corresponding value.
00535              */
00536             aopt = get_attribute_options(onerel->rd_id, stats->attr->attnum);
00537             if (aopt != NULL)
00538             {
00539                 float8      n_distinct;
00540 
00541                 n_distinct = inh ? aopt->n_distinct_inherited : aopt->n_distinct;
00542                 if (n_distinct != 0.0)
00543                     stats->stadistinct = n_distinct;
00544             }
00545 
00546             MemoryContextResetAndDeleteChildren(col_context);
00547         }
00548 
00549         if (hasindex)
00550             compute_index_stats(onerel, totalrows,
00551                                 indexdata, nindexes,
00552                                 rows, numrows,
00553                                 col_context);
00554 
00555         MemoryContextSwitchTo(old_context);
00556         MemoryContextDelete(col_context);
00557 
00558         /*
00559          * Emit the completed stats rows into pg_statistic, replacing any
00560          * previous statistics for the target columns.  (If there are stats in
00561          * pg_statistic for columns we didn't process, we leave them alone.)
00562          */
00563         update_attstats(RelationGetRelid(onerel), inh,
00564                         attr_cnt, vacattrstats);
00565 
00566         for (ind = 0; ind < nindexes; ind++)
00567         {
00568             AnlIndexData *thisdata = &indexdata[ind];
00569 
00570             update_attstats(RelationGetRelid(Irel[ind]), false,
00571                             thisdata->attr_cnt, thisdata->vacattrstats);
00572         }
00573     }
00574 
00575     /*
00576      * Update pages/tuples stats in pg_class ... but not if we're doing
00577      * inherited stats.
00578      */
00579     if (!inh)
00580         vac_update_relstats(onerel,
00581                             relpages,
00582                             totalrows,
00583                             visibilitymap_count(onerel),
00584                             hasindex,
00585                             InvalidTransactionId,
00586                             InvalidMultiXactId);
00587 
00588     /*
00589      * Same for indexes. Vacuum always scans all indexes, so if we're part of
00590      * VACUUM ANALYZE, don't overwrite the accurate count already inserted by
00591      * VACUUM.
00592      */
00593     if (!inh && !(vacstmt->options & VACOPT_VACUUM))
00594     {
00595         for (ind = 0; ind < nindexes; ind++)
00596         {
00597             AnlIndexData *thisdata = &indexdata[ind];
00598             double      totalindexrows;
00599 
00600             totalindexrows = ceil(thisdata->tupleFract * totalrows);
00601             vac_update_relstats(Irel[ind],
00602                                 RelationGetNumberOfBlocks(Irel[ind]),
00603                                 totalindexrows,
00604                                 0,
00605                                 false,
00606                                 InvalidTransactionId,
00607                                 InvalidMultiXactId);
00608         }
00609     }
00610 
00611     /*
00612      * Report ANALYZE to the stats collector, too.  However, if doing
00613      * inherited stats we shouldn't report, because the stats collector only
00614      * tracks per-table stats.
00615      */
00616     if (!inh)
00617         pgstat_report_analyze(onerel, totalrows, totaldeadrows);
00618 
00619     /* If this isn't part of VACUUM ANALYZE, let index AMs do cleanup */
00620     if (!(vacstmt->options & VACOPT_VACUUM))
00621     {
00622         for (ind = 0; ind < nindexes; ind++)
00623         {
00624             IndexBulkDeleteResult *stats;
00625             IndexVacuumInfo ivinfo;
00626 
00627             ivinfo.index = Irel[ind];
00628             ivinfo.analyze_only = true;
00629             ivinfo.estimated_count = true;
00630             ivinfo.message_level = elevel;
00631             ivinfo.num_heap_tuples = onerel->rd_rel->reltuples;
00632             ivinfo.strategy = vac_strategy;
00633 
00634             stats = index_vacuum_cleanup(&ivinfo, NULL);
00635 
00636             if (stats)
00637                 pfree(stats);
00638         }
00639     }
00640 
00641     /* Done with indexes */
00642     vac_close_indexes(nindexes, Irel, NoLock);
00643 
00644     /* Log the action if appropriate */
00645     if (IsAutoVacuumWorkerProcess() && Log_autovacuum_min_duration >= 0)
00646     {
00647         if (Log_autovacuum_min_duration == 0 ||
00648             TimestampDifferenceExceeds(starttime, GetCurrentTimestamp(),
00649                                        Log_autovacuum_min_duration))
00650             ereport(LOG,
00651                     (errmsg("automatic analyze of table \"%s.%s.%s\" system usage: %s",
00652                             get_database_name(MyDatabaseId),
00653                             get_namespace_name(RelationGetNamespace(onerel)),
00654                             RelationGetRelationName(onerel),
00655                             pg_rusage_show(&ru0))));
00656     }
00657 
00658     /* Roll back any GUC changes executed by index functions */
00659     AtEOXact_GUC(false, save_nestlevel);
00660 
00661     /* Restore userid and security context */
00662     SetUserIdAndSecContext(save_userid, save_sec_context);
00663 
00664     /* Restore current context and release memory */
00665     MemoryContextSwitchTo(caller_context);
00666     MemoryContextDelete(anl_context);
00667     anl_context = NULL;
00668 }
00669 
00670 /*
00671  * Compute statistics about indexes of a relation
00672  */
00673 static void
00674 compute_index_stats(Relation onerel, double totalrows,
00675                     AnlIndexData *indexdata, int nindexes,
00676                     HeapTuple *rows, int numrows,
00677                     MemoryContext col_context)
00678 {
00679     MemoryContext ind_context,
00680                 old_context;
00681     Datum       values[INDEX_MAX_KEYS];
00682     bool        isnull[INDEX_MAX_KEYS];
00683     int         ind,
00684                 i;
00685 
00686     ind_context = AllocSetContextCreate(anl_context,
00687                                         "Analyze Index",
00688                                         ALLOCSET_DEFAULT_MINSIZE,
00689                                         ALLOCSET_DEFAULT_INITSIZE,
00690                                         ALLOCSET_DEFAULT_MAXSIZE);
00691     old_context = MemoryContextSwitchTo(ind_context);
00692 
00693     for (ind = 0; ind < nindexes; ind++)
00694     {
00695         AnlIndexData *thisdata = &indexdata[ind];
00696         IndexInfo  *indexInfo = thisdata->indexInfo;
00697         int         attr_cnt = thisdata->attr_cnt;
00698         TupleTableSlot *slot;
00699         EState     *estate;
00700         ExprContext *econtext;
00701         List       *predicate;
00702         Datum      *exprvals;
00703         bool       *exprnulls;
00704         int         numindexrows,
00705                     tcnt,
00706                     rowno;
00707         double      totalindexrows;
00708 
00709         /* Ignore index if no columns to analyze and not partial */
00710         if (attr_cnt == 0 && indexInfo->ii_Predicate == NIL)
00711             continue;
00712 
00713         /*
00714          * Need an EState for evaluation of index expressions and
00715          * partial-index predicates.  Create it in the per-index context to be
00716          * sure it gets cleaned up at the bottom of the loop.
00717          */
00718         estate = CreateExecutorState();
00719         econtext = GetPerTupleExprContext(estate);
00720         /* Need a slot to hold the current heap tuple, too */
00721         slot = MakeSingleTupleTableSlot(RelationGetDescr(onerel));
00722 
00723         /* Arrange for econtext's scan tuple to be the tuple under test */
00724         econtext->ecxt_scantuple = slot;
00725 
00726         /* Set up execution state for predicate. */
00727         predicate = (List *)
00728             ExecPrepareExpr((Expr *) indexInfo->ii_Predicate,
00729                             estate);
00730 
00731         /* Compute and save index expression values */
00732         exprvals = (Datum *) palloc(numrows * attr_cnt * sizeof(Datum));
00733         exprnulls = (bool *) palloc(numrows * attr_cnt * sizeof(bool));
00734         numindexrows = 0;
00735         tcnt = 0;
00736         for (rowno = 0; rowno < numrows; rowno++)
00737         {
00738             HeapTuple   heapTuple = rows[rowno];
00739 
00740             /*
00741              * Reset the per-tuple context each time, to reclaim any cruft
00742              * left behind by evaluating the predicate or index expressions.
00743              */
00744             ResetExprContext(econtext);
00745 
00746             /* Set up for predicate or expression evaluation */
00747             ExecStoreTuple(heapTuple, slot, InvalidBuffer, false);
00748 
00749             /* If index is partial, check predicate */
00750             if (predicate != NIL)
00751             {
00752                 if (!ExecQual(predicate, econtext, false))
00753                     continue;
00754             }
00755             numindexrows++;
00756 
00757             if (attr_cnt > 0)
00758             {
00759                 /*
00760                  * Evaluate the index row to compute expression values. We
00761                  * could do this by hand, but FormIndexDatum is convenient.
00762                  */
00763                 FormIndexDatum(indexInfo,
00764                                slot,
00765                                estate,
00766                                values,
00767                                isnull);
00768 
00769                 /*
00770                  * Save just the columns we care about.  We copy the values
00771                  * into ind_context from the estate's per-tuple context.
00772                  */
00773                 for (i = 0; i < attr_cnt; i++)
00774                 {
00775                     VacAttrStats *stats = thisdata->vacattrstats[i];
00776                     int         attnum = stats->attr->attnum;
00777 
00778                     if (isnull[attnum - 1])
00779                     {
00780                         exprvals[tcnt] = (Datum) 0;
00781                         exprnulls[tcnt] = true;
00782                     }
00783                     else
00784                     {
00785                         exprvals[tcnt] = datumCopy(values[attnum - 1],
00786                                                    stats->attrtype->typbyval,
00787                                                    stats->attrtype->typlen);
00788                         exprnulls[tcnt] = false;
00789                     }
00790                     tcnt++;
00791                 }
00792             }
00793         }
00794 
00795         /*
00796          * Having counted the number of rows that pass the predicate in the
00797          * sample, we can estimate the total number of rows in the index.
00798          */
00799         thisdata->tupleFract = (double) numindexrows / (double) numrows;
00800         totalindexrows = ceil(thisdata->tupleFract * totalrows);
00801 
00802         /*
00803          * Now we can compute the statistics for the expression columns.
00804          */
00805         if (numindexrows > 0)
00806         {
00807             MemoryContextSwitchTo(col_context);
00808             for (i = 0; i < attr_cnt; i++)
00809             {
00810                 VacAttrStats *stats = thisdata->vacattrstats[i];
00811                 AttributeOpts *aopt =
00812                 get_attribute_options(stats->attr->attrelid,
00813                                       stats->attr->attnum);
00814 
00815                 stats->exprvals = exprvals + i;
00816                 stats->exprnulls = exprnulls + i;
00817                 stats->rowstride = attr_cnt;
00818                 (*stats->compute_stats) (stats,
00819                                          ind_fetch_func,
00820                                          numindexrows,
00821                                          totalindexrows);
00822 
00823                 /*
00824                  * If the n_distinct option is specified, it overrides the
00825                  * above computation.  For indices, we always use just
00826                  * n_distinct, not n_distinct_inherited.
00827                  */
00828                 if (aopt != NULL && aopt->n_distinct != 0.0)
00829                     stats->stadistinct = aopt->n_distinct;
00830 
00831                 MemoryContextResetAndDeleteChildren(col_context);
00832             }
00833         }
00834 
00835         /* And clean up */
00836         MemoryContextSwitchTo(ind_context);
00837 
00838         ExecDropSingleTupleTableSlot(slot);
00839         FreeExecutorState(estate);
00840         MemoryContextResetAndDeleteChildren(ind_context);
00841     }
00842 
00843     MemoryContextSwitchTo(old_context);
00844     MemoryContextDelete(ind_context);
00845 }
00846 
00847 /*
00848  * examine_attribute -- pre-analysis of a single column
00849  *
00850  * Determine whether the column is analyzable; if so, create and initialize
00851  * a VacAttrStats struct for it.  If not, return NULL.
00852  *
00853  * If index_expr isn't NULL, then we're trying to analyze an expression index,
00854  * and index_expr is the expression tree representing the column's data.
00855  */
00856 static VacAttrStats *
00857 examine_attribute(Relation onerel, int attnum, Node *index_expr)
00858 {
00859     Form_pg_attribute attr = onerel->rd_att->attrs[attnum - 1];
00860     HeapTuple   typtuple;
00861     VacAttrStats *stats;
00862     int         i;
00863     bool        ok;
00864 
00865     /* Never analyze dropped columns */
00866     if (attr->attisdropped)
00867         return NULL;
00868 
00869     /* Don't analyze column if user has specified not to */
00870     if (attr->attstattarget == 0)
00871         return NULL;
00872 
00873     /*
00874      * Create the VacAttrStats struct.  Note that we only have a copy of the
00875      * fixed fields of the pg_attribute tuple.
00876      */
00877     stats = (VacAttrStats *) palloc0(sizeof(VacAttrStats));
00878     stats->attr = (Form_pg_attribute) palloc(ATTRIBUTE_FIXED_PART_SIZE);
00879     memcpy(stats->attr, attr, ATTRIBUTE_FIXED_PART_SIZE);
00880 
00881     /*
00882      * When analyzing an expression index, believe the expression tree's type
00883      * not the column datatype --- the latter might be the opckeytype storage
00884      * type of the opclass, which is not interesting for our purposes.  (Note:
00885      * if we did anything with non-expression index columns, we'd need to
00886      * figure out where to get the correct type info from, but for now that's
00887      * not a problem.)  It's not clear whether anyone will care about the
00888      * typmod, but we store that too just in case.
00889      */
00890     if (index_expr)
00891     {
00892         stats->attrtypid = exprType(index_expr);
00893         stats->attrtypmod = exprTypmod(index_expr);
00894     }
00895     else
00896     {
00897         stats->attrtypid = attr->atttypid;
00898         stats->attrtypmod = attr->atttypmod;
00899     }
00900 
00901     typtuple = SearchSysCacheCopy1(TYPEOID,
00902                                    ObjectIdGetDatum(stats->attrtypid));
00903     if (!HeapTupleIsValid(typtuple))
00904         elog(ERROR, "cache lookup failed for type %u", stats->attrtypid);
00905     stats->attrtype = (Form_pg_type) GETSTRUCT(typtuple);
00906     stats->anl_context = anl_context;
00907     stats->tupattnum = attnum;
00908 
00909     /*
00910      * The fields describing the stats->stavalues[n] element types default to
00911      * the type of the data being analyzed, but the type-specific typanalyze
00912      * function can change them if it wants to store something else.
00913      */
00914     for (i = 0; i < STATISTIC_NUM_SLOTS; i++)
00915     {
00916         stats->statypid[i] = stats->attrtypid;
00917         stats->statyplen[i] = stats->attrtype->typlen;
00918         stats->statypbyval[i] = stats->attrtype->typbyval;
00919         stats->statypalign[i] = stats->attrtype->typalign;
00920     }
00921 
00922     /*
00923      * Call the type-specific typanalyze function.  If none is specified, use
00924      * std_typanalyze().
00925      */
00926     if (OidIsValid(stats->attrtype->typanalyze))
00927         ok = DatumGetBool(OidFunctionCall1(stats->attrtype->typanalyze,
00928                                            PointerGetDatum(stats)));
00929     else
00930         ok = std_typanalyze(stats);
00931 
00932     if (!ok || stats->compute_stats == NULL || stats->minrows <= 0)
00933     {
00934         heap_freetuple(typtuple);
00935         pfree(stats->attr);
00936         pfree(stats);
00937         return NULL;
00938     }
00939 
00940     return stats;
00941 }
00942 
00943 /*
00944  * BlockSampler_Init -- prepare for random sampling of blocknumbers
00945  *
00946  * BlockSampler is used for stage one of our new two-stage tuple
00947  * sampling mechanism as discussed on pgsql-hackers 2004-04-02 (subject
00948  * "Large DB").  It selects a random sample of samplesize blocks out of
00949  * the nblocks blocks in the table.  If the table has less than
00950  * samplesize blocks, all blocks are selected.
00951  *
00952  * Since we know the total number of blocks in advance, we can use the
00953  * straightforward Algorithm S from Knuth 3.4.2, rather than Vitter's
00954  * algorithm.
00955  */
00956 static void
00957 BlockSampler_Init(BlockSampler bs, BlockNumber nblocks, int samplesize)
00958 {
00959     bs->N = nblocks;            /* measured table size */
00960 
00961     /*
00962      * If we decide to reduce samplesize for tables that have less or not much
00963      * more than samplesize blocks, here is the place to do it.
00964      */
00965     bs->n = samplesize;
00966     bs->t = 0;                  /* blocks scanned so far */
00967     bs->m = 0;                  /* blocks selected so far */
00968 }
00969 
00970 static bool
00971 BlockSampler_HasMore(BlockSampler bs)
00972 {
00973     return (bs->t < bs->N) && (bs->m < bs->n);
00974 }
00975 
00976 static BlockNumber
00977 BlockSampler_Next(BlockSampler bs)
00978 {
00979     BlockNumber K = bs->N - bs->t;      /* remaining blocks */
00980     int         k = bs->n - bs->m;      /* blocks still to sample */
00981     double      p;              /* probability to skip block */
00982     double      V;              /* random */
00983 
00984     Assert(BlockSampler_HasMore(bs));   /* hence K > 0 and k > 0 */
00985 
00986     if ((BlockNumber) k >= K)
00987     {
00988         /* need all the rest */
00989         bs->m++;
00990         return bs->t++;
00991     }
00992 
00993     /*----------
00994      * It is not obvious that this code matches Knuth's Algorithm S.
00995      * Knuth says to skip the current block with probability 1 - k/K.
00996      * If we are to skip, we should advance t (hence decrease K), and
00997      * repeat the same probabilistic test for the next block.  The naive
00998      * implementation thus requires an anl_random_fract() call for each block
00999      * number.  But we can reduce this to one anl_random_fract() call per
01000      * selected block, by noting that each time the while-test succeeds,
01001      * we can reinterpret V as a uniform random number in the range 0 to p.
01002      * Therefore, instead of choosing a new V, we just adjust p to be
01003      * the appropriate fraction of its former value, and our next loop
01004      * makes the appropriate probabilistic test.
01005      *
01006      * We have initially K > k > 0.  If the loop reduces K to equal k,
01007      * the next while-test must fail since p will become exactly zero
01008      * (we assume there will not be roundoff error in the division).
01009      * (Note: Knuth suggests a "<=" loop condition, but we use "<" just
01010      * to be doubly sure about roundoff error.)  Therefore K cannot become
01011      * less than k, which means that we cannot fail to select enough blocks.
01012      *----------
01013      */
01014     V = anl_random_fract();
01015     p = 1.0 - (double) k / (double) K;
01016     while (V < p)
01017     {
01018         /* skip */
01019         bs->t++;
01020         K--;                    /* keep K == N - t */
01021 
01022         /* adjust p to be new cutoff point in reduced range */
01023         p *= 1.0 - (double) k / (double) K;
01024     }
01025 
01026     /* select */
01027     bs->m++;
01028     return bs->t++;
01029 }
01030 
01031 /*
01032  * acquire_sample_rows -- acquire a random sample of rows from the table
01033  *
01034  * Selected rows are returned in the caller-allocated array rows[], which
01035  * must have at least targrows entries.
01036  * The actual number of rows selected is returned as the function result.
01037  * We also estimate the total numbers of live and dead rows in the table,
01038  * and return them into *totalrows and *totaldeadrows, respectively.
01039  *
01040  * The returned list of tuples is in order by physical position in the table.
01041  * (We will rely on this later to derive correlation estimates.)
01042  *
01043  * As of May 2004 we use a new two-stage method:  Stage one selects up
01044  * to targrows random blocks (or all blocks, if there aren't so many).
01045  * Stage two scans these blocks and uses the Vitter algorithm to create
01046  * a random sample of targrows rows (or less, if there are less in the
01047  * sample of blocks).  The two stages are executed simultaneously: each
01048  * block is processed as soon as stage one returns its number and while
01049  * the rows are read stage two controls which ones are to be inserted
01050  * into the sample.
01051  *
01052  * Although every row has an equal chance of ending up in the final
01053  * sample, this sampling method is not perfect: not every possible
01054  * sample has an equal chance of being selected.  For large relations
01055  * the number of different blocks represented by the sample tends to be
01056  * too small.  We can live with that for now.  Improvements are welcome.
01057  *
01058  * An important property of this sampling method is that because we do
01059  * look at a statistically unbiased set of blocks, we should get
01060  * unbiased estimates of the average numbers of live and dead rows per
01061  * block.  The previous sampling method put too much credence in the row
01062  * density near the start of the table.
01063  */
01064 static int
01065 acquire_sample_rows(Relation onerel, int elevel,
01066                     HeapTuple *rows, int targrows,
01067                     double *totalrows, double *totaldeadrows)
01068 {
01069     int         numrows = 0;    /* # rows now in reservoir */
01070     double      samplerows = 0; /* total # rows collected */
01071     double      liverows = 0;   /* # live rows seen */
01072     double      deadrows = 0;   /* # dead rows seen */
01073     double      rowstoskip = -1;    /* -1 means not set yet */
01074     BlockNumber totalblocks;
01075     TransactionId OldestXmin;
01076     BlockSamplerData bs;
01077     double      rstate;
01078 
01079     Assert(targrows > 0);
01080 
01081     totalblocks = RelationGetNumberOfBlocks(onerel);
01082 
01083     /* Need a cutoff xmin for HeapTupleSatisfiesVacuum */
01084     OldestXmin = GetOldestXmin(onerel->rd_rel->relisshared, true);
01085 
01086     /* Prepare for sampling block numbers */
01087     BlockSampler_Init(&bs, totalblocks, targrows);
01088     /* Prepare for sampling rows */
01089     rstate = anl_init_selection_state(targrows);
01090 
01091     /* Outer loop over blocks to sample */
01092     while (BlockSampler_HasMore(&bs))
01093     {
01094         BlockNumber targblock = BlockSampler_Next(&bs);
01095         Buffer      targbuffer;
01096         Page        targpage;
01097         OffsetNumber targoffset,
01098                     maxoffset;
01099 
01100         vacuum_delay_point();
01101 
01102         /*
01103          * We must maintain a pin on the target page's buffer to ensure that
01104          * the maxoffset value stays good (else concurrent VACUUM might delete
01105          * tuples out from under us).  Hence, pin the page until we are done
01106          * looking at it.  We also choose to hold sharelock on the buffer
01107          * throughout --- we could release and re-acquire sharelock for each
01108          * tuple, but since we aren't doing much work per tuple, the extra
01109          * lock traffic is probably better avoided.
01110          */
01111         targbuffer = ReadBufferExtended(onerel, MAIN_FORKNUM, targblock,
01112                                         RBM_NORMAL, vac_strategy);
01113         LockBuffer(targbuffer, BUFFER_LOCK_SHARE);
01114         targpage = BufferGetPage(targbuffer);
01115         maxoffset = PageGetMaxOffsetNumber(targpage);
01116 
01117         /* Inner loop over all tuples on the selected page */
01118         for (targoffset = FirstOffsetNumber; targoffset <= maxoffset; targoffset++)
01119         {
01120             ItemId      itemid;
01121             HeapTupleData targtuple;
01122             bool        sample_it = false;
01123 
01124             itemid = PageGetItemId(targpage, targoffset);
01125 
01126             /*
01127              * We ignore unused and redirect line pointers.  DEAD line
01128              * pointers should be counted as dead, because we need vacuum to
01129              * run to get rid of them.  Note that this rule agrees with the
01130              * way that heap_page_prune() counts things.
01131              */
01132             if (!ItemIdIsNormal(itemid))
01133             {
01134                 if (ItemIdIsDead(itemid))
01135                     deadrows += 1;
01136                 continue;
01137             }
01138 
01139             ItemPointerSet(&targtuple.t_self, targblock, targoffset);
01140 
01141             targtuple.t_data = (HeapTupleHeader) PageGetItem(targpage, itemid);
01142             targtuple.t_len = ItemIdGetLength(itemid);
01143 
01144             switch (HeapTupleSatisfiesVacuum(targtuple.t_data,
01145                                              OldestXmin,
01146                                              targbuffer))
01147             {
01148                 case HEAPTUPLE_LIVE:
01149                     sample_it = true;
01150                     liverows += 1;
01151                     break;
01152 
01153                 case HEAPTUPLE_DEAD:
01154                 case HEAPTUPLE_RECENTLY_DEAD:
01155                     /* Count dead and recently-dead rows */
01156                     deadrows += 1;
01157                     break;
01158 
01159                 case HEAPTUPLE_INSERT_IN_PROGRESS:
01160 
01161                     /*
01162                      * Insert-in-progress rows are not counted.  We assume
01163                      * that when the inserting transaction commits or aborts,
01164                      * it will send a stats message to increment the proper
01165                      * count.  This works right only if that transaction ends
01166                      * after we finish analyzing the table; if things happen
01167                      * in the other order, its stats update will be
01168                      * overwritten by ours.  However, the error will be large
01169                      * only if the other transaction runs long enough to
01170                      * insert many tuples, so assuming it will finish after us
01171                      * is the safer option.
01172                      *
01173                      * A special case is that the inserting transaction might
01174                      * be our own.  In this case we should count and sample
01175                      * the row, to accommodate users who load a table and
01176                      * analyze it in one transaction.  (pgstat_report_analyze
01177                      * has to adjust the numbers we send to the stats
01178                      * collector to make this come out right.)
01179                      */
01180                     if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetXmin(targtuple.t_data)))
01181                     {
01182                         sample_it = true;
01183                         liverows += 1;
01184                     }
01185                     break;
01186 
01187                 case HEAPTUPLE_DELETE_IN_PROGRESS:
01188 
01189                     /*
01190                      * We count delete-in-progress rows as still live, using
01191                      * the same reasoning given above; but we don't bother to
01192                      * include them in the sample.
01193                      *
01194                      * If the delete was done by our own transaction, however,
01195                      * we must count the row as dead to make
01196                      * pgstat_report_analyze's stats adjustments come out
01197                      * right.  (Note: this works out properly when the row was
01198                      * both inserted and deleted in our xact.)
01199                      */
01200                     if (TransactionIdIsCurrentTransactionId(HeapTupleHeaderGetUpdateXid(targtuple.t_data)))
01201                         deadrows += 1;
01202                     else
01203                         liverows += 1;
01204                     break;
01205 
01206                 default:
01207                     elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
01208                     break;
01209             }
01210 
01211             if (sample_it)
01212             {
01213                 /*
01214                  * The first targrows sample rows are simply copied into the
01215                  * reservoir. Then we start replacing tuples in the sample
01216                  * until we reach the end of the relation.  This algorithm is
01217                  * from Jeff Vitter's paper (see full citation below). It
01218                  * works by repeatedly computing the number of tuples to skip
01219                  * before selecting a tuple, which replaces a randomly chosen
01220                  * element of the reservoir (current set of tuples).  At all
01221                  * times the reservoir is a true random sample of the tuples
01222                  * we've passed over so far, so when we fall off the end of
01223                  * the relation we're done.
01224                  */
01225                 if (numrows < targrows)
01226                     rows[numrows++] = heap_copytuple(&targtuple);
01227                 else
01228                 {
01229                     /*
01230                      * t in Vitter's paper is the number of records already
01231                      * processed.  If we need to compute a new S value, we
01232                      * must use the not-yet-incremented value of samplerows as
01233                      * t.
01234                      */
01235                     if (rowstoskip < 0)
01236                         rowstoskip = anl_get_next_S(samplerows, targrows,
01237                                                     &rstate);
01238 
01239                     if (rowstoskip <= 0)
01240                     {
01241                         /*
01242                          * Found a suitable tuple, so save it, replacing one
01243                          * old tuple at random
01244                          */
01245                         int         k = (int) (targrows * anl_random_fract());
01246 
01247                         Assert(k >= 0 && k < targrows);
01248                         heap_freetuple(rows[k]);
01249                         rows[k] = heap_copytuple(&targtuple);
01250                     }
01251 
01252                     rowstoskip -= 1;
01253                 }
01254 
01255                 samplerows += 1;
01256             }
01257         }
01258 
01259         /* Now release the lock and pin on the page */
01260         UnlockReleaseBuffer(targbuffer);
01261     }
01262 
01263     /*
01264      * If we didn't find as many tuples as we wanted then we're done. No sort
01265      * is needed, since they're already in order.
01266      *
01267      * Otherwise we need to sort the collected tuples by position
01268      * (itempointer). It's not worth worrying about corner cases where the
01269      * tuples are already sorted.
01270      */
01271     if (numrows == targrows)
01272         qsort((void *) rows, numrows, sizeof(HeapTuple), compare_rows);
01273 
01274     /*
01275      * Estimate total numbers of rows in relation.  For live rows, use
01276      * vac_estimate_reltuples; for dead rows, we have no source of old
01277      * information, so we have to assume the density is the same in unseen
01278      * pages as in the pages we scanned.
01279      */
01280     *totalrows = vac_estimate_reltuples(onerel, true,
01281                                         totalblocks,
01282                                         bs.m,
01283                                         liverows);
01284     if (bs.m > 0)
01285         *totaldeadrows = floor((deadrows / bs.m) * totalblocks + 0.5);
01286     else
01287         *totaldeadrows = 0.0;
01288 
01289     /*
01290      * Emit some interesting relation info
01291      */
01292     ereport(elevel,
01293             (errmsg("\"%s\": scanned %d of %u pages, "
01294                     "containing %.0f live rows and %.0f dead rows; "
01295                     "%d rows in sample, %.0f estimated total rows",
01296                     RelationGetRelationName(onerel),
01297                     bs.m, totalblocks,
01298                     liverows, deadrows,
01299                     numrows, *totalrows)));
01300 
01301     return numrows;
01302 }
01303 
01304 /* Select a random value R uniformly distributed in (0 - 1) */
01305 double
01306 anl_random_fract(void)
01307 {
01308     return ((double) random() + 1) / ((double) MAX_RANDOM_VALUE + 2);
01309 }
01310 
01311 /*
01312  * These two routines embody Algorithm Z from "Random sampling with a
01313  * reservoir" by Jeffrey S. Vitter, in ACM Trans. Math. Softw. 11, 1
01314  * (Mar. 1985), Pages 37-57.  Vitter describes his algorithm in terms
01315  * of the count S of records to skip before processing another record.
01316  * It is computed primarily based on t, the number of records already read.
01317  * The only extra state needed between calls is W, a random state variable.
01318  *
01319  * anl_init_selection_state computes the initial W value.
01320  *
01321  * Given that we've already read t records (t >= n), anl_get_next_S
01322  * determines the number of records to skip before the next record is
01323  * processed.
01324  */
01325 double
01326 anl_init_selection_state(int n)
01327 {
01328     /* Initial value of W (for use when Algorithm Z is first applied) */
01329     return exp(-log(anl_random_fract()) / n);
01330 }
01331 
01332 double
01333 anl_get_next_S(double t, int n, double *stateptr)
01334 {
01335     double      S;
01336 
01337     /* The magic constant here is T from Vitter's paper */
01338     if (t <= (22.0 * n))
01339     {
01340         /* Process records using Algorithm X until t is large enough */
01341         double      V,
01342                     quot;
01343 
01344         V = anl_random_fract(); /* Generate V */
01345         S = 0;
01346         t += 1;
01347         /* Note: "num" in Vitter's code is always equal to t - n */
01348         quot = (t - (double) n) / t;
01349         /* Find min S satisfying (4.1) */
01350         while (quot > V)
01351         {
01352             S += 1;
01353             t += 1;
01354             quot *= (t - (double) n) / t;
01355         }
01356     }
01357     else
01358     {
01359         /* Now apply Algorithm Z */
01360         double      W = *stateptr;
01361         double      term = t - (double) n + 1;
01362 
01363         for (;;)
01364         {
01365             double      numer,
01366                         numer_lim,
01367                         denom;
01368             double      U,
01369                         X,
01370                         lhs,
01371                         rhs,
01372                         y,
01373                         tmp;
01374 
01375             /* Generate U and X */
01376             U = anl_random_fract();
01377             X = t * (W - 1.0);
01378             S = floor(X);       /* S is tentatively set to floor(X) */
01379             /* Test if U <= h(S)/cg(X) in the manner of (6.3) */
01380             tmp = (t + 1) / term;
01381             lhs = exp(log(((U * tmp * tmp) * (term + S)) / (t + X)) / n);
01382             rhs = (((t + X) / (term + S)) * term) / t;
01383             if (lhs <= rhs)
01384             {
01385                 W = rhs / lhs;
01386                 break;
01387             }
01388             /* Test if U <= f(S)/cg(X) */
01389             y = (((U * (t + 1)) / term) * (t + S + 1)) / (t + X);
01390             if ((double) n < S)
01391             {
01392                 denom = t;
01393                 numer_lim = term + S;
01394             }
01395             else
01396             {
01397                 denom = t - (double) n + S;
01398                 numer_lim = t + 1;
01399             }
01400             for (numer = t + S; numer >= numer_lim; numer -= 1)
01401             {
01402                 y *= numer / denom;
01403                 denom -= 1;
01404             }
01405             W = exp(-log(anl_random_fract()) / n);      /* Generate W in advance */
01406             if (exp(log(y) / n) <= (t + X) / t)
01407                 break;
01408         }
01409         *stateptr = W;
01410     }
01411     return S;
01412 }
01413 
01414 /*
01415  * qsort comparator for sorting rows[] array
01416  */
01417 static int
01418 compare_rows(const void *a, const void *b)
01419 {
01420     HeapTuple   ha = *(const HeapTuple *) a;
01421     HeapTuple   hb = *(const HeapTuple *) b;
01422     BlockNumber ba = ItemPointerGetBlockNumber(&ha->t_self);
01423     OffsetNumber oa = ItemPointerGetOffsetNumber(&ha->t_self);
01424     BlockNumber bb = ItemPointerGetBlockNumber(&hb->t_self);
01425     OffsetNumber ob = ItemPointerGetOffsetNumber(&hb->t_self);
01426 
01427     if (ba < bb)
01428         return -1;
01429     if (ba > bb)
01430         return 1;
01431     if (oa < ob)
01432         return -1;
01433     if (oa > ob)
01434         return 1;
01435     return 0;
01436 }
01437 
01438 
01439 /*
01440  * acquire_inherited_sample_rows -- acquire sample rows from inheritance tree
01441  *
01442  * This has the same API as acquire_sample_rows, except that rows are
01443  * collected from all inheritance children as well as the specified table.
01444  * We fail and return zero if there are no inheritance children.
01445  */
01446 static int
01447 acquire_inherited_sample_rows(Relation onerel, int elevel,
01448                               HeapTuple *rows, int targrows,
01449                               double *totalrows, double *totaldeadrows)
01450 {
01451     List       *tableOIDs;
01452     Relation   *rels;
01453     double     *relblocks;
01454     double      totalblocks;
01455     int         numrows,
01456                 nrels,
01457                 i;
01458     ListCell   *lc;
01459 
01460     /*
01461      * Find all members of inheritance set.  We only need AccessShareLock on
01462      * the children.
01463      */
01464     tableOIDs =
01465         find_all_inheritors(RelationGetRelid(onerel), AccessShareLock, NULL);
01466 
01467     /*
01468      * Check that there's at least one descendant, else fail.  This could
01469      * happen despite analyze_rel's relhassubclass check, if table once had a
01470      * child but no longer does.  In that case, we can clear the
01471      * relhassubclass field so as not to make the same mistake again later.
01472      * (This is safe because we hold ShareUpdateExclusiveLock.)
01473      */
01474     if (list_length(tableOIDs) < 2)
01475     {
01476         /* CCI because we already updated the pg_class row in this command */
01477         CommandCounterIncrement();
01478         SetRelationHasSubclass(RelationGetRelid(onerel), false);
01479         return 0;
01480     }
01481 
01482     /*
01483      * Count the blocks in all the relations.  The result could overflow
01484      * BlockNumber, so we use double arithmetic.
01485      */
01486     rels = (Relation *) palloc(list_length(tableOIDs) * sizeof(Relation));
01487     relblocks = (double *) palloc(list_length(tableOIDs) * sizeof(double));
01488     totalblocks = 0;
01489     nrels = 0;
01490     foreach(lc, tableOIDs)
01491     {
01492         Oid         childOID = lfirst_oid(lc);
01493         Relation    childrel;
01494 
01495         /* We already got the needed lock */
01496         childrel = heap_open(childOID, NoLock);
01497 
01498         /* Ignore if temp table of another backend */
01499         if (RELATION_IS_OTHER_TEMP(childrel))
01500         {
01501             /* ... but release the lock on it */
01502             Assert(childrel != onerel);
01503             heap_close(childrel, AccessShareLock);
01504             continue;
01505         }
01506 
01507         rels[nrels] = childrel;
01508         relblocks[nrels] = (double) RelationGetNumberOfBlocks(childrel);
01509         totalblocks += relblocks[nrels];
01510         nrels++;
01511     }
01512 
01513     /*
01514      * Now sample rows from each relation, proportionally to its fraction of
01515      * the total block count.  (This might be less than desirable if the child
01516      * rels have radically different free-space percentages, but it's not
01517      * clear that it's worth working harder.)
01518      */
01519     numrows = 0;
01520     *totalrows = 0;
01521     *totaldeadrows = 0;
01522     for (i = 0; i < nrels; i++)
01523     {
01524         Relation    childrel = rels[i];
01525         double      childblocks = relblocks[i];
01526 
01527         if (childblocks > 0)
01528         {
01529             int         childtargrows;
01530 
01531             childtargrows = (int) rint(targrows * childblocks / totalblocks);
01532             /* Make sure we don't overrun due to roundoff error */
01533             childtargrows = Min(childtargrows, targrows - numrows);
01534             if (childtargrows > 0)
01535             {
01536                 int         childrows;
01537                 double      trows,
01538                             tdrows;
01539 
01540                 /* Fetch a random sample of the child's rows */
01541                 childrows = acquire_sample_rows(childrel,
01542                                                 elevel,
01543                                                 rows + numrows,
01544                                                 childtargrows,
01545                                                 &trows,
01546                                                 &tdrows);
01547 
01548                 /* We may need to convert from child's rowtype to parent's */
01549                 if (childrows > 0 &&
01550                     !equalTupleDescs(RelationGetDescr(childrel),
01551                                      RelationGetDescr(onerel)))
01552                 {
01553                     TupleConversionMap *map;
01554 
01555                     map = convert_tuples_by_name(RelationGetDescr(childrel),
01556                                                  RelationGetDescr(onerel),
01557                                  gettext_noop("could not convert row type"));
01558                     if (map != NULL)
01559                     {
01560                         int         j;
01561 
01562                         for (j = 0; j < childrows; j++)
01563                         {
01564                             HeapTuple   newtup;
01565 
01566                             newtup = do_convert_tuple(rows[numrows + j], map);
01567                             heap_freetuple(rows[numrows + j]);
01568                             rows[numrows + j] = newtup;
01569                         }
01570                         free_conversion_map(map);
01571                     }
01572                 }
01573 
01574                 /* And add to counts */
01575                 numrows += childrows;
01576                 *totalrows += trows;
01577                 *totaldeadrows += tdrows;
01578             }
01579         }
01580 
01581         /*
01582          * Note: we cannot release the child-table locks, since we may have
01583          * pointers to their TOAST tables in the sampled rows.
01584          */
01585         heap_close(childrel, NoLock);
01586     }
01587 
01588     return numrows;
01589 }
01590 
01591 
01592 /*
01593  *  update_attstats() -- update attribute statistics for one relation
01594  *
01595  *      Statistics are stored in several places: the pg_class row for the
01596  *      relation has stats about the whole relation, and there is a
01597  *      pg_statistic row for each (non-system) attribute that has ever
01598  *      been analyzed.  The pg_class values are updated by VACUUM, not here.
01599  *
01600  *      pg_statistic rows are just added or updated normally.  This means
01601  *      that pg_statistic will probably contain some deleted rows at the
01602  *      completion of a vacuum cycle, unless it happens to get vacuumed last.
01603  *
01604  *      To keep things simple, we punt for pg_statistic, and don't try
01605  *      to compute or store rows for pg_statistic itself in pg_statistic.
01606  *      This could possibly be made to work, but it's not worth the trouble.
01607  *      Note analyze_rel() has seen to it that we won't come here when
01608  *      vacuuming pg_statistic itself.
01609  *
01610  *      Note: there would be a race condition here if two backends could
01611  *      ANALYZE the same table concurrently.  Presently, we lock that out
01612  *      by taking a self-exclusive lock on the relation in analyze_rel().
01613  */
01614 static void
01615 update_attstats(Oid relid, bool inh, int natts, VacAttrStats **vacattrstats)
01616 {
01617     Relation    sd;
01618     int         attno;
01619 
01620     if (natts <= 0)
01621         return;                 /* nothing to do */
01622 
01623     sd = heap_open(StatisticRelationId, RowExclusiveLock);
01624 
01625     for (attno = 0; attno < natts; attno++)
01626     {
01627         VacAttrStats *stats = vacattrstats[attno];
01628         HeapTuple   stup,
01629                     oldtup;
01630         int         i,
01631                     k,
01632                     n;
01633         Datum       values[Natts_pg_statistic];
01634         bool        nulls[Natts_pg_statistic];
01635         bool        replaces[Natts_pg_statistic];
01636 
01637         /* Ignore attr if we weren't able to collect stats */
01638         if (!stats->stats_valid)
01639             continue;
01640 
01641         /*
01642          * Construct a new pg_statistic tuple
01643          */
01644         for (i = 0; i < Natts_pg_statistic; ++i)
01645         {
01646             nulls[i] = false;
01647             replaces[i] = true;
01648         }
01649 
01650         values[Anum_pg_statistic_starelid - 1] = ObjectIdGetDatum(relid);
01651         values[Anum_pg_statistic_staattnum - 1] = Int16GetDatum(stats->attr->attnum);
01652         values[Anum_pg_statistic_stainherit - 1] = BoolGetDatum(inh);
01653         values[Anum_pg_statistic_stanullfrac - 1] = Float4GetDatum(stats->stanullfrac);
01654         values[Anum_pg_statistic_stawidth - 1] = Int32GetDatum(stats->stawidth);
01655         values[Anum_pg_statistic_stadistinct - 1] = Float4GetDatum(stats->stadistinct);
01656         i = Anum_pg_statistic_stakind1 - 1;
01657         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
01658         {
01659             values[i++] = Int16GetDatum(stats->stakind[k]);     /* stakindN */
01660         }
01661         i = Anum_pg_statistic_staop1 - 1;
01662         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
01663         {
01664             values[i++] = ObjectIdGetDatum(stats->staop[k]);    /* staopN */
01665         }
01666         i = Anum_pg_statistic_stanumbers1 - 1;
01667         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
01668         {
01669             int         nnum = stats->numnumbers[k];
01670 
01671             if (nnum > 0)
01672             {
01673                 Datum      *numdatums = (Datum *) palloc(nnum * sizeof(Datum));
01674                 ArrayType  *arry;
01675 
01676                 for (n = 0; n < nnum; n++)
01677                     numdatums[n] = Float4GetDatum(stats->stanumbers[k][n]);
01678                 /* XXX knows more than it should about type float4: */
01679                 arry = construct_array(numdatums, nnum,
01680                                        FLOAT4OID,
01681                                        sizeof(float4), FLOAT4PASSBYVAL, 'i');
01682                 values[i++] = PointerGetDatum(arry);    /* stanumbersN */
01683             }
01684             else
01685             {
01686                 nulls[i] = true;
01687                 values[i++] = (Datum) 0;
01688             }
01689         }
01690         i = Anum_pg_statistic_stavalues1 - 1;
01691         for (k = 0; k < STATISTIC_NUM_SLOTS; k++)
01692         {
01693             if (stats->numvalues[k] > 0)
01694             {
01695                 ArrayType  *arry;
01696 
01697                 arry = construct_array(stats->stavalues[k],
01698                                        stats->numvalues[k],
01699                                        stats->statypid[k],
01700                                        stats->statyplen[k],
01701                                        stats->statypbyval[k],
01702                                        stats->statypalign[k]);
01703                 values[i++] = PointerGetDatum(arry);    /* stavaluesN */
01704             }
01705             else
01706             {
01707                 nulls[i] = true;
01708                 values[i++] = (Datum) 0;
01709             }
01710         }
01711 
01712         /* Is there already a pg_statistic tuple for this attribute? */
01713         oldtup = SearchSysCache3(STATRELATTINH,
01714                                  ObjectIdGetDatum(relid),
01715                                  Int16GetDatum(stats->attr->attnum),
01716                                  BoolGetDatum(inh));
01717 
01718         if (HeapTupleIsValid(oldtup))
01719         {
01720             /* Yes, replace it */
01721             stup = heap_modify_tuple(oldtup,
01722                                      RelationGetDescr(sd),
01723                                      values,
01724                                      nulls,
01725                                      replaces);
01726             ReleaseSysCache(oldtup);
01727             simple_heap_update(sd, &stup->t_self, stup);
01728         }
01729         else
01730         {
01731             /* No, insert new tuple */
01732             stup = heap_form_tuple(RelationGetDescr(sd), values, nulls);
01733             simple_heap_insert(sd, stup);
01734         }
01735 
01736         /* update indexes too */
01737         CatalogUpdateIndexes(sd, stup);
01738 
01739         heap_freetuple(stup);
01740     }
01741 
01742     heap_close(sd, RowExclusiveLock);
01743 }
01744 
01745 /*
01746  * Standard fetch function for use by compute_stats subroutines.
01747  *
01748  * This exists to provide some insulation between compute_stats routines
01749  * and the actual storage of the sample data.
01750  */
01751 static Datum
01752 std_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
01753 {
01754     int         attnum = stats->tupattnum;
01755     HeapTuple   tuple = stats->rows[rownum];
01756     TupleDesc   tupDesc = stats->tupDesc;
01757 
01758     return heap_getattr(tuple, attnum, tupDesc, isNull);
01759 }
01760 
01761 /*
01762  * Fetch function for analyzing index expressions.
01763  *
01764  * We have not bothered to construct index tuples, instead the data is
01765  * just in Datum arrays.
01766  */
01767 static Datum
01768 ind_fetch_func(VacAttrStatsP stats, int rownum, bool *isNull)
01769 {
01770     int         i;
01771 
01772     /* exprvals and exprnulls are already offset for proper column */
01773     i = rownum * stats->rowstride;
01774     *isNull = stats->exprnulls[i];
01775     return stats->exprvals[i];
01776 }
01777 
01778 
01779 /*==========================================================================
01780  *
01781  * Code below this point represents the "standard" type-specific statistics
01782  * analysis algorithms.  This code can be replaced on a per-data-type basis
01783  * by setting a nonzero value in pg_type.typanalyze.
01784  *
01785  *==========================================================================
01786  */
01787 
01788 
01789 /*
01790  * To avoid consuming too much memory during analysis and/or too much space
01791  * in the resulting pg_statistic rows, we ignore varlena datums that are wider
01792  * than WIDTH_THRESHOLD (after detoasting!).  This is legitimate for MCV
01793  * and distinct-value calculations since a wide value is unlikely to be
01794  * duplicated at all, much less be a most-common value.  For the same reason,
01795  * ignoring wide values will not affect our estimates of histogram bin
01796  * boundaries very much.
01797  */
01798 #define WIDTH_THRESHOLD  1024
01799 
01800 #define swapInt(a,b)    do {int _tmp; _tmp=a; a=b; b=_tmp;} while(0)
01801 #define swapDatum(a,b)  do {Datum _tmp; _tmp=a; a=b; b=_tmp;} while(0)
01802 
01803 /*
01804  * Extra information used by the default analysis routines
01805  */
01806 typedef struct
01807 {
01808     Oid         eqopr;          /* '=' operator for datatype, if any */
01809     Oid         eqfunc;         /* and associated function */
01810     Oid         ltopr;          /* '<' operator for datatype, if any */
01811 } StdAnalyzeData;
01812 
01813 typedef struct
01814 {
01815     Datum       value;          /* a data value */
01816     int         tupno;          /* position index for tuple it came from */
01817 } ScalarItem;
01818 
01819 typedef struct
01820 {
01821     int         count;          /* # of duplicates */
01822     int         first;          /* values[] index of first occurrence */
01823 } ScalarMCVItem;
01824 
01825 typedef struct
01826 {
01827     SortSupport ssup;
01828     int        *tupnoLink;
01829 } CompareScalarsContext;
01830 
01831 
01832 static void compute_minimal_stats(VacAttrStatsP stats,
01833                       AnalyzeAttrFetchFunc fetchfunc,
01834                       int samplerows,
01835                       double totalrows);
01836 static void compute_scalar_stats(VacAttrStatsP stats,
01837                      AnalyzeAttrFetchFunc fetchfunc,
01838                      int samplerows,
01839                      double totalrows);
01840 static int  compare_scalars(const void *a, const void *b, void *arg);
01841 static int  compare_mcvs(const void *a, const void *b);
01842 
01843 
01844 /*
01845  * std_typanalyze -- the default type-specific typanalyze function
01846  */
01847 bool
01848 std_typanalyze(VacAttrStats *stats)
01849 {
01850     Form_pg_attribute attr = stats->attr;
01851     Oid         ltopr;
01852     Oid         eqopr;
01853     StdAnalyzeData *mystats;
01854 
01855     /* If the attstattarget column is negative, use the default value */
01856     /* NB: it is okay to scribble on stats->attr since it's a copy */
01857     if (attr->attstattarget < 0)
01858         attr->attstattarget = default_statistics_target;
01859 
01860     /* Look for default "<" and "=" operators for column's type */
01861     get_sort_group_operators(stats->attrtypid,
01862                              false, false, false,
01863                              &ltopr, &eqopr, NULL,
01864                              NULL);
01865 
01866     /* If column has no "=" operator, we can't do much of anything */
01867     if (!OidIsValid(eqopr))
01868         return false;
01869 
01870     /* Save the operator info for compute_stats routines */
01871     mystats = (StdAnalyzeData *) palloc(sizeof(StdAnalyzeData));
01872     mystats->eqopr = eqopr;
01873     mystats->eqfunc = get_opcode(eqopr);
01874     mystats->ltopr = ltopr;
01875     stats->extra_data = mystats;
01876 
01877     /*
01878      * Determine which standard statistics algorithm to use
01879      */
01880     if (OidIsValid(ltopr))
01881     {
01882         /* Seems to be a scalar datatype */
01883         stats->compute_stats = compute_scalar_stats;
01884         /*--------------------
01885          * The following choice of minrows is based on the paper
01886          * "Random sampling for histogram construction: how much is enough?"
01887          * by Surajit Chaudhuri, Rajeev Motwani and Vivek Narasayya, in
01888          * Proceedings of ACM SIGMOD International Conference on Management
01889          * of Data, 1998, Pages 436-447.  Their Corollary 1 to Theorem 5
01890          * says that for table size n, histogram size k, maximum relative
01891          * error in bin size f, and error probability gamma, the minimum
01892          * random sample size is
01893          *      r = 4 * k * ln(2*n/gamma) / f^2
01894          * Taking f = 0.5, gamma = 0.01, n = 10^6 rows, we obtain
01895          *      r = 305.82 * k
01896          * Note that because of the log function, the dependence on n is
01897          * quite weak; even at n = 10^12, a 300*k sample gives <= 0.66
01898          * bin size error with probability 0.99.  So there's no real need to
01899          * scale for n, which is a good thing because we don't necessarily
01900          * know it at this point.
01901          *--------------------
01902          */
01903         stats->minrows = 300 * attr->attstattarget;
01904     }
01905     else
01906     {
01907         /* Can't do much but the minimal stuff */
01908         stats->compute_stats = compute_minimal_stats;
01909         /* Might as well use the same minrows as above */
01910         stats->minrows = 300 * attr->attstattarget;
01911     }
01912 
01913     return true;
01914 }
01915 
01916 /*
01917  *  compute_minimal_stats() -- compute minimal column statistics
01918  *
01919  *  We use this when we can find only an "=" operator for the datatype.
01920  *
01921  *  We determine the fraction of non-null rows, the average width, the
01922  *  most common values, and the (estimated) number of distinct values.
01923  *
01924  *  The most common values are determined by brute force: we keep a list
01925  *  of previously seen values, ordered by number of times seen, as we scan
01926  *  the samples.  A newly seen value is inserted just after the last
01927  *  multiply-seen value, causing the bottommost (oldest) singly-seen value
01928  *  to drop off the list.  The accuracy of this method, and also its cost,
01929  *  depend mainly on the length of the list we are willing to keep.
01930  */
01931 static void
01932 compute_minimal_stats(VacAttrStatsP stats,
01933                       AnalyzeAttrFetchFunc fetchfunc,
01934                       int samplerows,
01935                       double totalrows)
01936 {
01937     int         i;
01938     int         null_cnt = 0;
01939     int         nonnull_cnt = 0;
01940     int         toowide_cnt = 0;
01941     double      total_width = 0;
01942     bool        is_varlena = (!stats->attrtype->typbyval &&
01943                               stats->attrtype->typlen == -1);
01944     bool        is_varwidth = (!stats->attrtype->typbyval &&
01945                                stats->attrtype->typlen < 0);
01946     FmgrInfo    f_cmpeq;
01947     typedef struct
01948     {
01949         Datum       value;
01950         int         count;
01951     } TrackItem;
01952     TrackItem  *track;
01953     int         track_cnt,
01954                 track_max;
01955     int         num_mcv = stats->attr->attstattarget;
01956     StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
01957 
01958     /*
01959      * We track up to 2*n values for an n-element MCV list; but at least 10
01960      */
01961     track_max = 2 * num_mcv;
01962     if (track_max < 10)
01963         track_max = 10;
01964     track = (TrackItem *) palloc(track_max * sizeof(TrackItem));
01965     track_cnt = 0;
01966 
01967     fmgr_info(mystats->eqfunc, &f_cmpeq);
01968 
01969     for (i = 0; i < samplerows; i++)
01970     {
01971         Datum       value;
01972         bool        isnull;
01973         bool        match;
01974         int         firstcount1,
01975                     j;
01976 
01977         vacuum_delay_point();
01978 
01979         value = fetchfunc(stats, i, &isnull);
01980 
01981         /* Check for null/nonnull */
01982         if (isnull)
01983         {
01984             null_cnt++;
01985             continue;
01986         }
01987         nonnull_cnt++;
01988 
01989         /*
01990          * If it's a variable-width field, add up widths for average width
01991          * calculation.  Note that if the value is toasted, we use the toasted
01992          * width.  We don't bother with this calculation if it's a fixed-width
01993          * type.
01994          */
01995         if (is_varlena)
01996         {
01997             total_width += VARSIZE_ANY(DatumGetPointer(value));
01998 
01999             /*
02000              * If the value is toasted, we want to detoast it just once to
02001              * avoid repeated detoastings and resultant excess memory usage
02002              * during the comparisons.  Also, check to see if the value is
02003              * excessively wide, and if so don't detoast at all --- just
02004              * ignore the value.
02005              */
02006             if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
02007             {
02008                 toowide_cnt++;
02009                 continue;
02010             }
02011             value = PointerGetDatum(PG_DETOAST_DATUM(value));
02012         }
02013         else if (is_varwidth)
02014         {
02015             /* must be cstring */
02016             total_width += strlen(DatumGetCString(value)) + 1;
02017         }
02018 
02019         /*
02020          * See if the value matches anything we're already tracking.
02021          */
02022         match = false;
02023         firstcount1 = track_cnt;
02024         for (j = 0; j < track_cnt; j++)
02025         {
02026             /* We always use the default collation for statistics */
02027             if (DatumGetBool(FunctionCall2Coll(&f_cmpeq,
02028                                                DEFAULT_COLLATION_OID,
02029                                                value, track[j].value)))
02030             {
02031                 match = true;
02032                 break;
02033             }
02034             if (j < firstcount1 && track[j].count == 1)
02035                 firstcount1 = j;
02036         }
02037 
02038         if (match)
02039         {
02040             /* Found a match */
02041             track[j].count++;
02042             /* This value may now need to "bubble up" in the track list */
02043             while (j > 0 && track[j].count > track[j - 1].count)
02044             {
02045                 swapDatum(track[j].value, track[j - 1].value);
02046                 swapInt(track[j].count, track[j - 1].count);
02047                 j--;
02048             }
02049         }
02050         else
02051         {
02052             /* No match.  Insert at head of count-1 list */
02053             if (track_cnt < track_max)
02054                 track_cnt++;
02055             for (j = track_cnt - 1; j > firstcount1; j--)
02056             {
02057                 track[j].value = track[j - 1].value;
02058                 track[j].count = track[j - 1].count;
02059             }
02060             if (firstcount1 < track_cnt)
02061             {
02062                 track[firstcount1].value = value;
02063                 track[firstcount1].count = 1;
02064             }
02065         }
02066     }
02067 
02068     /* We can only compute real stats if we found some non-null values. */
02069     if (nonnull_cnt > 0)
02070     {
02071         int         nmultiple,
02072                     summultiple;
02073 
02074         stats->stats_valid = true;
02075         /* Do the simple null-frac and width stats */
02076         stats->stanullfrac = (double) null_cnt / (double) samplerows;
02077         if (is_varwidth)
02078             stats->stawidth = total_width / (double) nonnull_cnt;
02079         else
02080             stats->stawidth = stats->attrtype->typlen;
02081 
02082         /* Count the number of values we found multiple times */
02083         summultiple = 0;
02084         for (nmultiple = 0; nmultiple < track_cnt; nmultiple++)
02085         {
02086             if (track[nmultiple].count == 1)
02087                 break;
02088             summultiple += track[nmultiple].count;
02089         }
02090 
02091         if (nmultiple == 0)
02092         {
02093             /* If we found no repeated values, assume it's a unique column */
02094             stats->stadistinct = -1.0;
02095         }
02096         else if (track_cnt < track_max && toowide_cnt == 0 &&
02097                  nmultiple == track_cnt)
02098         {
02099             /*
02100              * Our track list includes every value in the sample, and every
02101              * value appeared more than once.  Assume the column has just
02102              * these values.
02103              */
02104             stats->stadistinct = track_cnt;
02105         }
02106         else
02107         {
02108             /*----------
02109              * Estimate the number of distinct values using the estimator
02110              * proposed by Haas and Stokes in IBM Research Report RJ 10025:
02111              *      n*d / (n - f1 + f1*n/N)
02112              * where f1 is the number of distinct values that occurred
02113              * exactly once in our sample of n rows (from a total of N),
02114              * and d is the total number of distinct values in the sample.
02115              * This is their Duj1 estimator; the other estimators they
02116              * recommend are considerably more complex, and are numerically
02117              * very unstable when n is much smaller than N.
02118              *
02119              * We assume (not very reliably!) that all the multiply-occurring
02120              * values are reflected in the final track[] list, and the other
02121              * nonnull values all appeared but once.  (XXX this usually
02122              * results in a drastic overestimate of ndistinct.  Can we do
02123              * any better?)
02124              *----------
02125              */
02126             int         f1 = nonnull_cnt - summultiple;
02127             int         d = f1 + nmultiple;
02128             double      numer,
02129                         denom,
02130                         stadistinct;
02131 
02132             numer = (double) samplerows *(double) d;
02133 
02134             denom = (double) (samplerows - f1) +
02135                 (double) f1 *(double) samplerows / totalrows;
02136 
02137             stadistinct = numer / denom;
02138             /* Clamp to sane range in case of roundoff error */
02139             if (stadistinct < (double) d)
02140                 stadistinct = (double) d;
02141             if (stadistinct > totalrows)
02142                 stadistinct = totalrows;
02143             stats->stadistinct = floor(stadistinct + 0.5);
02144         }
02145 
02146         /*
02147          * If we estimated the number of distinct values at more than 10% of
02148          * the total row count (a very arbitrary limit), then assume that
02149          * stadistinct should scale with the row count rather than be a fixed
02150          * value.
02151          */
02152         if (stats->stadistinct > 0.1 * totalrows)
02153             stats->stadistinct = -(stats->stadistinct / totalrows);
02154 
02155         /*
02156          * Decide how many values are worth storing as most-common values. If
02157          * we are able to generate a complete MCV list (all the values in the
02158          * sample will fit, and we think these are all the ones in the table),
02159          * then do so.  Otherwise, store only those values that are
02160          * significantly more common than the (estimated) average. We set the
02161          * threshold rather arbitrarily at 25% more than average, with at
02162          * least 2 instances in the sample.
02163          */
02164         if (track_cnt < track_max && toowide_cnt == 0 &&
02165             stats->stadistinct > 0 &&
02166             track_cnt <= num_mcv)
02167         {
02168             /* Track list includes all values seen, and all will fit */
02169             num_mcv = track_cnt;
02170         }
02171         else
02172         {
02173             double      ndistinct = stats->stadistinct;
02174             double      avgcount,
02175                         mincount;
02176 
02177             if (ndistinct < 0)
02178                 ndistinct = -ndistinct * totalrows;
02179             /* estimate # of occurrences in sample of a typical value */
02180             avgcount = (double) samplerows / ndistinct;
02181             /* set minimum threshold count to store a value */
02182             mincount = avgcount * 1.25;
02183             if (mincount < 2)
02184                 mincount = 2;
02185             if (num_mcv > track_cnt)
02186                 num_mcv = track_cnt;
02187             for (i = 0; i < num_mcv; i++)
02188             {
02189                 if (track[i].count < mincount)
02190                 {
02191                     num_mcv = i;
02192                     break;
02193                 }
02194             }
02195         }
02196 
02197         /* Generate MCV slot entry */
02198         if (num_mcv > 0)
02199         {
02200             MemoryContext old_context;
02201             Datum      *mcv_values;
02202             float4     *mcv_freqs;
02203 
02204             /* Must copy the target values into anl_context */
02205             old_context = MemoryContextSwitchTo(stats->anl_context);
02206             mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
02207             mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
02208             for (i = 0; i < num_mcv; i++)
02209             {
02210                 mcv_values[i] = datumCopy(track[i].value,
02211                                           stats->attrtype->typbyval,
02212                                           stats->attrtype->typlen);
02213                 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
02214             }
02215             MemoryContextSwitchTo(old_context);
02216 
02217             stats->stakind[0] = STATISTIC_KIND_MCV;
02218             stats->staop[0] = mystats->eqopr;
02219             stats->stanumbers[0] = mcv_freqs;
02220             stats->numnumbers[0] = num_mcv;
02221             stats->stavalues[0] = mcv_values;
02222             stats->numvalues[0] = num_mcv;
02223 
02224             /*
02225              * Accept the defaults for stats->statypid and others. They have
02226              * been set before we were called (see vacuum.h)
02227              */
02228         }
02229     }
02230     else if (null_cnt > 0)
02231     {
02232         /* We found only nulls; assume the column is entirely null */
02233         stats->stats_valid = true;
02234         stats->stanullfrac = 1.0;
02235         if (is_varwidth)
02236             stats->stawidth = 0;    /* "unknown" */
02237         else
02238             stats->stawidth = stats->attrtype->typlen;
02239         stats->stadistinct = 0.0;       /* "unknown" */
02240     }
02241 
02242     /* We don't need to bother cleaning up any of our temporary palloc's */
02243 }
02244 
02245 
02246 /*
02247  *  compute_scalar_stats() -- compute column statistics
02248  *
02249  *  We use this when we can find "=" and "<" operators for the datatype.
02250  *
02251  *  We determine the fraction of non-null rows, the average width, the
02252  *  most common values, the (estimated) number of distinct values, the
02253  *  distribution histogram, and the correlation of physical to logical order.
02254  *
02255  *  The desired stats can be determined fairly easily after sorting the
02256  *  data values into order.
02257  */
02258 static void
02259 compute_scalar_stats(VacAttrStatsP stats,
02260                      AnalyzeAttrFetchFunc fetchfunc,
02261                      int samplerows,
02262                      double totalrows)
02263 {
02264     int         i;
02265     int         null_cnt = 0;
02266     int         nonnull_cnt = 0;
02267     int         toowide_cnt = 0;
02268     double      total_width = 0;
02269     bool        is_varlena = (!stats->attrtype->typbyval &&
02270                               stats->attrtype->typlen == -1);
02271     bool        is_varwidth = (!stats->attrtype->typbyval &&
02272                                stats->attrtype->typlen < 0);
02273     double      corr_xysum;
02274     SortSupportData ssup;
02275     ScalarItem *values;
02276     int         values_cnt = 0;
02277     int        *tupnoLink;
02278     ScalarMCVItem *track;
02279     int         track_cnt = 0;
02280     int         num_mcv = stats->attr->attstattarget;
02281     int         num_bins = stats->attr->attstattarget;
02282     StdAnalyzeData *mystats = (StdAnalyzeData *) stats->extra_data;
02283 
02284     values = (ScalarItem *) palloc(samplerows * sizeof(ScalarItem));
02285     tupnoLink = (int *) palloc(samplerows * sizeof(int));
02286     track = (ScalarMCVItem *) palloc(num_mcv * sizeof(ScalarMCVItem));
02287 
02288     memset(&ssup, 0, sizeof(ssup));
02289     ssup.ssup_cxt = CurrentMemoryContext;
02290     /* We always use the default collation for statistics */
02291     ssup.ssup_collation = DEFAULT_COLLATION_OID;
02292     ssup.ssup_nulls_first = false;
02293 
02294     PrepareSortSupportFromOrderingOp(mystats->ltopr, &ssup);
02295 
02296     /* Initial scan to find sortable values */
02297     for (i = 0; i < samplerows; i++)
02298     {
02299         Datum       value;
02300         bool        isnull;
02301 
02302         vacuum_delay_point();
02303 
02304         value = fetchfunc(stats, i, &isnull);
02305 
02306         /* Check for null/nonnull */
02307         if (isnull)
02308         {
02309             null_cnt++;
02310             continue;
02311         }
02312         nonnull_cnt++;
02313 
02314         /*
02315          * If it's a variable-width field, add up widths for average width
02316          * calculation.  Note that if the value is toasted, we use the toasted
02317          * width.  We don't bother with this calculation if it's a fixed-width
02318          * type.
02319          */
02320         if (is_varlena)
02321         {
02322             total_width += VARSIZE_ANY(DatumGetPointer(value));
02323 
02324             /*
02325              * If the value is toasted, we want to detoast it just once to
02326              * avoid repeated detoastings and resultant excess memory usage
02327              * during the comparisons.  Also, check to see if the value is
02328              * excessively wide, and if so don't detoast at all --- just
02329              * ignore the value.
02330              */
02331             if (toast_raw_datum_size(value) > WIDTH_THRESHOLD)
02332             {
02333                 toowide_cnt++;
02334                 continue;
02335             }
02336             value = PointerGetDatum(PG_DETOAST_DATUM(value));
02337         }
02338         else if (is_varwidth)
02339         {
02340             /* must be cstring */
02341             total_width += strlen(DatumGetCString(value)) + 1;
02342         }
02343 
02344         /* Add it to the list to be sorted */
02345         values[values_cnt].value = value;
02346         values[values_cnt].tupno = values_cnt;
02347         tupnoLink[values_cnt] = values_cnt;
02348         values_cnt++;
02349     }
02350 
02351     /* We can only compute real stats if we found some sortable values. */
02352     if (values_cnt > 0)
02353     {
02354         int         ndistinct,  /* # distinct values in sample */
02355                     nmultiple,  /* # that appear multiple times */
02356                     num_hist,
02357                     dups_cnt;
02358         int         slot_idx = 0;
02359         CompareScalarsContext cxt;
02360 
02361         /* Sort the collected values */
02362         cxt.ssup = &ssup;
02363         cxt.tupnoLink = tupnoLink;
02364         qsort_arg((void *) values, values_cnt, sizeof(ScalarItem),
02365                   compare_scalars, (void *) &cxt);
02366 
02367         /*
02368          * Now scan the values in order, find the most common ones, and also
02369          * accumulate ordering-correlation statistics.
02370          *
02371          * To determine which are most common, we first have to count the
02372          * number of duplicates of each value.  The duplicates are adjacent in
02373          * the sorted list, so a brute-force approach is to compare successive
02374          * datum values until we find two that are not equal. However, that
02375          * requires N-1 invocations of the datum comparison routine, which are
02376          * completely redundant with work that was done during the sort.  (The
02377          * sort algorithm must at some point have compared each pair of items
02378          * that are adjacent in the sorted order; otherwise it could not know
02379          * that it's ordered the pair correctly.) We exploit this by having
02380          * compare_scalars remember the highest tupno index that each
02381          * ScalarItem has been found equal to.  At the end of the sort, a
02382          * ScalarItem's tupnoLink will still point to itself if and only if it
02383          * is the last item of its group of duplicates (since the group will
02384          * be ordered by tupno).
02385          */
02386         corr_xysum = 0;
02387         ndistinct = 0;
02388         nmultiple = 0;
02389         dups_cnt = 0;
02390         for (i = 0; i < values_cnt; i++)
02391         {
02392             int         tupno = values[i].tupno;
02393 
02394             corr_xysum += ((double) i) * ((double) tupno);
02395             dups_cnt++;
02396             if (tupnoLink[tupno] == tupno)
02397             {
02398                 /* Reached end of duplicates of this value */
02399                 ndistinct++;
02400                 if (dups_cnt > 1)
02401                 {
02402                     nmultiple++;
02403                     if (track_cnt < num_mcv ||
02404                         dups_cnt > track[track_cnt - 1].count)
02405                     {
02406                         /*
02407                          * Found a new item for the mcv list; find its
02408                          * position, bubbling down old items if needed. Loop
02409                          * invariant is that j points at an empty/ replaceable
02410                          * slot.
02411                          */
02412                         int         j;
02413 
02414                         if (track_cnt < num_mcv)
02415                             track_cnt++;
02416                         for (j = track_cnt - 1; j > 0; j--)
02417                         {
02418                             if (dups_cnt <= track[j - 1].count)
02419                                 break;
02420                             track[j].count = track[j - 1].count;
02421                             track[j].first = track[j - 1].first;
02422                         }
02423                         track[j].count = dups_cnt;
02424                         track[j].first = i + 1 - dups_cnt;
02425                     }
02426                 }
02427                 dups_cnt = 0;
02428             }
02429         }
02430 
02431         stats->stats_valid = true;
02432         /* Do the simple null-frac and width stats */
02433         stats->stanullfrac = (double) null_cnt / (double) samplerows;
02434         if (is_varwidth)
02435             stats->stawidth = total_width / (double) nonnull_cnt;
02436         else
02437             stats->stawidth = stats->attrtype->typlen;
02438 
02439         if (nmultiple == 0)
02440         {
02441             /* If we found no repeated values, assume it's a unique column */
02442             stats->stadistinct = -1.0;
02443         }
02444         else if (toowide_cnt == 0 && nmultiple == ndistinct)
02445         {
02446             /*
02447              * Every value in the sample appeared more than once.  Assume the
02448              * column has just these values.
02449              */
02450             stats->stadistinct = ndistinct;
02451         }
02452         else
02453         {
02454             /*----------
02455              * Estimate the number of distinct values using the estimator
02456              * proposed by Haas and Stokes in IBM Research Report RJ 10025:
02457              *      n*d / (n - f1 + f1*n/N)
02458              * where f1 is the number of distinct values that occurred
02459              * exactly once in our sample of n rows (from a total of N),
02460              * and d is the total number of distinct values in the sample.
02461              * This is their Duj1 estimator; the other estimators they
02462              * recommend are considerably more complex, and are numerically
02463              * very unstable when n is much smaller than N.
02464              *
02465              * Overwidth values are assumed to have been distinct.
02466              *----------
02467              */
02468             int         f1 = ndistinct - nmultiple + toowide_cnt;
02469             int         d = f1 + nmultiple;
02470             double      numer,
02471                         denom,
02472                         stadistinct;
02473 
02474             numer = (double) samplerows *(double) d;
02475 
02476             denom = (double) (samplerows - f1) +
02477                 (double) f1 *(double) samplerows / totalrows;
02478 
02479             stadistinct = numer / denom;
02480             /* Clamp to sane range in case of roundoff error */
02481             if (stadistinct < (double) d)
02482                 stadistinct = (double) d;
02483             if (stadistinct > totalrows)
02484                 stadistinct = totalrows;
02485             stats->stadistinct = floor(stadistinct + 0.5);
02486         }
02487 
02488         /*
02489          * If we estimated the number of distinct values at more than 10% of
02490          * the total row count (a very arbitrary limit), then assume that
02491          * stadistinct should scale with the row count rather than be a fixed
02492          * value.
02493          */
02494         if (stats->stadistinct > 0.1 * totalrows)
02495             stats->stadistinct = -(stats->stadistinct / totalrows);
02496 
02497         /*
02498          * Decide how many values are worth storing as most-common values. If
02499          * we are able to generate a complete MCV list (all the values in the
02500          * sample will fit, and we think these are all the ones in the table),
02501          * then do so.  Otherwise, store only those values that are
02502          * significantly more common than the (estimated) average. We set the
02503          * threshold rather arbitrarily at 25% more than average, with at
02504          * least 2 instances in the sample.  Also, we won't suppress values
02505          * that have a frequency of at least 1/K where K is the intended
02506          * number of histogram bins; such values might otherwise cause us to
02507          * emit duplicate histogram bin boundaries.  (We might end up with
02508          * duplicate histogram entries anyway, if the distribution is skewed;
02509          * but we prefer to treat such values as MCVs if at all possible.)
02510          */
02511         if (track_cnt == ndistinct && toowide_cnt == 0 &&
02512             stats->stadistinct > 0 &&
02513             track_cnt <= num_mcv)
02514         {
02515             /* Track list includes all values seen, and all will fit */
02516             num_mcv = track_cnt;
02517         }
02518         else
02519         {
02520             double      ndistinct = stats->stadistinct;
02521             double      avgcount,
02522                         mincount,
02523                         maxmincount;
02524 
02525             if (ndistinct < 0)
02526                 ndistinct = -ndistinct * totalrows;
02527             /* estimate # of occurrences in sample of a typical value */
02528             avgcount = (double) samplerows / ndistinct;
02529             /* set minimum threshold count to store a value */
02530             mincount = avgcount * 1.25;
02531             if (mincount < 2)
02532                 mincount = 2;
02533             /* don't let threshold exceed 1/K, however */
02534             maxmincount = (double) samplerows / (double) num_bins;
02535             if (mincount > maxmincount)
02536                 mincount = maxmincount;
02537             if (num_mcv > track_cnt)
02538                 num_mcv = track_cnt;
02539             for (i = 0; i < num_mcv; i++)
02540             {
02541                 if (track[i].count < mincount)
02542                 {
02543                     num_mcv = i;
02544                     break;
02545                 }
02546             }
02547         }
02548 
02549         /* Generate MCV slot entry */
02550         if (num_mcv > 0)
02551         {
02552             MemoryContext old_context;
02553             Datum      *mcv_values;
02554             float4     *mcv_freqs;
02555 
02556             /* Must copy the target values into anl_context */
02557             old_context = MemoryContextSwitchTo(stats->anl_context);
02558             mcv_values = (Datum *) palloc(num_mcv * sizeof(Datum));
02559             mcv_freqs = (float4 *) palloc(num_mcv * sizeof(float4));
02560             for (i = 0; i < num_mcv; i++)
02561             {
02562                 mcv_values[i] = datumCopy(values[track[i].first].value,
02563                                           stats->attrtype->typbyval,
02564                                           stats->attrtype->typlen);
02565                 mcv_freqs[i] = (double) track[i].count / (double) samplerows;
02566             }
02567             MemoryContextSwitchTo(old_context);
02568 
02569             stats->stakind[slot_idx] = STATISTIC_KIND_MCV;
02570             stats->staop[slot_idx] = mystats->eqopr;
02571             stats->stanumbers[slot_idx] = mcv_freqs;
02572             stats->numnumbers[slot_idx] = num_mcv;
02573             stats->stavalues[slot_idx] = mcv_values;
02574             stats->numvalues[slot_idx] = num_mcv;
02575 
02576             /*
02577              * Accept the defaults for stats->statypid and others. They have
02578              * been set before we were called (see vacuum.h)
02579              */
02580             slot_idx++;
02581         }
02582 
02583         /*
02584          * Generate a histogram slot entry if there are at least two distinct
02585          * values not accounted for in the MCV list.  (This ensures the
02586          * histogram won't collapse to empty or a singleton.)
02587          */
02588         num_hist = ndistinct - num_mcv;
02589         if (num_hist > num_bins)
02590             num_hist = num_bins + 1;
02591         if (num_hist >= 2)
02592         {
02593             MemoryContext old_context;
02594             Datum      *hist_values;
02595             int         nvals;
02596             int         pos,
02597                         posfrac,
02598                         delta,
02599                         deltafrac;
02600 
02601             /* Sort the MCV items into position order to speed next loop */
02602             qsort((void *) track, num_mcv,
02603                   sizeof(ScalarMCVItem), compare_mcvs);
02604 
02605             /*
02606              * Collapse out the MCV items from the values[] array.
02607              *
02608              * Note we destroy the values[] array here... but we don't need it
02609              * for anything more.  We do, however, still need values_cnt.
02610              * nvals will be the number of remaining entries in values[].
02611              */
02612             if (num_mcv > 0)
02613             {
02614                 int         src,
02615                             dest;
02616                 int         j;
02617 
02618                 src = dest = 0;
02619                 j = 0;          /* index of next interesting MCV item */
02620                 while (src < values_cnt)
02621                 {
02622                     int         ncopy;
02623 
02624                     if (j < num_mcv)
02625                     {
02626                         int         first = track[j].first;
02627 
02628                         if (src >= first)
02629                         {
02630                             /* advance past this MCV item */
02631                             src = first + track[j].count;
02632                             j++;
02633                             continue;
02634                         }
02635                         ncopy = first - src;
02636                     }
02637                     else
02638                         ncopy = values_cnt - src;
02639                     memmove(&values[dest], &values[src],
02640                             ncopy * sizeof(ScalarItem));
02641                     src += ncopy;
02642                     dest += ncopy;
02643                 }
02644                 nvals = dest;
02645             }
02646             else
02647                 nvals = values_cnt;
02648             Assert(nvals >= num_hist);
02649 
02650             /* Must copy the target values into anl_context */
02651             old_context = MemoryContextSwitchTo(stats->anl_context);
02652             hist_values = (Datum *) palloc(num_hist * sizeof(Datum));
02653 
02654             /*
02655              * The object of this loop is to copy the first and last values[]
02656              * entries along with evenly-spaced values in between.  So the
02657              * i'th value is values[(i * (nvals - 1)) / (num_hist - 1)].  But
02658              * computing that subscript directly risks integer overflow when
02659              * the stats target is more than a couple thousand.  Instead we
02660              * add (nvals - 1) / (num_hist - 1) to pos at each step, tracking
02661              * the integral and fractional parts of the sum separately.
02662              */
02663             delta = (nvals - 1) / (num_hist - 1);
02664             deltafrac = (nvals - 1) % (num_hist - 1);
02665             pos = posfrac = 0;
02666 
02667             for (i = 0; i < num_hist; i++)
02668             {
02669                 hist_values[i] = datumCopy(values[pos].value,
02670                                            stats->attrtype->typbyval,
02671                                            stats->attrtype->typlen);
02672                 pos += delta;
02673                 posfrac += deltafrac;
02674                 if (posfrac >= (num_hist - 1))
02675                 {
02676                     /* fractional part exceeds 1, carry to integer part */
02677                     pos++;
02678                     posfrac -= (num_hist - 1);
02679                 }
02680             }
02681 
02682             MemoryContextSwitchTo(old_context);
02683 
02684             stats->stakind[slot_idx] = STATISTIC_KIND_HISTOGRAM;
02685             stats->staop[slot_idx] = mystats->ltopr;
02686             stats->stavalues[slot_idx] = hist_values;
02687             stats->numvalues[slot_idx] = num_hist;
02688 
02689             /*
02690              * Accept the defaults for stats->statypid and others. They have
02691              * been set before we were called (see vacuum.h)
02692              */
02693             slot_idx++;
02694         }
02695 
02696         /* Generate a correlation entry if there are multiple values */
02697         if (values_cnt > 1)
02698         {
02699             MemoryContext old_context;
02700             float4     *corrs;
02701             double      corr_xsum,
02702                         corr_x2sum;
02703 
02704             /* Must copy the target values into anl_context */
02705             old_context = MemoryContextSwitchTo(stats->anl_context);
02706             corrs = (float4 *) palloc(sizeof(float4));
02707             MemoryContextSwitchTo(old_context);
02708 
02709             /*----------
02710              * Since we know the x and y value sets are both
02711              *      0, 1, ..., values_cnt-1
02712              * we have sum(x) = sum(y) =
02713              *      (values_cnt-1)*values_cnt / 2
02714              * and sum(x^2) = sum(y^2) =
02715              *      (values_cnt-1)*values_cnt*(2*values_cnt-1) / 6.
02716              *----------
02717              */
02718             corr_xsum = ((double) (values_cnt - 1)) *
02719                 ((double) values_cnt) / 2.0;
02720             corr_x2sum = ((double) (values_cnt - 1)) *
02721                 ((double) values_cnt) * (double) (2 * values_cnt - 1) / 6.0;
02722 
02723             /* And the correlation coefficient reduces to */
02724             corrs[0] = (values_cnt * corr_xysum - corr_xsum * corr_xsum) /
02725                 (values_cnt * corr_x2sum - corr_xsum * corr_xsum);
02726 
02727             stats->stakind[slot_idx] = STATISTIC_KIND_CORRELATION;
02728             stats->staop[slot_idx] = mystats->ltopr;
02729             stats->stanumbers[slot_idx] = corrs;
02730             stats->numnumbers[slot_idx] = 1;
02731             slot_idx++;
02732         }
02733     }
02734     else if (nonnull_cnt == 0 && null_cnt > 0)
02735     {
02736         /* We found only nulls; assume the column is entirely null */
02737         stats->stats_valid = true;
02738         stats->stanullfrac = 1.0;
02739         if (is_varwidth)
02740             stats->stawidth = 0;    /* "unknown" */
02741         else
02742             stats->stawidth = stats->attrtype->typlen;
02743         stats->stadistinct = 0.0;       /* "unknown" */
02744     }
02745 
02746     /* We don't need to bother cleaning up any of our temporary palloc's */
02747 }
02748 
02749 /*
02750  * qsort_arg comparator for sorting ScalarItems
02751  *
02752  * Aside from sorting the items, we update the tupnoLink[] array
02753  * whenever two ScalarItems are found to contain equal datums.  The array
02754  * is indexed by tupno; for each ScalarItem, it contains the highest
02755  * tupno that that item's datum has been found to be equal to.  This allows
02756  * us to avoid additional comparisons in compute_scalar_stats().
02757  */
02758 static int
02759 compare_scalars(const void *a, const void *b, void *arg)
02760 {
02761     Datum       da = ((const ScalarItem *) a)->value;
02762     int         ta = ((const ScalarItem *) a)->tupno;
02763     Datum       db = ((const ScalarItem *) b)->value;
02764     int         tb = ((const ScalarItem *) b)->tupno;
02765     CompareScalarsContext *cxt = (CompareScalarsContext *) arg;
02766     int         compare;
02767 
02768     compare = ApplySortComparator(da, false, db, false, cxt->ssup);
02769     if (compare != 0)
02770         return compare;
02771 
02772     /*
02773      * The two datums are equal, so update cxt->tupnoLink[].
02774      */
02775     if (cxt->tupnoLink[ta] < tb)
02776         cxt->tupnoLink[ta] = tb;
02777     if (cxt->tupnoLink[tb] < ta)
02778         cxt->tupnoLink[tb] = ta;
02779 
02780     /*
02781      * For equal datums, sort by tupno
02782      */
02783     return ta - tb;
02784 }
02785 
02786 /*
02787  * qsort comparator for sorting ScalarMCVItems by position
02788  */
02789 static int
02790 compare_mcvs(const void *a, const void *b)
02791 {
02792     int         da = ((const ScalarMCVItem *) a)->first;
02793     int         db = ((const ScalarMCVItem *) b)->first;
02794 
02795     return da - db;
02796 }