Postgresql 中文操作指南

36.10. Processing Embedded SQL Programs #

现在您已经了解如何形成嵌入式 SQL C 程序,您可能想知道如何编译它们。编译之前,通过嵌入式 SQL C 预处理器运行该文件,该预处理器将您用来调用特殊函数的 SQL 语句转换。编译后,您必须链接一个包含所需函数的特殊库。这些函数从参数中获取信息,利用 libpq 接口执行 SQL 命令,并将结果放到指定为输出的参数中。

Now that you have an idea how to form embedded SQL C programs, you probably want to know how to compile them. Before compiling you run the file through the embedded SQL C preprocessor, which converts the SQL statements you used to special function calls. After compiling, you must link with a special library that contains the needed functions. These functions fetch information from the arguments, perform the SQL command using the libpq interface, and put the result in the arguments specified for output.

预处理器程序称为 ecpg,并包含在正常的 PostgreSQL 安装中。嵌入式 SQL 程序通常以 .pgc 扩展命名。如果您有一个名为 prog1.pgc 的程序文件,可通过简单调用以下命令对其进行预处理:

The preprocessor program is called ecpg and is included in a normal PostgreSQL installation. Embedded SQL programs are typically named with an extension .pgc. If you have a program file called prog1.pgc, you can preprocess it by simply calling:

ecpg prog1.pgc

这将创建一个名为 prog1.c 的文件。如果您的输入文件不遵循建议的命名模式,则可以使用 -o 选项显式指定输出文件。

This will create a file called prog1.c. If your input files do not follow the suggested naming pattern, you can specify the output file explicitly using the -o option.

可以对预处理过的文件进行正常编译,例如:

The preprocessed file can be compiled normally, for example:

cc -c prog1.c

生成的 C 源文件包含 PostgreSQL 安装中的头文件,因此,如果您将 PostgreSQL 安装在默认情况下未搜索到的位置,则必须为编译命令行添加一个选项,例如 -I/usr/local/pgsql/include

The generated C source files include header files from the PostgreSQL installation, so if you installed PostgreSQL in a location that is not searched by default, you have to add an option such as -I/usr/local/pgsql/include to the compilation command line.

要链接嵌入式 SQL 程序,您需要包含 libecpg 库,如下所示:

To link an embedded SQL program, you need to include the libecpg library, like so:

cc -o myprog prog1.o prog2.o ... -lecpg

同样,您可能必须为该命令行添加 -L/usr/local/pgsql/lib 之类的选项。

Again, you might have to add an option like -L/usr/local/pgsql/lib to that command line.

你可以使用 pg_configpkg-config 以及程序包名称 libecpg 以获取安装路径。

You can use pg_config or pkg-config with package name libecpg to get the paths for your installation.

如果使用 make 管理较大型项目的构建过程,不妨在 Makefile 中包含以下隐含规则:

If you manage the build process of a larger project using make, it might be convenient to include the following implicit rule to your makefiles:

ECPG = ecpg

%.c: %.pgc
        $(ECPG) $<

ecpg 命令的完整语法在 ecpg 中详细说明。

The complete syntax of the ecpg command is detailed in ecpg.

默认情况下,ecpg 库是线程安全的。但是,你可能需要使用一些线程命令行选项来编译客户端代码。

The ecpg library is thread-safe by default. However, you might need to use some threading command-line options to compile your client code.