F.43. pg_freespacemap
Модуль pg_freespacemap предоставляет средства для исследования карты свободного пространства (FSM). В нём реализована функция pg_freespace, точнее, две перегруженных функции. Эти функции показывают значение, записанное в карте свободного пространства для данной страницы, либо для всех страниц отношения.
По умолчанию его использование разрешено только суперпользователям и ролям с правами роли pg_stat_scan_tables. Дать доступ другим можно с помощью GRANT.
F.43.1. Функции
-
pg_freespace(rel regclass IN, blkno bigint IN) returns int2 Возвращает объём свободного пространства на странице для отношения, заданного параметром
blkno, согласно FSM.-
pg_freespace(rel regclass IN, blkno OUT bigint, avail OUT int2) Выдаёт объём свободного пространства на каждой странице отношения, согласно FSM. Возвращается набор кортежей
(blkno bigint, avail int2), по одному кортежу для каждой страницы в отношении.-
pg_freespace_relation_logical_blocks(relationregclass[,forktext]) returns bigint Вычисляет объём, который занимает на диске один слой заданного отношения в блоках (страницах). Название интересующего слоя можно указать в параметре
fork. Возможные значения:mainвозвращает размер основного слоя данных отношения.fsmвозвращает размер карты свободного места (см. Раздел 73.3), связанной с отношением.vmвозвращает размер карты видимости (см. Раздел 73.4), связанной с отношением.
Примечание
Значение
initвсегда возвращает0, поскольку слойinitне связан с диском.Если параметр
forkопущен, функция вернёт размер основного слоя данных отношения.Данная функция возвращает корректные результаты как для сжатых, так и для несжатых таблиц.
Значения, хранимые в карте свободного пространства, не являются точными. Они округляются до 1/256 величины BLCKSZ (до 32 байт со значением BLCKSZ по умолчанию) и не поддерживаются в актуальном состоянии при каждом добавлении и изменении кортежей.
Для индексов отслеживаются полностью неиспользованные страницы, а не свободное пространство в страницах. Таким образом, эти значения отражают только то, что страница используется или свободна.
F.43.2. Пример вывода
postgres=# SELECT * FROM pg_freespace('foo');
blkno | avail
-------+-------
0 | 0
1 | 0
2 | 0
3 | 32
4 | 704
5 | 704
6 | 704
7 | 1216
8 | 704
9 | 704
10 | 704
11 | 704
12 | 704
13 | 704
14 | 704
15 | 704
16 | 704
17 | 704
18 | 704
19 | 3648
(20 rows)
postgres=# SELECT * FROM pg_freespace('foo', 7);
pg_freespace
--------------
1216
(1 row)F.43.3. Автор
Исходную версию разработал Марк Кирквуд <markir@paradise.net.nz>. Для версии 8.4 с новой реализацией FSM код адаптировал Хейкки Линнакангас <heikki@enterprisedb.com>
F.43. pg_freespacemap
The pg_freespacemap module provides a means for examining the free space map (FSM). It provides a function called pg_freespace, or two overloaded functions, to be precise. The functions show the value recorded in the free space map for a given page, or for all pages in the relation.
By default use is restricted to superusers and roles with privileges of the pg_stat_scan_tables role. Access may be granted to others using GRANT.
F.43.1. Functions
-
pg_freespace(rel regclass IN, blkno bigint IN) returns int2 Returns the amount of free space on the page of the relation, specified by
blkno, according to the FSM.-
pg_freespace(rel regclass IN, blkno OUT bigint, avail OUT int2) Displays the amount of free space on each page of the relation, according to the FSM. A set of
(blkno bigint, avail int2)tuples is returned, one tuple for each page in the relation.-
pg_freespace_relation_logical_blocks(relationregclass[,forktext]) returns bigint Computes the disk space used by one fork of the specified relation in blocks (pages). Use the
forkparameter to specify which fork to examine. Possible values:mainreturns the size of the main data fork of the relation.fsmreturns the size of the Free Space Map (see Section 73.3) associated with the relation.vmreturns the size of the Visibility Map (see Section 73.4) associated with the relation.
Note
The
initvalue will always return0, as theinitfork is not associated with the disk.If
forkis omitted, the function will return the size of the main data fork of the relation.This function returns correct results independent of whether the table is compressed or not.
The values stored in the free space map are not exact. They're rounded to precision of 1/256th of BLCKSZ (32 bytes with default BLCKSZ), and they're not kept fully up-to-date as tuples are inserted and updated.
For indexes, what is tracked is entirely-unused pages, rather than free space within pages. Therefore, the values are not meaningful, just whether a page is in-use or empty.
F.43.2. Sample Output
postgres=# SELECT * FROM pg_freespace('foo');
blkno | avail
-------+-------
0 | 0
1 | 0
2 | 0
3 | 32
4 | 704
5 | 704
6 | 704
7 | 1216
8 | 704
9 | 704
10 | 704
11 | 704
12 | 704
13 | 704
14 | 704
15 | 704
16 | 704
17 | 704
18 | 704
19 | 3648
(20 rows)
postgres=# SELECT * FROM pg_freespace('foo', 7);
pg_freespace
--------------
1216
(1 row)
F.43.3. Author
Original version by Mark Kirkwood <markir@paradise.net.nz>. Rewritten in version 8.4 to suit new FSM implementation by Heikki Linnakangas <heikki@enterprisedb.com>