南大通用GBase 8a一个CUDF样例

本文提供一个简单的GBase 8a数据库集群,采用C编写UDF的样例代码,仅供参考。

#include <gbase_global.h>
#include <gbase_sys.h>
#include <stdio.h>
#include <stdlib.h>
#include <m_string.h>
#include <gbase.h>
#include <ctype.h>
#include <string.h>
#include <time.h>

#define MAX_RES_LEN (255*3+1)

void Getpartid(unsigned char *key,int len,unsigned long *nr1,unsigned long *nr2)
{
        unsigned char sort_order[4] = {0};
        sort_order[0] = *key;
        const unsigned char *end= key + len;
        for (; key < (unsigned char*) end ; key++)
        {
                nr1[0]^=(unsigned long)((((unsigned int)nr1[0] & 63) + nr2[0]) * ((unsigned int) *key)) + (nr1[0] <<8 );
                nr2[0]+=3;
        }
}

my_bool getkeypartid_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
	if (args->arg_count != 2 ) 
	{
		strcpy(message, "Input params count is error!");
		return;
	}
	
	args->arg_type[0] = INT_RESULT;
	args->arg_type[1] = INT_RESULT;	

	initid->maybe_null = 1;  
	initid->extension = NULL;  
	initid->max_length = args->lengths[0] > 20 ? args->lengths[0] : 20; //最大返回值不会超过参数一的最大长度

	//最大长度如果超过预分配的内存大小,重新分配一块内存存放结果
	if (initid->max_length  > MAX_RES_LEN)
	{
		initid->ptr = (char *) malloc(initid->max_length);
		if(initid->ptr == NULL)
		{
			strcpy(message, "Malloc failed.");
			return 1;
		}
		memset(initid->ptr,0,initid->max_length);
	}
	
	return 0;
}

char * getkeypartid(UDF_INIT *initid, UDF_ARGS *args, char *result, unsigned long *length, char *is_null, char *error)
{
	unsigned char value[4]={0};
        int orivalue = *(int*)args->args[0];
	
	unsigned long returnval=0;	

        value[0]=(unsigned char) (orivalue)       & 0xFF;
        value[1]=(unsigned char) (orivalue >> 8)  & 0xFF;
        value[2]=(unsigned char) (orivalue >> 16) & 0xFF;
        value[3]=(unsigned char) (orivalue >> 24) & 0xFF;
        unsigned long nr1 = 1;
        unsigned long nr2 = 4;
        Getpartid(value,4,&nr1,&nr2);
	returnval=((unsigned int)(nr1)%(*(int*)(args->args[1]))+1);

	sprintf((char *)result,"%d",returnval);
	*length =  args->lengths[1];
        return result;

}
   
void  getkeypartid_deinit(UDF_INIT *initid)
{
	if (initid->ptr)
	{
		free(initid->ptr);
		initid->ptr = NULL;
	}
}