首先配置好本地源码编译环境,详情可参考http://plutolove.hatenablog.com/entry/2017/08/10/190138。添加用户自定义函数以strcon为例,其功能是连接两个字符串。
添加用户自定义函数
- 首先在
src/include/catalog/pg_proc.dat
中仿照现有的函数添加自定义函数,源码如下
{ oid => '6123', descr => 'strcon', proname => 'strcon', prorettype => 'text', proargtypes => 'text text', prosrc => 'strcon' }
- 其次在
src/backend/utils/adt/oracle_compat.c
中实现相应函数,源码如下
Datum strcon(PG_FUNCTION_ARGS) { text* final; text* str1 = PG_GETARG_TEXT_PP(0); text* str2 = PG_GETARG_TEXT_PP(1); char* result = palloc(VARSIZE_ANY_EXHDR(str1)+ VARSIZE_ANY_EXHDR(str2)+1); memcpy(result, VARDATA_ANY(str1), VARSIZE_ANY_EXHDR(str1)); memcpy(result+VARSIZE_ANY_EXHDR(str1), VARDATA_ANY(str2), VARSIZE_ANY_EXHDR(str2)); result[VARSIZE_ANY_EXHDR(str1)+ VARSIZE_ANY_EXHDR(str2)] = '\0'; final = cstring_to_text(result); PG_RETURN_TEXT_P(final); }
编译测试
make install #编译安装 postgres -D $PGDATA #新建数据库 createdb demo #进入SQL命令行 psql demo
执行select strcon('abc', '-123');
查看运行结果如下图