当尝试通过调用db2ReadLog的外部UDF获取DB2 LUW数据库上的事务日志信息时,将返回SQL0487N(尝试在SQL语句上执行)。使用与存储过程相同的共享库可以正常工作。
它需要成为UDF的原因是能够最终创建一个表值UDF,它将从事务日志中返回实际条目。
以下是UDF确定初始LRI的C源:
#include <sqlca.h>
#include <db2ApiDf.h>
#include <sqludf.h>
#include <string.h>
#include <stdio.h>
#include <inttypes.h>
#ifdef __plusplus
extern "C"
#endif
SQL_API_RC SQL_API_FN get_initial_lri(SQLUDF_CHAR *lri, SQLUDF_NULLIND
*lri_null_ind, SQLUDF_TRAIL_ARGS)
{
struct sqlca sqlca;
db2ReadLogStruct read_log_params;
db2ReadLogInfoStruct info;
SQL_API_RC rc;
char state_msg[1024], error_msg[1024];
memset(&sqlca, 0, sizeof sqlca);
memset(&read_log_params, 0, sizeof read_log_params);
memset(&info, 0, sizeof info);
read_log_params.iCallerAction = DB2READLOG_QUERY;
read_log_params.iFilterOption = DB2READLOG_FILTER_OFF;
read_log_params.poReadLogInfo = &info;
rc = db2ReadLog(db2Version1058, &read_log_params, &sqlca);
if (rc < 0) {
memcpy(SQLUDF_STATE, "38TA0", SQLUDF_SQLSTATE_LEN);
strncpy(SQLUDF_MSGTX, "Could not query log for initial LRI", SQLUDF_MSGTEXT_LEN);
goto error;
} else if (sqlca.sqlcode < 0) {
strncpy(SQLUDF_STATE, sqlca.sqlstate, SQLUDF_SQLSTATE_LEN);
SQLUDF_MSGTX[0] = '\0';
rc = sqlaintp(error_msg, sizeof error_msg, 80, &sqlca);
if (rc > 0) {
strncpy(SQLUDF_MSGTX, error_msg, SQLUDF_MSGTEXT_LEN);
}
strncat(SQLUDF_MSGTX, "|", SQLUDF_MSGTEXT_LEN);
rc = sqlogstt(state_msg, sizeof state_msg, 80, sqlca.sqlstate);
if (rc > 0) {
strncat(SQLUDF_MSGTX, state_msg, SQLUDF_MSGTEXT_LEN);
}
goto error;
} else {
snprintf(lri, 101, "%" PRIx64 ":%" PRIx64 ":%" PRIx64, info.nextStartLRI.lriType, info.nextStartLRI.part1, info.nextStartLRI.part2);
}
return 0;
error:
return SQLZ_DISCONNECT_PROC;
}
以下SQL用于将C函数注册为外部UDF:
create or replace function get_initial_lri()
returns varchar(100)
language c
external name 'get_initial_lri_0!get_initial_lri'
parameter style sql
fenced not threadsafe
reads sql data
no external action
no scratchpad
no final call
disallow parallel
no dbinfo
为了注册与存储过程相同的代码,SQL是:
create or replace procedure get_initial_lri_sp(out lri varchar(100))
language c
dynamic result sets 0
reads sql data
not deterministic
external name 'get_initial_lri_0!get_initial_lri'
fenced not threadsafe
no external action
program type sub
no dbinfo
parameter style sql
C源代码编译为:
gcc -o get_initial_lri_0 get_initial_lri.c -L ~/sqllib/lib64 -ldb2 -shared -fpic -D_REENTRANT -I ~/sqllib/include
DB2的版本是v10.5.0.8。
是否可以从用户定义的函数调用db2ReadLog API?