PostgreSQL Source Code git master
Data Structures | Macros | Typedefs | Functions
btreefuncs.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/nbtree.h"
#include "access/relation.h"
#include "catalog/namespace.h"
#include "catalog/pg_am.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "pageinspect.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/rel.h"
#include "utils/varlena.h"
Include dependency graph for btreefuncs.c:

Go to the source code of this file.

Data Structures

struct   BTPageStat
 
struct   ua_page_stats
 
struct   ua_page_items
 

Macros

#define  IS_INDEX(r)   ((r)->rd_rel->relkind == RELKIND_INDEX)
 
#define  IS_BTREE(r)   ((r)->rd_rel->relam == BTREE_AM_OID)
 
#define  BT_METAP_COLS_V1_8   9
 

Typedefs

typedef struct BTPageStat  BTPageStat
 
typedef struct ua_page_stats  ua_page_stats
 
typedef struct ua_page_items  ua_page_items
 

Functions

 
 
 
 
 
 
 
static void  GetBTPageStatistics (BlockNumber blkno, Buffer buffer, BTPageStat *stat)
 
static void  check_relation_block_range (Relation rel, int64 blkno)
 
static void  bt_index_block_validate (Relation rel, int64 blkno)
 
 
 
 
 
 
 
 
 
 
 

Macro Definition Documentation

BT_METAP_COLS_V1_8

#define BT_METAP_COLS_V1_8   9

Definition at line 828 of file btreefuncs.c.

IS_BTREE

#define IS_BTREE (   r )    ((r)->rd_rel->relam == BTREE_AM_OID)

Definition at line 53 of file btreefuncs.c.

IS_INDEX

#define IS_INDEX (   r )    ((r)->rd_rel->relkind == RELKIND_INDEX)

Definition at line 52 of file btreefuncs.c.

Typedef Documentation

BTPageStat

typedef struct BTPageStat BTPageStat

ua_page_items

typedef struct ua_page_items ua_page_items

ua_page_stats

typedef struct ua_page_stats ua_page_stats

Function Documentation

bt_index_block_validate()

static void bt_index_block_validate ( Relation  rel,
int64  blkno 
)
static

Definition at line 226 of file btreefuncs.c.

227{
228 if (!IS_INDEX(rel) || !IS_BTREE(rel))
230 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
231 errmsg("\"%s\" is not a %s index",
232 RelationGetRelationName(rel), "btree")));
233
234 /*
235 * Reject attempts to read non-local temporary relations; we would be
236 * likely to get wrong data since we have no visibility into the owning
237 * session's local buffers.
238 */
239 if (RELATION_IS_OTHER_TEMP(rel))
241 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
242 errmsg("cannot access temporary tables of other sessions")));
243
244 if (blkno == 0)
246 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
247 errmsg("block 0 is a meta page")));
248
249 check_relation_block_range(rel, blkno);
250}
#define IS_BTREE(r)
Definition: btreefuncs.c:53
static void check_relation_block_range(Relation rel, int64 blkno)
Definition: btreefuncs.c:204
#define IS_INDEX(r)
Definition: btreefuncs.c:52
int errcode(int sqlerrcode)
Definition: elog.c:854
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:150
#define RelationGetRelationName(relation)
Definition: rel.h:548
#define RELATION_IS_OTHER_TEMP(relation)
Definition: rel.h:667

References check_relation_block_range(), ereport, errcode(), errmsg(), ERROR, IS_BTREE, IS_INDEX, RELATION_IS_OTHER_TEMP, and RelationGetRelationName.

Referenced by bt_multi_page_stats(), bt_page_items_internal(), and bt_page_stats_internal().

bt_metap()

Datum bt_metap ( PG_FUNCTION_ARGS  )

Definition at line 839 of file btreefuncs.c.

