LoginSignup
1

More than 5 years have passed since last update.

MariaDB で、UDF (User-Defined Function) を使う

Last updated at Posted at 2017-05-18
msec.c
// ----------------------------------------------------------------------
//
//  msec.c
//
//                      May/19/2017
// ----------------------------------------------------------------------
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <mysql.h>

// ----------------------------------------------------------------------
my_bool msec_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
    return 0;
}

// ----------------------------------------------------------------------
void msec_deinit(UDF_INIT *initid __attribute__((unused)))
{
}

// ----------------------------------------------------------------------
char *msec(UDF_INIT *initid __attribute__((unused)),
    UDF_ARGS *args, char *result, unsigned long *length,
    char *is_null, char *error __attribute__((unused)))
{
    struct timeval tv;
    struct tm *tmptr = NULL;

    is_null = 0;

    gettimeofday(&tv, NULL);
    tmptr = localtime(&tv.tv_sec);

    if(args->arg_count > 0 && ! strcmp( args->args[0], "epoch")){
        sprintf(result, "Msec: %ld.%03ld",
            tv.tv_sec,
            tv.tv_usec / 1000);
    }
    else{
        sprintf(result, "Msec: %04d/%02d/%02d %02d:%02d:%02d:%03ld",
            tmptr->tm_year + 1900, tmptr->tm_mon + 1,
            tmptr->tm_mday, tmptr->tm_hour,
            tmptr->tm_min, tmptr->tm_sec,
            tv.tv_usec / 1000);
    }

    *length = strlen(result);

    return result;
}

// ----------------------------------------------------------------------

コンパイル

gcc -Wall -I/usr/include/mysql -shared -o msec.so -fPIC msec.c

MariaDB の再起動

sudo systemctl restart mysqld

使い方

$ mysql -uroot
MariaDB [(none)]> create function msec returns string soname 'msec.so';
MariaDB [(none)]> select msec ();
+-------------------------------+
| msec ()                       |
+-------------------------------+
| Msec: 2017/05/19 07:42:50:744 |
+-------------------------------+
1 row in set (0.00 sec)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1