pg_recvlogical
pg_recvlogical — управлять потоками логического декодирования Postgres Pro
Синтаксис
pg_recvlogical [параметр...]
Описание
Утилита pg_recvlogical управляет слотами логического декодирования и принимает данные из таких слотов репликации.
Она создаёт соединение в режиме репликации, так что на него распространяются те же ограничения, что и с pg_receivewal, плюс ограничения логической репликации (см. Главу 51).
pg_recvlogical не предоставляет возможностей, соответствующих режимам peek и get в SQL-интерфейсе логического декодирования. Она передаёт серверу подтверждения воспроизведения данных по мере их получения и при штатном выходе. Чтобы просмотреть данные, ожидающие передачи через слот, не принимая их, воспользуйтесь функцией pg_logical_slot_peek_changes.
Когда утилита pg_recvlogical получает сигнал SIGHUP, она закрывает текущий выходной файл и открывает новый с именем файла, переданным с параметром --file. Таким образом обеспечивается ротация выходного файла сначала за счёт переименовывания текущего файла, а затем за счёт отправки сигнала SIGHUP утилите pg_recvlogical.
Параметры
Для выбора действия необходимо указать минимум один из этих параметров:
--create-slotСоздать новый слот логической репликации с именем, заданным аргументом
--slot, используя модуль вывода, заданный аргументом--plugin, для базы данных, указанной в--dbname.Вы можете использовать параметр
--two-phaseс--create-slot, чтобы включить декодирование подготовленных транзакций.--drop-slotУдалить слот репликации с именем, заданным аргументом
--slot, и завершиться.--startНачать приём потока изменений из слота логической репликации с именем, заданным аргументом
--slot, и продолжать до сигнала прерывания. Если передача потока прерывается на другой стороне из-за выключения или остановки сервера, цикл подключения и передачи повторяется (если не добавлен параметр--no-loop).Формат потока определяется модулем вывода, выбранным при создании слота.
Для получения потока подключаться нужно к той же базе, для которой создавался слот.
Параметры --create-slot и --start исключают друг друга. Действие --drop-slot несовместимо с любыми другими действиями.
Следующие параметры командной строки управляют расположением и форматом выводимых данных, а также другим поведением репликации:
-Elsn--endpos=lsnВ режиме
--startавтоматически закончить репликацию и выйти с кодом обычного завершения 0, когда при приёме данных достигается указанный LSN. Если этот ключ указывается не в режиме--start, выдаётся ошибка.Если встречается запись с LSN, в точности равным
lsn, эта запись будет выведена.С указанием
--endposграницы транзакций не отслеживаются, так что вывод программы может оказаться обрезанным посередине транзакции. Частично полученная транзакция не будет считаться принятой и будет воспроизведена заново при следующем чтении из этого слота. Отдельные сообщения не обрезаются никогда.-fимя_файла--file=имя_файлаЗаписывать полученные и декодированные данные транзакций в указанный файл. Для вывода в stdout укажите
-(минус).-Fсекунды--fsync-interval=секундыУстанавливает, как часто pg_recvlogical будет вызывать
fsync(), чтобы гарантировать, что выходной файл надёжно сохранён на диске.Сервер время от времени даёт клиенту команду сохранить данные и сообщить сохранённую позицию, но этот параметр позволяет выполнять сохранение чаще.
При значении, равном
0, функцияfsync()вообще не вызывается, но серверу сообщается новая позиция. Это может привести к потере данных в случае сбоя.-Ilsn--startpos=lsnВ режиме
--startрепликация начнётся с данного LSN. Как это работает, подробно описывается в Главе 51 и Разделе 57.4. В других режимах игнорируется.--if-not-existsНе выдавать ошибку, когда указан параметр
--create-slotи слот с заданным именем уже существует.-n--no-loopКогда подключение к серверу потеряно, не повторять цикл, просто завершить работу.
-oимя[=значение]--option=имя[=значение]Передаёт параметр
имя_параметрамодулю вывода, при этом может быть передано и егозначение. Набор параметров и их действия зависят от выбранного модуля вывода.-Pмодуль--plugin=модульИспользовать указанный модуль вывода логического декодирования при создании слота. См. Главу 51. Этот параметр не действует, если слот уже существует.
-sсекунды--status-interval=секундыЭтот параметр действует так же, как одноимённый параметр pg_receivewal (см. его описание там).
-Sимя_слота--slot=имя_слотаЭтот параметр задаёт имя слота логической репликации, который будет использоваться в режиме
--start, создаваться в режиме--create-slotили удаляться в режиме--drop-slot.-t--two-phaseВключает декодирование подготовленных транзакций. Этот параметр можно указать только с
--create-slot.-v--verboseВключает режим подробных сообщений.
Далее описаны параметры управления подключением.
-dимя_бд--dbname=имя_бдИмя базы данных для подключения. Как именно используется данная база, рассказывается в описании действий программы. В данном аргументе может задаваться строка подключения. В этом случае параметры в строке подключения переопределяют одноимённые параметры, заданные в командной строке. По умолчанию в качестве имени базы выбирается имя пользователя.
-hимя_компьютера-или-ip--host=имя_компьютера-или-ipУказывает имя компьютера, на котором работает сервер. Если значение начинается с косой черты, оно определяет каталог Unix-сокета. Значение по умолчанию берётся из переменной окружения
PGHOST, если она установлена. В противном случае выполняется подключение к Unix-сокету.-pпорт--port=портУказывает TCP-порт или расширение файла локального Unix-сокета, через который сервер принимает подключения. Значение по умолчанию определяется переменной окружения
PGPORT, если она установлена, либо числом, заданным при компиляции.-Uuser--username=userИмя пользователя для подключения. По умолчанию это имя текущего пользователя операционной системы.
-w--no-passwordНе выдавать запрос на ввод пароля. Если сервер требует аутентификацию по паролю и пароль не доступен с помощью других средств, таких как файл
.pgpass, попытка соединения не удастся. Этот параметр может быть полезен в пакетных заданиях и скриптах, где нет пользователя, который вводит пароль.-W--passwordПринудительно запрашивать пароль перед подключением к базе данных.
Это несущественный параметр, так как pg_recvlogical запрашивает пароль автоматически, если сервер проверяет подлинность по паролю. Однако чтобы понять это, pg_recvlogical лишний раз подключается к серверу. Поэтому иногда имеет смысл ввести
-W, чтобы исключить эту ненужную попытку подключения.
Также есть следующие дополнительные параметры:
-V--versionСообщить версию pg_recvlogical и завершиться.
-?--helpПоказать справку по аргументам командной строки pg_recvlogical и завершиться.
Переменные окружения
Как и большинство других утилит Postgres Pro, приложение также использует переменные окружения, поддерживаемые libpq (см. Раздел 36.15).
Переменная окружения PG_COLOR выбирает вариант использования цвета в диагностических сообщениях. Возможные значения: always (всегда), auto (автоматически) и never (никогда).
Примечания
pg_recvlogical сохранит разрешения для группы в полученных файлах WAL, если такие разрешения установлены в исходном кластере.
Примеры
Примеры использования можно найти в Разделе 51.1.
См. также
pg_receivewalpg_recvlogical
pg_recvlogical — control Postgres Pro logical decoding streams
Synopsis
pg_recvlogical [option...]
Description
pg_recvlogical controls logical decoding replication slots and streams data from such replication slots.
It creates a replication-mode connection, so it is subject to the same constraints as pg_receivewal, plus those for logical replication (see Chapter 51).
pg_recvlogical has no equivalent to the logical decoding SQL interface's peek and get modes. It sends replay confirmations for data lazily as it receives it and on clean exit. To examine pending data on a slot without consuming it, use pg_logical_slot_peek_changes.
When pg_recvlogical receives a SIGHUP signal, it closes the current output file and opens a new one using the filename specified by the --file option. This allows us to rotate the output file by first renaming the current file and then sending a SIGHUP signal to pg_recvlogical.
Options
At least one of the following options must be specified to select an action:
--create-slotCreate a new logical replication slot with the name specified by
--slot, using the output plugin specified by--plugin, for the database specified by--dbname.The
--two-phasecan be specified with--create-slotto enable decoding of prepared transactions.--drop-slotDrop the replication slot with the name specified by
--slot, then exit.--startBegin streaming changes from the logical replication slot specified by
--slot, continuing until terminated by a signal. If the server side change stream ends with a server shutdown or disconnect, retry in a loop unless--no-loopis specified.The stream format is determined by the output plugin specified when the slot was created.
The connection must be to the same database used to create the slot.
--create-slot and --start can be specified together. --drop-slot cannot be combined with another action.
The following command-line options control the location and format of the output and other replication behavior:
-Elsn--endpos=lsnIn
--startmode, automatically stop replication and exit with normal exit status 0 when receiving reaches the specified LSN. If specified when not in--startmode, an error is raised.If there's a record with LSN exactly equal to
lsn, the record will be output.The
--endposoption is not aware of transaction boundaries and may truncate output partway through a transaction. Any partially output transaction will not be consumed and will be replayed again when the slot is next read from. Individual messages are never truncated.-ffilename--file=filenameWrite received and decoded transaction data into this file. Use
-for stdout.-Finterval_seconds--fsync-interval=interval_secondsSpecifies how often pg_recvlogical should issue
fsync()calls to ensure the output file is safely flushed to disk.The server will occasionally request the client to perform a flush and report the flush position to the server. This setting is in addition to that, to perform flushes more frequently.
Specifying an interval of
0disables issuingfsync()calls altogether, while still reporting progress to the server. In this case, data could be lost in the event of a crash.-Ilsn--startpos=lsnIn
--startmode, start replication from the given LSN. For details on the effect of this, see the documentation in Chapter 51 and Section 57.4. Ignored in other modes.--if-not-existsDo not error out when
--create-slotis specified and a slot with the specified name already exists.-n--no-loopWhen the connection to the server is lost, do not retry in a loop, just exit.
-oname[=value]--option=name[=value]Pass the option
nameto the output plugin with, if specified, the option valuevalue. Which options exist and their effects depends on the used output plugin.-Pplugin--plugin=pluginWhen creating a slot, use the specified logical decoding output plugin. See Chapter 51. This option has no effect if the slot already exists.
-sinterval_seconds--status-interval=interval_secondsThis option has the same effect as the option of the same name in pg_receivewal. See the description there.
-Sslot_name--slot=slot_nameIn
--startmode, use the existing logical replication slot namedslot_name. In--create-slotmode, create the slot with this name. In--drop-slotmode, delete the slot with this name.-t--two-phaseEnables decoding of prepared transactions. This option may only be specified with
--create-slot-v--verboseEnables verbose mode.
The following command-line options control the database connection parameters.
-ddbname--dbname=dbnameThe database to connect to. See the description of the actions for what this means in detail. The
dbnamecan be a connection string. If so, connection string parameters will override any conflicting command line options. Defaults to the user name.-hhostname-or-ip--host=hostname-or-ipSpecifies the host name of the machine on which the server is running. If the value begins with a slash, it is used as the directory for the Unix domain socket. The default is taken from the
PGHOSTenvironment variable, if set, else a Unix domain socket connection is attempted.-pport--port=portSpecifies the TCP port or local Unix domain socket file extension on which the server is listening for connections. Defaults to the
PGPORTenvironment variable, if set, or a compiled-in default.-Uuser--username=userUser name to connect as. Defaults to current operating system user name.
-w--no-passwordNever issue a password prompt. If the server requires password authentication and a password is not available by other means such as a
.pgpassfile, the connection attempt will fail. This option can be useful in batch jobs and scripts where no user is present to enter a password.-W--passwordForce pg_recvlogical to prompt for a password before connecting to a database.
This option is never essential, since pg_recvlogical will automatically prompt for a password if the server demands password authentication. However, pg_recvlogical will waste a connection attempt finding out that the server wants a password. In some cases it is worth typing
-Wto avoid the extra connection attempt.
The following additional options are available:
-V--versionPrint the pg_recvlogical version and exit.
-?--helpShow help about pg_recvlogical command line arguments, and exit.
Environment
This utility, like most other Postgres Pro utilities, uses the environment variables supported by libpq (see Section 36.15).
The environment variable PG_COLOR specifies whether to use color in diagnostic messages. Possible values are always, auto and never.
Notes
pg_recvlogical will preserve group permissions on the received WAL files if group permissions are enabled on the source cluster.
Examples
See Section 51.1 for an example.