udf2.c 2.1 KB
Newer Older
S
slzhou 已提交
1 2 3 4 5 6 7 8 9 10 11
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include "tudf.h"

#undef malloc
#define malloc malloc
#undef free
#define free free

wafwerar's avatar
wafwerar 已提交
12
DLL_EXPORT int32_t udf2_init() {
S
slzhou 已提交
13 14 15
  return 0;
}

wafwerar's avatar
wafwerar 已提交
16
DLL_EXPORT int32_t udf2_destroy() {
S
slzhou 已提交
17 18 19
  return 0;
}

wafwerar's avatar
wafwerar 已提交
20
DLL_EXPORT int32_t udf2_start(SUdfInterBuf *buf) {
21
  *(int64_t*)(buf->buf) = 0;
22
  buf->bufLen = sizeof(double);
23 24
  buf->numOfResult = 0;
  return 0;
S
slzhou 已提交
25 26
}

wafwerar's avatar
wafwerar 已提交
27
DLL_EXPORT int32_t udf2(SUdfDataBlock* block, SUdfInterBuf *interBuf, SUdfInterBuf *newInterBuf) {
28
  double sumSquares = *(double*)interBuf->buf;
29
  int8_t numNotNull = 0;
30 31
  for (int32_t i = 0; i < block->numOfCols; ++i) {
    SUdfColumn* col = block->udfCols[i];
32 33
    if (!(col->colMeta.type == TSDB_DATA_TYPE_INT || 
          col->colMeta.type == TSDB_DATA_TYPE_DOUBLE)) {
34 35 36
      return TSDB_CODE_UDF_INVALID_INPUT;
    }
  }
37
  for (int32_t i = 0; i < block->numOfCols; ++i) {
S
slzhou 已提交
38
    for (int32_t j = 0; j < block->numOfRows; ++j) {
39
      SUdfColumn* col = block->udfCols[i];
S
slzhou 已提交
40 41 42
      if (udfColDataIsNull(col, j)) {
        continue;
      }
43 44 45 46
      switch (col->colMeta.type) {
        case TSDB_DATA_TYPE_INT: {
          char* cell = udfColDataGetData(col, j);
          int32_t num = *(int32_t*)cell;
47
          sumSquares += (double)num * num;
48 49 50 51 52 53 54 55 56 57 58
          break;
        }
        case TSDB_DATA_TYPE_DOUBLE: {
          char* cell = udfColDataGetData(col, j);
          double num = *(double*)cell;
          sumSquares += num * num;
          break;
        }
        default: 
          break;
      }
59
      ++numNotNull;
S
slzhou 已提交
60 61 62
    }
  }

63 64 65 66 67 68 69
  *(double*)(newInterBuf->buf) = sumSquares;
  newInterBuf->bufLen = sizeof(double);

  if (interBuf->numOfResult == 0 && numNotNull == 0) {
    newInterBuf->numOfResult = 0;
  } else {
    newInterBuf->numOfResult = 1;
S
slzhou 已提交
70
  }
S
slzhou 已提交
71 72 73
  return 0;
}

wafwerar's avatar
wafwerar 已提交
74
DLL_EXPORT int32_t udf2_finish(SUdfInterBuf* buf, SUdfInterBuf *resultData) {
S
slzhou 已提交
75 76 77 78
  if (buf->numOfResult == 0) {
    resultData->numOfResult = 0;
    return 0;
  }
79
  double sumSquares = *(double*)(buf->buf);
80 81 82
  *(double*)(resultData->buf) = sqrt(sumSquares);
  resultData->bufLen = sizeof(double);
  resultData->numOfResult = 1;
S
slzhou 已提交
83 84
  return 0;
}