]> granicus.if.org Git - postgresql/blob - contrib/pgstattuple/pgstatindex.c
Revert no-op changes to BufferGetPage()
[postgresql] / contrib / pgstattuple / pgstatindex.c
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/heapam.h"
32 #include "access/htup_details.h"
33 #include "access/nbtree.h"
34 #include "catalog/namespace.h"
35 #include "catalog/pg_am.h"
36 #include "funcapi.h"
37 #include "miscadmin.h"
38 #include "storage/bufmgr.h"
39 #include "utils/builtins.h"
40 #include "utils/rel.h"
41
42
43 /*
44  * Because of backward-compatibility issue, we have decided to have
45  * two types of interfaces, with regclass-type input arg and text-type
46  * input arg, for each function.
47  *
48  * Those functions which have text-type input arg will be deprecated
49  * in the future release.
50  */
51 PG_FUNCTION_INFO_V1(pgstatindex);
52 PG_FUNCTION_INFO_V1(pgstatindexbyid);
53 PG_FUNCTION_INFO_V1(pg_relpages);
54 PG_FUNCTION_INFO_V1(pg_relpagesbyid);
55 PG_FUNCTION_INFO_V1(pgstatginindex);
56
57 #define IS_INDEX(r) ((r)->rd_rel->relkind == RELKIND_INDEX)
58 #define IS_BTREE(r) ((r)->rd_rel->relam == BTREE_AM_OID)
59 #define IS_GIN(r) ((r)->rd_rel->relam == GIN_AM_OID)
60
61 #define CHECK_PAGE_OFFSET_RANGE(pg, offnum) { \
62                 if ( !(FirstOffsetNumber <= (offnum) && \
63                                                 (offnum) <= PageGetMaxOffsetNumber(pg)) ) \
64                          elog(ERROR, "page offset number out of range"); }
65
66 /* note: BlockNumber is unsigned, hence can't be negative */
67 #define CHECK_RELATION_BLOCK_RANGE(rel, blkno) { \
68                 if ( RelationGetNumberOfBlocks(rel) <= (BlockNumber) (blkno) ) \
69                          elog(ERROR, "block number out of range"); }
70
71 /* ------------------------------------------------
72  * A structure for a whole btree index statistics
73  * used by pgstatindex().
74  * ------------------------------------------------
75  */
76 typedef struct BTIndexStat
77 {
78         uint32          version;
79         uint32          level;
80         BlockNumber root_blkno;
81
82         uint64          internal_pages;
83         uint64          leaf_pages;
84         uint64          empty_pages;
85         uint64          deleted_pages;
86
87         uint64          max_avail;
88         uint64          free_space;
89
90         uint64          fragments;
91 } BTIndexStat;
92
93 /* ------------------------------------------------
94  * A structure for a whole GIN index statistics
95  * used by pgstatginindex().
96  * ------------------------------------------------
97  */
98 typedef struct GinIndexStat
99 {
100         int32           version;
101
102         BlockNumber pending_pages;
103         int64           pending_tuples;
104 } GinIndexStat;
105
106 static Datum pgstatindex_impl(Relation rel, FunctionCallInfo fcinfo);
107
108 /* ------------------------------------------------------
109  * pgstatindex()
110  *
111  * Usage: SELECT * FROM pgstatindex('t1_pkey');
112  * ------------------------------------------------------
113  */
114 Datum
115 pgstatindex(PG_FUNCTION_ARGS)
116 {
117         text       *relname = PG_GETARG_TEXT_P(0);
118         Relation        rel;
119         RangeVar   *relrv;
120
121         if (!superuser())
122                 ereport(ERROR,
123                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
124                                  (errmsg("must be superuser to use pgstattuple functions"))));
125
126         relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));
127         rel = relation_openrv(relrv, AccessShareLock);
128
129         PG_RETURN_DATUM(pgstatindex_impl(rel, fcinfo));
130 }
131
132 Datum
133 pgstatindexbyid(PG_FUNCTION_ARGS)
134 {
135         Oid                     relid = PG_GETARG_OID(0);
136         Relation        rel;
137
138         if (!superuser())
139                 ereport(ERROR,
140                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
141                                  (errmsg("must be superuser to use pgstattuple functions"))));
142
143         rel = relation_open(relid, AccessShareLock);
144
145         PG_RETURN_DATUM(pgstatindex_impl(rel, fcinfo));
146 }
147
148 static Datum
149 pgstatindex_impl(Relation rel, FunctionCallInfo fcinfo)
150 {
151         Datum           result;
152         BlockNumber nblocks;
153         BlockNumber blkno;
154         BTIndexStat indexStat;
155         BufferAccessStrategy bstrategy = GetAccessStrategy(BAS_BULKREAD);
156
157         if (!IS_INDEX(rel) || !IS_BTREE(rel))
158                 elog(ERROR, "relation \"%s\" is not a btree index",
159                          RelationGetRelationName(rel));
160
161         /*
162          * Reject attempts to read non-local temporary relations; we would be
163          * likely to get wrong data since we have no visibility into the owning
164          * session's local buffers.
165          */
166         if (RELATION_IS_OTHER_TEMP(rel))
167                 ereport(ERROR,
168                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
169                                  errmsg("cannot access temporary tables of other sessions")));
170
171         /*
172          * Read metapage
173          */
174         {
175                 Buffer          buffer = ReadBufferExtended(rel, MAIN_FORKNUM, 0, RBM_NORMAL, bstrategy);
176                 Page            page = BufferGetPage(buffer);
177                 BTMetaPageData *metad = BTPageGetMeta(page);
178
179                 indexStat.version = metad->btm_version;
180                 indexStat.level = metad->btm_level;
181                 indexStat.root_blkno = metad->btm_root;
182
183                 ReleaseBuffer(buffer);
184         }
185
186         /* -- init counters -- */
187         indexStat.internal_pages = 0;
188         indexStat.leaf_pages = 0;
189         indexStat.empty_pages = 0;
190         indexStat.deleted_pages = 0;
191
192         indexStat.max_avail = 0;
193         indexStat.free_space = 0;
194
195         indexStat.fragments = 0;
196
197         /*
198          * Scan all blocks except the metapage
199          */
200         nblocks = RelationGetNumberOfBlocks(rel);
201
202         for (blkno = 1; blkno < nblocks; blkno++)
203         {
204                 Buffer          buffer;
205                 Page            page;
206                 BTPageOpaque opaque;
207
208                 CHECK_FOR_INTERRUPTS();
209
210                 /* Read and lock buffer */
211                 buffer = ReadBufferExtended(rel, MAIN_FORKNUM, blkno, RBM_NORMAL, bstrategy);
212                 LockBuffer(buffer, BUFFER_LOCK_SHARE);
213
214                 page = BufferGetPage(buffer);
215                 opaque = (BTPageOpaque) PageGetSpecialPointer(page);
216
217                 /* Determine page type, and update totals */
218
219                 if (P_ISDELETED(opaque))
220                         indexStat.deleted_pages++;
221                 else if (P_IGNORE(opaque))
222                         indexStat.empty_pages++;        /* this is the "half dead" state */
223                 else if (P_ISLEAF(opaque))
224                 {
225                         int                     max_avail;
226
227                         max_avail = BLCKSZ - (BLCKSZ - ((PageHeader) page)->pd_special + SizeOfPageHeaderData);
228                         indexStat.max_avail += max_avail;
229                         indexStat.free_space += PageGetFreeSpace(page);
230
231                         indexStat.leaf_pages++;
232
233                         /*
234                          * If the next leaf is on an earlier block, it means a
235                          * fragmentation.
236                          */
237                         if (opaque->btpo_next != P_NONE && opaque->btpo_next < blkno)
238                                 indexStat.fragments++;
239                 }
240                 else
241                         indexStat.internal_pages++;
242
243                 /* Unlock and release buffer */
244                 LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
245                 ReleaseBuffer(buffer);
246         }
247
248         relation_close(rel, AccessShareLock);
249
250         /*----------------------------
251          * Build a result tuple
252          *----------------------------
253          */
254         {
255                 TupleDesc       tupleDesc;
256                 int                     j;
257                 char       *values[10];
258                 HeapTuple       tuple;
259
260                 /* Build a tuple descriptor for our result type */
261                 if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
262                         elog(ERROR, "return type must be a row type");
263
264                 j = 0;
265                 values[j++] = psprintf("%d", indexStat.version);
266                 values[j++] = psprintf("%d", indexStat.level);
267                 values[j++] = psprintf(INT64_FORMAT,
268                                                            (1 +         /* include the metapage in index_size */
269                                                                 indexStat.leaf_pages +
270                                                                 indexStat.internal_pages +
271                                                                 indexStat.deleted_pages +
272                                                                 indexStat.empty_pages) * BLCKSZ);
273                 values[j++] = psprintf("%u", indexStat.root_blkno);
274                 values[j++] = psprintf(INT64_FORMAT, indexStat.internal_pages);
275                 values[j++] = psprintf(INT64_FORMAT, indexStat.leaf_pages);
276                 values[j++] = psprintf(INT64_FORMAT, indexStat.empty_pages);
277                 values[j++] = psprintf(INT64_FORMAT, indexStat.deleted_pages);
278                 if (indexStat.max_avail > 0)
279                         values[j++] = psprintf("%.2f",
280                                                                    100.0 - (double) indexStat.free_space / (double) indexStat.max_avail * 100.0);
281                 else
282                         values[j++] = pstrdup("NaN");
283                 if (indexStat.leaf_pages > 0)
284                         values[j++] = psprintf("%.2f",
285                                                                    (double) indexStat.fragments / (double) indexStat.leaf_pages * 100.0);
286                 else
287                         values[j++] = pstrdup("NaN");
288
289                 tuple = BuildTupleFromCStrings(TupleDescGetAttInMetadata(tupleDesc),
290                                                                            values);
291
292                 result = HeapTupleGetDatum(tuple);
293         }
294
295         return result;
296 }
297
298 /* --------------------------------------------------------
299  * pg_relpages()
300  *
301  * Get the number of pages of the table/index.
302  *
303  * Usage: SELECT pg_relpages('t1');
304  *                SELECT pg_relpages('t1_pkey');
305  * --------------------------------------------------------
306  */
307 Datum
308 pg_relpages(PG_FUNCTION_ARGS)
309 {
310         text       *relname = PG_GETARG_TEXT_P(0);
311         int64           relpages;
312         Relation        rel;
313         RangeVar   *relrv;
314
315         if (!superuser())
316                 ereport(ERROR,
317                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
318                                  (errmsg("must be superuser to use pgstattuple functions"))));
319
320         relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));
321         rel = relation_openrv(relrv, AccessShareLock);
322
323         /* note: this will work OK on non-local temp tables */
324
325         relpages = RelationGetNumberOfBlocks(rel);
326
327         relation_close(rel, AccessShareLock);
328
329         PG_RETURN_INT64(relpages);
330 }
331
332 Datum
333 pg_relpagesbyid(PG_FUNCTION_ARGS)
334 {
335         Oid                     relid = PG_GETARG_OID(0);
336         int64           relpages;
337         Relation        rel;
338
339         if (!superuser())
340                 ereport(ERROR,
341                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
342                                  (errmsg("must be superuser to use pgstattuple functions"))));
343
344         rel = relation_open(relid, AccessShareLock);
345
346         /* note: this will work OK on non-local temp tables */
347
348         relpages = RelationGetNumberOfBlocks(rel);
349
350         relation_close(rel, AccessShareLock);
351
352         PG_RETURN_INT64(relpages);
353 }
354
355 /* ------------------------------------------------------
356  * pgstatginindex()
357  *
358  * Usage: SELECT * FROM pgstatginindex('ginindex');
359  * ------------------------------------------------------
360  */
361 Datum
362 pgstatginindex(PG_FUNCTION_ARGS)
363 {
364         Oid                     relid = PG_GETARG_OID(0);
365         Relation        rel;
366         Buffer          buffer;
367         Page            page;
368         GinMetaPageData *metadata;
369         GinIndexStat stats;
370         HeapTuple       tuple;
371         TupleDesc       tupleDesc;
372         Datum           values[3];
373         bool            nulls[3] = {false, false, false};
374         Datum           result;
375
376         if (!superuser())
377                 ereport(ERROR,
378                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
379                                  (errmsg("must be superuser to use pgstattuple functions"))));
380
381         rel = relation_open(relid, AccessShareLock);
382
383         if (!IS_INDEX(rel) || !IS_GIN(rel))
384                 elog(ERROR, "relation \"%s\" is not a GIN index",
385                          RelationGetRelationName(rel));
386
387         /*
388          * Reject attempts to read non-local temporary relations; we would be
389          * likely to get wrong data since we have no visibility into the owning
390          * session's local buffers.
391          */
392         if (RELATION_IS_OTHER_TEMP(rel))
393                 ereport(ERROR,
394                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
395                            errmsg("cannot access temporary indexes of other sessions")));
396
397         /*
398          * Read metapage
399          */
400         buffer = ReadBuffer(rel, GIN_METAPAGE_BLKNO);
401         LockBuffer(buffer, GIN_SHARE);
402         page = BufferGetPage(buffer);
403         metadata = GinPageGetMeta(page);
404
405         stats.version = metadata->ginVersion;
406         stats.pending_pages = metadata->nPendingPages;
407         stats.pending_tuples = metadata->nPendingHeapTuples;
408
409         UnlockReleaseBuffer(buffer);
410         relation_close(rel, AccessShareLock);
411
412         /*
413          * Build a tuple descriptor for our result type
414          */
415         if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
416                 elog(ERROR, "return type must be a row type");
417
418         values[0] = Int32GetDatum(stats.version);
419         values[1] = UInt32GetDatum(stats.pending_pages);
420         values[2] = Int64GetDatum(stats.pending_tuples);
421
422         /*
423          * Build and return the tuple
424          */
425         tuple = heap_form_tuple(tupleDesc, values, nulls);
426         result = HeapTupleGetDatum(tuple);
427
428         PG_RETURN_DATUM(result);
429 }