next up previous contents index
Next: Compile the C Code Up: Extending POSTGRESQL Using C Previous: Extending POSTGRESQL Using C

Write the C Code

The best way to add a new function, operator, data type, or aggregate is to start with a copy of a file from the POSTGRESQL source directory pgsql/src/backend/utils/adt. Start with a file that contains functions similar to the ones you need, but make sure that your new function names are unique.

For example, Chapter [*] included a ftoc() SQL function that converted a temperature from Fahrenheit to centigrade degrees. Figure [*] shows a C function that converts from centigrade to Fahrenheit.  

        #include "postgres.h"
        double *ctof(double *deg)
        {
            double *ret = palloc(sizeof(double)); 
         
            *ret = (*deg * 9.0 / 5.0) + 32.0;
            return ret;
        }
 

While writing C functions, you may find it necessary to execute SQL queries from inside the function. The server programming interface (SPI ) allows C functions to execute SQL queries and process results from within these functions.


Bruce Momjian
2001-05-09