LCOV - differential code coverage report
Current view: top level - src/backend/commands - analyze.c (source / functions) Coverage Total Hit UNC LBC UBC GNC CBC EUB ECB DUB DCB
Current: a2387c32f2f8a1643c7d71b951587e6bcb2d4744 vs 371a302eecdc82274b0ae2967d18fd726a0aa6a1 Lines: 95.2 % 995 947 1 47 13 934 1 12
Current Date: 2025-10-26 12:31:50 -0700 Functions: 100.0 % 18 18 3 15 1
Baseline: lcov-20251027-010456-baseline Branches: 82.5 % 584 482 6 1 95 12 470 18 12
Baseline Date: 2025-10-26 11:01:32 +1300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 4 4 4
(30,360] days: 89.3 % 28 25 1 2 9 16
(360..) days: 95.3 % 963 918 45 918
Function coverage date bins:
(30,360] days: 100.0 % 1 1 1
(360..) days: 100.0 % 17 17 2 15
Branch coverage date bins:
(7,30] days: 62.5 % 8 5 3 5
(30,360] days: 71.4 % 14 10 3 1 7 3
(360..) days: 78.9 % 592 467 1 94 467 18 12

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

Generated by: LCOV version 2.4-beta