设为首页 收藏本站
查看: 1895|回复: 0

[经验分享] 使用C编写的动态链接库为PostgreSQL数据库添加自定义函数

[复制链接]

尚未签到

发表于 2016-11-21 06:54:21 | 显示全部楼层 |阅读模式
  不得不说,在这点上,PostgreSQL功能非常强大,不亚于任何家大型商业数据库。要添加一些自定义函数,不是那么复杂。
  下边的示例会添加如下函数:test(), concat_text(string, string) 还有另外两个,不作举例,您可以自行尝试

1. 代码如下:



/* $PostgreSQL: pgsql/src/tutorial/funcs_new.c,v 1.13 2007/02/27 23:48:10 tgl Exp $ */
/******************************************************************************
These are user-defined functions that can be bound to a Postgres backend
and called by Postgres to execute SQL functions of the same name.
The calling format for these functions is defined by the CREATE FUNCTION
SQL statement that binds them to the backend.
NOTE: this file shows examples of "new style" function call conventions.
See funcs.c for examples of "old style".
*****************************************************************************/
#include "postgres.h"/* general Postgres declarations */
#include "executor/executor.h"/* for GetAttributeByName() */
#include "utils/geo_decls.h"/* for point type */
#include "executor/spi.h"
PG_MODULE_MAGIC;
/* These prototypes just prevent possible warnings from gcc. */
//
//Datumadd_one(PG_FUNCTION_ARGS);
//Datumadd_one_float8(PG_FUNCTION_ARGS);
//Datummakepoint(PG_FUNCTION_ARGS);
//Datumcopytext(PG_FUNCTION_ARGS);
//Datumconcat_text(PG_FUNCTION_ARGS);
//Datumc_overpaid(PG_FUNCTION_ARGS);

/* By Value */
PG_FUNCTION_INFO_V1(add_one);
__declspec (dllexport) Datum
add_one(PG_FUNCTION_ARGS)
{
int32arg = PG_GETARG_INT32(0);
PG_RETURN_INT32(arg + 1);
}
/* By Reference, Fixed Length */
PG_FUNCTION_INFO_V1(add_one_float8);
__declspec (dllexport) Datum
add_one_float8(PG_FUNCTION_ARGS)
{
/* The macros for FLOAT8 hide its pass-by-reference nature */
float8arg = PG_GETARG_FLOAT8(0);
PG_RETURN_FLOAT8(arg + 1.0);
}
PG_FUNCTION_INFO_V1(makepoint);
__declspec (dllexport) Datum
makepoint(PG_FUNCTION_ARGS)
{
Point   *pointx = PG_GETARG_POINT_P(0);
Point   *pointy = PG_GETARG_POINT_P(1);
Point   *new_point = (Point *) palloc(sizeof(Point));
new_point->x = pointx->x;
new_point->y = pointy->y;
PG_RETURN_POINT_P(new_point);
}
/* By Reference, Variable Length */
PG_FUNCTION_INFO_V1(copytext);
__declspec (dllexport) Datum
copytext(PG_FUNCTION_ARGS)
{
text   *t = PG_GETARG_TEXT_P(0);
/*
* VARSIZE is the total size of the struct in bytes.
*/
text   *new_t = (text *) palloc(VARSIZE(t));
SET_VARSIZE(new_t, VARSIZE(t));
/*
* VARDATA is a pointer to the data region of the struct.
*/
memcpy((void *) VARDATA(new_t),/* destination */
(void *) VARDATA(t), /* source */
VARSIZE(t) - VARHDRSZ);/* how many bytes */
PG_RETURN_TEXT_P(new_t);
}
PG_FUNCTION_INFO_V1(concat_text);
__declspec (dllexport) Datum
concat_text(PG_FUNCTION_ARGS)
{
text   *arg1 = PG_GETARG_TEXT_P(0);
text   *arg2 = PG_GETARG_TEXT_P(1);
int32arg1_size = VARSIZE(arg1) - VARHDRSZ;
int32arg2_size = VARSIZE(arg2) - VARHDRSZ;
int32new_text_size = arg1_size + arg2_size + VARHDRSZ;
text   *new_text = (text *) palloc(new_text_size);
SET_VARSIZE(new_text, new_text_size);
memcpy(VARDATA(new_text), VARDATA(arg1), arg1_size);
memcpy(VARDATA(new_text) + arg1_size, VARDATA(arg2), arg2_size);
PG_RETURN_TEXT_P(new_text);
}
/* Composite types */
PG_FUNCTION_INFO_V1(c_overpaid);
__declspec (dllexport) Datum
c_overpaid(PG_FUNCTION_ARGS)
{
HeapTupleHeader t = PG_GETARG_HEAPTUPLEHEADER(0);
int32limit = PG_GETARG_INT32(1);
boolisnull;
int32salary;
salary = DatumGetInt32(GetAttributeByName(t, "salary", &isnull));
if (isnull)
PG_RETURN_BOOL(false);
/*
* Alternatively, we might prefer to do PG_RETURN_NULL() for null salary
*/
PG_RETURN_BOOL(salary > limit);
}
PG_FUNCTION_INFO_V1(test);
__declspec (dllexport)  Datum test(PG_FUNCTION_ARGS)
{
char *command;
int ret;
int proc;
command = "SELECT 1";
elog(INFO,"1");
SPI_connect();
elog(INFO,"2");
ret = SPI_exec(command, 1);
elog(INFO,"3");
proc = SPI_processed;
elog(INFO,"4");
if (ret > 0 && SPI_tuptable != NULL)
{
TupleDesc tupdesc = SPI_tuptable->tupdesc;
SPITupleTable *tuptable = SPI_tuptable;
char buf[8192];
int i, j;
elog(INFO,"5");
for (j = 0; j < proc; j++)
{
HeapTuple tuple = tuptable->vals[j];
elog(INFO,"6");
for (i = 1, buf[0] = 0; i <= tupdesc->natts; i++)
{
snprintf(buf + strlen (buf), sizeof(buf) - strlen(buf), " %s%s",
SPI_getvalue(tuple, tupdesc, i),
(i == tupdesc->natts) ? " " : " |");
elog(INFO,"7");
}
elog(INFO, "EXECQ: %s", buf);
}
}
SPI_finish();
// pfree(command);
}

