[2021-01-22]c语言实现postgresql函数

有时候可以自己用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=# 

参考资料:

https://www.postgresql.org/docs/11/xfunc-c.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值