我想为PostgreSQL编写一个C函数。对于此功能,我将需要使用libpq查询一些数据,因此我首先编写了一个虚拟函数来测试此部分:
#define _XOPEN_SOURCE #include#include #include #include #include #include "test.h" PG_FUNCTION_INFO_V1(getAnnotation); Datum getAnnotation(PG_FUNCTION_ARGS) { // Connection to the database PGconn *cOnn= PQsetdbLogin("localhost", "5432", "", "", "postgres", "postgres", "password"); // Databases names PGresult *res = PQexec (conn, "SELECT user FROM activity LIMIT 1;"); VarChar* i = PQgetvalue(res, 0, 0); PG_RETURN_VARCHAR_P(i); }
它只是应该返回我的一个表的第一行的第一列。很简单吧?好吧,它不起作用。
当我尝试在psql中使用它时,它说:
ERROR: could not load library "/usr/local/lib/postgresql/test.so": Error relocating /usr/local/lib/postgresql/test.so: PQexec: symbol not found
奇怪的是,两者PQsetdbLogin
和PQexec
都在libpq-fe.h
文件中,但是只有第二个会导致错误。如果我评论这一PQexec
行,那么PQsetdbLogin
也会引发一个错误。
这是我用来构建代码的Makefile:
PG_CPPFLAGS = -I$(libpq_srcdir) LDFLAGS_INTERNAL = -L$(libdir) SHLIB_LINK_INTERNAL = $(libpq) SHLIB_PREREQS = submake-libpq EXTENSION = test DATA = test--0.1.sql MODULES = test # REGRESS = ... # Script for tests PG_COnFIG= pg_config PGXS := $(shell $(PG_CONFIG) --pgxs) include $(PGXS)
如您所见,我在其中链接了libpq,因此一切正常。
我在Docker容器中使用PostgreSQL 9.6。