MySQL的UDF


在MYSQL中,通过CREATE FUNCTION命令可以调用不同的.so共享库文件.

在编译前需要加上选项:--with-mysqld-ldflags=-rdynamic

重新编译的时候出了点小问题,可能是升级系统时丢失了……

configure: error: No curses/termcap library found

解决方法:sudo apt-get install libncurses5-dev

之后重新configure通过。

在sql文件夹下有一个实例程序udf_example.c文件。可以对该文件进行单独编译,生成共享库文件:

gcc -shared -o udf_example.so udf_example.cc -I /usr/local/mysql/include/mysql

 

在sql文件夹下,文件udf_example.def给出了函数清单:

LIBRARY udf_example

VERSION 1.0

EXPORTS

lookup

lookup_init

reverse_lookup

reverse_lookup_init

metaphon_init

metaphon_deinit

metaphon

myfunc_double_init

myfunc_double

myfunc_int_init

myfunc_int

sequence_init

sequence_deinit

sequence

avgcost_init

avgcost_deinit

avgcost_reset

avgcost_add

avgcost_clear

avgcost

is_const

is_const_init

check_const_len

check_const_len_init

其中:xx_init表示加载函数,xx_deinit表示卸载函数,分别对应create function 和drop function

xx_clear:重置或归零相关值

xx_add:和xx_clear一起用于group by这样的需要分组的情形。

 

修改配置文件my.cnf

在mysqld中增加行:plugin_dir = /usr/local/mysql/lib/plugin,所有的共享库文件都被存储在这个文件夹中

我们将udf_example.so文件cp到该文件夹中,然后打开服务器,执行:mysql> create function metaphon returns string soname "udf_example.so";

报错:ERROR 1127 (HY000): Can't find symbol 'metaphon' in library

 

共享库文件位置正确,权限也没啥问题,百思不的其解,网上找了很多,也没找到正确的解答,寻思可能是编译UDF源文件出错,经过多次尝试,以如下格式编译,调用成功:

make udf_example.o

gcc -Wall -shared -DMYSQL_DYNAMIC_PLUGIN udf_example.o -o udf_example.so

然后将udf_example.so拷贝到/usr/local/mysql/lib/plugin文件夹下,执行成功:

mysql> create function metaphon returns string soname "udf_example.so";

Query OK, 0 rows affected (0.00 sec)

相关内容