2013-08-29

C, MySQL: A minimal UDF

An example, how to start writing an UDF for MySQL.
#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