An extension function is loaded into a running PostgreSQL server process as needed. If you don't actually use an extension, it will not be loaded. Extension functions must be created in the form of a dynamically loadable object module. In the Windows world, an extension is contained within a DLL. In the Linux/Unix environment, an extension is contained within a shared object module.
There are two phases to the process of adding an extension function to the PostgreSQL server. First, you create the extension function in the language of your choice, compiling it into a dynamic object module (.dll or .so). Next, tell the PostgreSQL server about the function. The CREATE FUNCTION command adds a new function to a database.
I'll show you two examples that should help clarify this process.
The first example adds a simple function, named filesize, to the PostgreSQL server. Given the name of a file, it returns the size of the file (in bytes). If the file does not exist, cannot be examined, or is not a regular[1] file, this function returns NULL. You might find this function (and the filelist() function shown later) useful for performing system administration tasks from within a PostgreSQL application. After you have created the filesize function, you can call it like this:
[1] In this context, a file is considered "regular" if it is not a directory, named pipe, symbolic link, device file, or socket.
movies=# SELECT filesize( '/bin/bash' ); filesize ---------- 512668
We'll develop the filesize function in C (see Listing 6.1).
The filesize function takes a single argumenta pathname in the form of a TEXT value. This function returns the size of the named file as an INTEGER value.
Listing 6.1. filesize.c
1 /* 2 ** Filename: filesize.c 3 */ 4 5 #include "postgres.h" 6 #include "fmgr.h" 7 #include 8 9 PG_FUNCTION_INFO_V1(filesize); 10 11 Datum filesize(PG_FUNCTION_ARGS) 12 { 13 text * fileNameText = PG_GETARG_TEXT_P(0); 14 size_t fileNameLen = VARSIZE( fileNameText ) - VARHDRSZ; 15 char * fileName = (char *)palloc( fileNameLen + 1 ); 16 struct stat statBuf; 17 18 memcpy( fileName, VARDATA( fileNameText ), fileNameLen ); 19 fileName[fileNameLen] = '