F.22. file_fdw — обращение к файлам данных в файловой системе сервера #
Модуль file_fdw реализует обёртку сторонних данных file_fdw, с помощью которой можно обращаться к файлам данных в файловой системе сервера или выполнять программы на сервере и читать их вывод. Файлы и вывод программ должны быть в формате, который понимает команда COPY FROM; он рассматривается в описании COPY. В настоящее время файлы доступны только для чтения.
Для сторонней таблицы, создаваемой через эту обёртку, можно задать следующие параметры:
filenameОпределяет имя файла, который нужно прочитать. При указании относительного пути он рассматривается от каталога данных. Вы должны определить либо параметр
filename, либоprogram, но не оба сразу.programОпределяет команду, которая будет выполнена. Поток стандартного вывода этой команды будет прочитан так же, как и с
COPY FROM PROGRAM. Необходимо определить либо параметрprogram, либоfilename, но не оба сразу.formatОпределяет формат файла (аналогично указанию
FORMATв командеCOPY).headerУказывает, что данные содержат строку заголовка с именами столбцов (аналогично указанию
HEADERв командеCOPY).delimiterЗадаёт символ, разделяющий столбцы в данных (аналогично указанию
DELIMITERв командеCOPY).quoteЗадаёт символ, используемый для заключения данных в кавычки (аналогично указанию
QUOTEв командеCOPY).escapeЗадаёт символ, используемый для экранирования данных (аналогично указанию
ESCAPEв командеCOPY).nullОпределяет строку, задающую значение
NULLв данных (аналогично указаниюNULLв командеCOPY).defaultЗадаёт строку, представляющую значение по умолчанию, аналогично указанию
DEFAULTв командеCOPY.encodingЗадаёт кодировку данных (аналогично указанию
ENCODINGв командеCOPY).on_errorУказывает, как обрабатывать ошибку при преобразовании входящих значений в тип данных столбца (аналогично указанию
ON_ERRORкомандыCOPY).reject_limitОпределяет максимально допустимое число ошибок при преобразовании входных значений столбца к его типу данных (аналогично указанию
REJECT_LIMITкомандыCOPY).log_verbosityУказывает количество сообщений, выводимых
file_fdw(аналогично указаниюLOG_VERBOSITYкомандыCOPY).
Заметьте, что хотя COPY принимает указания, такие как HEADER, без соответствующего значения, синтаксис обёртки сторонних данных требует, чтобы значение присутствовало во всех случаях. Чтобы активировать указания COPY, которым значение обычно не передаётся, им можно просто передать значение TRUE, так как все они являются логическими.
Для столбцов сторонней таблицы, создаваемой через эту обёртку, можно задать следующие параметры:
force_not_nullЛогическое значение. Если true, то значение столбца не должно сверяться со значением NULL (заданным в параметре
nullна уровне таблицы). Аналогично включению столбца в список указанияFORCE_NOT_NULLкомандыCOPY.force_nullЛогическое значение. Если true, значения столбцов нужно сверять со значением NULL (заданным в параметре
NULL), даже если они заключены в кавычки. Без этого параметра только значения без кавычек, соответствующие значениюnull, будут возвращаться как NULL. Аналогично включению столбца в список указанияFORCE_NULLкомандыCOPY.
В настоящее время file_fdw не поддерживает указание FORCE_QUOTE команды COPY.
Перечисленные параметры применимы только для сторонних таблиц или их столбцов. Их нельзя указать для обёртки сторонних данных file_fdw, серверов или сопоставлений пользователей, использующих эту обёртку.
Для изменения параметров, определяемых для таблицы, требуется быть суперпользователем или иметь права роли pg_read_server_files (для указания имени файла) или роли pg_execute_server_program (для указания программы). Это сделано в целях безопасности: только избранные пользователи должны выбирать, какой файл читать или какую программу запускать. В принципе право изменения остальных параметров можно предоставить и обычным пользователям, но в настоящий момент это не реализовано.
Задавая параметр program, помните, что эта строка выполняется оболочкой ОС. Если вы хотите передавать заданной команде параметры из недоверенного источника, позаботьтесь об исключении или экранировании всех символов, которые могут иметь особое назначение в оболочке. По соображениям безопасности лучше, чтобы эта командная строка была фиксированной или как минимум в ней не передавались данные, поступающие от пользователя.
Для сторонних таблиц, работающих через file_fdw, команда EXPLAIN показывает имя используемого файла или запускаемой программы. Если не указывать COSTS OFF, то выводится и размер файла (в байтах).
Пример F.6. Создание сторонней таблицы для журнала сервера Postgres Pro
Одно из очевидных применений file_fdw — это предоставление доступа к журналу сообщений Postgres Pro как к таблице. Для этого необходимо предварительно настроить вывод сообщений в файл CSV (дальше мы будем считать, что это файл pglog.csv). Сначала установите расширение file_fdw:
CREATE EXTENSION file_fdw;
Затем создайте сторонний сервер:
CREATE SERVER pglog FOREIGN DATA WRAPPER file_fdw;
Всё готово для создания сторонней таблицы. В команде CREATE FOREIGN TABLE нужно перечислить столбцы таблицы, указать файл CSV и его формат:
CREATE FOREIGN TABLE pglog ( log_time timestamp(3) with time zone, user_name text, database_name text, process_id integer, connection_from text, session_id text, session_line_num bigint, command_tag text, session_start_time timestamp with time zone, virtual_transaction_id text, transaction_id bigint, error_severity text, sql_state_code text, message text, detail text, hint text, internal_query text, internal_query_pos integer, context text, query text, query_pos integer, location text, application_name text, backend_type text, leader_pid integer, query_id bigint ) SERVER pglog OPTIONS ( filename 'log/pglog.csv', format 'csv' );
Вот и всё. Теперь для просмотра журнала сервера можно просто выполнять запросы к таблице. В производственной среде, разумеется, ещё потребуется как-то учесть ротацию файлов журнала.
Пример F.7. Создать внешнюю таблицу с параметром для столбца
Чтобы задать параметр force_null для столбца, используйте ключевое слово OPTIONS.
CREATE FOREIGN TABLE films ( code char(5) NOT NULL, title text NOT NULL, rating text OPTIONS (force_null 'true') ) SERVER film_server OPTIONS ( filename 'films/db.csv', format 'csv' );
F.22. file_fdw — access data files in the server's file system #
The file_fdw module provides the foreign-data wrapper file_fdw, which can be used to access data files in the server's file system, or to execute programs on the server and read their output. The data file or program output must be in a format that can be read by COPY FROM; see COPY for details. Access to data files is currently read-only.
A foreign table created using this wrapper can have the following options:
filenameSpecifies the file to be read. Relative paths are relative to the data directory. Either
filenameorprogrammust be specified, but not both.programSpecifies the command to be executed. The standard output of this command will be read as though
COPY FROM PROGRAMwere used. Eitherprogramorfilenamemust be specified, but not both.formatSpecifies the data format, the same as
COPY'sFORMAToption.headerSpecifies whether the data has a header line, the same as
COPY'sHEADERoption.delimiterSpecifies the data delimiter character, the same as
COPY'sDELIMITERoption.quoteSpecifies the data quote character, the same as
COPY'sQUOTEoption.escapeSpecifies the data escape character, the same as
COPY'sESCAPEoption.nullSpecifies the data null string, the same as
COPY'sNULLoption.defaultSpecifies the string that represents a default value, the same as
COPY'sDEFAULToption.encodingSpecifies the data encoding, the same as
COPY'sENCODINGoption.on_errorSpecifies how to behave when encountering an error converting a column's input value into its data type, the same as
COPY'sON_ERRORoption.reject_limitSpecifies the maximum number of errors tolerated while converting a column's input value to its data type, the same as
COPY'sREJECT_LIMIToption.log_verbositySpecifies the amount of messages emitted by
file_fdw, the same asCOPY'sLOG_VERBOSITYoption.
Note that while COPY allows options such as HEADER to be specified without a corresponding value, the foreign table option syntax requires a value to be present in all cases. To activate COPY options typically written without a value, you can pass the value TRUE, since all such options are Booleans.
A column of a foreign table created using this wrapper can have the following options:
force_not_nullThis is a Boolean option. If true, it specifies that values of the column should not be matched against the null string (that is, the table-level
nulloption). This has the same effect as listing the column inCOPY'sFORCE_NOT_NULLoption.force_nullThis is a Boolean option. If true, it specifies that values of the column which match the null string are returned as
NULLeven if the value is quoted. Without this option, only unquoted values matching the null string are returned asNULL. This has the same effect as listing the column inCOPY'sFORCE_NULLoption.
COPY's FORCE_QUOTE option is currently not supported by file_fdw.
These options can only be specified for a foreign table or its columns, not in the options of the file_fdw foreign-data wrapper, nor in the options of a server or user mapping using the wrapper.
Changing table-level options requires being a superuser or having the privileges of the role pg_read_server_files (to use a filename) or the role pg_execute_server_program (to use a program), for security reasons: only certain users should be able to control which file is read or which program is run. In principle regular users could be allowed to change the other options, but that's not supported at present.
When specifying the program option, keep in mind that the option string is executed by the shell. If you need to pass any arguments to the command that come from an untrusted source, you must be careful to strip or escape any characters that might have special meaning to the shell. For security reasons, it is best to use a fixed command string, or at least avoid passing any user input in it.
For a foreign table using file_fdw, EXPLAIN shows the name of the file to be read or program to be run. For a file, unless COSTS OFF is specified, the file size (in bytes) is shown as well.
Example F.6. Create a Foreign Table for Postgres Pro CSV Logs
One of the obvious uses for file_fdw is to make the Postgres Pro activity log available as a table for querying. To do this, first you must be logging to a CSV file, which here we will call pglog.csv. First, install file_fdw as an extension:
CREATE EXTENSION file_fdw;
Then create a foreign server:
CREATE SERVER pglog FOREIGN DATA WRAPPER file_fdw;
Now you are ready to create the foreign data table. Using the CREATE FOREIGN TABLE command, you will need to define the columns for the table, the CSV file name, and its format:
CREATE FOREIGN TABLE pglog ( log_time timestamp(3) with time zone, user_name text, database_name text, process_id integer, connection_from text, session_id text, session_line_num bigint, command_tag text, session_start_time timestamp with time zone, virtual_transaction_id text, transaction_id bigint, error_severity text, sql_state_code text, message text, detail text, hint text, internal_query text, internal_query_pos integer, context text, query text, query_pos integer, location text, application_name text, backend_type text, leader_pid integer, query_id bigint ) SERVER pglog OPTIONS ( filename 'log/pglog.csv', format 'csv' );
That's it — now you can query your log directly. In production, of course, you would need to define some way to deal with log rotation.
Example F.7. Create a Foreign Table with an Option on a Column
To set the force_null option for a column, use the OPTIONS keyword.
CREATE FOREIGN TABLE films ( code char(5) NOT NULL, title text NOT NULL, rating text OPTIONS (force_null 'true') ) SERVER film_server OPTIONS ( filename 'films/db.csv', format 'csv' );