I think that you could use another pattern where you init the PQExpBufferData structure instead of create it, so that only the string is malloced.
In v26, I have the functions return PQExpBuffer. The two calling functions then free it, which should solve any leak.
I think that you should use appendPQExpBufferChar and Str instead of relying on the format variant which is probably expensive. Something like:
if (num_options > 0) append...Char(buf, ' '); append...Str(buf, ...);
All flavors of appendPQExpBuffer*() I can find have a const *char format string, so no way to append a naked string. If you know differently, I'm listening. Not fixed.
These prototypes are from "pqexpbuffer.h", and do not seem to rely on a format:
Here's an addendum that does that. I can combine them in v27, but figured this was quicker.