This page in other versions: 9.0 / 9.1 / 9.2 / 9.3  |  Development versions: devel / 9.4  |  Unsupported versions: 7.4 / 8.0 / 8.1 / 8.2 / 8.3 / 8.4

Chapter 46. Writing A Procedural Language Handler

All calls to functions that are written in a language other than the current "version 1" interface for compiled languages (this includes functions in user-defined procedural languages, functions written in SQL, and functions using the version 0 compiled language interface), go through a call handler function for the specific language. It is the responsibility of the call handler to execute the function in a meaningful way, such as by interpreting the supplied source text. This chapter outlines how a new procedural language's call handler can be written.

The call handler for a procedural language is a "normal" function that must be written in a compiled language such as C, using the version-1 interface, and registered with PostgreSQL as taking no arguments and returning the type language_handler. This special pseudotype identifies the function as a call handler and prevents it from being called directly in SQL commands.

The call handler is called in the same way as any other function: It receives a pointer to a FunctionCallInfoData struct containing argument values and information about the called function, and it is expected to return a Datum result (and possibly set the isnull field of the FunctionCallInfoData structure, if it wishes to return an SQL null result). The difference between a call handler and an ordinary callee function is that the flinfo->fn_oid field of the FunctionCallInfoData structure will contain the OID of the actual function to be called, not of the call handler itself. The call handler must use this field to determine which function to execute. Also, the passed argument list has been set up according to the declaration of the target function, not of the call handler.

It's up to the call handler to fetch the entry of the function from the system table pg_proc and to analyze the argument and return types of the called function. The AS clause from the CREATE FUNCTION command for the function will be found in the prosrc column of the pg_proc row. This is commonly source text in the procedural language, but in theory it could be something else, such as a path name to a file, or anything else that tells the call handler what to do in detail.

Often, the same function is called many times per SQL statement. A call handler can avoid repeated lookups of information about the called function by using the flinfo->fn_extra field. This will initially be NULL, but can be set by the call handler to point at information about the called function. On subsequent calls, if flinfo->fn_extra is already non-NULL then it can be used and the information lookup step skipped. The call handler must make sure that flinfo->fn_extra is made to point at memory that will live at least until the end of the current query, since an FmgrInfo data structure could be kept that long. One way to do this is to allocate the extra data in the memory context specified by flinfo->fn_mcxt; such data will normally have the same lifespan as the FmgrInfo itself. But the handler could also choose to use a longer-lived memory context so that it can cache function definition information across queries.

When a procedural-language function is invoked as a trigger, no arguments are passed in the usual way, but the FunctionCallInfoData's context field points at a TriggerData structure, rather than being NULL as it is in a plain function call. A language handler should provide mechanisms for procedural-language functions to get at the trigger information.

This is a template for a procedural-language handler written in C:

#include "postgres.h"
#include "executor/spi.h"
#include "commands/trigger.h"
#include "fmgr.h"
#include "access/heapam.h"
#include "utils/syscache.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"

PG_FUNCTION_INFO_V1(plsample_call_handler);

Datum
plsample_call_handler(PG_FUNCTION_ARGS)
{
    Datum          retval;

    if (CALLED_AS_TRIGGER(fcinfo))
    {
        /*
         * Called as a trigger procedure
         */
        TriggerData    *trigdata = (TriggerData *) fcinfo->context;

        retval = ...
    }
    else
    {
        /*
         * Called as a function
         */

        retval = ...
    }

    return retval;
}

Only a few thousand lines of code have to be added instead of the dots to complete the call handler.

After having compiled the handler function into a loadable module (see Section 32.9.6), the following commands then register the sample procedural language:

CREATE FUNCTION plsample_call_handler() RETURNS language_handler
    AS 'filename'
    LANGUAGE C;
CREATE LANGUAGE plsample
    HANDLER plsample_call_handler;

The procedural languages included in the standard distribution are good references when trying to write your own call handler. Look into the src/pl subdirectory of the source tree.

Comments


Dec. 28, 2005, 1:40 p.m.

Much precise template (without trigger):

#include "postgres.h"
#include "executor/spi.h"
#include "commands/trigger.h"
#include "fmgr.h"
#include "access/heapam.h"
#include "utils/syscache.h"
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"

PG_FUNCTION_INFO_V1(scriptql_function_handler);
PG_FUNCTION_INFO_V1(scriptql_call_handler);

Datum scriptql_function_handler (PG_FUNCTION_ARGS)
{
HeapTuple script_tuple;
Form_pg_proc script_struct;
char *script_name;
short int script_argc;
char *script_argv;
char *script_source;
int i;

script_tuple = SearchSysCache (PROCOID, ObjectIdGetDatum (fcinfo->flinfo->fn_oid), 0, 0, 0);
if (!HeapTupleIsValid (script_tuple)) elog (ERROR, "cache lookup failed for function %u", fcinfo->flinfo->fn_oid);
script_struct = (Form_pg_proc) GETSTRUCT (script_tuple);
script_name = pstrdup (NameStr (script_struct->proname));
script_argc = script_struct->pronargs;
script_source = DatumGetCString (DirectFunctionCall1 (textout, PointerGetDatum (&script_struct->prosrc)));

elog (NOTICE, "script name: %s", script_name);
elog (NOTICE, "script argc: %d", script_argc);
for (i = 0; i != script_argc; i ++)
{
script_argv = DatumGetCString (DirectFunctionCall1 (textout, PointerGetDatum (PG_GETARG_TEXT_P (0))));
elog (NOTICE, "script argv[%d]: %s", i, script_argv);
pfree (script_argv);
}
elog (NOTICE, "script source: %s", script_source);

pfree (script_source);
ReleaseSysCache (script_tuple);

return (Datum)0;
}

Datum scriptql_call_handler (PG_FUNCTION_ARGS)
{
Datum retval;

if (SPI_connect () != SPI_OK_CONNECT) elog (ERROR, "SPI_connect failed");

retval = scriptql_function_handler (fcinfo);

if (SPI_finish () != SPI_OK_FINISH) elog (ERROR, "SPI_finish failed");
return retval;
}


Dec. 28, 2005, 1:45 p.m.

PG_GETARG_TEXT_P (0) <- here you should choose your type of current (i) argument.

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group