840{
842 Datum result;
843 Relation rel;
844 RangeVar *relrv;
845 BTMetaPageData *metad;
846 TupleDesc tupleDesc;
847 int j;
848 char *values[9];
849 Buffer buffer;
850 Page page;
851 HeapTuple tuple;
852
853 if (!superuser())
855 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
856 errmsg("must be superuser to use pageinspect functions")));
857
859 rel = relation_openrv(relrv, AccessShareLock);
860
861 if (!IS_INDEX(rel) || !IS_BTREE(rel))
863 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
864 errmsg("\"%s\" is not a %s index",
865 RelationGetRelationName(rel), "btree")));
866
867 /*
868 * Reject attempts to read non-local temporary relations; we would be
869 * likely to get wrong data since we have no visibility into the owning
870 * session's local buffers.
871 */
872 if (RELATION_IS_OTHER_TEMP(rel))
874 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
875 errmsg("cannot access temporary tables of other sessions")));
876
877 buffer = ReadBuffer(rel, 0);
879
880 page = BufferGetPage(buffer);
881 metad = BTPageGetMeta(page);
882
883 /* Build a tuple descriptor for our result type */
884 if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
885 elog(ERROR, "return type must be a row type");
886
887 /*
888 * We need a kluge here to detect API versions prior to 1.8. Earlier
889 * versions incorrectly used int4 for certain columns.
890 *
891 * There is no way to reliably avoid the problems created by the old
892 * function definition at this point, so insist that the user update the
893 * extension.
894 */
895 if (tupleDesc->natts < BT_METAP_COLS_V1_8)
897 (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
898 errmsg("function has wrong number of declared columns"),
899 errhint("To resolve the problem, update the \"pageinspect\" extension to the latest version.")));
900
901 j = 0;
902 values[j++] = psprintf("%d", metad->btm_magic);
903 values[j++] = psprintf("%d", metad->btm_version);
904 values[j++] = psprintf(INT64_FORMAT, (int64) metad->btm_root);
908
909 /*
910 * Get values of extended metadata if available, use default values
911 * otherwise. Note that we rely on the assumption that btm_allequalimage
912 * is initialized to zero with indexes that were built on versions prior
913 * to Postgres 13 (just like _bt_metaversion()).
914 */
915 if (metad->btm_version >= BTREE_NOVAC_VERSION)
916 {
920 values[j++] = metad->btm_allequalimage ? "t" : "f";
921 }
922 else
923 {
924 values[j++] = "0";
925 values[j++] = "-1";
926 values[j++] = "f";
927 }
928
930 values);
931
932 result = HeapTupleGetDatum(tuple);
933
934 UnlockReleaseBuffer(buffer);
936
937 PG_RETURN_DATUM(result);
938}
static Datum values[MAXATTR]
Definition: bootstrap.c:153
#define BT_METAP_COLS_V1_8
Definition: btreefuncs.c:828
int Buffer
Definition: buf.h:23
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:5355
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:5572
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:758
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:197
static Page BufferGetPage(Buffer buffer)
Definition: bufmgr.h:417
PageData * Page
Definition: bufpage.h:82
#define INT64_FORMAT
Definition: c.h:556
int64_t int64
Definition: c.h:535
int errhint(const char *fmt,...)
Definition: elog.c:1321
#define elog(elevel,...)
Definition: elog.h:226
HeapTuple BuildTupleFromCStrings(AttInMetadata *attinmeta, char **values)
Definition: execTuples.c:2324
AttInMetadata * TupleDescGetAttInMetadata(TupleDesc tupdesc)
Definition: execTuples.c:2275
#define PG_GETARG_TEXT_PP(n)
Definition: fmgr.h:309
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:276
@ TYPEFUNC_COMPOSITE
Definition: funcapi.h:149
static Datum HeapTupleGetDatum(const HeapTupleData *tuple)
Definition: funcapi.h:230
j
int j
Definition: isn.c:78
#define AccessShareLock
Definition: lockdefs.h:36
RangeVar * makeRangeVarFromNameList(const List *names)
Definition: namespace.c:3624
#define BTPageGetMeta(p)
Definition: nbtree.h:122
#define BTREE_NOVAC_VERSION
Definition: nbtree.h:153
NameData relname
Definition: pg_class.h:38
uint64_t Datum
Definition: postgres.h:70
char * psprintf(const char *fmt,...)
Definition: psprintf.c:43
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: relation.c:137
uint32 btm_last_cleanup_num_delpages
Definition: nbtree.h:115
uint32 btm_level
Definition: nbtree.h:109
float8 btm_last_cleanup_num_heap_tuples
Definition: nbtree.h:117
BlockNumber btm_fastroot
Definition: nbtree.h:110
uint32 btm_version
Definition: nbtree.h:107
uint32 btm_magic
Definition: nbtree.h:106
BlockNumber btm_root
Definition: nbtree.h:108
bool btm_allequalimage
Definition: nbtree.h:119
uint32 btm_fastlevel
Definition: nbtree.h:111
Definition: rel.h:56
int natts
Definition: tupdesc.h:137
Definition: c.h:692
bool superuser(void)
Definition: superuser.c:46
List * textToQualifiedNameList(text *textval)
Definition: varlena.c:2686

References AccessShareLock, BT_METAP_COLS_V1_8, BTMetaPageData::btm_allequalimage, BTMetaPageData::btm_fastlevel, BTMetaPageData::btm_fastroot, BTMetaPageData::btm_last_cleanup_num_delpages, BTMetaPageData::btm_last_cleanup_num_heap_tuples, BTMetaPageData::btm_level, BTMetaPageData::btm_magic, BTMetaPageData::btm_root, BTMetaPageData::btm_version, BTPageGetMeta, BTREE_NOVAC_VERSION, BUFFER_LOCK_SHARE, BufferGetPage(), BuildTupleFromCStrings(), elog, ereport, errcode(), errhint(), errmsg(), ERROR, get_call_result_type(), HeapTupleGetDatum(), INT64_FORMAT, IS_BTREE, IS_INDEX, j, LockBuffer(), makeRangeVarFromNameList(), TupleDescData::natts, PG_GETARG_TEXT_PP, PG_RETURN_DATUM, psprintf(), ReadBuffer(), relation_close(), RELATION_IS_OTHER_TEMP, relation_openrv(), RelationGetRelationName, relname, superuser(), textToQualifiedNameList(), TupleDescGetAttInMetadata(), TYPEFUNC_COMPOSITE, UnlockReleaseBuffer(), and values.

bt_multi_page_stats()

Datum bt_multi_page_stats ( PG_FUNCTION_ARGS  )

Definition at line 344 of file btreefuncs.c.

