Skip to content

Instantly share code, notes, and snippets.

@jbenner-radham
Created November 7, 2013 05:01
Show Gist options
  • Save jbenner-radham/7349214 to your computer and use it in GitHub Desktop.
Save jbenner-radham/7349214 to your computer and use it in GitHub Desktop.
MariaDB/MySQL UDF to capitalize the first letter of each word in a space separated string. Tested on MariaDB 5.5.33a on Ubuntu 12.10.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "mysql.h"
// sudo gcc -Wall -std=c11 -I/usr/include/mysql -shared word_uc.c -o /usr/lib/mysql/plugin/word_uc.so -fPIC
my_bool word_uc_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
if (args->arg_count != 1) {
memcpy(message, "Missing message argument.", 26);
return 1;
}
if (args->arg_type[0] != STRING_RESULT) {
args->arg_type = STRING_RESULT;
}
return 0;
}
// -------------------------------
char *word_uc(
UDF_INIT *initid,
UDF_ARGS *args,
char *result,
unsigned long *length,
char *is_null,
char *error
)
{
*length = strlen(args->args[0]);
if (*length > 255) {
*is_null = 1;
return NULL;
}
size_t space_flag = 0;
size_t str_len = strlen(args->args[0]);
char* temp = (char*)malloc(sizeof args->args[0]);
for (size_t i = 0; i < str_len; ++i) {
if (i == 0 || (islower(args->args[0][i]) && space_flag)) {
temp[i] = toupper(args->args[0][i]);
space_flag = 0;
} else {
if (isspace(args->args[0][i])) {
space_flag = 1;
}
temp[i] = args->args[0][i];
}
}
sprintf(result, "%s", temp);
/* Free it up!!! */
free(temp);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment