LCOV - code coverage report
Current view: top level - contrib/pgstattuple - pgstatindex.c (source / functions) Hit Total Coverage
Test: PostgreSQL 12beta2 Lines: 165 243 67.9 %
Date: 2019-06-19 16:07:09 Functions: 21 26 80.8 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :  * contrib/pgstattuple/pgstatindex.c
       3             :  *
       4             :  *
       5             :  * pgstatindex
       6             :  *
       7             :  * Copyright (c) 2006 Satoshi Nagayasu <nagayasus@nttdata.co.jp>
       8             :  *
       9             :  * Permission to use, copy, modify, and distribute this software and
      10             :  * its documentation for any purpose, without fee, and without a
      11             :  * written agreement is hereby granted, provided that the above
      12             :  * copyright notice and this paragraph and the following two
      13             :  * paragraphs appear in all copies.
      14             :  *
      15             :  * IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT,
      16             :  * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
      17             :  * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
      18             :  * DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED
      19             :  * OF THE POSSIBILITY OF SUCH DAMAGE.
      20             :  *
      21             :  * THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
      22             :  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
      23             :  * A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS
      24             :  * IS" BASIS, AND THE AUTHOR HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE,
      25             :  * SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
      26             :  */
      27             : 
      28             : #include "postgres.h"
      29             : 
      30             : #include "access/gin_private.h"
      31             : #include "access/hash.h"
      32             : #include "access/htup_details.h"
      33             : #include "access/nbtree.h"
      34             : #include "access/relation.h"
      35             : #include "access/table.h"
      36             : #include "catalog/namespace.h"
      37             : #include "catalog/pg_am.h"
      38             : #include "funcapi.h"
      39             : #include "miscadmin.h"
      40             : #include "storage/bufmgr.h"
      41             : #include "storage/lmgr.h"
      42             : #include "utils/builtins.h"
      43             : #include "utils/rel.h"
      44             : #include "utils/varlena.h"
      45             : 
      46             : 
      47             : /*
      48             :  * Because of backward-compatibility issue, we have decided to have
      49             :  * two types of interfaces, with regclass-type input arg and text-type
      50             :  * input arg, for each function.
      51             :  *
      52             :  * Those functions which have text-type input arg will be deprecated
      53             :  * in the future release.
      54             :  */
      55           2 : PG_FUNCTION_INFO_V1(pgstatindex);
      56           2 : PG_FUNCTION_INFO_V1(pgstatindexbyid);
      57           2 : PG_FUNCTION_INFO_V1(pg_relpages);
      58           2 : PG_FUNCTION_INFO_V1(pg_relpagesbyid);
      59           2 : PG_FUNCTION_INFO_V1(pgstatginindex);
      60           4 : PG_FUNCTION_INFO_V1(pgstathashindex);
      61             : 
      62           4 : PG_FUNCTION_INFO_V1(pgstatindex_v1_5);
      63           4 : PG_FUNCTION_INFO_V1(pgstatindexbyid_v1_5);
      64           4 : PG_FUNCTION_INFO_V1(pg_relpages_v1_5);
      65           4 : PG_FUNCTION_INFO_V1(pg_relpagesbyid_v1_5);
      66           4 : PG_FUNCTION_INFO_V1(pgstatginindex_v1_5);
      67             : 
      68             : Datum       pgstatginindex_internal(Oid relid, FunctionCallInfo fcinfo);
      69             : 
      70             : #define IS_INDEX(r) ((r)->rd_rel->relkind == RELKIND_INDEX)
      71             : #define IS_BTREE(r) ((r)->rd_rel->relam == BTREE_AM_OID)
      72             : #define IS_GIN(r) ((r)->rd_rel->relam == GIN_AM_OID)
      73             : #define IS_HASH(r) ((r)->rd_rel->relam == HASH_AM_OID)
      74             : 
      75             : /* ------------------------------------------------
      76             :  * A structure for a whole btree index statistics
      77             :  * used by pgstatindex().
      78             :  * ------------------------------------------------
      79             :  */
      80             : typedef struct BTIndexStat
      81             : {
      82             :     uint32      version;
      83             :     uint32      level;
      84             :     BlockNumber root_blkno;
      85             : 
      86             :     uint64      internal_pages;
      87             :     uint64      leaf_pages;
      88             :     uint64      empty_pages;
      89             :     uint64      deleted_pages;
      90             : 
      91             :     uint64      max_avail;
      92             :     uint64      free_space;
      93             : 
      94             :     uint64      fragments;
      95             : } BTIndexStat;
      96             : 
      97             : /* ------------------------------------------------
      98             :  * A structure for a whole GIN index statistics
      99             :  * used by pgstatginindex().
     100             :  * ------------------------------------------------
     101             :  */
     102             : typedef struct GinIndexStat
     103             : {
     104             :     int32       version;
     105             : 
     106             :     BlockNumber pending_pages;
     107             :     int64       pending_tuples;
     108             : } GinIndexStat;
     109             : 
     110             : /* ------------------------------------------------
     111             :  * A structure for a whole HASH index statistics
     112             :  * used by pgstathashindex().
     113             :  * ------------------------------------------------
     114             :  */
     115             : typedef struct HashIndexStat
     116             : {
     117             :     int32       version;
     118             :     int32       space_per_page;
     119             : 
     120             :     BlockNumber bucket_pages;
     121             :     BlockNumber overflow_pages;
     122             :     BlockNumber bitmap_pages;
     123             :     BlockNumber unused_pages;
     124             : 
     125             :     int64       live_items;
     126             :     int64       dead_items;
     127             :     uint64      free_space;
     128             : } HashIndexStat;
     129             : 
     130             : static Datum pgstatindex_impl(Relation rel, FunctionCallInfo fcinfo);
     131             : static void GetHashPageStats(Page page, HashIndexStat *stats);
     132             : static void check_relation_relkind(Relation rel);
     133             : 
     134             : /* ------------------------------------------------------
     135             :  * pgstatindex()
     136             :  *
     137             :  * Usage: SELECT * FROM pgstatindex('t1_pkey');
     138             :  *
     139             :  * The superuser() check here must be kept as the library might be upgraded
     140             :  * without the extension being upgraded, meaning that in pre-1.5 installations
     141             :  * these functions could be called by any user.
     142             :  * ------------------------------------------------------
     143             :  */
     144             : Datum
     145           0 : pgstatindex(PG_FUNCTION_ARGS)
     146             : {
     147           0 :     text       *relname = PG_GETARG_TEXT_PP(0);
     148             :     Relation    rel;
     149             :     RangeVar   *relrv;
     150             : 
     151           0 :     if (!superuser())
     152           0 :         ereport(ERROR,
     153             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     154             :                  (errmsg("must be superuser to use pgstattuple functions"))));
     155             : 
     156           0 :     relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));
     157           0 :     rel = relation_openrv(relrv, AccessShareLock);
     158             : 
     159           0 :     PG_RETURN_DATUM(pgstatindex_impl(rel, fcinfo));
     160             : }
     161             : 
     162             : /*
     163             :  * As of pgstattuple version 1.5, we no longer need to check if the user
     164             :  * is a superuser because we REVOKE EXECUTE on the function from PUBLIC.
     165             :  * Users can then grant access to it based on their policies.
     166             :  *
     167             :  * Otherwise identical to pgstatindex (above).
     168             :  */
     169             : Datum
     170          20 : pgstatindex_v1_5(PG_FUNCTION_ARGS)
     171             : {
     172          20 :     text       *relname = PG_GETARG_TEXT_PP(0);
     173             :     Relation    rel;
     174             :     RangeVar   *relrv;
     175             : 
     176          20 :     relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));
     177          20 :     rel = relation_openrv(relrv, AccessShareLock);
     178             : 
     179          20 :     PG_RETURN_DATUM(pgstatindex_impl(rel, fcinfo));
     180             : }
     181             : 
     182             : /*
     183             :  * The superuser() check here must be kept as the library might be upgraded
     184             :  * without the extension being upgraded, meaning that in pre-1.5 installations
     185             :  * these functions could be called by any user.
     186             :  */
     187             : Datum
     188           0 : pgstatindexbyid(PG_FUNCTION_ARGS)
     189             : {
     190           0 :     Oid         relid = PG_GETARG_OID(0);
     191             :     Relation    rel;
     192             : 
     193           0 :     if (!superuser())
     194           0 :         ereport(ERROR,
     195             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     196             :                  (errmsg("must be superuser to use pgstattuple functions"))));
     197             : 
     198           0 :     rel = relation_open(relid, AccessShareLock);
     199             : 
     200           0 :     PG_RETURN_DATUM(pgstatindex_impl(rel, fcinfo));
     201             : }
     202             : 
     203             : /* No need for superuser checks in v1.5, see above */
     204             : Datum
     205           2 : pgstatindexbyid_v1_5(PG_FUNCTION_ARGS)
     206             : {
     207           2 :     Oid         relid = PG_GETARG_OID(0);
     208             :     Relation    rel;
     209             : 
     210           2 :     rel = relation_open(relid, AccessShareLock);
     211             : 
     212           2 :     PG_RETURN_DATUM(pgstatindex_impl(rel, fcinfo));
     213             : }
     214             : 
     215             : static Datum
     216          22 : pgstatindex_impl(Relation rel, FunctionCallInfo fcinfo)
     217             : {
     218             :     Datum       result;
     219             :     BlockNumber nblocks;
     220             :     BlockNumber blkno;
     221             :     BTIndexStat indexStat;
     222          22 :     BufferAccessStrategy bstrategy = GetAccessStrategy(BAS_BULKREAD);
     223             : 
     224          22 :     if (!IS_INDEX(rel) || !IS_BTREE(rel))
     225          12 :         ereport(ERROR,
     226             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     227             :                  errmsg("relation \"%s\" is not a btree index",
     228             :                         RelationGetRelationName(rel))));
     229             : 
     230             :     /*
     231             :      * Reject attempts to read non-local temporary relations; we would be
     232             :      * likely to get wrong data since we have no visibility into the owning
     233             :      * session's local buffers.
     234             :      */
     235          10 :     if (RELATION_IS_OTHER_TEMP(rel))
     236           0 :         ereport(ERROR,
     237             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     238             :                  errmsg("cannot access temporary tables of other sessions")));
     239             : 
     240             :     /*
     241             :      * Read metapage
     242             :      */
     243             :     {
     244          10 :         Buffer      buffer = ReadBufferExtended(rel, MAIN_FORKNUM, 0, RBM_NORMAL, bstrategy);
     245          10 :         Page        page = BufferGetPage(buffer);
     246          10 :         BTMetaPageData *metad = BTPageGetMeta(page);
     247             : 
     248          10 :         indexStat.version = metad->btm_version;
     249          10 :         indexStat.level = metad->btm_level;
     250          10 :         indexStat.root_blkno = metad->btm_root;
     251             : 
     252          10 :         ReleaseBuffer(buffer);
     253             :     }
     254             : 
     255             :     /* -- init counters -- */
     256          10 :     indexStat.internal_pages = 0;
     257          10 :     indexStat.leaf_pages = 0;
     258          10 :     indexStat.empty_pages = 0;
     259          10 :     indexStat.deleted_pages = 0;
     260             : 
     261          10 :     indexStat.max_avail = 0;
     262          10 :     indexStat.free_space = 0;
     263             : 
     264          10 :     indexStat.fragments = 0;
     265             : 
     266             :     /*
     267             :      * Scan all blocks except the metapage
     268             :      */
     269          10 :     nblocks = RelationGetNumberOfBlocks(rel);
     270             : 
     271          10 :     for (blkno = 1; blkno < nblocks; blkno++)
     272             :     {
     273             :         Buffer      buffer;
     274             :         Page        page;
     275             :         BTPageOpaque opaque;
     276             : 
     277           0 :         CHECK_FOR_INTERRUPTS();
     278             : 
     279             :         /* Read and lock buffer */
     280           0 :         buffer = ReadBufferExtended(rel, MAIN_FORKNUM, blkno, RBM_NORMAL, bstrategy);
     281           0 :         LockBuffer(buffer, BUFFER_LOCK_SHARE);
     282             : 
     283           0 :         page = BufferGetPage(buffer);
     284           0 :         opaque = (BTPageOpaque) PageGetSpecialPointer(page);
     285             : 
     286             :         /* Determine page type, and update totals */
     287             : 
     288           0 :         if (P_ISDELETED(opaque))
     289           0 :             indexStat.deleted_pages++;
     290           0 :         else if (P_IGNORE(opaque))
     291           0 :             indexStat.empty_pages++;    /* this is the "half dead" state */
     292           0 :         else if (P_ISLEAF(opaque))
     293             :         {
     294             :             int         max_avail;
     295             : 
     296           0 :             max_avail = BLCKSZ - (BLCKSZ - ((PageHeader) page)->pd_special + SizeOfPageHeaderData);
     297           0 :             indexStat.max_avail += max_avail;
     298           0 :             indexStat.free_space += PageGetFreeSpace(page);
     299             : 
     300           0 :             indexStat.leaf_pages++;
     301             : 
     302             :             /*
     303             :              * If the next leaf is on an earlier block, it means a
     304             :              * fragmentation.
     305             :              */
     306           0 :             if (opaque->btpo_next != P_NONE && opaque->btpo_next < blkno)
     307           0 :                 indexStat.fragments++;
     308             :         }
     309             :         else
     310           0 :             indexStat.internal_pages++;
     311             : 
     312             :         /* Unlock and release buffer */
     313           0 :         LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
     314           0 :         ReleaseBuffer(buffer);
     315             :     }
     316             : 
     317          10 :     relation_close(rel, AccessShareLock);
     318             : 
     319             :     /*----------------------------
     320             :      * Build a result tuple
     321             :      *----------------------------
     322             :      */
     323             :     {
     324             :         TupleDesc   tupleDesc;
     325             :         int         j;
     326             :         char       *values[10];
     327             :         HeapTuple   tuple;
     328             : 
     329             :         /* Build a tuple descriptor for our result type */
     330          10 :         if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
     331           0 :             elog(ERROR, "return type must be a row type");
     332             : 
     333          10 :         j = 0;
     334          10 :         values[j++] = psprintf("%d", indexStat.version);
     335          10 :         values[j++] = psprintf("%d", indexStat.level);
     336          20 :         values[j++] = psprintf(INT64_FORMAT,
     337             :                                (1 + /* include the metapage in index_size */
     338          20 :                                 indexStat.leaf_pages +
     339          20 :                                 indexStat.internal_pages +
     340          20 :                                 indexStat.deleted_pages +
     341          10 :                                 indexStat.empty_pages) * BLCKSZ);
     342          10 :         values[j++] = psprintf("%u", indexStat.root_blkno);
     343          10 :         values[j++] = psprintf(INT64_FORMAT, indexStat.internal_pages);
     344          10 :         values[j++] = psprintf(INT64_FORMAT, indexStat.leaf_pages);
     345          10 :         values[j++] = psprintf(INT64_FORMAT, indexStat.empty_pages);
     346          10 :         values[j++] = psprintf(INT64_FORMAT, indexStat.deleted_pages);
     347          10 :         if (indexStat.max_avail > 0)
     348           0 :             values[j++] = psprintf("%.2f",
     349           0 :                                    100.0 - (double) indexStat.free_space / (double) indexStat.max_avail * 100.0);
     350             :         else
     351          10 :             values[j++] = pstrdup("NaN");
     352          10 :         if (indexStat.leaf_pages > 0)
     353           0 :             values[j++] = psprintf("%.2f",
     354           0 :                                    (double) indexStat.fragments / (double) indexStat.leaf_pages * 100.0);
     355             :         else
     356          10 :             values[j++] = pstrdup("NaN");
     357             : 
     358          10 :         tuple = BuildTupleFromCStrings(TupleDescGetAttInMetadata(tupleDesc),
     359             :                                        values);
     360             : 
     361          10 :         result = HeapTupleGetDatum(tuple);
     362             :     }
     363             : 
     364          10 :     return result;
     365             : }
     366             : 
     367             : /* --------------------------------------------------------
     368             :  * pg_relpages()
     369             :  *
     370             :  * Get the number of pages of the table/index.
     371             :  *
     372             :  * Usage: SELECT pg_relpages('t1');
     373             :  *        SELECT pg_relpages('t1_pkey');
     374             :  *
     375             :  * Must keep superuser() check, see above.
     376             :  * --------------------------------------------------------
     377             :  */
     378             : Datum
     379           0 : pg_relpages(PG_FUNCTION_ARGS)
     380             : {
     381           0 :     text       *relname = PG_GETARG_TEXT_PP(0);
     382             :     int64       relpages;
     383             :     Relation    rel;
     384             :     RangeVar   *relrv;
     385             : 
     386           0 :     if (!superuser())
     387           0 :         ereport(ERROR,
     388             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     389             :                  (errmsg("must be superuser to use pgstattuple functions"))));
     390             : 
     391           0 :     relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));
     392           0 :     rel = relation_openrv(relrv, AccessShareLock);
     393             : 
     394             :     /* only some relkinds have storage */
     395           0 :     check_relation_relkind(rel);
     396             : 
     397             :     /* note: this will work OK on non-local temp tables */
     398             : 
     399           0 :     relpages = RelationGetNumberOfBlocks(rel);
     400             : 
     401           0 :     relation_close(rel, AccessShareLock);
     402             : 
     403           0 :     PG_RETURN_INT64(relpages);
     404             : }
     405             : 
     406             : /* No need for superuser checks in v1.5, see above */
     407             : Datum
     408          18 : pg_relpages_v1_5(PG_FUNCTION_ARGS)
     409             : {
     410          18 :     text       *relname = PG_GETARG_TEXT_PP(0);
     411             :     int64       relpages;
     412             :     Relation    rel;
     413             :     RangeVar   *relrv;
     414             : 
     415          18 :     relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));
     416          18 :     rel = relation_openrv(relrv, AccessShareLock);
     417             : 
     418             :     /* only some relkinds have storage */
     419          18 :     check_relation_relkind(rel);
     420             : 
     421             :     /* note: this will work OK on non-local temp tables */
     422             : 
     423          12 :     relpages = RelationGetNumberOfBlocks(rel);
     424             : 
     425          12 :     relation_close(rel, AccessShareLock);
     426             : 
     427          12 :     PG_RETURN_INT64(relpages);
     428             : }
     429             : 
     430             : /* Must keep superuser() check, see above. */
     431             : Datum
     432           0 : pg_relpagesbyid(PG_FUNCTION_ARGS)
     433             : {
     434           0 :     Oid         relid = PG_GETARG_OID(0);
     435             :     int64       relpages;
     436             :     Relation    rel;
     437             : 
     438           0 :     if (!superuser())
     439           0 :         ereport(ERROR,
     440             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     441             :                  (errmsg("must be superuser to use pgstattuple functions"))));
     442             : 
     443           0 :     rel = relation_open(relid, AccessShareLock);
     444             : 
     445             :     /* only some relkinds have storage */
     446           0 :     check_relation_relkind(rel);
     447             : 
     448             :     /* note: this will work OK on non-local temp tables */
     449             : 
     450           0 :     relpages = RelationGetNumberOfBlocks(rel);
     451             : 
     452           0 :     relation_close(rel, AccessShareLock);
     453             : 
     454           0 :     PG_RETURN_INT64(relpages);
     455             : }
     456             : 
     457             : /* No need for superuser checks in v1.5, see above */
     458             : Datum
     459           4 : pg_relpagesbyid_v1_5(PG_FUNCTION_ARGS)
     460             : {
     461           4 :     Oid         relid = PG_GETARG_OID(0);
     462             :     int64       relpages;
     463             :     Relation    rel;
     464             : 
     465           4 :     rel = relation_open(relid, AccessShareLock);
     466             : 
     467             :     /* only some relkinds have storage */
     468           4 :     check_relation_relkind(rel);
     469             : 
     470             :     /* note: this will work OK on non-local temp tables */
     471             : 
     472           4 :     relpages = RelationGetNumberOfBlocks(rel);
     473             : 
     474           4 :     relation_close(rel, AccessShareLock);
     475             : 
     476           4 :     PG_RETURN_INT64(relpages);
     477             : }
     478             : 
     479             : /* ------------------------------------------------------
     480             :  * pgstatginindex()
     481             :  *
     482             :  * Usage: SELECT * FROM pgstatginindex('ginindex');
     483             :  *
     484             :  * Must keep superuser() check, see above.
     485             :  * ------------------------------------------------------
     486             :  */
     487             : Datum
     488           0 : pgstatginindex(PG_FUNCTION_ARGS)
     489             : {
     490           0 :     Oid         relid = PG_GETARG_OID(0);
     491             : 
     492           0 :     if (!superuser())
     493           0 :         ereport(ERROR,
     494             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     495             :                  (errmsg("must be superuser to use pgstattuple functions"))));
     496             : 
     497           0 :     PG_RETURN_DATUM(pgstatginindex_internal(relid, fcinfo));
     498             : }
     499             : 
     500             : /* No need for superuser checks in v1.5, see above */
     501             : Datum
     502          14 : pgstatginindex_v1_5(PG_FUNCTION_ARGS)
     503             : {
     504          14 :     Oid         relid = PG_GETARG_OID(0);
     505             : 
     506          14 :     PG_RETURN_DATUM(pgstatginindex_internal(relid, fcinfo));
     507             : }
     508             : 
     509             : Datum
     510          14 : pgstatginindex_internal(Oid relid, FunctionCallInfo fcinfo)
     511             : {
     512             :     Relation    rel;
     513             :     Buffer      buffer;
     514             :     Page        page;
     515             :     GinMetaPageData *metadata;
     516             :     GinIndexStat stats;
     517             :     HeapTuple   tuple;
     518             :     TupleDesc   tupleDesc;
     519             :     Datum       values[3];
     520          14 :     bool        nulls[3] = {false, false, false};
     521             :     Datum       result;
     522             : 
     523          14 :     rel = relation_open(relid, AccessShareLock);
     524             : 
     525          14 :     if (!IS_INDEX(rel) || !IS_GIN(rel))
     526          12 :         ereport(ERROR,
     527             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     528             :                  errmsg("relation \"%s\" is not a GIN index",
     529             :                         RelationGetRelationName(rel))));
     530             : 
     531             :     /*
     532             :      * Reject attempts to read non-local temporary relations; we would be
     533             :      * likely to get wrong data since we have no visibility into the owning
     534             :      * session's local buffers.
     535             :      */
     536           2 :     if (RELATION_IS_OTHER_TEMP(rel))
     537           0 :         ereport(ERROR,
     538             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     539             :                  errmsg("cannot access temporary indexes of other sessions")));
     540             : 
     541             :     /*
     542             :      * Read metapage
     543             :      */
     544           2 :     buffer = ReadBuffer(rel, GIN_METAPAGE_BLKNO);
     545           2 :     LockBuffer(buffer, GIN_SHARE);
     546           2 :     page = BufferGetPage(buffer);
     547           2 :     metadata = GinPageGetMeta(page);
     548             : 
     549           2 :     stats.version = metadata->ginVersion;
     550           2 :     stats.pending_pages = metadata->nPendingPages;
     551           2 :     stats.pending_tuples = metadata->nPendingHeapTuples;
     552             : 
     553           2 :     UnlockReleaseBuffer(buffer);
     554           2 :     relation_close(rel, AccessShareLock);
     555             : 
     556             :     /*
     557             :      * Build a tuple descriptor for our result type
     558             :      */
     559           2 :     if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
     560           0 :         elog(ERROR, "return type must be a row type");
     561             : 
     562           2 :     values[0] = Int32GetDatum(stats.version);
     563           2 :     values[1] = UInt32GetDatum(stats.pending_pages);
     564           2 :     values[2] = Int64GetDatum(stats.pending_tuples);
     565             : 
     566             :     /*
     567             :      * Build and return the tuple
     568             :      */
     569           2 :     tuple = heap_form_tuple(tupleDesc, values, nulls);
     570           2 :     result = HeapTupleGetDatum(tuple);
     571             : 
     572           2 :     return result;
     573             : }
     574             : 
     575             : /* ------------------------------------------------------
     576             :  * pgstathashindex()
     577             :  *
     578             :  * Usage: SELECT * FROM pgstathashindex('hashindex');
     579             :  * ------------------------------------------------------
     580             :  */
     581             : Datum
     582          16 : pgstathashindex(PG_FUNCTION_ARGS)
     583             : {
     584          16 :     Oid         relid = PG_GETARG_OID(0);
     585             :     BlockNumber nblocks;
     586             :     BlockNumber blkno;
     587             :     Relation    rel;
     588             :     HashIndexStat stats;
     589             :     BufferAccessStrategy bstrategy;
     590             :     HeapTuple   tuple;
     591             :     TupleDesc   tupleDesc;
     592             :     Datum       values[8];
     593             :     bool        nulls[8];
     594             :     Buffer      metabuf;
     595             :     HashMetaPage metap;
     596             :     float8      free_percent;
     597             :     uint64      total_space;
     598             : 
     599          16 :     rel = index_open(relid, AccessShareLock);
     600             : 
     601             :     /* index_open() checks that it's an index */
     602           8 :     if (!IS_HASH(rel))
     603           4 :         ereport(ERROR,
     604             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     605             :                  errmsg("relation \"%s\" is not a hash index",
     606             :                         RelationGetRelationName(rel))));
     607             : 
     608             :     /*
     609             :      * Reject attempts to read non-local temporary relations; we would be
     610             :      * likely to get wrong data since we have no visibility into the owning
     611             :      * session's local buffers.
     612             :      */
     613           4 :     if (RELATION_IS_OTHER_TEMP(rel))
     614           0 :         ereport(ERROR,
     615             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     616             :                  errmsg("cannot access temporary indexes of other sessions")));
     617             : 
     618             :     /* Get the information we need from the metapage. */
     619           4 :     memset(&stats, 0, sizeof(stats));
     620           4 :     metabuf = _hash_getbuf(rel, HASH_METAPAGE, HASH_READ, LH_META_PAGE);
     621           4 :     metap = HashPageGetMeta(BufferGetPage(metabuf));
     622           4 :     stats.version = metap->hashm_version;
     623           4 :     stats.space_per_page = metap->hashm_bsize;
     624           4 :     _hash_relbuf(rel, metabuf);
     625             : 
     626             :     /* Get the current relation length */
     627           4 :     nblocks = RelationGetNumberOfBlocks(rel);
     628             : 
     629             :     /* prepare access strategy for this index */
     630           4 :     bstrategy = GetAccessStrategy(BAS_BULKREAD);
     631             : 
     632             :     /* Start from blkno 1 as 0th block is metapage */
     633          32 :     for (blkno = 1; blkno < nblocks; blkno++)
     634             :     {
     635             :         Buffer      buf;
     636             :         Page        page;
     637             : 
     638          28 :         CHECK_FOR_INTERRUPTS();
     639             : 
     640          28 :         buf = ReadBufferExtended(rel, MAIN_FORKNUM, blkno, RBM_NORMAL,
     641             :                                  bstrategy);
     642          28 :         LockBuffer(buf, BUFFER_LOCK_SHARE);
     643          28 :         page = (Page) BufferGetPage(buf);
     644             : 
     645          28 :         if (PageIsNew(page))
     646           0 :             stats.unused_pages++;
     647          28 :         else if (PageGetSpecialSize(page) !=
     648             :                  MAXALIGN(sizeof(HashPageOpaqueData)))
     649           0 :             ereport(ERROR,
     650             :                     (errcode(ERRCODE_INDEX_CORRUPTED),
     651             :                      errmsg("index \"%s\" contains corrupted page at block %u",
     652             :                             RelationGetRelationName(rel),
     653             :                             BufferGetBlockNumber(buf))));
     654             :         else
     655             :         {
     656             :             HashPageOpaque opaque;
     657             :             int         pagetype;
     658             : 
     659          28 :             opaque = (HashPageOpaque) PageGetSpecialPointer(page);
     660          28 :             pagetype = opaque->hasho_flag & LH_PAGE_TYPE;
     661             : 
     662          28 :             if (pagetype == LH_BUCKET_PAGE)
     663             :             {
     664          24 :                 stats.bucket_pages++;
     665          24 :                 GetHashPageStats(page, &stats);
     666             :             }
     667           4 :             else if (pagetype == LH_OVERFLOW_PAGE)
     668             :             {
     669           0 :                 stats.overflow_pages++;
     670           0 :                 GetHashPageStats(page, &stats);
     671             :             }
     672           4 :             else if (pagetype == LH_BITMAP_PAGE)
     673           4 :                 stats.bitmap_pages++;
     674           0 :             else if (pagetype == LH_UNUSED_PAGE)
     675           0 :                 stats.unused_pages++;
     676             :             else
     677           0 :                 ereport(ERROR,
     678             :                         (errcode(ERRCODE_INDEX_CORRUPTED),
     679             :                          errmsg("unexpected page type 0x%04X in HASH index \"%s\" block %u",
     680             :                                 opaque->hasho_flag, RelationGetRelationName(rel),
     681             :                                 BufferGetBlockNumber(buf))));
     682             :         }
     683          28 :         UnlockReleaseBuffer(buf);
     684             :     }
     685             : 
     686             :     /* Done accessing the index */
     687           4 :     index_close(rel, AccessShareLock);
     688             : 
     689             :     /* Count unused pages as free space. */
     690           4 :     stats.free_space += (uint64) stats.unused_pages * stats.space_per_page;
     691             : 
     692             :     /*
     693             :      * Total space available for tuples excludes the metapage and the bitmap
     694             :      * pages.
     695             :      */
     696           8 :     total_space = (uint64) (nblocks - (stats.bitmap_pages + 1)) *
     697           4 :         stats.space_per_page;
     698             : 
     699           4 :     if (total_space == 0)
     700           0 :         free_percent = 0.0;
     701             :     else
     702           4 :         free_percent = 100.0 * stats.free_space / total_space;
     703             : 
     704             :     /*
     705             :      * Build a tuple descriptor for our result type
     706             :      */
     707           4 :     if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
     708           0 :         elog(ERROR, "return type must be a row type");
     709             : 
     710           4 :     tupleDesc = BlessTupleDesc(tupleDesc);
     711             : 
     712             :     /*
     713             :      * Build and return the tuple
     714             :      */
     715           4 :     MemSet(nulls, 0, sizeof(nulls));
     716           4 :     values[0] = Int32GetDatum(stats.version);
     717           4 :     values[1] = Int64GetDatum((int64) stats.bucket_pages);
     718           4 :     values[2] = Int64GetDatum((int64) stats.overflow_pages);
     719           4 :     values[3] = Int64GetDatum((int64) stats.bitmap_pages);
     720           4 :     values[4] = Int64GetDatum((int64) stats.unused_pages);
     721           4 :     values[5] = Int64GetDatum(stats.live_items);
     722           4 :     values[6] = Int64GetDatum(stats.dead_items);
     723           4 :     values[7] = Float8GetDatum(free_percent);
     724           4 :     tuple = heap_form_tuple(tupleDesc, values, nulls);
     725             : 
     726           4 :     PG_RETURN_DATUM(HeapTupleGetDatum(tuple));
     727             : }
     728             : 
     729             : /* -------------------------------------------------
     730             :  * GetHashPageStatis()
     731             :  *
     732             :  * Collect statistics of single hash page
     733             :  * -------------------------------------------------
     734             :  */
     735             : static void
     736          24 : GetHashPageStats(Page page, HashIndexStat *stats)
     737             : {
     738          24 :     OffsetNumber maxoff = PageGetMaxOffsetNumber(page);
     739             :     int         off;
     740             : 
     741             :     /* count live and dead tuples, and free space */
     742          24 :     for (off = FirstOffsetNumber; off <= maxoff; off++)
     743             :     {
     744           0 :         ItemId      id = PageGetItemId(page, off);
     745             : 
     746           0 :         if (!ItemIdIsDead(id))
     747           0 :             stats->live_items++;
     748             :         else
     749           0 :             stats->dead_items++;
     750             :     }
     751          24 :     stats->free_space += PageGetExactFreeSpace(page);
     752          24 : }
     753             : 
     754             : /*
     755             :  * check_relation_relkind - convenience routine to check that relation
     756             :  * is of the relkind supported by the callers
     757             :  */
     758             : static void
     759          22 : check_relation_relkind(Relation rel)
     760             : {
     761          40 :     if (rel->rd_rel->relkind != RELKIND_RELATION &&
     762          24 :         rel->rd_rel->relkind != RELKIND_INDEX &&
     763          12 :         rel->rd_rel->relkind != RELKIND_MATVIEW &&
     764          12 :         rel->rd_rel->relkind != RELKIND_SEQUENCE &&
     765           6 :         rel->rd_rel->relkind != RELKIND_TOASTVALUE)
     766           6 :         ereport(ERROR,
     767             :                 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
     768             :                  errmsg("\"%s\" is not a table, index, materialized view, sequence, or TOAST table",
     769             :                         RelationGetRelationName(rel))));
     770          16 : }

Generated by: LCOV version 1.13