345{
346 Relation rel;
347 ua_page_stats *uargs;
348 FuncCallContext *fctx;
349 MemoryContext mctx;
350
351 if (!superuser())
353 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
354 errmsg("must be superuser to use pageinspect functions")));
355
356 if (SRF_IS_FIRSTCALL())
357 {
359 int64 blkno = PG_GETARG_INT64(1);
360 int64 blk_count = PG_GETARG_INT64(2);
361 RangeVar *relrv;
362
363 fctx = SRF_FIRSTCALL_INIT();
364
366 rel = relation_openrv(relrv, AccessShareLock);
367
368 /* Check that rel is a valid btree index and 1st block number is OK */
369 bt_index_block_validate(rel, blkno);
370
371 /*
372 * Check if upper bound of the specified range is valid. If only one
373 * page is requested, skip as we've already validated the page. (Also,
374 * it's important to skip this if blk_count is negative.)
375 */
376 if (blk_count > 1)
377 check_relation_block_range(rel, blkno + blk_count - 1);
378
379 /* Save arguments for reuse */
381
382 uargs = palloc(sizeof(ua_page_stats));
383
384 uargs->relid = RelationGetRelid(rel);
385 uargs->blkno = blkno;
386 uargs->blk_count = blk_count;
387 uargs->allpages = (blk_count < 0);
388
389 fctx->user_fctx = uargs;
390
392
393 /*
394 * To avoid possibly leaking a relcache reference if the SRF isn't run
395 * to completion, we close and re-open the index rel each time
396 * through, using the index's OID for re-opens to ensure we get the
397 * same rel. Keep the AccessShareLock though, to ensure it doesn't go
398 * away underneath us.
399 */
401 }
402
403 fctx = SRF_PERCALL_SETUP();
404 uargs = fctx->user_fctx;
405
406 /* We should have lock already */
407 rel = relation_open(uargs->relid, NoLock);
408
409 /* In all-pages mode, recheck the index length each time */
410 if (uargs->allpages)
411 uargs->blk_count = RelationGetNumberOfBlocks(rel) - uargs->blkno;
412
413 if (uargs->blk_count > 0)
414 {
415 /* We need to fetch next block statistics */
416 Buffer buffer;
417 Datum result;
418 HeapTuple tuple;
419 int j;
420 char *values[11];
422 TupleDesc tupleDesc;
423
424 buffer = ReadBuffer(rel, uargs->blkno);
426
427 /* keep compiler quiet */
428 stat.btpo_prev = stat.btpo_next = InvalidBlockNumber;
429 stat.btpo_flags = stat.free_size = stat.avg_item_size = 0;
430
431 GetBTPageStatistics(uargs->blkno, buffer, &stat);
432
433 UnlockReleaseBuffer(buffer);
435
436 /* Build a tuple descriptor for our result type */
437 if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
438 elog(ERROR, "return type must be a row type");
439
440 j = 0;
441 values[j++] = psprintf("%u", stat.blkno);
442 values[j++] = psprintf("%c", stat.type);
443 values[j++] = psprintf("%u", stat.live_items);
444 values[j++] = psprintf("%u", stat.dead_items);
445 values[j++] = psprintf("%u", stat.avg_item_size);
446 values[j++] = psprintf("%u", stat.page_size);
447 values[j++] = psprintf("%u", stat.free_size);
448 values[j++] = psprintf("%u", stat.btpo_prev);
449 values[j++] = psprintf("%u", stat.btpo_next);
450 values[j++] = psprintf("%u", stat.btpo_level);
451 values[j++] = psprintf("%d", stat.btpo_flags);
452
453 /* Construct tuple to be returned */
455 values);
456
457 result = HeapTupleGetDatum(tuple);
458
459 /*
460 * Move to the next block number and decrement the number of blocks
461 * still to be fetched
462 */
463 uargs->blkno++;
464 uargs->blk_count--;
465
466 SRF_RETURN_NEXT(fctx, result);
467 }
468
469 /* Done, so finally we can release the index lock */
471 SRF_RETURN_DONE(fctx);
472}
#define InvalidBlockNumber
Definition: block.h:33
static void bt_index_block_validate(Relation rel, int64 blkno)
Definition: btreefuncs.c:226
static void GetBTPageStatistics(BlockNumber blkno, Buffer buffer, BTPageStat *stat)
Definition: btreefuncs.c:109
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:283
#define PG_GETARG_INT64(n)
Definition: fmgr.h:283
#define SRF_IS_FIRSTCALL()
Definition: funcapi.h:304
#define SRF_PERCALL_SETUP()
Definition: funcapi.h:308
#define SRF_RETURN_NEXT(_funcctx, _result)
Definition: funcapi.h:310
#define SRF_FIRSTCALL_INIT()
Definition: funcapi.h:306
#define SRF_RETURN_DONE(_funcctx)
Definition: funcapi.h:328
#define NoLock
Definition: lockdefs.h:34
void * palloc(Size size)
Definition: mcxt.c:1365
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
#define RelationGetRelid(relation)
Definition: rel.h:514
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:47
void * user_fctx
Definition: funcapi.h:82
MemoryContext multi_call_memory_ctx
Definition: funcapi.h:101
Definition: win32_port.h:255
int64 blk_count
Definition: btreefuncs.c:85
int64 blkno
Definition: btreefuncs.c:84
bool allpages
Definition: btreefuncs.c:86
#define stat
Definition: win32_port.h:274

References AccessShareLock, ua_page_stats::allpages, ua_page_stats::blk_count, ua_page_stats::blkno, bt_index_block_validate(), BUFFER_LOCK_SHARE, BuildTupleFromCStrings(), check_relation_block_range(), elog, ereport, errcode(), errmsg(), ERROR, get_call_result_type(), GetBTPageStatistics(), HeapTupleGetDatum(), InvalidBlockNumber, j, LockBuffer(), makeRangeVarFromNameList(), MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, NoLock, palloc(), PG_GETARG_INT64, PG_GETARG_TEXT_PP, psprintf(), ReadBuffer(), relation_close(), relation_open(), relation_openrv(), RelationGetNumberOfBlocks, RelationGetRelid, ua_page_stats::relid, relname, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, stat, superuser(), textToQualifiedNameList(), TupleDescGetAttInMetadata(), TYPEFUNC_COMPOSITE, UnlockReleaseBuffer(), FuncCallContext::user_fctx, and values.

bt_page_items()

Datum bt_page_items ( PG_FUNCTION_ARGS  )

Definition at line 719 of file btreefuncs.c.

720{
722}
static Datum bt_page_items_internal(PG_FUNCTION_ARGS, enum pageinspect_version ext_version)
Definition: btreefuncs.c:624
@ PAGEINSPECT_V1_8
Definition: pageinspect.h:23

References bt_page_items_internal(), and PAGEINSPECT_V1_8.

bt_page_items_1_9()

Datum bt_page_items_1_9 ( PG_FUNCTION_ARGS  )

Definition at line 712 of file btreefuncs.c.

713{
715}
@ PAGEINSPECT_V1_9
Definition: pageinspect.h:24

References bt_page_items_internal(), and PAGEINSPECT_V1_9.

bt_page_items_bytea()

Datum bt_page_items_bytea ( PG_FUNCTION_ARGS  )

Definition at line 734 of file btreefuncs.c.

735{
736 bytea *raw_page = PG_GETARG_BYTEA_P(0);
737 Datum result;
738 FuncCallContext *fctx;
739 ua_page_items *uargs;
740
741 if (!superuser())
743 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
744 errmsg("must be superuser to use raw page functions")));
745
746 if (SRF_IS_FIRSTCALL())
747 {
748 BTPageOpaque opaque;
749 MemoryContext mctx;
750 TupleDesc tupleDesc;
751
752 fctx = SRF_FIRSTCALL_INIT();
754
755 uargs = palloc(sizeof(ua_page_items));
756
757 uargs->page = get_page_from_raw(raw_page);
758
759 if (PageIsNew(uargs->page))
760 {
763 }
764
765 uargs->offset = FirstOffsetNumber;
766
767 /* verify the special space has the expected size */
768 if (PageGetSpecialSize(uargs->page) != MAXALIGN(sizeof(BTPageOpaqueData)))
770 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
771 errmsg("input page is not a valid %s page", "btree"),
772 errdetail("Expected special size %d, got %d.",
773 (int) MAXALIGN(sizeof(BTPageOpaqueData)),
774 (int) PageGetSpecialSize(uargs->page))));
775
776 opaque = BTPageGetOpaque(uargs->page);
777
778 if (P_ISMETA(opaque))
780 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
781 errmsg("block is a meta page")));
782
783 if (P_ISLEAF(opaque) && opaque->btpo_level != 0)
785 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
786 errmsg("block is not a valid btree leaf page")));
787
788 if (P_ISDELETED(opaque))
789 elog(NOTICE, "page is deleted");
790
791 if (!P_ISDELETED(opaque))
792 fctx->max_calls = PageGetMaxOffsetNumber(uargs->page);
793 else
794 {
795 /* Don't interpret BTDeletedPageData as index tuples */
796 elog(NOTICE, "page from block is deleted");
797 fctx->max_calls = 0;
798 }
799 uargs->leafpage = P_ISLEAF(opaque);
800 uargs->rightmost = P_RIGHTMOST(opaque);
801
802 /* Build a tuple descriptor for our result type */
803 if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
804 elog(ERROR, "return type must be a row type");
805 tupleDesc = BlessTupleDesc(tupleDesc);
806
807 uargs->tupd = tupleDesc;
808
809 fctx->user_fctx = uargs;
810
812 }
813
814 fctx = SRF_PERCALL_SETUP();
815 uargs = fctx->user_fctx;
816
817 if (fctx->call_cntr < fctx->max_calls)
818 {
819 result = bt_page_print_tuples(uargs);
820 uargs->offset++;
821 SRF_RETURN_NEXT(fctx, result);
822 }
823
824 SRF_RETURN_DONE(fctx);
825}
static Datum bt_page_print_tuples(ua_page_items *uargs)
Definition: btreefuncs.c:481
static uint16 PageGetSpecialSize(const PageData *page)
Definition: bufpage.h:317
static bool PageIsNew(const PageData *page)
Definition: bufpage.h:234
static OffsetNumber PageGetMaxOffsetNumber(const PageData *page)
Definition: bufpage.h:372
#define MAXALIGN(LEN)
Definition: c.h:810
int errdetail(const char *fmt,...)
Definition: elog.c:1207
#define NOTICE
Definition: elog.h:35
TupleDesc BlessTupleDesc(TupleDesc tupdesc)
Definition: execTuples.c:2260
#define PG_RETURN_NULL()
Definition: fmgr.h:345
#define PG_GETARG_BYTEA_P(n)
Definition: fmgr.h:335
#define P_ISLEAF(opaque)
Definition: nbtree.h:221
#define P_ISMETA(opaque)
Definition: nbtree.h:224
#define BTPageGetOpaque(page)
Definition: nbtree.h:74
#define P_ISDELETED(opaque)
Definition: nbtree.h:223
#define P_RIGHTMOST(opaque)
Definition: nbtree.h:220
#define FirstOffsetNumber
Definition: off.h:27
Page get_page_from_raw(bytea *raw_page)
Definition: rawpage.c:218
uint32 btpo_level
Definition: nbtree.h:67
uint64 max_calls
Definition: funcapi.h:74
uint64 call_cntr
Definition: funcapi.h:65
OffsetNumber offset
Definition: btreefuncs.c:95
Page page
Definition: btreefuncs.c:94
TupleDesc tupd
Definition: btreefuncs.c:98
bool leafpage
Definition: btreefuncs.c:96
bool rightmost
Definition: btreefuncs.c:97

References BlessTupleDesc(), bt_page_print_tuples(), BTPageGetOpaque, BTPageOpaqueData::btpo_level, FuncCallContext::call_cntr, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, FirstOffsetNumber, get_call_result_type(), get_page_from_raw(), ua_page_items::leafpage, FuncCallContext::max_calls, MAXALIGN, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, NOTICE, ua_page_items::offset, P_ISDELETED, P_ISLEAF, P_ISMETA, P_RIGHTMOST, ua_page_items::page, PageGetMaxOffsetNumber(), PageGetSpecialSize(), PageIsNew(), palloc(), PG_GETARG_BYTEA_P, PG_RETURN_NULL, ua_page_items::rightmost, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, superuser(), ua_page_items::tupd, TYPEFUNC_COMPOSITE, and FuncCallContext::user_fctx.

bt_page_items_internal()

static Datum bt_page_items_internal ( PG_FUNCTION_ARGS  ,
enum pageinspect_version  ext_version 
)
static

Definition at line 624 of file btreefuncs.c.

