User-Defined Functions (UDF)

The built-in functions of TDengine may not be sufficient for the use cases of every application. In this case, you can define custom functions for use in TDengine queries. These are known as user-defined functions (UDF). A user-defined function takes one column of data or the result of a subquery as its input.

TDengine supports user-defined functions written in C or C++. This document describes the usage of user-defined functions.

User-defined functions can be scalar functions or aggregate functions. Scalar functions, such as abs, sin, and concat, output a value for every row of data. Aggregate functions, such as avg and max output one value for multiple rows of data.

When you create a user-defined function, you must implement standard interface functions:

  • For scalar functions, implement the scalarfn interface function.
  • For aggregate functions, implement the aggfn_start, aggfn, and aggfn_finish interface functions.
  • To initialize your function, implement the udf_init function. To terminate your function, implement the udf_destroy function.

There are strict naming conventions for these interface functions. The names of the start, finish, init, and destroy interfaces must be <udf-name>_start, <udf-name>_finish, <udf-name>_init, and <udf-name>_destroy, respectively. Replace scalarfn, aggfn, and udf with the name of your user-defined function.

Implementing a Scalar Function

The implementation of a scalar function is described as follows:

  1. #include "taos.h"
  2. #include "taoserror.h"
  3. #include "taosudf.h"
  4. // initialization function. if no initialization, we can skip definition of it. The initialization function shall be concatenation of the udf name and _init suffix
  5. // @return error number defined in taoserror.h
  6. int32_t scalarfn_init() {
  7. // initialization.
  8. return TSDB_CODE_SUCCESS;
  9. }
  10. // scalar function main computation function
  11. // @param inputDataBlock, input data block composed of multiple columns with each column defined by SUdfColumn
  12. // @param resultColumn, output column
  13. // @return error number defined in taoserror.h
  14. int32_t scalarfn(SUdfDataBlock* inputDataBlock, SUdfColumn* resultColumn) {
  15. // read data from inputDataBlock and process, then output to resultColumn.
  16. return TSDB_CODE_SUCCESS;
  17. }
  18. // cleanup function. if no cleanup related processing, we can skip definition of it. The destroy function shall be concatenation of the udf name and _destroy suffix.
  19. // @return error number defined in taoserror.h
  20. int32_t scalarfn_destroy() {
  21. // clean up
  22. return TSDB_CODE_SUCCESS;
  23. }

Replace scalarfn with the name of your function.

Implementing an Aggregate Function

The implementation of an aggregate function is described as follows:

  1. #include "taos.h"
  2. #include "taoserror.h"
  3. #include "taosudf.h"
  4. // Initialization function. if no initialization, we can skip definition of it. The initialization function shall be concatenation of the udf name and _init suffix
  5. // @return error number defined in taoserror.h
  6. int32_t aggfn_init() {
  7. // initialization.
  8. return TSDB_CODE_SUCCESS;
  9. }
  10. // aggregate start function. The intermediate value or the state(@interBuf) is initialized in this function. The function name shall be concatenation of udf name and _start suffix
  11. // @param interbuf intermediate value to intialize
  12. // @return error number defined in taoserror.h
  13. int32_t aggfn_start(SUdfInterBuf* interBuf) {
  14. // initialize intermediate value in interBuf
  15. return TSDB_CODE_SUCESS;
  16. }
  17. // aggregate reduce function. This function aggregate old state(@interbuf) and one data bock(inputBlock) and output a new state(@newInterBuf).
  18. // @param inputBlock input data block
  19. // @param interBuf old state
  20. // @param newInterBuf new state
  21. // @return error number defined in taoserror.h
  22. int32_t aggfn(SUdfDataBlock* inputBlock, SUdfInterBuf *interBuf, SUdfInterBuf *newInterBuf) {
  23. // read from inputBlock and interBuf and output to newInterBuf
  24. return TSDB_CODE_SUCCESS;
  25. }
  26. // aggregate function finish function. This function transforms the intermediate value(@interBuf) into the final output(@result). The function name must be concatenation of aggfn and _finish suffix.
  27. // @interBuf : intermediate value
  28. // @result: final result
  29. // @return error number defined in taoserror.h
  30. int32_t int32_t aggfn_finish(SUdfInterBuf* interBuf, SUdfInterBuf *result) {
  31. // read data from inputDataBlock and process, then output to result
  32. return TSDB_CODE_SUCCESS;
  33. }
  34. // cleanup function. if no cleanup related processing, we can skip definition of it. The destroy function shall be concatenation of the udf name and _destroy suffix.
  35. // @return error number defined in taoserror.h
  36. int32_t aggfn_destroy() {
  37. // clean up
  38. return TSDB_CODE_SUCCESS;
  39. }

Replace aggfn with the name of your function.

Interface Functions

There are strict naming conventions for interface functions. The names of the start, finish, init, and destroy interfaces must be <udf-name>_start, <udf-name>_finish, <udf-name>_init, and <udf-name>_destroy, respectively. Replace scalarfn, aggfn, and udf with the name of your user-defined function.

