今度は自分でUDFを作ってみました

なんか眠れないので作ってみました.一度慣れちゃうとあっという間ですね.
指定した時間(ミリ秒)だけsleepする関数です.UDFの関数名は"the_world".某有名スタンドからw

SuSE Linux 10 + MySQL 5.0.18です.

ソースコード丸ごとはこちら
http://ikda.net/resource/mysql/the_world.cc

関数the_world_initでパラメータのチェック

my_bool the_world_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
  printf("the_world_init is invoked!\n");

  if (args->arg_count != 1 || args->arg_type[0] != INT_RESULT)
  {
    strcpy(message, "Wrong arguments to the_world; Use one integer parameter to specifiy milliseconds");
    return 1;
  }  
  return 0;
}

関数the_worldでパラメータを1000倍してusleepを呼び出し.パラメータをそのまま戻り値として返す.

longlong the_world(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error)
{
  printf("the_world is invoked!\n");
   
  unsigned long val = 0; 

  val = *((longlong*) args->args[0]);  

  usleep(val * 1000);
  return val;
}

興味本位それぞれprintf文を仕込んで見ました.

ちなみに関数the_world_deinitも

void the_world_init(UDF_INIT *initid)
{
  printf("the_world_deinit is invoked!\n");
}

コンパイルは普通通りに以下でやってます.

shell> g++ -I "/usr/local/mysql/include" -c -o the_world.o the_world.cc
shell> g++ -shared -o the_world.so the_world.o

the_world.soを"/usr/lib"にコピーしてからちゃんと動くかテスト.

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2 to server version: 5.0.18-max

Type 'help;' or '\h' for help. Type '\c' to clear the buffer.

mysql> CREATE FUNCTION the_world RETURNS INTEGER SONAME "the_world.so";
Query OK, 0 rows affected (0.01 sec)

インストールが上手く行きましたね.続いて呼び出し.

mysql> SELECT the_world(1000);
+-----------------+
| the_world(1000) |
+-----------------+
|            1000 |
+-----------------+
1 row in set (1.01 sec)

1.01秒になってますがまあオーバーヘッドで1/100秒加算されちゃったのでしょう.

mysql> SELECT the_world(2000);
+-----------------+
| the_world(2000) |
+-----------------+
|            2000 |
+-----------------+
1 row in set (2.00 sec)

今度はずばり2.00秒.

mysql> SELECT the_world("hoge");
ERROR:
Wrong arguments to the_world; Use one integer parameter to specifiy milliseconds

ちゃんとパラメータチェックも出来ました.

しこんでおいたprintfは想定どおりmysqldを起動したコンソールに出ていました.



感想:
しかしUDFってのは面白い仕組みですよね.SQLの世界からC/C++の世界へコンニチハですから.udf_example.ccにはlookup関数(ホスト名からIP)とか入ってましたが世界が広がりますね.

UDF側がコンポーネントRDBMS側がフレームワーク,とも見れるのかな.