udf2.c 1.9 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
  *(int64_t*)(buf->buf) = 0;
22
  buf->bufLen = sizeof(double);
23 24
  buf->numOfResult = 0;
  return 0;
S
slzhou 已提交
25 26
}

S
shenglian zhou 已提交
27
int32_t udf2(SUdfDataBlock* block, SUdfInterBuf *interBuf, SUdfInterBuf *newInterBuf) {
28
  double sumSquares = *(double*)interBuf->buf;
S
slzhou 已提交
29
  int8_t numOutput = 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;
      }
S
slzhou 已提交
59
      numOutput = 1;
S
slzhou 已提交
60 61 62
    }
  }

S
slzhou 已提交
63
  if (numOutput == 1) {
64 65
    *(double*)(newInterBuf->buf) = sumSquares;
    newInterBuf->bufLen = sizeof(double);
S
slzhou 已提交
66 67
  }
  newInterBuf->numOfResult = numOutput;
S
slzhou 已提交
68 69 70
  return 0;
}

71
int32_t udf2_finish(SUdfInterBuf* buf, SUdfInterBuf *resultData) {
S
slzhou 已提交
72 73 74 75
  if (buf->numOfResult == 0) {
    resultData->numOfResult = 0;
    return 0;
  }
76
  double sumSquares = *(double*)(buf->buf);
77 78 79
  *(double*)(resultData->buf) = sqrt(sumSquares);
  resultData->bufLen = sizeof(double);
  resultData->numOfResult = 1;
S
slzhou 已提交
80 81
  return 0;
}