LCOV - differential code coverage report
Current view: top level - src/backend/commands - analyze.c (source / functions) Coverage Total Hit LBC UBC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 95.7 % 1028 984 44 22 962 23
Current Date: 2026-11-28 16:48:44 +0900 Functions: 100.0 % 21 21 6 15
Baseline: lcov-20261128-baseline Branches: 83.1 % 610 507 2 101 507
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 100.0 % 47 47 47
(30,360] days: 93.7 % 95 89 6 22 67
(360..) days: 95.7 % 886 848 38 848
Function coverage date bins:
(7,30] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 3 3 1 2
(360..) days: 100.0 % 17 17 5 12
Branch coverage date bins:
(7,30] days: 100.0 % 22 22 22
(30,360] days: 75.0 % 68 51 17 51
(360..) days: 83.5 % 520 434 2 84 434

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

Generated by: LCOV version 2.0-1