udf2.c 1.5 KB
Newer Older
S
slzhou 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

#include "tudf.h"

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

int32_t udf2_init() {
  return 0;
}

int32_t udf2_destroy() {
  return 0;
}

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

S
shenglian zhou 已提交
27
int32_t udf2(SUdfDataBlock* block, SUdfInterBuf *interBuf, SUdfInterBuf *newInterBuf) {
28
  int64_t sumSquares = *(int64_t*)interBuf->buf;
S
slzhou 已提交
29
  int8_t numOutput = 0;
30 31 32 33 34 35
  for (int32_t i = 0; i < block->numOfCols; ++i) {
    SUdfColumn* col = block->udfCols[i];
    if (col->colMeta.type != TSDB_DATA_TYPE_INT) {
      return TSDB_CODE_UDF_INVALID_INPUT;
    }
  }
36
  for (int32_t i = 0; i < block->numOfCols; ++i) {
S
slzhou 已提交
37
    for (int32_t j = 0; j < block->numOfRows; ++j) {
38
      SUdfColumn* col = block->udfCols[i];
S
slzhou 已提交
39 40 41 42 43 44 45 46
      if (udfColDataIsNull(col, j)) {
        continue;
      }

      char* cell = udfColDataGetData(col, j);
      int32_t num = *(int32_t*)cell;
      sumSquares += num * num;
      numOutput = 1;
S
slzhou 已提交
47 48 49
    }
  }

S
slzhou 已提交
50 51 52 53 54
  if (numOutput == 1) {
    *(int64_t*)(newInterBuf->buf) = sumSquares;
    newInterBuf->bufLen = sizeof(int64_t);
  }
  newInterBuf->numOfResult = numOutput;
S
slzhou 已提交
55 56 57
  return 0;
}

58
int32_t udf2_finish(SUdfInterBuf* buf, SUdfInterBuf *resultData) {
S
slzhou 已提交
59 60 61 62
  if (buf->numOfResult == 0) {
    resultData->numOfResult = 0;
    return 0;
  }
63 64 65 66
  int64_t sumSquares = *(int64_t*)(buf->buf);
  *(double*)(resultData->buf) = sqrt(sumSquares);
  resultData->bufLen = sizeof(double);
  resultData->numOfResult = 1;
S
slzhou 已提交
67 68
  return 0;
}