Skip to content

Instantly share code, notes, and snippets.

@eatonphil
Last active January 9, 2024 04:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eatonphil/fc0c6761ac2f01910800f38d1e5de3d7 to your computer and use it in GitHub Desktop.
Save eatonphil/fc0c6761ac2f01910800f38d1e5de3d7 to your computer and use it in GitHub Desktop.
Minimal UDF for MariaDB in C

Assume that you've got MariaDB built and running locally. Let's say the install directory is in $MARIADB_LOCAL_INSTALL.

Enter the following into udf_minimal.c:

#include "mariadb.h"

my_bool mysum_init(UDF_INIT* initid, UDF_ARGS* args, char* message);
long long mysum(UDF_INIT* initid, UDF_ARGS* args, char* result,
              unsigned long* length, char* is_null, char* error);

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

long long mysum(UDF_INIT* initid, UDF_ARGS* args, char* result,
                unsigned long* length, char* is_null, char* error) {
  uint i = 0;
  long long sum = 0;
  for (i = 0; i < args->arg_count; i++) {
    if (args->args[i] == NULL) {
      continue;
    }

    sum += *((long long*)args->args[i]);
  }

  return sum;
}

Now build a shared library from it:

$ gcc -I$MARIADB_LOCAL_INSTALL/include -I$MARIADB_LOCAL_INSTALL/sql -I$MARIADB_LOCAL_INSTALL/build/include -shared -o udf_minimal.so udf_minimal.c
$ cp udf_minimal.so $MARIADB_LOCAL_INSTALL/dbplugins

And within the MariaDB client run:

MariaDB [(none)]> CREATE FUNCTION mysum RETURNS INTEGER SONAME 'udf_minimal.so';
Query OK, 0 rows affected (0.003 sec)

And try using the function!

MariaDB [(none)]> select mysum(20, 30);
+---------------+
| mysum(20, 30) |
+---------------+
|            50 |
+---------------+
1 row in set (0.000 sec)

Huzzah!

Sources:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment