Branch data Line data Source code
1 : : /*
2 : : * contrib/pageinspect/btreefuncs.c
3 : : *
4 : : *
5 : : * btreefuncs.c
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/htup_details.h"
31 : : #include "access/nbtree.h"
32 : : #include "access/relation.h"
33 : : #include "catalog/namespace.h"
34 : : #include "catalog/pg_am.h"
35 : : #include "catalog/pg_type.h"
36 : : #include "funcapi.h"
37 : : #include "miscadmin.h"
38 : : #include "pageinspect.h"
39 : : #include "utils/array.h"
40 : : #include "utils/builtins.h"
41 : : #include "utils/rel.h"
42 : : #include "utils/varlena.h"
43 : :
44 : 33 : PG_FUNCTION_INFO_V1(bt_metap);
45 : 9 : PG_FUNCTION_INFO_V1(bt_page_items_1_9);
46 : 17 : PG_FUNCTION_INFO_V1(bt_page_items);
47 : 17 : PG_FUNCTION_INFO_V1(bt_page_items_bytea);
48 : 9 : PG_FUNCTION_INFO_V1(bt_page_stats_1_9);
49 : 9 : PG_FUNCTION_INFO_V1(bt_page_stats);
50 : 9 : PG_FUNCTION_INFO_V1(bt_multi_page_stats);
51 : :
52 : : #define IS_INDEX(r) ((r)->rd_rel->relkind == RELKIND_INDEX)
53 : : #define IS_BTREE(r) ((r)->rd_rel->relam == BTREE_AM_OID)
54 : :
55 : : /* ------------------------------------------------
56 : : * structure for single btree page statistics
57 : : * ------------------------------------------------
58 : : */
59 : : typedef struct BTPageStat
60 : : {
61 : : uint32 blkno;
62 : : uint32 live_items;
63 : : uint32 dead_items;
64 : : uint32 page_size;
65 : : uint32 max_avail;
66 : : uint32 free_size;
67 : : uint32 avg_item_size;
68 : : char type;
69 : :
70 : : /* opaque data */
71 : : BlockNumber btpo_prev;
72 : : BlockNumber btpo_next;
73 : : uint32 btpo_level;
74 : : uint16 btpo_flags;
75 : : BTCycleId btpo_cycleid;
76 : : } BTPageStat;
77 : :
78 : : /*
79 : : * cross-call data structure for SRF for page stats
80 : : */
81 : : typedef struct ua_page_stats
82 : : {
83 : : Oid relid;
84 : : int64 blkno;
85 : : int64 blk_count;
86 : : bool allpages;
87 : : } ua_page_stats;
88 : :
89 : : /*
90 : : * cross-call data structure for SRF for page items
91 : : */
92 : : typedef struct ua_page_items
93 : : {
94 : : Page page;
95 : : OffsetNumber offset;
96 : : bool leafpage;
97 : : bool rightmost;
98 : : TupleDesc tupd;
99 : : } ua_page_items;
100 : :
101 : :
102 : : /* -------------------------------------------------
103 : : * GetBTPageStatistics()
104 : : *
105 : : * Collect statistics of single b-tree page
106 : : * -------------------------------------------------
107 : : */
108 : : static void
109 : 10 : GetBTPageStatistics(BlockNumber blkno, Buffer buffer, BTPageStat *stat)
110 : : {
111 : 10 : Page page = BufferGetPage(buffer);
112 : 10 : PageHeader phdr = (PageHeader) page;
113 : 10 : OffsetNumber maxoff = PageGetMaxOffsetNumber(page);
114 : 10 : BTPageOpaque opaque = BTPageGetOpaque(page);
115 : 10 : int item_size = 0;
116 : : int off;
117 : :
118 : 10 : stat->blkno = blkno;
119 : :
120 : 10 : stat->max_avail = BLCKSZ - (BLCKSZ - phdr->pd_special + SizeOfPageHeaderData);
121 : :
122 : 10 : stat->dead_items = stat->live_items = 0;
123 : :
124 : 10 : stat->page_size = PageGetPageSize(page);
125 : :
126 : : /* page type (flags) */
127 [ - + ]: 10 : if (P_ISDELETED(opaque))
128 : : {
129 : : /* We divide deleted pages into leaf ('d') or internal ('D') */
130 [ # # # # ]: 0 : if (P_ISLEAF(opaque) || !P_HAS_FULLXID(opaque))
131 : 0 : stat->type = 'd';
132 : : else
133 : 0 : 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 [ # # ]: 0 : if (P_HAS_FULLXID(opaque))
143 : : {
144 : 0 : FullTransactionId safexid = BTPageGetDeleteXid(page);
145 : :
146 [ # # ]: 0 : elog(DEBUG2, "deleted page from block %u has safexid %u:%u",
147 : : blkno, EpochFromFullTransactionId(safexid),
148 : : XidFromFullTransactionId(safexid));
149 : : }
150 : : else
151 [ # # ]: 0 : 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 : 0 : maxoff = InvalidOffsetNumber;
156 : : }
157 [ - + ]: 10 : else if (P_IGNORE(opaque))
158 : 0 : stat->type = 'e';
159 [ + + ]: 10 : else if (P_ISLEAF(opaque))
160 : 8 : stat->type = 'l';
161 [ + - ]: 2 : else if (P_ISROOT(opaque))
162 : 2 : stat->type = 'r';
163 : : else
164 : 0 : stat->type = 'i';
165 : :
166 : : /* btpage opaque data */
167 : 10 : stat->btpo_prev = opaque->btpo_prev;
168 : 10 : stat->btpo_next = opaque->btpo_next;
169 : 10 : stat->btpo_level = opaque->btpo_level;
170 : 10 : stat->btpo_flags = opaque->btpo_flags;
171 : 10 : stat->btpo_cycleid = opaque->btpo_cycleid;
172 : :
173 : : /* count live and dead tuples, and free space */
174 [ + + ]: 2022 : for (off = FirstOffsetNumber; off <= maxoff; off++)
175 : : {
176 : : IndexTuple itup;
177 : :
178 : 2012 : ItemId id = PageGetItemId(page, off);
179 : :
180 : 2012 : itup = (IndexTuple) PageGetItem(page, id);
181 : :
182 : 2012 : item_size += IndexTupleSize(itup);
183 : :
184 [ + - ]: 2012 : if (!ItemIdIsDead(id))
185 : 2012 : stat->live_items++;
186 : : else
187 : 0 : stat->dead_items++;
188 : : }
189 : 10 : stat->free_size = PageGetFreeSpace(page);
190 : :
191 [ + - ]: 10 : if ((stat->live_items + stat->dead_items) > 0)
192 : 10 : stat->avg_item_size = item_size / (stat->live_items + stat->dead_items);
193 : : else
194 : 0 : stat->avg_item_size = 0;
195 : 10 : }
196 : :
197 : : /* -----------------------------------------------
198 : : * check_relation_block_range()
199 : : *
200 : : * Verify that a block number (given as int64) is valid for the relation.
201 : : * -----------------------------------------------
202 : : */
203 : : static void
204 : 15 : check_relation_block_range(Relation rel, int64 blkno)
205 : : {
206 : : /* Ensure we can cast to BlockNumber */
207 [ + + - + ]: 15 : if (blkno < 0 || blkno > MaxBlockNumber)
208 [ + - ]: 2 : ereport(ERROR,
209 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
210 : : errmsg("invalid block number %" PRId64, blkno)));
211 : :
212 [ + + ]: 13 : if ((BlockNumber) (blkno) >= RelationGetNumberOfBlocks(rel))
213 [ + - ]: 3 : ereport(ERROR,
214 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
215 : : errmsg("block number %" PRId64 " is out of range", blkno)));
216 : 10 : }
217 : :
218 : : /* -----------------------------------------------
219 : : * bt_index_block_validate()
220 : : *
221 : : * Validate index type is btree and block number
222 : : * is valid (and not the metapage).
223 : : * -----------------------------------------------
224 : : */
225 : : static void
226 : 18 : bt_index_block_validate(Relation rel, int64 blkno)
227 : : {
228 [ + - + + ]: 18 : if (!IS_INDEX(rel) || !IS_BTREE(rel))
229 [ + - ]: 2 : ereport(ERROR,
230 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
231 : : errmsg("\"%s\" is not a %s index",
232 : : RelationGetRelationName(rel), "btree")));
233 : :
234 : 16 : check_relation_supported(rel, MAIN_FORKNUM);
235 : :
236 [ + + ]: 16 : if (blkno == 0)
237 [ + - ]: 3 : ereport(ERROR,
238 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
239 : : errmsg("block 0 is a meta page")));
240 : :
241 : 13 : check_relation_block_range(rel, blkno);
242 : 8 : }
243 : :
244 : : /* -----------------------------------------------
245 : : * bt_page_stats()
246 : : *
247 : : * Usage: SELECT * FROM bt_page_stats('t1_pkey', 1);
248 : : * Arguments are index relation name and block number
249 : : * -----------------------------------------------
250 : : */
251 : : static Datum
252 : 6 : bt_page_stats_internal(PG_FUNCTION_ARGS, enum pageinspect_version ext_version)
253 : : {
254 : 6 : text *relname = PG_GETARG_TEXT_PP(0);
255 [ + + ]: 6 : int64 blkno = (ext_version == PAGEINSPECT_V1_8 ? PG_GETARG_UINT32(1) : PG_GETARG_INT64(1));
256 : : Buffer buffer;
257 : : Relation rel;
258 : : RangeVar *relrv;
259 : : Datum result;
260 : : HeapTuple tuple;
261 : : TupleDesc tupleDesc;
262 : : int j;
263 : : char *values[11];
264 : : BTPageStat stat;
265 : :
266 [ - + ]: 6 : if (!superuser())
267 [ # # ]: 0 : ereport(ERROR,
268 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
269 : : errmsg("must be superuser to use pageinspect functions")));
270 : :
271 : 6 : relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));
272 : 6 : rel = relation_openrv(relrv, AccessShareLock);
273 : :
274 : 6 : bt_index_block_validate(rel, blkno);
275 : :
276 : 2 : buffer = ReadBuffer(rel, blkno);
277 : 2 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
278 : :
279 : : /* keep compiler quiet */
280 : 2 : stat.btpo_prev = stat.btpo_next = InvalidBlockNumber;
281 : 2 : stat.btpo_flags = stat.free_size = stat.avg_item_size = 0;
282 : :
283 : 2 : GetBTPageStatistics(blkno, buffer, &stat);
284 : :
285 : 2 : UnlockReleaseBuffer(buffer);
286 : 2 : relation_close(rel, AccessShareLock);
287 : :
288 : : /* Build a tuple descriptor for our result type */
289 [ - + ]: 2 : if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
290 [ # # ]: 0 : elog(ERROR, "return type must be a row type");
291 : :
292 : 2 : j = 0;
293 : 2 : values[j++] = psprintf("%u", stat.blkno);
294 : 2 : values[j++] = psprintf("%c", stat.type);
295 : 2 : values[j++] = psprintf("%u", stat.live_items);
296 : 2 : values[j++] = psprintf("%u", stat.dead_items);
297 : 2 : values[j++] = psprintf("%u", stat.avg_item_size);
298 : 2 : values[j++] = psprintf("%u", stat.page_size);
299 : 2 : values[j++] = psprintf("%u", stat.free_size);
300 : 2 : values[j++] = psprintf("%u", stat.btpo_prev);
301 : 2 : values[j++] = psprintf("%u", stat.btpo_next);
302 : 2 : values[j++] = psprintf("%u", stat.btpo_level);
303 : 2 : values[j++] = psprintf("%d", stat.btpo_flags);
304 : :
305 : 2 : tuple = BuildTupleFromCStrings(TupleDescGetAttInMetadata(tupleDesc),
306 : : values);
307 : :
308 : 2 : result = HeapTupleGetDatum(tuple);
309 : :
310 : 2 : PG_RETURN_DATUM(result);
311 : : }
312 : :
313 : : Datum
314 : 5 : bt_page_stats_1_9(PG_FUNCTION_ARGS)
315 : : {
316 : 5 : return bt_page_stats_internal(fcinfo, PAGEINSPECT_V1_9);
317 : : }
318 : :
319 : : /* entry point for old extension version */
320 : : Datum
321 : 1 : bt_page_stats(PG_FUNCTION_ARGS)
322 : : {
323 : 1 : return bt_page_stats_internal(fcinfo, PAGEINSPECT_V1_8);
324 : : }
325 : :
326 : :
327 : : /* -----------------------------------------------
328 : : * bt_multi_page_stats()
329 : : *
330 : : * Usage: SELECT * FROM bt_page_stats('t1_pkey', 1, 2);
331 : : * Arguments are index relation name, first block number, number of blocks
332 : : * (but number of blocks can be negative to mean "read all the rest")
333 : : * -----------------------------------------------
334 : : */
335 : : Datum
336 : 14 : bt_multi_page_stats(PG_FUNCTION_ARGS)
337 : : {
338 : : Relation rel;
339 : : ua_page_stats *uargs;
340 : : FuncCallContext *fctx;
341 : : MemoryContext mctx;
342 : :
343 [ - + ]: 14 : if (!superuser())
344 [ # # ]: 0 : ereport(ERROR,
345 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
346 : : errmsg("must be superuser to use pageinspect functions")));
347 : :
348 [ + + ]: 14 : if (SRF_IS_FIRSTCALL())
349 : : {
350 : 6 : text *relname = PG_GETARG_TEXT_PP(0);
351 : 6 : int64 blkno = PG_GETARG_INT64(1);
352 : 6 : int64 blk_count = PG_GETARG_INT64(2);
353 : : RangeVar *relrv;
354 : :
355 : 6 : fctx = SRF_FIRSTCALL_INIT();
356 : :
357 : 6 : relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));
358 : 6 : rel = relation_openrv(relrv, AccessShareLock);
359 : :
360 : : /* Check that rel is a valid btree index and 1st block number is OK */
361 : 6 : bt_index_block_validate(rel, blkno);
362 : :
363 : : /*
364 : : * Check if upper bound of the specified range is valid. If only one
365 : : * page is requested, skip as we've already validated the page. (Also,
366 : : * it's important to skip this if blk_count is negative.)
367 : : */
368 [ + + ]: 4 : if (blk_count > 1)
369 : 2 : check_relation_block_range(rel, blkno + blk_count - 1);
370 : :
371 : : /* Save arguments for reuse */
372 : 4 : mctx = MemoryContextSwitchTo(fctx->multi_call_memory_ctx);
373 : :
374 : 4 : uargs = palloc_object(ua_page_stats);
375 : :
376 : 4 : uargs->relid = RelationGetRelid(rel);
377 : 4 : uargs->blkno = blkno;
378 : 4 : uargs->blk_count = blk_count;
379 : 4 : uargs->allpages = (blk_count < 0);
380 : :
381 : 4 : fctx->user_fctx = uargs;
382 : :
383 : 4 : MemoryContextSwitchTo(mctx);
384 : :
385 : : /*
386 : : * To avoid possibly leaking a relcache reference if the SRF isn't run
387 : : * to completion, we close and re-open the index rel each time
388 : : * through, using the index's OID for re-opens to ensure we get the
389 : : * same rel. Keep the AccessShareLock though, to ensure it doesn't go
390 : : * away underneath us.
391 : : */
392 : 4 : relation_close(rel, NoLock);
393 : : }
394 : :
395 : 12 : fctx = SRF_PERCALL_SETUP();
396 : 12 : uargs = fctx->user_fctx;
397 : :
398 : : /* We should have lock already */
399 : 12 : rel = relation_open(uargs->relid, NoLock);
400 : :
401 : : /* In all-pages mode, recheck the index length each time */
402 [ + + ]: 12 : if (uargs->allpages)
403 : 5 : uargs->blk_count = RelationGetNumberOfBlocks(rel) - uargs->blkno;
404 : :
405 [ + + ]: 12 : if (uargs->blk_count > 0)
406 : : {
407 : : /* We need to fetch next block statistics */
408 : : Buffer buffer;
409 : : Datum result;
410 : : HeapTuple tuple;
411 : : int j;
412 : : char *values[11];
413 : : BTPageStat stat;
414 : : TupleDesc tupleDesc;
415 : :
416 : 8 : buffer = ReadBuffer(rel, uargs->blkno);
417 : 8 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
418 : :
419 : : /* keep compiler quiet */
420 : 8 : stat.btpo_prev = stat.btpo_next = InvalidBlockNumber;
421 : 8 : stat.btpo_flags = stat.free_size = stat.avg_item_size = 0;
422 : :
423 : 8 : GetBTPageStatistics(uargs->blkno, buffer, &stat);
424 : :
425 : 8 : UnlockReleaseBuffer(buffer);
426 : 8 : relation_close(rel, NoLock);
427 : :
428 : : /* Build a tuple descriptor for our result type */
429 [ - + ]: 8 : if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
430 [ # # ]: 0 : elog(ERROR, "return type must be a row type");
431 : :
432 : 8 : j = 0;
433 : 8 : values[j++] = psprintf("%u", stat.blkno);
434 : 8 : values[j++] = psprintf("%c", stat.type);
435 : 8 : values[j++] = psprintf("%u", stat.live_items);
436 : 8 : values[j++] = psprintf("%u", stat.dead_items);
437 : 8 : values[j++] = psprintf("%u", stat.avg_item_size);
438 : 8 : values[j++] = psprintf("%u", stat.page_size);
439 : 8 : values[j++] = psprintf("%u", stat.free_size);
440 : 8 : values[j++] = psprintf("%u", stat.btpo_prev);
441 : 8 : values[j++] = psprintf("%u", stat.btpo_next);
442 : 8 : values[j++] = psprintf("%u", stat.btpo_level);
443 : 8 : values[j++] = psprintf("%d", stat.btpo_flags);
444 : :
445 : : /* Construct tuple to be returned */
446 : 8 : tuple = BuildTupleFromCStrings(TupleDescGetAttInMetadata(tupleDesc),
447 : : values);
448 : :
449 : 8 : result = HeapTupleGetDatum(tuple);
450 : :
451 : : /*
452 : : * Move to the next block number and decrement the number of blocks
453 : : * still to be fetched
454 : : */
455 : 8 : uargs->blkno++;
456 : 8 : uargs->blk_count--;
457 : :
458 : 8 : SRF_RETURN_NEXT(fctx, result);
459 : : }
460 : :
461 : : /* Done, so finally we can release the index lock */
462 : 4 : relation_close(rel, AccessShareLock);
463 : 4 : SRF_RETURN_DONE(fctx);
464 : : }
465 : :
466 : : /*-------------------------------------------------------
467 : : * bt_page_print_tuples()
468 : : *
469 : : * Form a tuple describing index tuple at a given offset
470 : : * ------------------------------------------------------
471 : : */
472 : : static Datum
473 : 3 : bt_page_print_tuples(ua_page_items *uargs)
474 : : {
475 : 3 : Page page = uargs->page;
476 : 3 : OffsetNumber offset = uargs->offset;
477 : 3 : bool leafpage = uargs->leafpage;
478 : 3 : bool rightmost = uargs->rightmost;
479 : : bool ispivottuple;
480 : : Datum values[9];
481 : : bool nulls[9];
482 : : HeapTuple tuple;
483 : : ItemId id;
484 : : IndexTuple itup;
485 : : int j;
486 : : int off;
487 : : int dlen;
488 : : char *dump,
489 : : *datacstring;
490 : : char *ptr;
491 : : ItemPointer htid;
492 : :
493 : 3 : id = PageGetItemId(page, offset);
494 : :
495 [ - + ]: 3 : if (!ItemIdIsValid(id))
496 [ # # ]: 0 : elog(ERROR, "invalid ItemId");
497 : :
498 : 3 : itup = (IndexTuple) PageGetItem(page, id);
499 : :
500 : 3 : j = 0;
501 : 3 : memset(nulls, 0, sizeof(nulls));
502 : 3 : values[j++] = Int16GetDatum(offset);
503 : 3 : values[j++] = ItemPointerGetDatum(&itup->t_tid);
504 : 3 : values[j++] = Int16GetDatum(IndexTupleSize(itup));
505 : 3 : values[j++] = BoolGetDatum(IndexTupleHasNulls(itup));
506 : 3 : values[j++] = BoolGetDatum(IndexTupleHasVarwidths(itup));
507 : :
508 : 3 : ptr = (char *) itup + IndexInfoFindDataOffset(itup->t_info);
509 : 3 : dlen = IndexTupleSize(itup) - IndexInfoFindDataOffset(itup->t_info);
510 : :
511 : : /*
512 : : * Make sure that "data" column does not include posting list or pivot
513 : : * tuple representation of heap TID(s).
514 : : *
515 : : * Note: BTreeTupleIsPivot() won't work reliably on !heapkeyspace indexes
516 : : * (those built before BTREE_VERSION 4), but we have no way of determining
517 : : * if this page came from a !heapkeyspace index. We may only have a bytea
518 : : * nbtree page image to go on, so in general there is no metapage that we
519 : : * can check.
520 : : *
521 : : * That's okay here because BTreeTupleIsPivot() can only return false for
522 : : * a !heapkeyspace pivot, never true for a !heapkeyspace non-pivot. Since
523 : : * heap TID isn't part of the keyspace in a !heapkeyspace index anyway,
524 : : * there cannot possibly be a pivot tuple heap TID representation that we
525 : : * fail to make an adjustment for. A !heapkeyspace index can have
526 : : * BTreeTupleIsPivot() return true (due to things like suffix truncation
527 : : * for INCLUDE indexes in Postgres v11), but when that happens
528 : : * BTreeTupleGetHeapTID() can be trusted to work reliably (i.e. return
529 : : * NULL).
530 : : *
531 : : * Note: BTreeTupleIsPosting() always works reliably, even with
532 : : * !heapkeyspace indexes.
533 : : */
534 [ - + ]: 3 : if (BTreeTupleIsPosting(itup))
535 : 0 : dlen -= IndexTupleSize(itup) - BTreeTupleGetPostingOffset(itup);
536 [ - + - - ]: 3 : else if (BTreeTupleIsPivot(itup) && BTreeTupleGetHeapTID(itup) != NULL)
537 : 0 : dlen -= MAXALIGN(sizeof(ItemPointerData));
538 : :
539 [ + - - + ]: 3 : if (dlen < 0 || dlen > INDEX_SIZE_MASK)
540 [ # # ]: 0 : elog(ERROR, "invalid tuple length %d for tuple at offset number %u",
541 : : dlen, offset);
542 : 3 : dump = palloc0(dlen * 3 + 1);
543 : 3 : datacstring = dump;
544 [ + + ]: 27 : for (off = 0; off < dlen; off++)
545 : : {
546 [ + + ]: 24 : if (off > 0)
547 : 21 : *dump++ = ' ';
548 : 24 : sprintf(dump, "%02x", *(ptr + off) & 0xff);
549 : 24 : dump += 2;
550 : : }
551 : 3 : values[j++] = CStringGetTextDatum(datacstring);
552 : 3 : pfree(datacstring);
553 : :
554 : : /*
555 : : * We need to work around the BTreeTupleIsPivot() !heapkeyspace limitation
556 : : * again. Deduce whether or not tuple must be a pivot tuple based on
557 : : * whether or not the page is a leaf page, as well as the page offset
558 : : * number of the tuple.
559 : : */
560 [ + - - + : 3 : ispivottuple = (!leafpage || (!rightmost && offset == P_HIKEY));
- - ]
561 : :
562 : : /* LP_DEAD bit can never be set for pivot tuples, so show a NULL there */
563 [ + - ]: 3 : if (!ispivottuple)
564 : 3 : values[j++] = BoolGetDatum(ItemIdIsDead(id));
565 : : else
566 : : {
567 : : Assert(!ItemIdIsDead(id));
568 : 0 : nulls[j++] = true;
569 : : }
570 : :
571 : 3 : htid = BTreeTupleGetHeapTID(itup);
572 [ - + - - ]: 3 : if (ispivottuple && !BTreeTupleIsPivot(itup))
573 : : {
574 : : /* Don't show bogus heap TID in !heapkeyspace pivot tuple */
575 : 0 : htid = NULL;
576 : : }
577 : :
578 [ + - ]: 3 : if (htid)
579 : 3 : values[j++] = ItemPointerGetDatum(htid);
580 : : else
581 : 0 : nulls[j++] = true;
582 : :
583 [ - + ]: 3 : if (BTreeTupleIsPosting(itup))
584 : : {
585 : : /* Build an array of item pointers */
586 : : ItemPointer tids;
587 : : Datum *tids_datum;
588 : : int nposting;
589 : :
590 : 0 : tids = BTreeTupleGetPosting(itup);
591 : 0 : nposting = BTreeTupleGetNPosting(itup);
592 : 0 : tids_datum = palloc_array(Datum, nposting);
593 [ # # ]: 0 : for (int i = 0; i < nposting; i++)
594 : 0 : tids_datum[i] = ItemPointerGetDatum(&tids[i]);
595 : 0 : values[j++] = PointerGetDatum(construct_array_builtin(tids_datum, nposting, TIDOID));
596 : 0 : pfree(tids_datum);
597 : : }
598 : : else
599 : 3 : nulls[j++] = true;
600 : :
601 : : /* Build and return the result tuple */
602 : 3 : tuple = heap_form_tuple(uargs->tupd, values, nulls);
603 : :
604 : 3 : return HeapTupleGetDatum(tuple);
605 : : }
606 : :
607 : : /*-------------------------------------------------------
608 : : * bt_page_items()
609 : : *
610 : : * Get IndexTupleData set in a btree page
611 : : *
612 : : * Usage: SELECT * FROM bt_page_items('t1_pkey', 1);
613 : : *-------------------------------------------------------
614 : : */
615 : : static Datum
616 : 8 : bt_page_items_internal(PG_FUNCTION_ARGS, enum pageinspect_version ext_version)
617 : : {
618 : 8 : text *relname = PG_GETARG_TEXT_PP(0);
619 [ + + ]: 8 : int64 blkno = (ext_version == PAGEINSPECT_V1_8 ? PG_GETARG_UINT32(1) : PG_GETARG_INT64(1));
620 : : Datum result;
621 : : FuncCallContext *fctx;
622 : : MemoryContext mctx;
623 : : ua_page_items *uargs;
624 : :
625 [ - + ]: 8 : if (!superuser())
626 [ # # ]: 0 : ereport(ERROR,
627 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
628 : : errmsg("must be superuser to use pageinspect functions")));
629 : :
630 [ + + ]: 8 : if (SRF_IS_FIRSTCALL())
631 : : {
632 : : RangeVar *relrv;
633 : : Relation rel;
634 : : Buffer buffer;
635 : : BTPageOpaque opaque;
636 : : TupleDesc tupleDesc;
637 : :
638 : 6 : fctx = SRF_FIRSTCALL_INIT();
639 : :
640 : 6 : relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));
641 : 6 : rel = relation_openrv(relrv, AccessShareLock);
642 : :
643 : 6 : bt_index_block_validate(rel, blkno);
644 : :
645 : 2 : buffer = ReadBuffer(rel, blkno);
646 : 2 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
647 : :
648 : : /*
649 : : * We copy the page into local storage to avoid holding pin on the
650 : : * buffer longer than we must, and possibly failing to release it at
651 : : * all if the calling query doesn't fetch all rows.
652 : : */
653 : 2 : mctx = MemoryContextSwitchTo(fctx->multi_call_memory_ctx);
654 : :
655 : 2 : uargs = palloc_object(ua_page_items);
656 : :
657 : 2 : uargs->page = palloc(BLCKSZ);
658 : 2 : memcpy(uargs->page, BufferGetPage(buffer), BLCKSZ);
659 : :
660 : 2 : UnlockReleaseBuffer(buffer);
661 : 2 : relation_close(rel, AccessShareLock);
662 : :
663 : 2 : uargs->offset = FirstOffsetNumber;
664 : :
665 : 2 : opaque = BTPageGetOpaque(uargs->page);
666 : :
667 [ + - ]: 2 : if (!P_ISDELETED(opaque))
668 : 2 : fctx->max_calls = PageGetMaxOffsetNumber(uargs->page);
669 : : else
670 : : {
671 : : /* Don't interpret BTDeletedPageData as index tuples */
672 [ # # ]: 0 : elog(NOTICE, "page from block " INT64_FORMAT " is deleted", blkno);
673 : 0 : fctx->max_calls = 0;
674 : : }
675 : 2 : uargs->leafpage = P_ISLEAF(opaque);
676 : 2 : uargs->rightmost = P_RIGHTMOST(opaque);
677 : :
678 : : /* Build a tuple descriptor for our result type */
679 [ - + ]: 2 : if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
680 [ # # ]: 0 : elog(ERROR, "return type must be a row type");
681 : 2 : tupleDesc = BlessTupleDesc(tupleDesc);
682 : :
683 : 2 : uargs->tupd = tupleDesc;
684 : :
685 : 2 : fctx->user_fctx = uargs;
686 : :
687 : 2 : MemoryContextSwitchTo(mctx);
688 : : }
689 : :
690 : 4 : fctx = SRF_PERCALL_SETUP();
691 : 4 : uargs = fctx->user_fctx;
692 : :
693 [ + + ]: 4 : if (fctx->call_cntr < fctx->max_calls)
694 : : {
695 : 2 : result = bt_page_print_tuples(uargs);
696 : 2 : uargs->offset++;
697 : 2 : SRF_RETURN_NEXT(fctx, result);
698 : : }
699 : :
700 : 2 : SRF_RETURN_DONE(fctx);
701 : : }
702 : :
703 : : Datum
704 : 6 : bt_page_items_1_9(PG_FUNCTION_ARGS)
705 : : {
706 : 6 : return bt_page_items_internal(fcinfo, PAGEINSPECT_V1_9);
707 : : }
708 : :
709 : : /* entry point for old extension version */
710 : : Datum
711 : 2 : bt_page_items(PG_FUNCTION_ARGS)
712 : : {
713 : 2 : return bt_page_items_internal(fcinfo, PAGEINSPECT_V1_8);
714 : : }
715 : :
716 : : /*-------------------------------------------------------
717 : : * bt_page_items_bytea()
718 : : *
719 : : * Get IndexTupleData set in a btree page
720 : : *
721 : : * Usage: SELECT * FROM bt_page_items(get_raw_page('t1_pkey', 1));
722 : : *-------------------------------------------------------
723 : : */
724 : :
725 : : Datum
726 : 9 : bt_page_items_bytea(PG_FUNCTION_ARGS)
727 : : {
728 : 9 : bytea *raw_page = PG_GETARG_BYTEA_P(0);
729 : : Datum result;
730 : : FuncCallContext *fctx;
731 : : ua_page_items *uargs;
732 : :
733 [ - + ]: 9 : if (!superuser())
734 [ # # ]: 0 : ereport(ERROR,
735 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
736 : : errmsg("must be superuser to use raw page functions")));
737 : :
738 [ + + ]: 9 : if (SRF_IS_FIRSTCALL())
739 : : {
740 : : BTPageOpaque opaque;
741 : : MemoryContext mctx;
742 : : TupleDesc tupleDesc;
743 : :
744 : 8 : fctx = SRF_FIRSTCALL_INIT();
745 : 8 : mctx = MemoryContextSwitchTo(fctx->multi_call_memory_ctx);
746 : :
747 : 8 : uargs = palloc_object(ua_page_items);
748 : :
749 : 8 : uargs->page = get_page_from_raw(raw_page);
750 : :
751 [ + + ]: 7 : if (PageIsNew(uargs->page))
752 : : {
753 : 1 : MemoryContextSwitchTo(mctx);
754 : 1 : PG_RETURN_NULL();
755 : : }
756 : :
757 : 6 : uargs->offset = FirstOffsetNumber;
758 : :
759 : : /* verify the special space has the expected size */
760 [ + + ]: 6 : if (PageGetSpecialSize(uargs->page) != MAXALIGN(sizeof(BTPageOpaqueData)))
761 [ + - ]: 2 : ereport(ERROR,
762 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
763 : : errmsg("input page is not a valid %s page", "btree"),
764 : : errdetail("Expected special size %d, got %d.",
765 : : (int) MAXALIGN(sizeof(BTPageOpaqueData)),
766 : : (int) PageGetSpecialSize(uargs->page))));
767 : :
768 : 4 : opaque = BTPageGetOpaque(uargs->page);
769 : :
770 [ + + ]: 4 : if (P_ISMETA(opaque))
771 [ + - ]: 2 : ereport(ERROR,
772 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
773 : : errmsg("block is a meta page")));
774 : :
775 [ + - + + ]: 2 : if (P_ISLEAF(opaque) && opaque->btpo_level != 0)
776 [ + - ]: 1 : ereport(ERROR,
777 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
778 : : errmsg("block is not a valid btree leaf page")));
779 : :
780 [ - + ]: 1 : if (P_ISDELETED(opaque))
781 [ # # ]: 0 : elog(NOTICE, "page is deleted");
782 : :
783 [ + - ]: 1 : if (!P_ISDELETED(opaque))
784 : 1 : fctx->max_calls = PageGetMaxOffsetNumber(uargs->page);
785 : : else
786 : : {
787 : : /* Don't interpret BTDeletedPageData as index tuples */
788 [ # # ]: 0 : elog(NOTICE, "page from block is deleted");
789 : 0 : fctx->max_calls = 0;
790 : : }
791 : 1 : uargs->leafpage = P_ISLEAF(opaque);
792 : 1 : uargs->rightmost = P_RIGHTMOST(opaque);
793 : :
794 : : /* Build a tuple descriptor for our result type */
795 [ - + ]: 1 : if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
796 [ # # ]: 0 : elog(ERROR, "return type must be a row type");
797 : 1 : tupleDesc = BlessTupleDesc(tupleDesc);
798 : :
799 : 1 : uargs->tupd = tupleDesc;
800 : :
801 : 1 : fctx->user_fctx = uargs;
802 : :
803 : 1 : MemoryContextSwitchTo(mctx);
804 : : }
805 : :
806 : 2 : fctx = SRF_PERCALL_SETUP();
807 : 2 : uargs = fctx->user_fctx;
808 : :
809 [ + + ]: 2 : if (fctx->call_cntr < fctx->max_calls)
810 : : {
811 : 1 : result = bt_page_print_tuples(uargs);
812 : 1 : uargs->offset++;
813 : 1 : SRF_RETURN_NEXT(fctx, result);
814 : : }
815 : :
816 : 1 : SRF_RETURN_DONE(fctx);
817 : : }
818 : :
819 : : /* Number of output arguments (columns) for bt_metap() */
820 : : #define BT_METAP_COLS_V1_8 9
821 : :
822 : : /* ------------------------------------------------
823 : : * bt_metap()
824 : : *
825 : : * Get a btree's meta-page information
826 : : *
827 : : * Usage: SELECT * FROM bt_metap('t1_pkey')
828 : : * ------------------------------------------------
829 : : */
830 : : Datum
831 : 2 : bt_metap(PG_FUNCTION_ARGS)
832 : : {
833 : 2 : text *relname = PG_GETARG_TEXT_PP(0);
834 : : Datum result;
835 : : Relation rel;
836 : : RangeVar *relrv;
837 : : BTMetaPageData *metad;
838 : : TupleDesc tupleDesc;
839 : : int j;
840 : : char *values[9];
841 : : Buffer buffer;
842 : : Page page;
843 : : HeapTuple tuple;
844 : :
845 [ - + ]: 2 : if (!superuser())
846 [ # # ]: 0 : ereport(ERROR,
847 : : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
848 : : errmsg("must be superuser to use pageinspect functions")));
849 : :
850 : 2 : relrv = makeRangeVarFromNameList(textToQualifiedNameList(relname));
851 : 2 : rel = relation_openrv(relrv, AccessShareLock);
852 : :
853 [ + - + + ]: 2 : if (!IS_INDEX(rel) || !IS_BTREE(rel))
854 [ + - ]: 1 : ereport(ERROR,
855 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
856 : : errmsg("\"%s\" is not a %s index",
857 : : RelationGetRelationName(rel), "btree")));
858 : :
859 : 1 : check_relation_supported(rel, MAIN_FORKNUM);
860 : :
861 : 1 : buffer = ReadBuffer(rel, 0);
862 : 1 : LockBuffer(buffer, BUFFER_LOCK_SHARE);
863 : :
864 : 1 : page = BufferGetPage(buffer);
865 : 1 : metad = BTPageGetMeta(page);
866 : :
867 : : /* Build a tuple descriptor for our result type */
868 [ - + ]: 1 : if (get_call_result_type(fcinfo, NULL, &tupleDesc) != TYPEFUNC_COMPOSITE)
869 [ # # ]: 0 : elog(ERROR, "return type must be a row type");
870 : :
871 : : /*
872 : : * We need a kluge here to detect API versions prior to 1.8. Earlier
873 : : * versions incorrectly used int4 for certain columns.
874 : : *
875 : : * There is no way to reliably avoid the problems created by the old
876 : : * function definition at this point, so insist that the user update the
877 : : * extension.
878 : : */
879 [ - + ]: 1 : if (tupleDesc->natts < BT_METAP_COLS_V1_8)
880 [ # # ]: 0 : ereport(ERROR,
881 : : (errcode(ERRCODE_INVALID_FUNCTION_DEFINITION),
882 : : errmsg("function has wrong number of declared columns"),
883 : : errhint("To resolve the problem, update the \"pageinspect\" extension to the latest version.")));
884 : :
885 : 1 : j = 0;
886 : 1 : values[j++] = psprintf("%d", metad->btm_magic);
887 : 1 : values[j++] = psprintf("%d", metad->btm_version);
888 : 1 : values[j++] = psprintf("%u", metad->btm_root);
889 : 1 : values[j++] = psprintf("%u", metad->btm_level);
890 : 1 : values[j++] = psprintf("%u", metad->btm_fastroot);
891 : 1 : values[j++] = psprintf("%u", metad->btm_fastlevel);
892 : :
893 : : /*
894 : : * Get values of extended metadata if available, use default values
895 : : * otherwise. Note that we rely on the assumption that btm_allequalimage
896 : : * is initialized to zero with indexes that were built on versions prior
897 : : * to Postgres 13 (just like _bt_metaversion()).
898 : : */
899 [ + - ]: 1 : if (metad->btm_version >= BTREE_NOVAC_VERSION)
900 : : {
901 : 1 : values[j++] = psprintf("%u", metad->btm_last_cleanup_num_delpages);
902 : 1 : values[j++] = psprintf("%f", metad->btm_last_cleanup_num_heap_tuples);
903 [ + - ]: 1 : values[j++] = metad->btm_allequalimage ? "t" : "f";
904 : : }
905 : : else
906 : : {
907 : 0 : values[j++] = "0";
908 : 0 : values[j++] = "-1";
909 : 0 : values[j++] = "f";
910 : : }
911 : :
912 : 1 : tuple = BuildTupleFromCStrings(TupleDescGetAttInMetadata(tupleDesc),
913 : : values);
914 : :
915 : 1 : result = HeapTupleGetDatum(tuple);
916 : :
917 : 1 : UnlockReleaseBuffer(buffer);
918 : 1 : relation_close(rel, AccessShareLock);
919 : :
920 : 1 : PG_RETURN_DATUM(result);
921 : : }
|