2013-08-29

C, MySQL: A minimal UDF

An example, how to start writing an UDF for MySQL.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <stdio.h>
#include <string.h>
 
#include <mysql/my_global.h>
#include <mysql/my_sys.h>
#include <mysql/mysql.h>
#include <mysql/m_ctype.h>
#include <mysql/m_string.h>
 
#define UUID_LEN 36
#define FMASK "%36s"
#define UUID "/proc/sys/kernel/random/uuid"
 
my_bool newid_init(UDF_INIT *initid, UDF_ARGS *args, char *message);
void new_deinit(UDF_INIT *initid);
char *newid(UDF_INIT *initid, UDF_ARGS *args, char *result, unsigned long *length, char *is_null, char *error);
 
my_bool newid_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
    if (args->arg_count != 0 || args->arg_type[0] != STRING_RESULT)
    {
        strcpy(message, "Wrong arguments to newid; Use the source");
        return 1;
    }
    initid->max_length=UUID_LEN;
    return 0;
}
 
void newid_deinit(UDF_INIT *initid)
{
//
}
 
char *newid(UDF_INIT *initid, UDF_ARGS *args, char *result, unsigned long *length, char *is_null, char *error)
{
FILE *fp;
char id[UUID_LEN];
 
    if ((fp = fopen(UUID, "r")) != NULL) {
        fscanf(fp, FMASK, id);
        memcpy(result, id, initid->max_length); // UUID_LEN
        *length = initid->max_length; // UUID_LEN
        *error = 0;
        *is_null = 0;
        return result;
    }
    *is_null = 1;
    *error = 1;
    free(result);
    return NULL;
}

Provides a newid function, which returns an UUID from the kernel's random pool.

No comments :

Post a Comment