linux下mysql扩展,自定义函数实现(…

来源:互联网 发布:男士服装搭配软件 编辑:程序博客网 时间:2024/06/03 21:29
Adding a New User-DefinedFunction
"The MySQL source distribution includes a filesql/udf_example.c that defines 5 new functions"
下载mysql在目录中可看到sql/udf_example.c,我们可以参考。
流程:编译自己的动态库=>创建函数
首先建立一个简单的测试函数库,返回值为字符串类型
代码为:
//mtest.h
#ifndef MTEST_H_
#define MTEST_H_
#include <my_global.h>
#include <mysql.h>

my_bool mtest_init(UDF_INIT *initid, UDF_ARGS *args, char*message);

char *mtest(UDF_INIT *initid, UDF_ARGS *args,
         char *result, unsigned long*length,
         char *is_null, char*error);

void mtest_deinit(UDF_INIT *initid);

#endif
//mtest.c
#include <string.h>
#include "mtest.h"

my_bool mtest_init(UDF_INIT *initid, UDF_ARGS *args, char*message)
{
if(0 != args->arg_count){
strncpy(message, "mtest has no arguments", strlen("mtest hasno arguments") + 1);
return 1;
}

initid->ptr = calloc(1, 1024);

return 0;
}

char *mtest(UDF_INIT *initid, UDF_ARGS *args,
         char *result, unsigned long*length,
         char *is_null, char*error)
{
char *ps = "mysql plugin string type test.";
*length = strlen(ps);

memcpy(initid->ptr, ps, *length + 1);

return initid->ptr;
}

void mtest_deinit(UDF_INIT *initid)
{
free(initid->ptr);
}
编译为libmtest.so,复制到plugin目录下
重启mysql
$mysql -h127.0.0.1 -u root -P3306
//create
mysql> CREATE FUNCTION mtest RETURNS STRINGSONAME 'libmtest.so';
mysql> select mtest();
+--------------------------------+
| mtest()                    |
+--------------------------------+
| mysql plugin string type test. | 
+--------------------------------+
1 row in set (0.02 sec)

//drop
mysql> DROP FUNCTION mtest;