在开发PG的扩展插件过程中,经常需要实现自定义Function,此文就录PG自定义Function开发流程.
1、完整流程
2、modulename.c举例【例如如下的add_func.c】
#include "postgres.h"
#include "fmgr.h"
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(add_ab);
PG_FUNCTION_INFO_V1(add_ab_null);
Datum add_ab(PG_FUNCTION_ARGS);
Datum add_ab_null(PG_FUNCTION_ARGS);
Datum add_ab(PG_FUNCTION_ARGS)
{
int32 argc_a = PG_GETARG_INT32(0);
int32 argc_b = PG_GETARG_INT32(1);
PG_RETURN_INT32(argc_a + argc_b);
}
Datum add_ab_null(PG_FUNCTION_ARGS)
{
int32 not_null = 0;
int32 sum = 0;
if (!PG_ARGISNULL(0))
{
sum += PG_GETARG_INT32(0);
not_null = 1;
}
if (!PG_ARGISNULL(1))
{
sum += PG_GETARG_INT32(1);
not_null = 1;
}
if (not_null)
{
PG_RETURN_INT32(sum);
}
PG_RETURN_NULL();
}
3、modulename.sql.in举例【例如如下的add_func.sql.in】
/**在“add_func.c”中函数add_ab与“sql中add函数”之间建立关联**/
CREATE FUNCTION add(int, int) RETURNs int
AS 'MODULE_PATHNAME', 'add_ab'
LANGUAGE C STRICT;
/**在“add_func.c”中函数add_ab_null与“sql中add_null函数”之间建立关联**/
CREATE FUNCTION add_null(int, int) RETURNs int
AS 'MODULE_PATHNAME', 'add_ab_null'
LANGUAGE C;
4、Makefile举例【例如如下的add_func.c】
DATA_built = add_func.sql #依据add_func.sql.in生成当前名为“add_func.sql”的文件
MODULES = add_func
PG_CONFIG = pg_config
PGXS = $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)