F.19. file_fdw
Модуль file_fdw реализует обёртку сторонних данных file_fdw для доступа к файлам на сервере. Файлы должны быть в формате, который понимает команда COPY FROM; он рассматривается в описании COPY. В настоящий момент файлы доступны только для чтения.
Для сторонней таблицы, создаваемой через эту обёртку, можно задать следующие параметры:
filenameИмя файла данных. Указывается обязательно. При указании относительного пути он рассматривается от каталога данных.
formatФормат файла. Аналогично указанию
FORMATв командеCOPY.headerПоказывает, что файл содержит строку заголовка с именами столбцов. Аналогично указанию
HEADERв командеCOPY.delimiterЗадаёт символ, разделяющий столбцы в строках файла. Аналогично указанию
DELIMITERв командеCOPY.quoteЗадаёт символ, используемый для заключения данных в кавычки. Аналогично указанию
QUOTEв командеCOPY.escapeЗадаёт символ, который будет выводиться перед символом данных, совпавшим со значением
QUOTE. Аналогично указаниюESCAPEв командеCOPY.nullОпределяет строку, задающую значение
NULL. Аналогично указаниюNULLв командеCOPY.encodingЗадаёт кодировку файла. Аналогично указанию
ENCODINGв командеCOPY.
Заметьте, что хотя COPY принимает указания, такие как OIDS и 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 не поддерживает указания OIDS и FORCE_QUOTE команды COPY.
Перечисленные параметры применимы только для сторонних таблиц или их столбцов. Их нельзя указать для обёртки сторонних данных file_fdw, серверов или сопоставлений пользователей, использующих эту обёртку.
Для изменения параметров, определяемых для таблицы, требуются права суперпользователя. Это сделано в целях безопасности: только суперпользователь должен решать, какой файл использовать. В принципе, доступ на изменение остальных параметров можно предоставить и не суперпользователям, но в настоящий момент это не реализовано.
Для сторонних таблиц, работающих через file_fdw, команда EXPLAIN показывает имя используемого файла. Если не указывать COSTS OFF, то выводится и размер файла (в байтах).
Пример F.1. Создание сторонней таблицы для журнала сервера 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 ) SERVER pglog OPTIONS ( filename '/home/josh/9.1/data/pg_log/pglog.csv', format 'csv' );
Вот и всё. Теперь для просмотра журнала сервера можно просто выполнять запросы к таблице. В производственной среде, разумеется, ещё потребуется как-то учесть ротацию файлов журнала.
F.19. file_fdw
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. Data files must be in a format that can be read by COPY FROM; see COPY for details. Access to such data files is currently read-only.
A foreign table created using this wrapper can have the following options:
filenameSpecifies the file to be read. Required. Relative paths are relative to the data directory.
formatSpecifies the file's format, the same as
COPY'sFORMAToption.headerSpecifies whether the file has a header line, the same as
COPY'sHEADERoption.delimiterSpecifies the file's delimiter character, the same as
COPY'sDELIMITERoption.quoteSpecifies the file's quote character, the same as
COPY'sQUOTEoption.escapeSpecifies the file's escape character, the same as
COPY'sESCAPEoption.nullSpecifies the file's null string, the same as
COPY'sNULLoption.encodingSpecifies the file's encoding, the same as
COPY'sENCODINGoption.
Note that while COPY allows options such as OIDS and HEADER to be specified without a corresponding value, the foreign data wrapper syntax requires a value to be present in all cases. To activate COPY options normally supplied without a value, you can instead pass the value TRUE.
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 file-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 OIDS and FORCE_QUOTE options are 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 superuser privileges, for security reasons: only a superuser should be able to determine which file is read. In principle non-superusers could be allowed to change the other options, but that's not supported at present.
For a foreign table using file_fdw, EXPLAIN shows the name of the file to be read. Unless COSTS OFF is specified, the file size (in bytes) is shown as well.
Example F.1. 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 ) SERVER pglog OPTIONS ( filename '/home/josh/9.1/data/pg_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.