625{
627 int64 blkno = (ext_version == PAGEINSPECT_V1_8 ? PG_GETARG_UINT32(1) : PG_GETARG_INT64(1));
628 Datum result;
629 FuncCallContext *fctx;
630 MemoryContext mctx;
631 ua_page_items *uargs;
632
633 if (!superuser())
635 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
636 errmsg("must be superuser to use pageinspect functions")));
637
638 if (SRF_IS_FIRSTCALL())
639 {
640 RangeVar *relrv;
641 Relation rel;
642 Buffer buffer;
643 BTPageOpaque opaque;
644 TupleDesc tupleDesc;
645
646 fctx = SRF_FIRSTCALL_INIT();
647
649 rel = relation_openrv(relrv, AccessShareLock);
650
651 bt_index_block_validate(rel, blkno);
652
653 buffer = ReadBuffer(rel, blkno);
655
656 /*
657 * We copy the page into local storage to avoid holding pin on the
658 * buffer longer than we must, and possibly failing to release it at
659 * all if the calling query doesn't fetch all rows.
660 */
662
663 uargs = palloc(sizeof(ua_page_items));
664
665 uargs->page = palloc(BLCKSZ);
666 memcpy(uargs->page, BufferGetPage(buffer), BLCKSZ);
667
668 UnlockReleaseBuffer(buffer);
670
671 uargs->offset = FirstOffsetNumber;
672
673 opaque = BTPageGetOpaque(uargs->page);
674
675 if (!P_ISDELETED(opaque))
676 fctx->max_calls = PageGetMaxOffsetNumber(uargs->page);
677 else
678 {
679 /* Don't interpret BTDeletedPageData as index tuples */
680 elog(NOTICE, "page from block " INT64_FORMAT " is deleted", blkno);
681 fctx->max_calls = 0;
682 }
683 uargs->leafpage = P_ISLEAF(opaque);
684 uargs->rightmost = P_RIGHTMOST(opaque);
685
686 /* Build a tuple descriptor for our result type */
687 if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
688 elog(ERROR, "return type must be a row type");
689 tupleDesc = BlessTupleDesc(tupleDesc);
690
691 uargs->tupd = tupleDesc;
692
693 fctx->user_fctx = uargs;
694
696 }
697
698 fctx = SRF_PERCALL_SETUP();
699 uargs = fctx->user_fctx;
700
701 if (fctx->call_cntr < fctx->max_calls)
702 {
703 result = bt_page_print_tuples(uargs);
704 uargs->offset++;
705 SRF_RETURN_NEXT(fctx, result);
706 }
707
708 SRF_RETURN_DONE(fctx);
709}
#define PG_GETARG_UINT32(n)
Definition: fmgr.h:270

References AccessShareLock, BlessTupleDesc(), bt_index_block_validate(), bt_page_print_tuples(), BTPageGetOpaque, BUFFER_LOCK_SHARE, BufferGetPage(), FuncCallContext::call_cntr, elog, ereport, errcode(), errmsg(), ERROR, FirstOffsetNumber, get_call_result_type(), INT64_FORMAT, ua_page_items::leafpage, LockBuffer(), makeRangeVarFromNameList(), FuncCallContext::max_calls, MemoryContextSwitchTo(), FuncCallContext::multi_call_memory_ctx, NOTICE, ua_page_items::offset, P_ISDELETED, P_ISLEAF, P_RIGHTMOST, ua_page_items::page, PageGetMaxOffsetNumber(), PAGEINSPECT_V1_8, palloc(), PG_GETARG_INT64, PG_GETARG_TEXT_PP, PG_GETARG_UINT32, ReadBuffer(), relation_close(), relation_openrv(), relname, ua_page_items::rightmost, SRF_FIRSTCALL_INIT, SRF_IS_FIRSTCALL, SRF_PERCALL_SETUP, SRF_RETURN_DONE, SRF_RETURN_NEXT, superuser(), textToQualifiedNameList(), ua_page_items::tupd, TYPEFUNC_COMPOSITE, UnlockReleaseBuffer(), and FuncCallContext::user_fctx.

Referenced by bt_page_items(), and bt_page_items_1_9().

bt_page_print_tuples()

static Datum bt_page_print_tuples ( ua_page_itemsuargs )
static

Definition at line 481 of file btreefuncs.c.

