F.26. pg_freespacemap
Модуль pg_freespacemap
предоставляет средства для исследования карты свободного пространства (FSM). В нём реализована функция pg_freespace
, точнее, две перегруженных функции. Эти функции показывают значение, записанное в карте свободного пространства для данной страницы, либо для всех страниц отношения.
По умолчанию его использование разрешено только суперпользователям и членам роли pg_stat_scan_tables
. Дать доступ другим можно с помощью GRANT
.
F.26.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)
, по одному кортежу для каждой страницы в отношении.
Значения, хранимые в карте свободного пространства, не являются точными. Они округляются до 1/256 величины BLCKSZ
(до 32 байт со значением BLCKSZ
по умолчанию) и не поддерживаются в актуальном состоянии при каждом добавлении и изменении кортежей.
Для индексов отслеживаются полностью неиспользованные страницы, а не свободное пространство в страницах. Таким образом, эти значения отражают только то, что страница занята или свободна.
Примечание
Интерфейс был изменён в версии 8.4, в соответствии с нововведениями реализации FSM, которые появились в этой версии.
F.26.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.26.3. Автор
Исходную версию разработал Марк Кирквуд <markir@paradise.net.nz>
. Для версии 8.4 с новой реализацией FSM код адаптировал Хейкки Линнакангас <heikki@enterprisedb.com>
33.9. Asynchronous Notification #
Postgres Pro offers asynchronous notification via the LISTEN
and NOTIFY
commands. A client session registers its interest in a particular notification channel with the LISTEN
command (and can stop listening with the UNLISTEN
command). All sessions listening on a particular channel will be notified asynchronously when a NOTIFY
command with that channel name is executed by any session. A “payload” string can be passed to communicate additional data to the listeners.
libpq applications submit LISTEN
, UNLISTEN
, and NOTIFY
commands as ordinary SQL commands. The arrival of NOTIFY
messages can subsequently be detected by calling PQnotifies
.
The function PQnotifies
returns the next notification from a list of unhandled notification messages received from the server. It returns a null pointer if there are no pending notifications. Once a notification is returned from PQnotifies
, it is considered handled and will be removed from the list of notifications.
PGnotify *PQnotifies(PGconn *conn); typedef struct pgNotify { char *relname; /* notification channel name */ int be_pid; /* process ID of notifying server process */ char *extra; /* notification payload string */ } PGnotify;
After processing a PGnotify
object returned by PQnotifies
, be sure to free it with PQfreemem
. It is sufficient to free the PGnotify
pointer; the relname
and extra
fields do not represent separate allocations. (The names of these fields are historical; in particular, channel names need not have anything to do with relation names.)
Example 33.2 gives a sample program that illustrates the use of asynchronous notification.
PQnotifies
does not actually read data from the server; it just returns messages previously absorbed by another libpq function. In ancient releases of libpq, the only way to ensure timely receipt of NOTIFY
messages was to constantly submit commands, even empty ones, and then check PQnotifies
after each PQexec
. While this still works, it is deprecated as a waste of processing power.
A better way to check for NOTIFY
messages when you have no useful commands to execute is to call PQconsumeInput
, then check PQnotifies
. You can use select()
to wait for data to arrive from the server, thereby using no CPU power unless there is something to do. (See PQsocket
to obtain the file descriptor number to use with select()
.) Note that this will work OK whether you submit commands with PQsendQuery
/PQgetResult
or simply use PQexec
. You should, however, remember to check PQnotifies
after each PQgetResult
or PQexec
, to see if any notifications came in during the processing of the command.