User-defined functions can be written in C language. Such functions are compiled into dynamically loadable objects.
function implementation in c
The version-1 calling convention relies on macros to suppress most of the complexity of passing arguments and results. the declaration of a version-1 function will be as follows
Datum funcname(PG_FUNCTION_ARGS)
before that we will add the macro call
PG_FUNCTION_INFO_V1(funcname);
to declare the function name
then the function implementation of adding two numbers will be as follows.
#include "postgres.h"
#include <string.h>
#include "fmgr.h"
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(add_one);
Datum
add_two_numbers(PG_FUNCTION_ARGS)
{
int32 arg1 = PG_GETARG_INT32(0);
int32 arg2 = PG_GETARG_INT32(1);
PG_RETURN_INT32(arg1 + arg2);
}
notice that PG_RETURN_xxx
or PG_GETARG_xxx
where xxx
refer to the variable datatype
then, we could define the functions to PostgreSQL with commands like this
CREATE FUNCTION add_one(integer)
RETURNS integer
AS 'DIRECTORY/funcs', 'add_two_numbers'
LANGUAGE C;
Top comments (3)
Hello. Thank you for sharing your knowledge in this article! As someone who hasn't used postgresSQL before, it was a bit hard to follow along. Perhaps a bit more context on why you're writing this function in C when postgres is a SQL system. And maybe an explanation of what a version-1 calling convention is.
Hi Anneta, PostgreSQL provides four kinds of functions:
there are different calling convention types (version-1, version-0)
but version-0 is deprecated. it's a style of getting the function arguments
in version-1 getting function arguments like that
but in version-0 was like that
i hope this answers your questions and sorry for the late reply
Thank you! That makes things more clear.