LCOV - code coverage report
Current view: top level - contrib/pgstattuple - pgstatapprox.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 62.0 % 121 75
Test Date: 2026-11-30 02:16:10 Functions: 85.7 % 7 6
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 36.4 % 55 20

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * pgstatapprox.c
       4                 :             :  *        Bloat estimation functions
       5                 :             :  *
       6                 :             :  * Copyright (c) 2014-2026, PostgreSQL Global Development Group
       7                 :             :  *
       8                 :             :  * IDENTIFICATION
       9                 :             :  *        contrib/pgstattuple/pgstatapprox.c
      10                 :             :  *
      11                 :             :  *-------------------------------------------------------------------------
      12                 :             :  */
      13                 :             : #include "postgres.h"
      14                 :             : 
      15                 :             : #include "access/heapam.h"
      16                 :             : #include "access/htup_details.h"
      17                 :             : #include "access/relation.h"
      18                 :             : #include "access/visibilitymap.h"
      19                 :             : #include "catalog/pg_am_d.h"
      20                 :             : #include "commands/vacuum.h"
      21                 :             : #include "funcapi.h"
      22                 :             : #include "miscadmin.h"
      23                 :             : #include "pgstattuple.h"
      24                 :             : #include "storage/bufmgr.h"
      25                 :             : #include "storage/freespace.h"
      26                 :             : #include "storage/procarray.h"
      27                 :             : #include "storage/read_stream.h"
      28                 :             : 
      29                 :           1 : PG_FUNCTION_INFO_V1(pgstattuple_approx);
      30                 :           2 : PG_FUNCTION_INFO_V1(pgstattuple_approx_v1_5);
      31                 :             : 
      32                 :             : Datum       pgstattuple_approx_internal(Oid relid, FunctionCallInfo fcinfo);
      33                 :             : 
      34                 :             : typedef struct output_type
      35                 :             : {
      36                 :             :     uint64      table_len;
      37                 :             :     double      scanned_percent;
      38                 :             :     uint64      tuple_count;
      39                 :             :     bool        tuple_count_is_unknown;
      40                 :             :     uint64      tuple_len;
      41                 :             :     double      tuple_percent;
      42                 :             :     uint64      dead_tuple_count;
      43                 :             :     uint64      dead_tuple_len;
      44                 :             :     double      dead_tuple_percent;
      45                 :             :     uint64      free_space;
      46                 :             :     double      free_percent;
      47                 :             : } output_type;
      48                 :             : 
      49                 :             : #define NUM_OUTPUT_COLUMNS 10
      50                 :             : 
      51                 :             : /*
      52                 :             :  * Struct for statapprox_heap read stream callback.
      53                 :             :  */
      54                 :             : typedef struct StatApproxReadStreamPrivate
      55                 :             : {
      56                 :             :     Relation    rel;
      57                 :             :     output_type *stat;
      58                 :             :     BlockNumber current_blocknum;
      59                 :             :     BlockNumber nblocks;
      60                 :             :     BlockNumber scanned;        /* count of pages actually read */
      61                 :             :     BlockNumber scanned_new;    /* count of scanned PageIsNew pages */
      62                 :             :     Buffer      vmbuffer;       /* for VM lookups */
      63                 :             : } StatApproxReadStreamPrivate;
      64                 :             : 
      65                 :             : /*
      66                 :             :  * Read stream callback for statapprox_heap.
      67                 :             :  *
      68                 :             :  * This callback checks the visibility map for each block.  If the block is
      69                 :             :  * all-visible, we can get the free space from the FSM without reading the
      70                 :             :  * actual page, and skip to the next block.  Only the blocks that are not
      71                 :             :  * all-visible are returned for actual reading after being locked.
      72                 :             :  */
      73                 :             : static BlockNumber
      74                 :           3 : statapprox_heap_read_stream_next(ReadStream *stream,
      75                 :             :                                  void *callback_private_data,
      76                 :             :                                  void *per_buffer_data)
      77                 :             : {
      78                 :           3 :     StatApproxReadStreamPrivate *p =
      79                 :             :         (StatApproxReadStreamPrivate *) callback_private_data;
      80                 :             : 
      81         [ +  + ]:           4 :     while (p->current_blocknum < p->nblocks)
      82                 :             :     {
      83                 :           1 :         BlockNumber blkno = p->current_blocknum++;
      84                 :             :         Size        freespace;
      85                 :             : 
      86         [ -  + ]:           1 :         CHECK_FOR_INTERRUPTS();
      87                 :             : 
      88                 :             :         /*
      89                 :             :          * If the page has only visible tuples, then we can find out the free
      90                 :             :          * space from the FSM and move on without reading the page.
      91                 :             :          */
      92         [ +  - ]:           1 :         if (VM_ALL_VISIBLE(p->rel, blkno, &p->vmbuffer))
      93                 :             :         {
      94                 :           1 :             freespace = GetRecordedFreeSpace(p->rel, blkno);
      95                 :           1 :             p->stat->tuple_len += BLCKSZ - freespace;
      96                 :           1 :             p->stat->free_space += freespace;
      97                 :           1 :             continue;
      98                 :             :         }
      99                 :             : 
     100                 :             :         /* This block needs to be read */
     101                 :           0 :         p->scanned++;
     102                 :           0 :         return blkno;
     103                 :             :     }
     104                 :             : 
     105                 :           3 :     return InvalidBlockNumber;
     106                 :             : }
     107                 :             : 
     108                 :             : /*
     109                 :             :  * This function takes an already open relation and scans its pages,
     110                 :             :  * skipping those that have the corresponding visibility map bit set.
     111                 :             :  * For pages we skip, we find the free space from the free space map
     112                 :             :  * and approximate tuple_len on that basis. For the others, we count
     113                 :             :  * the exact number of dead tuples etc.
     114                 :             :  *
     115                 :             :  * This scan is loosely based on vacuumlazy.c:lazy_scan_heap(), but
     116                 :             :  * we do not try to avoid skipping single pages.
     117                 :             :  */
     118                 :             : static void
     119                 :           3 : statapprox_heap(Relation rel, output_type *stat)
     120                 :             : {
     121                 :             :     BlockNumber nblocks;
     122                 :             :     BufferAccessStrategy bstrategy;
     123                 :             :     double      estimated_tuple_count;
     124                 :             :     TransactionId OldestXmin;
     125                 :             :     StatApproxReadStreamPrivate p;
     126                 :             :     ReadStream *stream;
     127                 :             : 
     128                 :           3 :     OldestXmin = GetOldestNonRemovableTransactionId(rel);
     129                 :           3 :     bstrategy = GetAccessStrategy(BAS_BULKREAD);
     130                 :             : 
     131                 :           3 :     nblocks = RelationGetNumberOfBlocks(rel);
     132                 :             : 
     133                 :             :     /* Initialize read stream private data */
     134                 :           3 :     p.rel = rel;
     135                 :           3 :     p.stat = stat;
     136                 :           3 :     p.current_blocknum = 0;
     137                 :           3 :     p.nblocks = nblocks;
     138                 :           3 :     p.scanned = 0;
     139                 :           3 :     p.scanned_new = 0;
     140                 :           3 :     p.vmbuffer = InvalidBuffer;
     141                 :             : 
     142                 :             :     /*
     143                 :             :      * Create the read stream. We don't use READ_STREAM_USE_BATCHING because
     144                 :             :      * the callback accesses the visibility map which may need to read VM
     145                 :             :      * pages. While this shouldn't cause deadlocks, we err on the side of
     146                 :             :      * caution.
     147                 :             :      */
     148                 :           3 :     stream = read_stream_begin_relation(READ_STREAM_FULL,
     149                 :             :                                         bstrategy,
     150                 :             :                                         rel,
     151                 :             :                                         MAIN_FORKNUM,
     152                 :             :                                         statapprox_heap_read_stream_next,
     153                 :             :                                         &p,
     154                 :             :                                         0);
     155                 :             : 
     156                 :             :     for (;;)
     157                 :           0 :     {
     158                 :             :         Buffer      buf;
     159                 :             :         Page        page;
     160                 :             :         OffsetNumber offnum,
     161                 :             :                     maxoff;
     162                 :             :         BlockNumber blkno;
     163                 :             : 
     164                 :           3 :         buf = read_stream_next_buffer(stream, NULL);
     165         [ +  - ]:           3 :         if (buf == InvalidBuffer)
     166                 :           3 :             break;
     167                 :             : 
     168                 :           0 :         LockBuffer(buf, BUFFER_LOCK_SHARE);
     169                 :             : 
     170                 :           0 :         page = BufferGetPage(buf);
     171                 :           0 :         blkno = BufferGetBlockNumber(buf);
     172                 :             : 
     173                 :           0 :         stat->free_space += PageGetExactFreeSpace(page);
     174                 :             : 
     175         [ #  # ]:           0 :         if (PageIsNew(page))
     176                 :             :         {
     177                 :           0 :             p.scanned_new++;
     178                 :           0 :             UnlockReleaseBuffer(buf);
     179                 :           0 :             continue;
     180                 :             :         }
     181                 :             : 
     182         [ #  # ]:           0 :         if (PageIsEmpty(page))
     183                 :             :         {
     184                 :           0 :             UnlockReleaseBuffer(buf);
     185                 :           0 :             continue;
     186                 :             :         }
     187                 :             : 
     188                 :             :         /*
     189                 :             :          * Look at each tuple on the page and decide whether it's live or
     190                 :             :          * dead, then count it and its size. Unlike lazy_scan_heap, we can
     191                 :             :          * afford to ignore problems and special cases.
     192                 :             :          */
     193                 :           0 :         maxoff = PageGetMaxOffsetNumber(page);
     194                 :             : 
     195                 :           0 :         for (offnum = FirstOffsetNumber;
     196         [ #  # ]:           0 :              offnum <= maxoff;
     197                 :           0 :              offnum = OffsetNumberNext(offnum))
     198                 :             :         {
     199                 :             :             ItemId      itemid;
     200                 :             :             HeapTupleData tuple;
     201                 :             : 
     202                 :           0 :             itemid = PageGetItemId(page, offnum);
     203                 :             : 
     204   [ #  #  #  # ]:           0 :             if (!ItemIdIsUsed(itemid) || ItemIdIsRedirected(itemid) ||
     205         [ #  # ]:           0 :                 ItemIdIsDead(itemid))
     206                 :             :             {
     207                 :           0 :                 continue;
     208                 :             :             }
     209                 :             : 
     210                 :             :             Assert(ItemIdIsNormal(itemid));
     211                 :             : 
     212                 :           0 :             ItemPointerSet(&(tuple.t_self), blkno, offnum);
     213                 :             : 
     214                 :           0 :             tuple.t_data = (HeapTupleHeader) PageGetItem(page, itemid);
     215                 :           0 :             tuple.t_len = ItemIdGetLength(itemid);
     216                 :           0 :             tuple.t_tableOid = RelationGetRelid(rel);
     217                 :             : 
     218                 :             :             /*
     219                 :             :              * We follow VACUUM's lead in counting INSERT_IN_PROGRESS tuples
     220                 :             :              * as "dead" while DELETE_IN_PROGRESS tuples are "live".  We don't
     221                 :             :              * bother distinguishing tuples inserted/deleted by our own
     222                 :             :              * transaction.
     223                 :             :              */
     224      [ #  #  # ]:           0 :             switch (HeapTupleSatisfiesVacuum(&tuple, OldestXmin, buf))
     225                 :             :             {
     226                 :           0 :                 case HEAPTUPLE_LIVE:
     227                 :             :                 case HEAPTUPLE_DELETE_IN_PROGRESS:
     228                 :           0 :                     stat->tuple_len += tuple.t_len;
     229                 :           0 :                     stat->tuple_count++;
     230                 :           0 :                     break;
     231                 :           0 :                 case HEAPTUPLE_DEAD:
     232                 :             :                 case HEAPTUPLE_RECENTLY_DEAD:
     233                 :             :                 case HEAPTUPLE_INSERT_IN_PROGRESS:
     234                 :           0 :                     stat->dead_tuple_len += tuple.t_len;
     235                 :           0 :                     stat->dead_tuple_count++;
     236                 :           0 :                     break;
     237                 :           0 :                 default:
     238         [ #  # ]:           0 :                     elog(ERROR, "unexpected HeapTupleSatisfiesVacuum result");
     239                 :             :                     break;
     240                 :             :             }
     241                 :             :         }
     242                 :             : 
     243                 :           0 :         UnlockReleaseBuffer(buf);
     244                 :             :     }
     245                 :             : 
     246                 :             :     Assert(p.current_blocknum == nblocks);
     247                 :           3 :     read_stream_end(stream);
     248                 :             : 
     249                 :           3 :     stat->table_len = (uint64) nblocks * BLCKSZ;
     250                 :             : 
     251                 :             :     /*
     252                 :             :      * We don't know how many tuples are in the pages we didn't scan, so
     253                 :             :      * extrapolate the live-tuple count to the whole table in the same way
     254                 :             :      * that VACUUM does.  (Like VACUUM, we're not taking a random sample, so
     255                 :             :      * just extrapolating linearly seems unsafe.)  There should be no dead
     256                 :             :      * tuples in all-visible pages, so no correction is needed for that, and
     257                 :             :      * we already accounted for the space in those pages, too.
     258                 :             :      */
     259                 :           3 :     estimated_tuple_count = vac_estimate_reltuples(rel, nblocks, p.scanned,
     260                 :             :                                                    p.scanned_new,
     261                 :           3 :                                                    stat->tuple_count);
     262                 :             : 
     263         [ +  + ]:           3 :     if (estimated_tuple_count < 0)
     264                 :           1 :         stat->tuple_count_is_unknown = true;
     265                 :             :     else
     266                 :           2 :         stat->tuple_count = estimated_tuple_count;
     267                 :             : 
     268                 :             :     /*
     269                 :             :      * Calculate percentages if the relation has one or more pages.
     270                 :             :      */
     271         [ +  + ]:           3 :     if (nblocks != 0)
     272                 :             :     {
     273                 :             :         /*
     274                 :             :          * Includes PageIsNew blocks that were read but excluded from the
     275                 :             :          * live-tuple estimate.
     276                 :             :          */
     277                 :           1 :         stat->scanned_percent = 100.0 * p.scanned / nblocks;
     278                 :           1 :         stat->tuple_percent = 100.0 * stat->tuple_len / stat->table_len;
     279                 :           1 :         stat->dead_tuple_percent = 100.0 * stat->dead_tuple_len / stat->table_len;
     280                 :           1 :         stat->free_percent = 100.0 * stat->free_space / stat->table_len;
     281                 :             :     }
     282                 :             : 
     283         [ +  + ]:           3 :     if (BufferIsValid(p.vmbuffer))
     284                 :             :     {
     285                 :           1 :         ReleaseBuffer(p.vmbuffer);
     286                 :           1 :         p.vmbuffer = InvalidBuffer;
     287                 :             :     }
     288                 :           3 : }
     289                 :             : 
     290                 :             : /*
     291                 :             :  * Returns estimated live/dead tuple statistics for the given relid.
     292                 :             :  *
     293                 :             :  * The superuser() check here must be kept as the library might be upgraded
     294                 :             :  * without the extension being upgraded, meaning that in pre-1.5 installations
     295                 :             :  * these functions could be called by any user.
     296                 :             :  */
     297                 :             : Datum
     298                 :           0 : pgstattuple_approx(PG_FUNCTION_ARGS)
     299                 :             : {
     300                 :           0 :     Oid         relid = PG_GETARG_OID(0);
     301                 :             : 
     302         [ #  # ]:           0 :     if (!superuser())
     303         [ #  # ]:           0 :         ereport(ERROR,
     304                 :             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     305                 :             :                  errmsg("must be superuser to use pgstattuple functions")));
     306                 :             : 
     307                 :           0 :     PG_RETURN_DATUM(pgstattuple_approx_internal(relid, fcinfo));
     308                 :             : }
     309                 :             : 
     310                 :             : /*
     311                 :             :  * As of pgstattuple version 1.5, we no longer need to check if the user
     312                 :             :  * is a superuser because we REVOKE EXECUTE on the SQL function from PUBLIC.
     313                 :             :  * Users can then grant access to it based on their policies.
     314                 :             :  *
     315                 :             :  * Otherwise identical to pgstattuple_approx (above).
     316                 :             :  */
     317                 :             : Datum
     318                 :           7 : pgstattuple_approx_v1_5(PG_FUNCTION_ARGS)
     319                 :             : {
     320                 :           7 :     Oid         relid = PG_GETARG_OID(0);
     321                 :             : 
     322                 :           7 :     PG_RETURN_DATUM(pgstattuple_approx_internal(relid, fcinfo));
     323                 :             : }
     324                 :             : 
     325                 :             : Datum
     326                 :           7 : pgstattuple_approx_internal(Oid relid, FunctionCallInfo fcinfo)
     327                 :             : {
     328                 :             :     Relation    rel;
     329                 :           7 :     output_type stat = {0};
     330                 :             :     TupleDesc   tupdesc;
     331                 :             :     bool        nulls[NUM_OUTPUT_COLUMNS];
     332                 :             :     Datum       values[NUM_OUTPUT_COLUMNS];
     333                 :             :     HeapTuple   ret;
     334                 :           7 :     int         i = 0;
     335                 :             : 
     336         [ -  + ]:           7 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
     337         [ #  # ]:           0 :         elog(ERROR, "return type must be a row type");
     338                 :             : 
     339         [ -  + ]:           7 :     if (tupdesc->natts != NUM_OUTPUT_COLUMNS)
     340         [ #  # ]:           0 :         elog(ERROR, "incorrect number of output arguments");
     341                 :             : 
     342                 :           7 :     rel = relation_open(relid, AccessShareLock);
     343                 :             : 
     344                 :           7 :     check_relation_supported(rel);
     345                 :             : 
     346                 :             :     /*
     347                 :             :      * We support only relation kinds with a visibility map and a free space
     348                 :             :      * map.
     349                 :             :      */
     350         [ +  + ]:           7 :     if (!(rel->rd_rel->relkind == RELKIND_RELATION ||
     351         [ +  - ]:           5 :           rel->rd_rel->relkind == RELKIND_MATVIEW ||
     352         [ +  + ]:           5 :           rel->rd_rel->relkind == RELKIND_TOASTVALUE))
     353         [ +  - ]:           4 :         ereport(ERROR,
     354                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     355                 :             :                  errmsg("relation \"%s\" is of wrong relation kind",
     356                 :             :                         RelationGetRelationName(rel)),
     357                 :             :                  errdetail_relkind_not_supported(rel->rd_rel->relkind)));
     358                 :             : 
     359         [ -  + ]:           3 :     if (rel->rd_rel->relam != HEAP_TABLE_AM_OID)
     360         [ #  # ]:           0 :         ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     361                 :             :                         errmsg("only heap AM is supported")));
     362                 :             : 
     363                 :           3 :     statapprox_heap(rel, &stat);
     364                 :             : 
     365                 :           3 :     relation_close(rel, AccessShareLock);
     366                 :             : 
     367                 :           3 :     memset(nulls, 0, sizeof(nulls));
     368                 :             : 
     369                 :           3 :     values[i++] = Int64GetDatum(stat.table_len);
     370                 :           3 :     values[i++] = Float8GetDatum(stat.scanned_percent);
     371                 :           3 :     values[i] = Int64GetDatum(stat.tuple_count);
     372                 :           3 :     nulls[i++] = stat.tuple_count_is_unknown;
     373                 :           3 :     values[i++] = Int64GetDatum(stat.tuple_len);
     374                 :           3 :     values[i++] = Float8GetDatum(stat.tuple_percent);
     375                 :           3 :     values[i++] = Int64GetDatum(stat.dead_tuple_count);
     376                 :           3 :     values[i++] = Int64GetDatum(stat.dead_tuple_len);
     377                 :           3 :     values[i++] = Float8GetDatum(stat.dead_tuple_percent);
     378                 :           3 :     values[i++] = Int64GetDatum(stat.free_space);
     379                 :           3 :     values[i++] = Float8GetDatum(stat.free_percent);
     380                 :             : 
     381                 :           3 :     ret = heap_form_tuple(tupdesc, values, nulls);
     382                 :           3 :     return HeapTupleGetDatum(ret);
     383                 :             : }
        

Generated by: LCOV version 2.0-1