postgres扩展开发

扩展开发的基本组成

demo--1.0.sql

demo.c

demo.control

Makefile

demo.c当中包含了自定义函数的实现,纯C语言,目录下可包含多个.c文件。
demo—1.0.sql对自定义函数的声明,在pg启动的时候会执行这个sql。
demo.control这个应该是版本控制,以及module_pathname告诉PG在执行到用户自定义函数的时候去这个路径下找库文件。
Makefile编译文件。

开发的基本技巧

写扩展函数的基本三部曲
第一步:(必须要的)
#ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif
第二步:(必须要的)
PG_FUNCTION_INFO_V1(test_add_fun);
第三步:(必须要的)
test_add_fun函数功能的实现。

获取外部参数函数是PG_GETARG_XXXX();
返回值的返回函数PG_RETURN_XXXX();
Ps:按照这一套你就能进行扩展开发了。

demo.c代码如下:

  #ifdef PG_MODULE_MAGIC
PG_MODULE_MAGIC;
#endif PG_FUNCTION_INFO_V1(test_add_fun); Datum test_add_fun(PG_FUNCTION_ARGS); Datum test_add_fun(PG_FUNCTION_ARGS)
{
int sum,a,b; a = PG_GETARG_INT32();
b = PG_GETARG_INT32(); sum = a + b;
PG_RETURN_INT32(sum);
}

Makfile如下:

 MODULE_big = demo

 IBASE_VERSION=1.0

 OBJS =  demo.o

 EXTENSION = demo
DATA = demo--1.0.sql SHLIB_LINK += $(filter -lm, $(LIBS))
USE_PGXS=
ifdef USE_PGXS
PG_CONFIG = /usr/local/postgres/bin/pg_config
PGXS := $(shell $(PG_CONFIG) --pgxs)
include $(PGXS)
else
subdir = contrib/demo
top_builddir = ../..
include $(top_builddir)/src/Makefile.global
include $(top_srcdir)/contrib/contrib-global.mk
endif

编译安装

[root@centos01 demo]# make
gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -g -O0 -fpic -I. -I./ -I/usr/local/postgres/include/server -I/usr/local/postgres/include/internal -D_GNU_SOURCE -c -o demo.o demo.c
gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels -Wmissing-format-attribute -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -g -O0 -fpic -shared -o demo.so demo.o -L/usr/local/postgres/lib -Wl,--as-needed -Wl,-rpath,'/usr/local/postgres/lib',--enable-new-dtags -lm
[root@centos01 demo]# make install
/usr/bin/mkdir -p '/usr/local/postgres/lib'
/usr/bin/mkdir -p '/usr/local/postgres/share/extension'
/usr/bin/mkdir -p '/usr/local/postgres/share/extension'
/usr/bin/install -c -m demo.so '/usr/local/postgres/lib/demo.so'
/usr/bin/install -c -m demo.control '/usr/local/postgres/share/extension/'
/usr/bin/install -c -m demo--1.0.sql '/usr/local/postgres/share/extension/'

创建扩展并使用

postgres=# create extension demo;
CREATE EXTENSION
postgres=# \sf test_add_fun
CREATE OR REPLACE FUNCTION public.test_add_fun(a integer, b integer)
RETURNS integer
LANGUAGE c
STRICT
AS '$libdir/demo', $function$test_add_fun$function$
postgres=# select test_add_fun(,);
test_add_fun
-------------- ( row)
上一篇:其他(一)Visual Studio 自动排版快捷键


下一篇:关于PHP扩展开发(收藏)