pg_recvlogical
Описание
Утилита pg_recvlogical управляет слотами логического декодирования и принимает данные из таких слотов репликации.
Она создаёт соединение в режиме репликации, так что на него распространяются те же ограничения, что и с pg_receivexlog, плюс ограничения логической репликации (см. Главу 46).
Параметры
Для выбора действия необходимо указать минимум один из этих параметров:
- --create-slot
Создать новый слот логической репликации с именем, заданным аргументом --slot, используя модуль вывода, заданный аргументом --plugin, для базы данных, указанной в --dbname.
- --drop-slot
Удалить слот репликации с именем, заданным аргументом --slot, и завершиться.
- --start
Начать приём потока изменений из слота логической репликации с именем, заданным аргументом --slot, и продолжать до сигнала прерывания. Если передача потока прерывается на другой стороне из-за выключения или остановки сервера, цикл подключения и передачи повторяется (если не добавлен параметр --no-loop).
Формат потока определяется модулем вывода, выбранным при создании слота.
Для получения потока подключаться нужно к той же базе, для которой создавался слот.
Параметры --create-slot и --start исключают друг друга. Действие --drop-slot несовместимо с любыми другими действиями.
Следующие параметры командной строки управляют расположением и форматом выводимых данных, а также другим поведением репликации:
- -f имя_файла
--file=имя_файла Записывать полученные и декодированные данные транзакций в указанный файл. Для вывода в stdout укажите - (минус).
- -F секунды
--fsync-interval=секунды Устанавливает, как часто pg_recvlogical будет вызывать
fsync(), чтобы гарантировать, что выходной файл надёжно сохранён на диске.Сервер время от времени даёт клиенту команду сохранить данные и сообщить сохранённую позицию, но этот параметр позволяет выполнять сохранение чаще.
При значении, равном 0, функция
fsync()вообще не вызывается, но серверу сообщается новая позиция. Это может привести к потере данных в случае сбоя.- -I lsn
--startpos=lsn В режиме --start репликация начнётся с данного LSN. Как это работает, подробно описывается в Главе 46 и Разделе 49.3. В других режимах игнорируется.
- -n
--no-loop Когда подключение к серверу потеряно, не повторять цикл, просто завершить работу.
- -o имя[=значение]
--option=имя[=значение] Передаёт параметр имя_параметра модулю вывода, при этом может быть передано и его значение. Набор параметров и их действия зависят от выбранного модуля вывода.
- -P модуль
--plugin=модуль Использовать указанный модуль вывода логического декодирования при создании слота. См. Главу 46. Этот параметр не действует, если слот уже существует.
- -s секунды
--status-interval=секунды Этот параметр действует так же, как одноимённый параметр pg_receivexlog (см. его описание там).
- -S имя_слота
--slot=имя_слота Этот параметр задаёт имя слота логической репликации, который будет использоваться в режиме --start, создаваться в режиме --create-slot или удаляться в режиме --drop-slot.
- -v
--verbose Включает режим подробных сообщений.
Далее описаны параметры управления подключением.
- -d database
--dbname=database Этот параметр выбирает базу данных для подключения. Как именно она используется, можно узнать в описании соответствующих действий. Это может быть строка подключения libpq; за дополнительными сведениями обратитесь к Подразделу 31.1.1. По умолчанию её имя определяется именем пользователя.
- -h имя_компьютера-или-ip
--host=имя_компьютера-или-ip Указывает имя компьютера, на котором запущен сервер. Если значение начинается с косой черты, оно интерпретируется как имя каталога с доменным сокетом Unix. Значение по умолчанию берётся из переменной окружения PGHOST, если она установлена. В противном случае выполняется подключение к доменному сокету.
- -p порт
--port=порт Указывает TCP-порт или расширение локального файла Unix-сокета, на котором сервер слушает подключения. По умолчанию берётся значение переменной окружения PGPORT, если оно установлено, либо значение времени компиляции.
- -U user
--username=user Имя пользователя для подключения. По умолчанию это имя текущего пользователя операционной системы.
- -w
--no-password Не выдавать запрос на ввод пароля. Если сервер требует аутентификацию по паролю и пароль не доступен с помощью других средств, таких как файл .pgpass, попытка соединения не удастся. Этот параметр может быть полезен в пакетных заданиях и скриптах, где нет пользователя, который вводит пароль.
- -W
--password Принудительно запрашивать пароль перед подключением к базе данных.
Это несущественный параметр, так как pg_recvlogical запрашивает пароль автоматически, если сервер проверяет подлинность по паролю. Однако, чтобы понять это, pg_recvlogical лишний раз подключается к серверу. Поэтому иногда имеет смысл ввести -W, чтобы исключить эту ненужную попытку подключения.
Также есть следующие дополнительные параметры:
- -V
--version Сообщить версию pg_recvlogical и завершиться.
- -?
--help Показать справку по аргументам командной строки pg_recvlogical и завершиться.
Переменные окружения
Как и большинство других утилит PostgreSQL, приложение также использует переменные окружения, поддерживаемые libpq (см. Раздел 31.14).
| Пред. | Начало | След. |
| pg_receivexlog | Уровень выше | pg_restore |
pg_recvlogical
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_receivexlog, plus those for logical replication (see Chapter 46).
Options
At least one of the following options must be specified to select an action:
- --create-slot
Create a new logical replication slot with the name specified by --slot, using the output plugin specified by --plugin, for the database specified by --dbname.
- --drop-slot
Drop the replication slot with the name specified by --slot, then exit.
- --start
Begin 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-loop is 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:
- -f filename
--file=filename Write received and decoded transaction data into this file. Use - for stdout.
- -F interval_seconds
--fsync-interval=interval_seconds Specifies 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 0 disables issuing
fsync()calls altogether, while still reporting progress to the server. In this case, data could be lost in the event of a crash.- -I lsn
--startpos=lsn In --start mode, start replication from the given LSN. For details on the effect of this, see the documentation in Chapter 46 and Section 49.3. Ignored in other modes.
- -n
--no-loop When the connection to the server is lost, do not retry in a loop, just exit.
- -o name[=value]
--option=name[=value] Pass the option name to the output plugin with, if specified, the option value value. Which options exist and their effects depends on the used output plugin.
- -P plugin
--plugin=plugin When creating a slot, use the specified logical decoding output plugin. See Chapter 46. This option has no effect if the slot already exists.
- -s interval_seconds
--status-interval=interval_seconds This option has the same effect as the option of the same name in pg_receivexlog. See the description there.
- -S slot_name
--slot=slot_name In --start mode, use the existing logical replication slot named slot_name. In --create-slot mode, create the slot with this name. In --drop-slot mode, delete the slot with this name.
- -v
--verbose Enables verbose mode.
The following command-line options control the database connection parameters.
- -d database
--dbname=database The database to connect to. See the description of the actions for what this means in detail. This can be a libpq connection string; see Section 31.1.1 for more information. Defaults to user name.
- -h hostname-or-ip
--host=hostname-or-ip Specifies 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 PGHOST environment variable, if set, else a Unix domain socket connection is attempted.
- -p port
--port=port Specifies the TCP port or local Unix domain socket file extension on which the server is listening for connections. Defaults to the PGPORT environment variable, if set, or a compiled-in default.
- -U user
--username=user Username to connect as. Defaults to current operating system user name.
- -w
--no-password Never issue a password prompt. If the server requires password authentication and a password is not available by other means such as a .pgpass file, 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
--password Force 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 -W to avoid the extra connection attempt.
The following additional options are available:
- -V
--version Print the pg_recvlogical version and exit.
- -?
--help Show help about pg_recvlogical command line arguments, and exit.
Environment
This utility, like most other PostgreSQL utilities, uses the environment variables supported by libpq (see Section 31.14).