482{
483 Page page = uargs->page;
484 OffsetNumber offset = uargs->offset;
485 bool leafpage = uargs->leafpage;
486 bool rightmost = uargs->rightmost;
487 bool ispivottuple;
488 Datum values[9];
489 bool nulls[9];
490 HeapTuple tuple;
491 ItemId id;
492 IndexTuple itup;
493 int j;
494 int off;
495 int dlen;
496 char *dump,
497 *datacstring;
498 char *ptr;
499 ItemPointer htid;
500
501 id = PageGetItemId(page, offset);
502
503 if (!ItemIdIsValid(id))
504 elog(ERROR, "invalid ItemId");
505
506 itup = (IndexTuple) PageGetItem(page, id);
507
508 j = 0;
509 memset(nulls, 0, sizeof(nulls));
510 values[j++] = Int16GetDatum(offset);
511 values[j++] = ItemPointerGetDatum(&itup->t_tid);
512 values[j++] = Int32GetDatum((int) IndexTupleSize(itup));
515
516 ptr = (char *) itup + IndexInfoFindDataOffset(itup->t_info);
517 dlen = IndexTupleSize(itup) - IndexInfoFindDataOffset(itup->t_info);
518
519 /*
520 * Make sure that "data" column does not include posting list or pivot
521 * tuple representation of heap TID(s).
522 *
523 * Note: BTreeTupleIsPivot() won't work reliably on !heapkeyspace indexes
524 * (those built before BTREE_VERSION 4), but we have no way of determining
525 * if this page came from a !heapkeyspace index. We may only have a bytea
526 * nbtree page image to go on, so in general there is no metapage that we
527 * can check.
528 *
529 * That's okay here because BTreeTupleIsPivot() can only return false for
530 * a !heapkeyspace pivot, never true for a !heapkeyspace non-pivot. Since
531 * heap TID isn't part of the keyspace in a !heapkeyspace index anyway,
532 * there cannot possibly be a pivot tuple heap TID representation that we
533 * fail to make an adjustment for. A !heapkeyspace index can have
534 * BTreeTupleIsPivot() return true (due to things like suffix truncation
535 * for INCLUDE indexes in Postgres v11), but when that happens
536 * BTreeTupleGetHeapTID() can be trusted to work reliably (i.e. return
537 * NULL).
538 *
539 * Note: BTreeTupleIsPosting() always works reliably, even with
540 * !heapkeyspace indexes.
541 */
542 if (BTreeTupleIsPosting(itup))
543 dlen -= IndexTupleSize(itup) - BTreeTupleGetPostingOffset(itup);
544 else if (BTreeTupleIsPivot(itup) && BTreeTupleGetHeapTID(itup) != NULL)
545 dlen -= MAXALIGN(sizeof(ItemPointerData));
546
547 if (dlen < 0 || dlen > INDEX_SIZE_MASK)
548 elog(ERROR, "invalid tuple length %d for tuple at offset number %u",
549 dlen, offset);
550 dump = palloc0(dlen * 3 + 1);
551 datacstring = dump;
552 for (off = 0; off < dlen; off++)
553 {
554 if (off > 0)
555 *dump++ = ' ';
556 sprintf(dump, "%02x", *(ptr + off) & 0xff);
557 dump += 2;
558 }
559 values[j++] = CStringGetTextDatum(datacstring);
560 pfree(datacstring);
561
562 /*
563 * We need to work around the BTreeTupleIsPivot() !heapkeyspace limitation
564 * again. Deduce whether or not tuple must be a pivot tuple based on
565 * whether or not the page is a leaf page, as well as the page offset
566 * number of the tuple.
567 */
568 ispivottuple = (!leafpage || (!rightmost && offset == P_HIKEY));
569
570 /* LP_DEAD bit can never be set for pivot tuples, so show a NULL there */
571 if (!ispivottuple)
573 else
574 {
575 Assert(!ItemIdIsDead(id));
576 nulls[j++] = true;
577 }
578
579 htid = BTreeTupleGetHeapTID(itup);
580 if (ispivottuple && !BTreeTupleIsPivot(itup))
581 {
582 /* Don't show bogus heap TID in !heapkeyspace pivot tuple */
583 htid = NULL;
584 }
585
586 if (htid)
587 values[j++] = ItemPointerGetDatum(htid);
588 else
589 nulls[j++] = true;
590
591 if (BTreeTupleIsPosting(itup))
592 {
593 /* Build an array of item pointers */
594 ItemPointer tids;
595 Datum *tids_datum;
596 int nposting;
597
598 tids = BTreeTupleGetPosting(itup);
599 nposting = BTreeTupleGetNPosting(itup);
600 tids_datum = (Datum *) palloc(nposting * sizeof(Datum));
601 for (int i = 0; i < nposting; i++)
602 tids_datum[i] = ItemPointerGetDatum(&tids[i]);
603 values[j++] = PointerGetDatum(construct_array_builtin(tids_datum, nposting, TIDOID));
604 pfree(tids_datum);
605 }
606 else
607 nulls[j++] = true;
608
609 /* Build and return the result tuple */
610 tuple = heap_form_tuple(uargs->tupd, values, nulls);
611
612 return HeapTupleGetDatum(tuple);
613}
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
Definition: arrayfuncs.c:3382
static Item PageGetItem(const PageData *page, const ItemIdData *itemId)
Definition: bufpage.h:354
static ItemId PageGetItemId(Page page, OffsetNumber offsetNumber)
Definition: bufpage.h:244
#define CStringGetTextDatum(s)
Definition: builtins.h:97
Assert(PointerIsAligned(start, uint64))
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1117
i
int i
Definition: isn.c:77
#define ItemIdIsDead(itemId)
Definition: itemid.h:113
#define ItemIdIsValid(itemId)
Definition: itemid.h:86
static Datum ItemPointerGetDatum(const ItemPointerData *X)
Definition: itemptr.h:237
static bool IndexTupleHasVarwidths(const IndexTupleData *itup)
Definition: itup.h:83
IndexTupleData * IndexTuple
Definition: itup.h:53
static bool IndexTupleHasNulls(const IndexTupleData *itup)
Definition: itup.h:77
static Size IndexTupleSize(const IndexTupleData *itup)
Definition: itup.h:71
static Size IndexInfoFindDataOffset(unsigned short t_info)
Definition: itup.h:112
#define INDEX_SIZE_MASK
Definition: itup.h:65
void pfree(void *pointer)
Definition: mcxt.c:1594
void * palloc0(Size size)
Definition: mcxt.c:1395
static uint16 BTreeTupleGetNPosting(IndexTuple posting)
Definition: nbtree.h:519
static bool BTreeTupleIsPivot(IndexTuple itup)
Definition: nbtree.h:481
#define P_HIKEY
Definition: nbtree.h:368
static ItemPointer BTreeTupleGetPosting(IndexTuple posting)
Definition: nbtree.h:538
static uint32 BTreeTupleGetPostingOffset(IndexTuple posting)
Definition: nbtree.h:530
static bool BTreeTupleIsPosting(IndexTuple itup)
Definition: nbtree.h:493
static ItemPointer BTreeTupleGetHeapTID(IndexTuple itup)
Definition: nbtree.h:639
uint16 OffsetNumber
Definition: off.h:24
#define sprintf
Definition: port.h:241
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:332
static Datum Int16GetDatum(int16 X)
Definition: postgres.h:182
static Datum BoolGetDatum(bool X)
Definition: postgres.h:112
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:222
ItemPointerData t_tid
Definition: itup.h:37
unsigned short t_info
Definition: itup.h:49
Definition: itemid.h:26

