A summing aggregate UDF
As discussed earlier in this chapter, aggregate UDFs are great for performing operations on groups of rows. Things work slightly differently here, we have a new keyword to use when installing UDFs and two extra functions to deal with individual rows and to clean up after every group of rows.
Let's write an aggregating UDF that will add up floating point numbers. We will call it udf_floatsum:
#include <stdlib.h> #include <string.h> #include <mysql.h> my_bool udf_floatsum_init(UDF_INIT *initid, UDF_ARGS *args, char *message) { double* float_total = malloc(sizeof(double)); *float_total = 0; initid->ptr = (char*) float_total;
To aggregate we need an accumulator, a variable of the type double
to keep the running totals as we are seeing rows one by one. Different queries invoking our UDF must have different running totals, in other words, initid->ptr
is exactly what's needed. We allocate memory for one double
and save a pointer to it in initid...