Interface functions return a value that indicates whether the operation was successful. If an operation fails, the interface function returns an error code. Otherwise, it returns TSDB_CODE_SUCCESS. The error codes are defined in taoserror.h and in the common API error codes in taos.h. For example, TSDB_CODE_UDF_INVALID_INPUT indicates invalid input. TSDB_CODE_OUT_OF_MEMORY indicates insufficient memory.

For information about the parameters for interface functions, see Data Model

Interfaces for Scalar Functions

int32_t scalarfn(SUdfDataBlock* inputDataBlock, SUdfColumn *resultColumn)

Replace scalarfn with the name of your function. This function performs scalar calculations on data blocks. You can configure a value through the parameters in the resultColumn structure.

The parameters in the function are defined as follows:

  • inputDataBlock: The data block to input.
  • resultColumn: The column to output. The column to output.

Interfaces for Aggregate Functions

int32_t aggfn_start(SUdfInterBuf *interBuf)

int32_t aggfn(SUdfDataBlock* inputBlock, SUdfInterBuf *interBuf, SUdfInterBuf *newInterBuf)

int32_t aggfn_finish(SUdfInterBuf* interBuf, SUdfInterBuf *result)

Replace aggfn with the name of your function. In the function, aggfn_start is called to generate a result buffer. Data is then divided between multiple blocks, and aggfn is called on each block to update the result. Finally, aggfn_finish is called to generate final results from the intermediate results. The final result contains only one or zero data points.

The parameters in the function are defined as follows:

  • interBuf: The intermediate result buffer.
  • inputBlock: The data block to input.
  • newInterBuf: The new intermediate result buffer.
  • result: The final result.

Initializing and Terminating User-Defined Functions

int32_t udf_init()

int32_t udf_destroy()

Replace udfwith the name of your function. udf_init initializes the function. udf_destroy terminates the function. If it is not necessary to initialize your function, udf_init is not required. If it is not necessary to terminate your function, udf_destroy is not required.

Data Structure of User-Defined Functions

  1. typedef struct SUdfColumnMeta {
  2. int16_t type;
  3. int32_t bytes;
  4. uint8_t precision;
  5. uint8_t scale;
  6. } SUdfColumnMeta;
  7. typedef struct SUdfColumnData {
  8. int32_t numOfRows;
  9. int32_t rowsAlloc;
  10. union {
  11. struct {
  12. int32_t nullBitmapLen;
  13. char *nullBitmap;
  14. int32_t dataLen;
  15. char *data;
  16. } fixLenCol;
  17. struct {
  18. int32_t varOffsetsLen;
  19. int32_t *varOffsets;
  20. int32_t payloadLen;
  21. char *payload;
  22. int32_t payloadAllocLen;
  23. } varLenCol;
  24. };
  25. } SUdfColumnData;
  26. typedef struct SUdfColumn {
  27. SUdfColumnMeta colMeta;
  28. bool hasNull;
  29. SUdfColumnData colData;
  30. } SUdfColumn;
  31. typedef struct SUdfDataBlock {
  32. int32_t numOfRows;
  33. int32_t numOfCols;
  34. SUdfColumn **udfCols;
  35. } SUdfDataBlock;
  36. typedef struct SUdfInterBuf {
  37. int32_t bufLen;
  38. char* buf;
  39. int8_t numOfResult; //zero or one
  40. } SUdfInterBuf;

The data structure is described as follows:

  • The SUdfDataBlock block includes the number of rows (numOfRows) and number of columns (numCols). udfCols[i] (0 <= i <= numCols-1) indicates that each column is of type SUdfColumn.
  • SUdfColumn includes the definition of the data type of the column (colMeta) and the data in the column (colData).
  • The member definitions of SUdfColumnMeta are the same as the data type definitions in taos.h.
  • The data in SUdfColumnData can become longer. varLenCol indicates variable-length data, and fixLenCol indicates fixed-length data.
  • SUdfInterBuf defines the intermediate structure buffer and the number of results in the buffer numOfResult.

Additional functions are defined in taosudf.h to make it easier to work with these structures.

Compile UDF

To use your user-defined function in TDengine, first compile it to a dynamically linked library (DLL).

For example, the sample UDF bit_and.c can be compiled into a DLL as follows:

  1. gcc -g -O0 -fPIC -shared bit_and.c -o libbitand.so

The generated DLL file libbitand.so can now be used to implement your function. Note: GCC 7.5 or later is required.

Manage and Use User-Defined Functions

After compiling your function into a DLL, you add it to TDengine. For more information, see User-Defined Functions.

Sample Code

Sample scalar function: bit_and

The bit_and function implements bitwise addition for multiple columns. If there is only one column, the column is returned. The bit_and function ignores null values.

