Adding a New User-Defined Function
"The MySQL source distribution includes a file
sql/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,
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 has no arguments") + 1);
return 1;
}
initid->ptr = calloc(1, 1024);
return 0;
}
char *mtest(UDF_INIT *initid, UDF_ARGS *args,
{
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 STRING SONAME 'libmtest.so';
mysql> select mtest();
+--------------------------------+
| mtest()
|
+--------------------------------+
| mysql plugin string type test. |
+--------------------------------+
1 row in set (0.02 sec)
//drop
mysql> DROP FUNCTION mtest;