We now turn to the more difficult task of writing programming language functions. Be warned: this section of the manual will not make you a programmer. You must have a good understanding of C (including the use of pointers and the malloc memory manager) before trying to write C functions for use with PostgreSQL. While it may be possible to load functions written in languages other than C into PostgreSQL, this is often difficult (when it is possible at all) because other languages, such as FORTRAN and 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 programming language functions are written in C.
The basic rules for building C functions are as follows:
The relevant header (include) files are installed under /usr/include/pgsql/ or equivalent. You can use pg_config --includedir to find out where it is on your system. For very low-level work you might need to have a complete Red Hat Database source tree available.
When allocating memory, use the Red Hat Database routines palloc and pfree instead of the corresponding C library routines malloc and free. The memory allocated by palloc will be freed automatically at the end of each transaction, preventing memory leaks.
Always zero the bytes of your structures using memset or bzero. Several routines (such as the hash access method, hash join and the sort algorithm) compute functions of the raw bits contained in your structure. Even if you initialize all fields of your structure, there may be several bytes of alignment padding (holes in the structure) that may contain random values.
Most of the internal Red Hat Database 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 is best to include postgres.h first, before any other system or user header files. Including postgres.h will also include c.h, elog.h and palloc.h for you.
To learn how to run SQL queries inside user-defined C functions, see Chapter 11.
Symbol names defined within object files must not conflict with each other or with symbols defined in the Red Hat Database server executable. You will have to rename your functions or variables if you get error messages to this effect.
Compiling and linking your object code so that it can be dynamically loaded into Red Hat Database always requires special flags. See the Section called Compiling and Linking Dynamically-Loaded Functions for a detailed explanation of how to do it.