bit_and.c

  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include "taosudf.h"
  5. DLL_EXPORT int32_t bit_and_init() {
  6. return 0;
  7. }
  8. DLL_EXPORT int32_t bit_and_destroy() {
  9. return 0;
  10. }
  11. DLL_EXPORT int32_t bit_and(SUdfDataBlock* block, SUdfColumn *resultCol) {
  12. if (block->numOfCols < 2) {
  13. return TSDB_CODE_UDF_INVALID_INPUT;
  14. }
  15. for (int32_t i = 0; i < block->numOfCols; ++i) {
  16. SUdfColumn* col = block->udfCols[i];
  17. if (!(col->colMeta.type == TSDB_DATA_TYPE_INT)) {
  18. return TSDB_CODE_UDF_INVALID_INPUT;
  19. }
  20. }
  21. SUdfColumnMeta *meta = &resultCol->colMeta;
  22. meta->bytes = 4;
  23. meta->type = TSDB_DATA_TYPE_INT;
  24. meta->scale = 0;
  25. meta->precision = 0;
  26. SUdfColumnData *resultData = &resultCol->colData;
  27. resultData->numOfRows = block->numOfRows;
  28. for (int32_t i = 0; i < resultData->numOfRows; ++i) {
  29. if (udfColDataIsNull(block->udfCols[0], i)) {
  30. udfColDataSetNull(resultCol, i);
  31. continue;
  32. }
  33. int32_t result = *(int32_t*)udfColDataGetData(block->udfCols[0], i);
  34. int j = 1;
  35. for (; j < block->numOfCols; ++j) {
  36. if (udfColDataIsNull(block->udfCols[j], i)) {
  37. udfColDataSetNull(resultCol, i);
  38. break;
  39. }
  40. char* colData = udfColDataGetData(block->udfCols[j], i);
  41. result &= *(int32_t*)colData;
  42. }
  43. if (j == block->numOfCols) {
  44. udfColDataSet(resultCol, i, (char*)&result, false);
  45. }
  46. }
  47. return TSDB_CODE_SUCCESS;
  48. }

view source code

Sample aggregate function: l2norm

The l2norm function finds the second-order norm for all data in the input column. This squares the values, takes a cumulative sum, and finds the square root.

l2norm.c

  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <math.h>
  5. #include "taosudf.h"
  6. DLL_EXPORT int32_t l2norm_init() {
  7. return 0;
  8. }
  9. DLL_EXPORT int32_t l2norm_destroy() {
  10. return 0;
  11. }
  12. DLL_EXPORT int32_t l2norm_start(SUdfInterBuf *buf) {
  13. *(int64_t*)(buf->buf) = 0;
  14. buf->bufLen = sizeof(double);
  15. buf->numOfResult = 0;
  16. return 0;
  17. }
  18. DLL_EXPORT int32_t l2norm(SUdfDataBlock* block, SUdfInterBuf *interBuf, SUdfInterBuf *newInterBuf) {
  19. double sumSquares = *(double*)interBuf->buf;
  20. int8_t numNotNull = 0;
  21. for (int32_t i = 0; i < block->numOfCols; ++i) {
  22. SUdfColumn* col = block->udfCols[i];
  23. if (!(col->colMeta.type == TSDB_DATA_TYPE_INT ||
  24. col->colMeta.type == TSDB_DATA_TYPE_DOUBLE)) {
  25. return TSDB_CODE_UDF_INVALID_INPUT;
  26. }
  27. }
  28. for (int32_t i = 0; i < block->numOfCols; ++i) {
  29. for (int32_t j = 0; j < block->numOfRows; ++j) {
  30. SUdfColumn* col = block->udfCols[i];
  31. if (udfColDataIsNull(col, j)) {
  32. continue;
  33. }
  34. switch (col->colMeta.type) {
  35. case TSDB_DATA_TYPE_INT: {
  36. char* cell = udfColDataGetData(col, j);
  37. int32_t num = *(int32_t*)cell;
  38. sumSquares += (double)num * num;
  39. break;
  40. }
  41. case TSDB_DATA_TYPE_DOUBLE: {
  42. char* cell = udfColDataGetData(col, j);
  43. double num = *(double*)cell;
  44. sumSquares += num * num;
  45. break;
  46. }
  47. default:
  48. break;
  49. }
  50. ++numNotNull;
  51. }
  52. }
  53. *(double*)(newInterBuf->buf) = sumSquares;
  54. newInterBuf->bufLen = sizeof(double);
  55. if (interBuf->numOfResult == 0 && numNotNull == 0) {
  56. newInterBuf->numOfResult = 0;
  57. } else {
  58. newInterBuf->numOfResult = 1;
  59. }
  60. return 0;
  61. }
  62. DLL_EXPORT int32_t l2norm_finish(SUdfInterBuf* buf, SUdfInterBuf *resultData) {
  63. if (buf->numOfResult == 0) {
  64. resultData->numOfResult = 0;
  65. return 0;
  66. }
  67. double sumSquares = *(double*)(buf->buf);
  68. *(double*)(resultData->buf) = sqrt(sumSquares);
  69. resultData->bufLen = sizeof(double);
  70. resultData->numOfResult = 1;
  71. return 0;
  72. }

view source code