有时候可以自己用C语言来实现一些特定功能的函数,C语言实现的函数如何被PostgreSQL引用呢,下面就介绍下PostgreSQL引用C语言函数的方法
创建funcs.c文件,里面实现两个数相加的功能
#include "postgres.h"
#include <string.h>
#include "fmgr.h"
#include "utils/geo_decls.h"
PG_MODULE_MAGIC;
/* by value */
PG_FUNCTION_INFO_V1(add_one);
Datum
add_one(PG_FUNCTION_ARGS)
{
int32 arg = PG_GETARG_INT32(0);
int32 arg1 = PG_GETARG_INT32(1);
PG_RETURN_INT32(arg + arg1);
}
--//编译
gcc -I`pg_config --includedir-server` -fPIC -c cfunc.c
--//pg_config --includedir-server也可以替换为postgres解压源码中的/src/include目录,如下:
gcc -I/opt/soft_bak/postgresql-11.1/src/include -fPIC -c funcs.c
--//生成动态链接库,并把生成的.so文件拷贝到PostgreSQL的lib文件
[postgres@postgres include]$ pg_config --libdir
/opt/pgsql11/lib
[postgres@postgres include]$
--切换root
[root@postgres c]# gcc -shared -o cfunc.so cfunc.o
[root@postgres c]# cp cfunc.so /opt/pgsql11/lib/
--//在psql中创建函数,创建函数时指定参数个数
postgres=# CREATE FUNCTION add_one(integer,integer) RETURNS integer
postgres-# AS '/opt/pgsql11/lib/funcs', 'add_one'
postgres-# LANGUAGE C STRICT;
CREATE FUNCTION
postgres=#
postgres=#
--//测试
postgres=# select add_one(1,2);
add_one
---------
3
(1 row)
postgres=# select add_one(3,5);
add_one
---------
8
(1 row)
postgres=#
参考资料: