Search code examples
cpostgresqlhstore

PostgreSQL UDF in C using hstore


I'm writing an extension for PostgreSQL in C and I need to use hstore in my UDFs. I can build without errors (using pgxc) but can't use any function in SQL queries.

I've tried PG_LIBS=hstore but got undefined reference errors while loading the library.

Next try was SHLIB_LINK=-L/usr/lib/postgresql/9.1/lib -lhstore (libhstore.so is not present in the system, only hstore.so, so i've tried with sym and hard links) and got

psql:libname.sql:69: ERROR:  could not load library
"/usr/lib/postgresql/9.1/lib/libname.so": libhstore.so: cannot open shared 
object file: No such file or directory

Solution

  • From memory, hstore doesn't expose much of a C API. You have to use it via the server programming interface (SPI), using its SQL-level interfaces via your C extension. UPDATE: Or, as Tom Lane points out on the mailing list, use the fmgr to invoke the SQL functions it exposes, rather than using the SPI to run full SQL statements. UPDATE2: Another option is to load_external_function("extension", "symbol") the C functions directly; see fmgr.h.

    Most of the functions you're trying to use in hstore will be declared static (so they're local to the hstore module) which is probably why you're getting undefined references. You can only use what's declared in hstore.h as a macro or extern function. You can't just call any function you find in (say) hstore_io.c via direct C linkage.

    PG_LIBS allows you to specify shared libraries to link to, but hstore.so isn't a typical shared library that's intended for linking to during compilation. It's a PostgreSQL extension module that's intended to be dlopen()ed by the server. I don't think one extension module linking to another is really supported. That means you probably can't even use the extern functions without quite a bit of hacking around.

    Use the SPI, the fmgr, or load_external_function.

    If using load_external_function you're likely to need to manage memory contexts and other call context. Try to find examples of its use.

    See: