在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)