| The PostgreSQL 9.0 Reference Manual - Volume 2 - Programming Guide
by The PostgreSQL Global Development Group Paperback (6"x9"), 478 pages ISBN 9781906966065 RRP £14.95 ($19.95) Sales of this book support the PostgreSQL project! Get a printed copy>>> |
5.9.5 Writing Code
Before we turn to the more advanced topics, we should discuss some coding rules for PostgreSQL C-language functions. While it might be possible to load functions written in languages other than C into PostgreSQL, this is usually difficult (when it is possible at all) because other languages, such as C++, FORTRAN, or Pascal often do not follow the same calling convention as C. That is, other languages do not pass argument and return values between functions in the same way. For this reason, we will assume that your C-language functions are actually written in C.
The basic rules for writing and building C functions are as follows:
-
Use
pg_config --includedir-serverto find out where the PostgreSQL server header files are installed on your system (or the system that your users will be running on). - Compiling and linking your code so that it can be dynamically loaded into PostgreSQL always requires special flags. See section 5.9.6 Compiling and Linking Dynamically-Loaded Functions for a detailed explanation of how to do it for your particular operating system.
- Remember to define a “magic block” for your shared library, as described in section 5.9.1 Dynamic Loading.
-
When allocating memory, use the
PostgreSQL functions
pallocandpfreeinstead of the corresponding C library functionsmallocandfree. The memory allocated bypallocwill be freed automatically at the end of each transaction, preventing memory leaks. -
Always zero the bytes of your structures using
memset. Without this, it's difficult to support hash indexes or hash joins, as you must pick out only the significant bits of your data structure to compute a hash. Even if you initialize all fields of your structure, there might be alignment padding (holes in the structure) that contain garbage values. -
Most of the internal PostgreSQL
types are declared in ‘postgres.h’, while
the function manager interfaces
(
PG_FUNCTION_ARGS, etc.) are in ‘fmgr.h’, so you will need to include at least these two files. For portability reasons it's best to include ‘postgres.h’ first, before any other system or user header files. Including ‘postgres.h’ will also include ‘elog.h’ and ‘palloc.h’ for you. - Symbol names defined within object files must not conflict with each other or with symbols defined in the PostgreSQL server executable. You will have to rename your functions or variables if you get error messages to this effect.
| ISBN 9781906966065 | The PostgreSQL 9.0 Reference Manual - Volume 2 - Programming Guide | See the print edition |