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