References Assert(), BoolGetDatum(), BTreeTupleGetHeapTID(), BTreeTupleGetNPosting(), BTreeTupleGetPosting(), BTreeTupleGetPostingOffset(), BTreeTupleIsPivot(), BTreeTupleIsPosting(), construct_array_builtin(), CStringGetTextDatum, elog, ERROR, heap_form_tuple(), HeapTupleGetDatum(), i, INDEX_SIZE_MASK, IndexInfoFindDataOffset(), IndexTupleHasNulls(), IndexTupleHasVarwidths(), IndexTupleSize(), Int16GetDatum(), Int32GetDatum(), ItemIdIsDead, ItemIdIsValid, ItemPointerGetDatum(), j, ua_page_items::leafpage, MAXALIGN, ua_page_items::offset, P_HIKEY, ua_page_items::page, PageGetItem(), PageGetItemId(), palloc(), palloc0(), pfree(), PointerGetDatum(), ua_page_items::rightmost, sprintf, IndexTupleData::t_info, IndexTupleData::t_tid, ua_page_items::tupd, and values.

Referenced by bt_page_items_bytea(), and bt_page_items_internal().

bt_page_stats()

Datum bt_page_stats ( PG_FUNCTION_ARGS  )

Definition at line 329 of file btreefuncs.c.

330{
332}
static Datum bt_page_stats_internal(PG_FUNCTION_ARGS, enum pageinspect_version ext_version)
Definition: btreefuncs.c:260

References bt_page_stats_internal(), and PAGEINSPECT_V1_8.

bt_page_stats_1_9()

Datum bt_page_stats_1_9 ( PG_FUNCTION_ARGS  )

Definition at line 322 of file btreefuncs.c.

323{
325}

References bt_page_stats_internal(), and PAGEINSPECT_V1_9.

bt_page_stats_internal()

static Datum bt_page_stats_internal ( PG_FUNCTION_ARGS  ,
enum pageinspect_version  ext_version 
)
static

Definition at line 260 of file btreefuncs.c.

261{
263 int64 blkno = (ext_version == PAGEINSPECT_V1_8 ? PG_GETARG_UINT32(1) : PG_GETARG_INT64(1));
264 Buffer buffer;
265 Relation rel;
266 RangeVar *relrv;
267 Datum result;
268 HeapTuple tuple;
269 TupleDesc tupleDesc;
270 int j;
271 char *values[11];
273
274 if (!superuser())
276 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
277 errmsg("must be superuser to use pageinspect functions")));
278
280 rel = relation_openrv(relrv, AccessShareLock);
281
282 bt_index_block_validate(rel, blkno);
283
284 buffer = ReadBuffer(rel, blkno);
286
287 /* keep compiler quiet */
288 stat.btpo_prev = stat.btpo_next = InvalidBlockNumber;
289 stat.btpo_flags = stat.free_size = stat.avg_item_size = 0;
290
291 GetBTPageStatistics(blkno, buffer, &stat);
292
293 UnlockReleaseBuffer(buffer);
295
296 /* Build a tuple descriptor for our result type */
297 if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
298 elog(ERROR, "return type must be a row type");
299
300 j = 0;
301 values[j++] = psprintf("%u", stat.blkno);
302 values[j++] = psprintf("%c", stat.type);
303 values[j++] = psprintf("%u", stat.live_items);
304 values[j++] = psprintf("%u", stat.dead_items);
305 values[j++] = psprintf("%u", stat.avg_item_size);
306 values[j++] = psprintf("%u", stat.page_size);
307 values[j++] = psprintf("%u", stat.free_size);
308 values[j++] = psprintf("%u", stat.btpo_prev);
309 values[j++] = psprintf("%u", stat.btpo_next);
310 values[j++] = psprintf("%u", stat.btpo_level);
311 values[j++] = psprintf("%d", stat.btpo_flags);
312
314 values);
315
316 result = HeapTupleGetDatum(tuple);
317
318 PG_RETURN_DATUM(result);
319}

References AccessShareLock, bt_index_block_validate(), BUFFER_LOCK_SHARE, BuildTupleFromCStrings(), elog, ereport, errcode(), errmsg(), ERROR, get_call_result_type(), GetBTPageStatistics(), HeapTupleGetDatum(), InvalidBlockNumber, j, LockBuffer(), makeRangeVarFromNameList(), PAGEINSPECT_V1_8, PG_GETARG_INT64, PG_GETARG_TEXT_PP, PG_GETARG_UINT32, PG_RETURN_DATUM, psprintf(), ReadBuffer(), relation_close(), relation_openrv(), relname, stat, superuser(), textToQualifiedNameList(), TupleDescGetAttInMetadata(), TYPEFUNC_COMPOSITE, UnlockReleaseBuffer(), and values.

Referenced by bt_page_stats(), and bt_page_stats_1_9().

check_relation_block_range()

static void check_relation_block_range ( Relation  rel,
int64  blkno 
)
static

Definition at line 204 of file btreefuncs.c.

205{
206 /* Ensure we can cast to BlockNumber */
207 if (blkno < 0 || blkno > MaxBlockNumber)
209 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
210 errmsg("invalid block number %" PRId64, blkno)));
211
212 if ((BlockNumber) (blkno) >= RelationGetNumberOfBlocks(rel))
214 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
215 errmsg("block number %" PRId64 " is out of range", blkno)));
216}
uint32 BlockNumber
Definition: block.h:31
#define MaxBlockNumber
Definition: block.h:35

References ereport, errcode(), errmsg(), ERROR, MaxBlockNumber, and RelationGetNumberOfBlocks.

Referenced by bt_index_block_validate(), and bt_multi_page_stats().

GetBTPageStatistics()

static void GetBTPageStatistics ( BlockNumber  blkno,
Buffer  buffer,
BTPageStatstat 
)
static

Definition at line 109 of file btreefuncs.c.

