自行定制UDF,以提供current_ms方法
1. 编写 C 文件
#ifdef STANDARD
#include <stdio.h>
#include <string.h>
#ifdef __WIN__
typedef unsigned __int64 ulonglong;
typedef unsigned __int64 longlong;
#else
typedef unsigned long long ulonglong;
typedef long long longlong;
#endif /*__WIN__*/
#else
#include <my_global.h>
#include <my_sys.h>
#endif
#include <mysql.h>
#include <m_ctype.h>
#include <m_string.h>
#include <sys/time.h>
#ifdef HAVE_DLOPEN
/* These must be right or mysqld will not find the symbol! */
extern "C" {
my_bool current_ms_init(UDF_INIT *initid, UDF_ARGS *args, char *message);
void current_ms_deinit(UDF_INIT *initid);
longlong current_ms(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error);
}
my_bool current_ms_init(UDF_INIT *initid, UDF_ARGS *args, char *message) {
return 0;
}
void current_ms_deinit(UDF_INIT *initid) {
}
longlong current_ms(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error) {
struct timeval tv;
gettimeofday(&tv, NULL);
longlong value = tv.tv_sec*1000 + (tv.tv_usec/1000);
return value;
}
#endif /* HAVE_DLOPEN */
2. 编写 Makefile 文件
#其中 mysql 的安装位置要根据您的机器自行修改 (可用 mysql_config --cfalgs mysql_config --libs 来获取)
MYSQLCFLAGS = -I/opt/soft/mysql/include/mysql -DUNIV_LINUX -DUNIV_LINUX
MYSQLLIBS = -rdynamic -L/opt/soft/mysql/lib/mysql -lmysqlclient -lz -lcrypt -lnsl -lm
libcurrent_ms.so : libcurrent_ms.o
ld -shared -o libcurrent_ms.so libcurrent_ms.o -fPIC
libcurrent_ms.o : libcurrent_ms.cc
gcc -Wall $(MYSQLCFLAGS) $(MYSQLLIBS) -c libcurrent_ms.cc -o libcurrent_ms.o -fPIC
clean:
rm libcurrent_ms.o libcurrent_ms.so
install:
cp libcurrent_ms.so /opt/soft/mysql/lib/mysql/plugin/
3. make clean
4. make
5. make install
6. 登录mysql
7. 创建UDF
create function current_ms returns integer soname 'libcurrent_ms.so';
8. 使用 current_ms 方法
select current_ms();
9. 销毁UDF
drop function current_ms;