ecpg
ecpg — встроенный C-препроцессор SQL
Синтаксис
ecpg [параметр...] файл...
Описание
ecpg — это встроенный SQL препроцессор для программ, написанных на языке C. Он преобразует программы на C, содержащие SQL-выражения, заменяя их вызовами встроенных функций. Получаемые на выходе файлы можно затем скомпилировать и скомпоновать.
ecpg преобразует каждый файл, переданный в параметрах, в соответствующий файл на C. Если имя входного файла указано без расширения, подразумевается .pgc. Указанное имя, но с расширением .c, становится по умолчанию именем выходного файла. Переопределить имя выходного файла можно, воспользовавшись параметром -o.
Если в качестве имени входного файла указано -, ecpg читает программу с устройства стандартного ввода (и выводит результат в стандартный вывод, если не задан параметр -o).
Данный раздел не содержит описания встроенного SQL-языка. Для более подробной информации см. Главу 34.
Параметры
ecpg принимает в качестве аргументов:
-cАвтоматически генерировать код, написанный на языке C, из кода SQL. Сейчас это справедливо для
EXEC SQL TYPE.-CрежимУстановить режим совместимости;
режимможет принимать значения:INFORMIX,INFORMIX_SEиORACLE.-Dсимвол[=значение]Определить символ начала команд препроцессора, аналогично использованию директивы
EXEC SQL DEFINE. Еслизначениене указано, символ определяется1.-hОбрабатывать заголовочные файлы. Когда добавляется этот параметр, расширением выходного файла становится не
.c, а.h, и расширением входного файла по умолчанию считается не.pgc, а.pgh. Кроме этого с данным параметром подразумевается-c.-iТакже разбирать и системные включения.
-IкаталогУказать дополнительный путь включаемых файлов, используемый при выполнении
EXEC SQL INCLUDE. По умолчанию используются.(текущий каталог),/usr/local/include, каталог, задаваемый при компиляции PostgreSQL (обычно —/usr/local/pgsql/include), и/usr/include, в порядке, как это перечислено.-oимя_файлаЗадаёт
имя файла, в который программаecpgдолжна выводить результат. Указание-o -направляет результат в устройство стандартного вывода.-rпараметрОпределяет поведение времени выполнения.
Флагможет принимать следующие значения:no_indicatorИспользовать специальные символы для представления значений null. Исторически некоторые базы данных используют такой подход.
prepareСформировать подготовленные выражения. libecpg сформирует кеш подготовленных выражений и будет использовать их при необходимости повторно. В случае переполнения кеша, libecpg освободит память за счёт вытеснения наименее используемых выражений.
questionmarksРазрешает использовать знак вопроса в качестве аргумента подстановки в целях совместимости. Ранее это было поведением по умолчанию.
-tВключить автоматическую фиксацию транзакций. В этом режиме каждая SQL-команда будет автоматически фиксироваться, пока не будет явно включена в блок транзакции. В режиме по умолчанию команды фиксируются лишь при явном вызове
EXEC SQL COMMIT.-vВывести информацию о версии, а также путях поиска включаемых файлов.
--versionВывести версию ecpg.
-?--helpВывести справку по команде ecpg.
Примечания
При компиляции полученных файлов, компилятор должен иметь возможность найти заголовочные файлы ECPG в каталоге включений PostgreSQL. Для этого можно использовать флаг -I во время компиляции, например, -I/usr/local/pgsql/include.
Программы на C со встроенным SQL необходимо скомпоновать с библиотекой libecpg, например, используя флаг компоновщика -L/usr/local/pgsql/lib -lecpg.
Имена каталогов, подходящих для установки, можно найти в разделе pg_config.
Примеры
Если имеется исходный файл на C prog1.pgc со встроенным SQL, можно создать исполняемую программу, используя следующую последовательность команд:
ecpg prog1.pgc cc -I/usr/local/pgsql/include -c prog1.c cc -o prog1 prog1.o -L/usr/local/pgsql/lib -lecpg
ecpg
ecpg — embedded SQL C preprocessor
Synopsis
ecpg [option...] file...
Description
ecpg is the embedded SQL preprocessor for C programs. It converts C programs with embedded SQL statements to normal C code by replacing the SQL invocations with special function calls. The output files can then be processed with any C compiler tool chain.
ecpg will convert each input file given on the command line to the corresponding C output file. If an input file name does not have any extension, .pgc is assumed. The file's extension will be replaced by .c to construct the output file name. But the output file name can be overridden using the -o option.
If an input file name is just -, ecpg reads the program from standard input (and writes to standard output, unless that is overridden with -o).
This reference page does not describe the embedded SQL language. See Chapter 34 for more information on that topic.
Options
ecpg accepts the following command-line arguments:
-cAutomatically generate certain C code from SQL code. Currently, this works for
EXEC SQL TYPE.-CmodeSet a compatibility mode.
modecan beINFORMIX,INFORMIX_SE, orORACLE.-Dsymbol[=value]Define a preprocessor symbol, equivalently to the
EXEC SQL DEFINEdirective. If novalueis specified, the symbol is defined with the value1.-hProcess header files. When this option is specified, the output file extension becomes
.hnot.c, and the default input file extension is.pghnot.pgc. Also, the-coption is forced on.-iParse system include files as well.
-IdirectorySpecify an additional include path, used to find files included via
EXEC SQL INCLUDE. Defaults are.(current directory),/usr/local/include, the PostgreSQL include directory which is defined at compile time (default:/usr/local/pgsql/include), and/usr/include, in that order.-ofilenameSpecifies that
ecpgshould write all its output to the givenfilename. Write-o -to send all output to standard output.-roptionSelects run-time behavior.
Optioncan be one of the following:no_indicatorDo not use indicators but instead use special values to represent null values. Historically there have been databases using this approach.
preparePrepare all statements before using them. Libecpg will keep a cache of prepared statements and reuse a statement if it gets executed again. If the cache runs full, libecpg will free the least used statement.
questionmarksAllow question mark as placeholder for compatibility reasons. This used to be the default long ago.
-tTurn on autocommit of transactions. In this mode, each SQL command is automatically committed unless it is inside an explicit transaction block. In the default mode, commands are committed only when
EXEC SQL COMMITis issued.-vPrint additional information including the version and the "include" path.
--versionPrint the ecpg version and exit.
-?--helpShow help about ecpg command line arguments, and exit.
Notes
When compiling the preprocessed C code files, the compiler needs to be able to find the ECPG header files in the PostgreSQL include directory. Therefore, you might have to use the -I option when invoking the compiler (e.g., -I/usr/local/pgsql/include).
Programs using C code with embedded SQL have to be linked against the libecpg library, for example using the linker options -L/usr/local/pgsql/lib -lecpg.
The value of either of these directories that is appropriate for the installation can be found out using pg_config.
Examples
If you have an embedded SQL C source file named prog1.pgc, you can create an executable program using the following sequence of commands:
ecpg prog1.pgc cc -I/usr/local/pgsql/include -c prog1.c cc -o prog1 prog1.o -L/usr/local/pgsql/lib -lecpg