110{
111 Page page = BufferGetPage(buffer);
112 PageHeader phdr = (PageHeader) page;
114 BTPageOpaque opaque = BTPageGetOpaque(page);
115 int item_size = 0;
116 int off;
117
118 stat->blkno = blkno;
119
120 stat->max_avail = BLCKSZ - (BLCKSZ - phdr->pd_special + SizeOfPageHeaderData);
121
122 stat->dead_items = stat->live_items = 0;
123
124 stat->page_size = PageGetPageSize(page);
125
126 /* page type (flags) */
127 if (P_ISDELETED(opaque))
128 {
129 /* We divide deleted pages into leaf ('d') or internal ('D') */
130 if (P_ISLEAF(opaque) || !P_HAS_FULLXID(opaque))
131 stat->type = 'd';
132 else
133 stat->type = 'D';
134
135 /*
136 * Report safexid in a deleted page.
137 *
138 * Handle pg_upgrade'd deleted pages that used the previous safexid
139 * representation in btpo_level field (this used to be a union type
140 * called "bpto").
141 */
142 if (P_HAS_FULLXID(opaque))
143 {
145
146 elog(DEBUG2, "deleted page from block %u has safexid %u:%u",
147 blkno, EpochFromFullTransactionId(safexid),
148 XidFromFullTransactionId(safexid));
149 }
150 else
151 elog(DEBUG2, "deleted page from block %u has safexid %u",
152 blkno, opaque->btpo_level);
153
154 /* Don't interpret BTDeletedPageData as index tuples */
155 maxoff = InvalidOffsetNumber;
156 }
157 else if (P_IGNORE(opaque))
158 stat->type = 'e';
159 else if (P_ISLEAF(opaque))
160 stat->type = 'l';
161 else if (P_ISROOT(opaque))
162 stat->type = 'r';
163 else
164 stat->type = 'i';
165
166 /* btpage opaque data */
167 stat->btpo_prev = opaque->btpo_prev;
168 stat->btpo_next = opaque->btpo_next;
169 stat->btpo_level = opaque->btpo_level;
170 stat->btpo_flags = opaque->btpo_flags;
171 stat->btpo_cycleid = opaque->btpo_cycleid;
172
173 /* count live and dead tuples, and free space */
174 for (off = FirstOffsetNumber; off <= maxoff; off++)
175 {
176 IndexTuple itup;
177
178 ItemId id = PageGetItemId(page, off);
179
180 itup = (IndexTuple) PageGetItem(page, id);
181
182 item_size += IndexTupleSize(itup);
183
184 if (!ItemIdIsDead(id))
185 stat->live_items++;
186 else
187 stat->dead_items++;
188 }
189 stat->free_size = PageGetFreeSpace(page);
190
191 if ((stat->live_items + stat->dead_items) > 0)
192 stat->avg_item_size = item_size / (stat->live_items + stat->dead_items);
193 else
194 stat->avg_item_size = 0;
195}
Size PageGetFreeSpace(const PageData *page)
Definition: bufpage.c:906
PageHeaderData * PageHeader
Definition: bufpage.h:174
static Size PageGetPageSize(const PageData *page)
Definition: bufpage.h:277
#define SizeOfPageHeaderData
Definition: bufpage.h:217
#define DEBUG2
Definition: elog.h:29
#define P_HAS_FULLXID(opaque)
Definition: nbtree.h:229
static FullTransactionId BTPageGetDeleteXid(Page page)
Definition: nbtree.h:261
#define P_ISROOT(opaque)
Definition: nbtree.h:222
#define P_IGNORE(opaque)
Definition: nbtree.h:226
#define InvalidOffsetNumber
Definition: off.h:26
BlockNumber btpo_next
Definition: nbtree.h:66
BlockNumber btpo_prev
Definition: nbtree.h:65
uint16 btpo_flags
Definition: nbtree.h:68
BTCycleId btpo_cycleid
Definition: nbtree.h:69
LocationIndex pd_special
Definition: bufpage.h:168
#define EpochFromFullTransactionId(x)
Definition: transam.h:47
#define XidFromFullTransactionId(x)
Definition: transam.h:48

References BTPageGetDeleteXid(), BTPageGetOpaque, BTPageOpaqueData::btpo_cycleid, BTPageOpaqueData::btpo_flags, BTPageOpaqueData::btpo_level, BTPageOpaqueData::btpo_next, BTPageOpaqueData::btpo_prev, BufferGetPage(), DEBUG2, elog, EpochFromFullTransactionId, FirstOffsetNumber, IndexTupleSize(), InvalidOffsetNumber, ItemIdIsDead, P_HAS_FULLXID, P_IGNORE, P_ISDELETED, P_ISLEAF, P_ISROOT, PageGetFreeSpace(), PageGetItem(), PageGetItemId(), PageGetMaxOffsetNumber(), PageGetPageSize(), PageHeaderData::pd_special, SizeOfPageHeaderData, and XidFromFullTransactionId.

Referenced by bt_multi_page_stats(), and bt_page_stats_internal().

PG_FUNCTION_INFO_V1() [1/7]

PG_FUNCTION_INFO_V1 ( bt_metap  )

PG_FUNCTION_INFO_V1() [2/7]

PG_FUNCTION_INFO_V1 ( bt_multi_page_stats  )

PG_FUNCTION_INFO_V1() [3/7]

PG_FUNCTION_INFO_V1 ( bt_page_items  )

PG_FUNCTION_INFO_V1() [4/7]

PG_FUNCTION_INFO_V1 ( bt_page_items_1_9  )

PG_FUNCTION_INFO_V1() [5/7]

PG_FUNCTION_INFO_V1 ( bt_page_items_bytea  )

PG_FUNCTION_INFO_V1() [6/7]

PG_FUNCTION_INFO_V1 ( bt_page_stats  )

PG_FUNCTION_INFO_V1() [7/7]

PG_FUNCTION_INFO_V1 ( bt_page_stats_1_9  )

AltStyle によって変換されたページ (->オリジナル) /