2. 编译过程


  要注意的是编译过程,需要添加头文件路径,lib路径,bin路径,以完成编译,最后得到func1.dll,以本例为例,过程并不复杂。在linux平台,相信更简单。
  以windows为例,您可以先从http://download.csdn.net/detail/iihero/2979577 下载整个示例工程,应该是vs2005的vc++工程,添加如下include路径,最前头带PG(9.0或以上)的安装路径:
  include\server
include\server\port\win32
include\server\port\win32_msvc
include\
  最后得到func1.dll,将其复制到${PG_HOME}\bin下边。

3. 验证创建的函数

create function mytest() RETURNs VARCHAR(256)
AS 'd:/pg921/bin/func1', 'test'
LANGUAGE C STRICT;
说明: 添加SQL函数mytest, 不带参数,它的实现是func1.dll中的test,含义非常明确。  
iihero=# create function mytest() RETURNs VARCHAR(256)
iihero-# AS 'd:/pg921/bin/func1', 'test'
iihero-# LANGUAGE C STRICT;
CREATE FUNCTION
iihero=# select mytest();
INFO:  1
INFO:  2
INFO:  3
INFO:  4
INFO:  5
INFO:  6
INFO:  7
INFO:  EXECQ:  1
server closed the connection unexpectedly
This probably means the server terminated abnormally
before or while processing the request.
The connection to the server was lost. Attempting reset: Succeeded.

create function myconcat(varchar(256), varchar(256)) RETURNs VARCHAR(512)
AS 'd:/pg921/bin/func1', 'concat_text'
LANGUAGE C STRICT;
说明: 添加函数myconcat, 带两个字符串参数,它的实现是func1.dll中的concat_text,含义非常明确。
iihero=# create function myconcat(varchar(256), varchar(256)) RETURNs VARCHAR(512)
iihero-# AS 'd:/pg921/bin/func1', 'concat_text'
iihero-# LANGUAGE C STRICT;
CREATE FUNCTION
iihero=# select myconcat('abc###, ', 'bcd1234');
myconcat
-----------------
abc###, bcd1234
(1 row)

iihero=#



其实,在其它商业数据库里,至少Sybase ASE/ASA, Oracle是支持这种C函数扩展的,就是编写起来,可能更麻烦一些。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-303083-1-1.html 上篇帖子: PostGis设置SRID(报错为org.postgresql.util.PSQLException:错误: Operation on mixed SRID g 下篇帖子: PostgreSQL-01学习--表的定义&系统字段&表的修改&权限
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表