DELAEMON BLOG

Live as if you were to die tomorrow. Learn as if you were to live forever.

MySQL UserDefinedFunction

http://dev.mysql.com/doc/refman/4.1/ja/adding-udf.html

単純関数のUDFでhello world的なものを作ってみる。

orz.c

#include <string.h>
#include <mysql/mysql.h>

my_bool orz_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
    return 0;
}

void orz_deinit(UDF_INIT *initid)
{

}

char* orz(UDF_INIT *initid, UDF_ARGS *args, char *res, unsigned long *res_length, char *is_null, char *error)
{
    strcpy(res, "orz...orz...orz...");
    *res_length = strlen(res);
    return res;
}

pluginのディレクトリを調べる

mysql> SHOW VARIABLES LIKE 'plugin_dir';
+---------------+------------------------+
| Variable_name | Value                  |
+---------------+------------------------+
| plugin_dir    | /usr/lib/mysql/plugin/ |
+---------------+------------------------+
1 row in set (0.00 sec)

コンパイルして*.soをpluginのディレクトリに置く

$ gcc -o orz.so orz.c `mysql_config --cflags` -shared -fPIC
$ sudo cp orz.so /usr/lib/mysql/plugin/

mysqlに作った関数を登録

mysql> CREATE FUNCTION orz RETURNS STRING SONAME "orz.so";

実行

mysql> SELECT orz();
+--------------------+
| orz()              |
+--------------------+
| orz...orz...orz... |
+--------------------+
1 row in set (0.00 sec)

この本が詳しいらしいので、あとで読む

Mysql 5.1 Plugin Development

Mysql 5.1 Plugin Development