sclfunc.c 88.4 KB
Newer Older
H
Hongze Cheng 已提交
1
#include "cJSON.h"
H
Haojun Liao 已提交
2 3
#include "function.h"
#include "scalar.h"
H
Haojun Liao 已提交
4
#include "sclInt.h"
D
dapan1121 已提交
5
#include "sclvector.h"
6
#include "tdatablock.h"
wmmhello's avatar
wmmhello 已提交
7
#include "tjson.h"
8
#include "ttime.h"
9

G
Ganlin Zhao 已提交
10 11 12 13
typedef float (*_float_fn)(float);
typedef double (*_double_fn)(double);
typedef double (*_double_fn_2)(double, double);
typedef int (*_conv_fn)(int);
H
Hongze Cheng 已提交
14
typedef void (*_trim_fn)(char *, char *, int32_t, int32_t);
G
Ganlin Zhao 已提交
15
typedef int16_t (*_len_fn)(char *, int32_t);
G
Ganlin Zhao 已提交
16

17
/** Math functions **/
H
Hongze Cheng 已提交
18
static double tlog(double v) { return log(v); }
19 20

static double tlog2(double v, double base) {
21 22 23 24 25 26
  double a = log(v);
  double b = log(base);
  if (isnan(a) || isinf(a)) {
    return a;
  } else if (isnan(b) || isinf(b)) {
    return b;
27 28
  } else {
    return a / b;
29
  }
30 31
}

32
int32_t absFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
33
  SColumnInfoData *pInputData = pInput->columnData;
H
Haojun Liao 已提交
34 35 36
  SColumnInfoData *pOutputData = pOutput->columnData;

  int32_t type = GET_PARAM_TYPE(pInput);
37

H
Haojun Liao 已提交
38
  switch (type) {
39
    case TSDB_DATA_TYPE_FLOAT: {
H
Hongze Cheng 已提交
40
      float *in = (float *)pInputData->pData;
H
Haojun Liao 已提交
41
      float *out = (float *)pOutputData->pData;
42
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
43 44
        if (colDataIsNull_s(pInputData, i)) {
          colDataAppendNULL(pOutputData, i);
H
Haojun Liao 已提交
45 46
          continue;
        }
H
Hongze Cheng 已提交
47
        out[i] = (in[i] >= 0) ? in[i] : -in[i];
48
      }
H
Haojun Liao 已提交
49
      break;
50 51 52
    }

    case TSDB_DATA_TYPE_DOUBLE: {
H
Hongze Cheng 已提交
53
      double *in = (double *)pInputData->pData;
H
Haojun Liao 已提交
54
      double *out = (double *)pOutputData->pData;
55
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
56 57
        if (colDataIsNull_s(pInputData, i)) {
          colDataAppendNULL(pOutputData, i);
H
Haojun Liao 已提交
58 59
          continue;
        }
H
Hongze Cheng 已提交
60
        out[i] = (in[i] >= 0) ? in[i] : -in[i];
H
Haojun Liao 已提交
61 62
      }
      break;
63 64
    }

H
Haojun Liao 已提交
65
    case TSDB_DATA_TYPE_TINYINT: {
H
Hongze Cheng 已提交
66
      int8_t *in = (int8_t *)pInputData->pData;
H
Haojun Liao 已提交
67
      int8_t *out = (int8_t *)pOutputData->pData;
68
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
69 70
        if (colDataIsNull_s(pInputData, i)) {
          colDataAppendNULL(pOutputData, i);
H
Haojun Liao 已提交
71 72
          continue;
        }
H
Hongze Cheng 已提交
73
        out[i] = (in[i] >= 0) ? in[i] : -in[i];
74
      }
H
Haojun Liao 已提交
75 76
      break;
    }
77

H
Haojun Liao 已提交
78
    case TSDB_DATA_TYPE_SMALLINT: {
H
Hongze Cheng 已提交
79
      int16_t *in = (int16_t *)pInputData->pData;
H
Haojun Liao 已提交
80
      int16_t *out = (int16_t *)pOutputData->pData;
81
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
82 83
        if (colDataIsNull_s(pInputData, i)) {
          colDataAppendNULL(pOutputData, i);
H
Haojun Liao 已提交
84 85
          continue;
        }
H
Hongze Cheng 已提交
86
        out[i] = (in[i] >= 0) ? in[i] : -in[i];
87
      }
H
Haojun Liao 已提交
88 89
      break;
    }
90

H
Haojun Liao 已提交
91
    case TSDB_DATA_TYPE_INT: {
H
Hongze Cheng 已提交
92
      int32_t *in = (int32_t *)pInputData->pData;
H
Haojun Liao 已提交
93
      int32_t *out = (int32_t *)pOutputData->pData;
94
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
95 96
        if (colDataIsNull_s(pInputData, i)) {
          colDataAppendNULL(pOutputData, i);
H
Haojun Liao 已提交
97 98
          continue;
        }
H
Hongze Cheng 已提交
99
        out[i] = (in[i] >= 0) ? in[i] : -in[i];
100
      }
H
Haojun Liao 已提交
101 102
      break;
    }
103

H
Haojun Liao 已提交
104
    case TSDB_DATA_TYPE_BIGINT: {
H
Hongze Cheng 已提交
105
      int64_t *in = (int64_t *)pInputData->pData;
H
Haojun Liao 已提交
106
      int64_t *out = (int64_t *)pOutputData->pData;
107
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
108 109
        if (colDataIsNull_s(pInputData, i)) {
          colDataAppendNULL(pOutputData, i);
H
Haojun Liao 已提交
110 111
          continue;
        }
H
Hongze Cheng 已提交
112
        out[i] = (in[i] >= 0) ? in[i] : -in[i];
113
      }
H
Haojun Liao 已提交
114
      break;
115 116
    }

117 118 119 120 121 122 123
    case TSDB_DATA_TYPE_NULL: {
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
        colDataAppendNULL(pOutputData, i);
      }
      break;
    }

H
Haojun Liao 已提交
124
    default: {
125
      colDataAssign(pOutputData, pInputData, pInput->numOfRows, NULL);
126 127
    }
  }
128

H
Haojun Liao 已提交
129
  pOutput->numOfRows = pInput->numOfRows;
130
  return TSDB_CODE_SUCCESS;
131 132
}

H
Hongze Cheng 已提交
133
static int32_t doScalarFunctionUnique(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput, _double_fn valFn) {
H
Haojun Liao 已提交
134
  int32_t type = GET_PARAM_TYPE(pInput);
135

136
  SColumnInfoData *pInputData = pInput->columnData;
H
Haojun Liao 已提交
137
  SColumnInfoData *pOutputData = pOutput->columnData;
138

139
  _getDoubleValue_fn_t getValueFn = getVectorDoubleValueFn(type);
140

141
  double *out = (double *)pOutputData->pData;
142

143
  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
144
    if (colDataIsNull_s(pInputData, i) || IS_NULL_TYPE(type)) {
145
      colDataAppendNULL(pOutputData, i);
146
      continue;
147
    }
148 149 150 151 152 153
    double result = valFn(getValueFn(pInputData->pData, i));
    if (isinf(result) || isnan(result)) {
      colDataAppendNULL(pOutputData, i);
    } else {
      out[i] = result;
    }
154
  }
155

H
Haojun Liao 已提交
156
  pOutput->numOfRows = pInput->numOfRows;
157
  return TSDB_CODE_SUCCESS;
158 159
}

H
Hongze Cheng 已提交
160 161 162 163
static int32_t doScalarFunctionUnique2(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput,
                                       _double_fn_2 valFn) {
  SColumnInfoData     *pInputData[2];
  SColumnInfoData     *pOutputData = pOutput->columnData;
G
Ganlin Zhao 已提交
164
  _getDoubleValue_fn_t getValueFn[2];
165

G
Ganlin Zhao 已提交
166 167
  for (int32_t i = 0; i < inputNum; ++i) {
    pInputData[i] = pInput[i].columnData;
H
Hongze Cheng 已提交
168
    getValueFn[i] = getVectorDoubleValueFn(GET_PARAM_TYPE(&pInput[i]));
G
Ganlin Zhao 已提交
169
  }
170

171
  double *out = (double *)pOutputData->pData;
H
Hongze Cheng 已提交
172
  double  result;
173

H
Hongze Cheng 已提交
174
  bool hasNullType = (IS_NULL_TYPE(GET_PARAM_TYPE(&pInput[0])) || IS_NULL_TYPE(GET_PARAM_TYPE(&pInput[1])));
175

wafwerar's avatar
wafwerar 已提交
176
  int32_t numOfRows = TMAX(pInput[0].numOfRows, pInput[1].numOfRows);
177 178
  if (pInput[0].numOfRows == pInput[1].numOfRows) {
    for (int32_t i = 0; i < numOfRows; ++i) {
H
Hongze Cheng 已提交
179
      if (colDataIsNull_s(pInputData[0], i) || colDataIsNull_s(pInputData[1], i) || hasNullType) {
180 181 182 183 184 185 186 187 188
        colDataAppendNULL(pOutputData, i);
        continue;
      }
      result = valFn(getValueFn[0](pInputData[0]->pData, i), getValueFn[1](pInputData[1]->pData, i));
      if (isinf(result) || isnan(result)) {
        colDataAppendNULL(pOutputData, i);
      } else {
        out[i] = result;
      }
189
    }
H
Hongze Cheng 已提交
190
  } else if (pInput[0].numOfRows == 1) {  // left operand is constant
191
    if (colDataIsNull_s(pInputData[0], 0) || hasNullType) {
192
      colDataAppendNNULL(pOutputData, 0, pInput[1].numOfRows);
193
    } else {
194 195 196 197 198
      for (int32_t i = 0; i < numOfRows; ++i) {
        if (colDataIsNull_s(pInputData[1], i)) {
          colDataAppendNULL(pOutputData, i);
          continue;
        }
199

200 201 202 203 204 205 206 207
        result = valFn(getValueFn[0](pInputData[0]->pData, 0), getValueFn[1](pInputData[1]->pData, i));
        if (isinf(result) || isnan(result)) {
          colDataAppendNULL(pOutputData, i);
          continue;
        }

        out[i] = result;
      }
208
    }
209
  } else if (pInput[1].numOfRows == 1) {
210
    if (colDataIsNull_s(pInputData[1], 0) || hasNullType) {
211
      colDataAppendNNULL(pOutputData, 0, pInput[0].numOfRows);
212
    } else {
213 214 215 216 217 218 219 220 221 222 223 224 225 226
      for (int32_t i = 0; i < numOfRows; ++i) {
        if (colDataIsNull_s(pInputData[0], i)) {
          colDataAppendNULL(pOutputData, i);
          continue;
        }

        result = valFn(getValueFn[0](pInputData[0]->pData, i), getValueFn[1](pInputData[1]->pData, 0));
        if (isinf(result) || isnan(result)) {
          colDataAppendNULL(pOutputData, i);
          continue;
        }

        out[i] = result;
      }
227
    }
228
  }
229

230
  pOutput->numOfRows = numOfRows;
231 232 233
  return TSDB_CODE_SUCCESS;
}

H
Hongze Cheng 已提交
234 235
static int32_t doScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput, _float_fn f1,
                                _double_fn d1) {
H
Haojun Liao 已提交
236
  int32_t type = GET_PARAM_TYPE(pInput);
237

H
Hongze Cheng 已提交
238
  SColumnInfoData *pInputData = pInput->columnData;
H
Haojun Liao 已提交
239
  SColumnInfoData *pOutputData = pOutput->columnData;
240

H
Haojun Liao 已提交
241 242
  switch (type) {
    case TSDB_DATA_TYPE_FLOAT: {
H
Hongze Cheng 已提交
243
      float *in = (float *)pInputData->pData;
H
Haojun Liao 已提交
244
      float *out = (float *)pOutputData->pData;
245

246
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
247 248
        if (colDataIsNull_s(pInputData, i)) {
          colDataAppendNULL(pOutputData, i);
H
Haojun Liao 已提交
249 250
          continue;
        }
251
        out[i] = f1(in[i]);
252
      }
H
Haojun Liao 已提交
253 254
      break;
    }
255

H
Haojun Liao 已提交
256
    case TSDB_DATA_TYPE_DOUBLE: {
H
Hongze Cheng 已提交
257
      double *in = (double *)pInputData->pData;
H
Haojun Liao 已提交
258
      double *out = (double *)pOutputData->pData;
259

260
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
261 262
        if (colDataIsNull_s(pInputData, i)) {
          colDataAppendNULL(pOutputData, i);
H
Haojun Liao 已提交
263 264
          continue;
        }
265
        out[i] = d1(in[i]);
266
      }
H
Haojun Liao 已提交
267 268 269
      break;
    }

270 271 272 273 274 275 276
    case TSDB_DATA_TYPE_NULL: {
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
        colDataAppendNULL(pOutputData, i);
      }
      break;
    }

H
Haojun Liao 已提交
277
    default: {
278
      colDataAssign(pOutputData, pInputData, pInput->numOfRows, NULL);
279
    }
280 281
  }

H
Haojun Liao 已提交
282
  pOutput->numOfRows = pInput->numOfRows;
283 284
  return TSDB_CODE_SUCCESS;
}
285

G
Ganlin Zhao 已提交
286
/** String functions **/
H
Hongze Cheng 已提交
287
static int16_t tlength(char *input, int32_t type) { return varDataLen(input); }
G
Ganlin Zhao 已提交
288

289
static int16_t tcharlength(char *input, int32_t type) {
G
Ganlin Zhao 已提交
290 291
  if (type == TSDB_DATA_TYPE_VARCHAR) {
    return varDataLen(input);
H
Hongze Cheng 已提交
292
  } else {  // NCHAR
G
Ganlin Zhao 已提交
293
    return varDataLen(input) / TSDB_NCHAR_SIZE;
G
Ganlin Zhao 已提交
294
  }
G
Ganlin Zhao 已提交
295
}
G
Ganlin Zhao 已提交
296

297
static void tltrim(char *input, char *output, int32_t type, int32_t charLen) {
G
Ganlin Zhao 已提交
298 299 300 301 302 303 304 305
  int32_t numOfSpaces = 0;
  if (type == TSDB_DATA_TYPE_VARCHAR) {
    for (int32_t i = 0; i < charLen; ++i) {
      if (!isspace(*(varDataVal(input) + i))) {
        break;
      }
      numOfSpaces++;
    }
H
Hongze Cheng 已提交
306
  } else {  // NCHAR
G
Ganlin Zhao 已提交
307 308 309 310 311 312 313
    for (int32_t i = 0; i < charLen; ++i) {
      if (!iswspace(*((uint32_t *)varDataVal(input) + i))) {
        break;
      }
      numOfSpaces++;
    }
  }
G
Ganlin Zhao 已提交
314

G
Ganlin Zhao 已提交
315 316 317 318 319 320 321 322
  int32_t resLen;
  if (type == TSDB_DATA_TYPE_VARCHAR) {
    resLen = charLen - numOfSpaces;
    memcpy(varDataVal(output), varDataVal(input) + numOfSpaces, resLen);
  } else {
    resLen = (charLen - numOfSpaces) * TSDB_NCHAR_SIZE;
    memcpy(varDataVal(output), varDataVal(input) + numOfSpaces * TSDB_NCHAR_SIZE, resLen);
  }
G
Ganlin Zhao 已提交
323

G
Ganlin Zhao 已提交
324 325 326
  varDataSetLen(output, resLen);
}

327
static void trtrim(char *input, char *output, int32_t type, int32_t charLen) {
G
Ganlin Zhao 已提交
328 329 330 331 332 333 334 335
  int32_t numOfSpaces = 0;
  if (type == TSDB_DATA_TYPE_VARCHAR) {
    for (int32_t i = charLen - 1; i >= 0; --i) {
      if (!isspace(*(varDataVal(input) + i))) {
        break;
      }
      numOfSpaces++;
    }
H
Hongze Cheng 已提交
336
  } else {  // NCHAR
337
    for (int32_t i = charLen - 1; i >= 0; --i) {
G
Ganlin Zhao 已提交
338 339 340 341
      if (!iswspace(*((uint32_t *)varDataVal(input) + i))) {
        break;
      }
      numOfSpaces++;
G
Ganlin Zhao 已提交
342
    }
G
Ganlin Zhao 已提交
343
  }
G
Ganlin Zhao 已提交
344

G
Ganlin Zhao 已提交
345 346 347 348 349
  int32_t resLen;
  if (type == TSDB_DATA_TYPE_VARCHAR) {
    resLen = charLen - numOfSpaces;
  } else {
    resLen = (charLen - numOfSpaces) * TSDB_NCHAR_SIZE;
G
Ganlin Zhao 已提交
350
  }
G
Ganlin Zhao 已提交
351
  memcpy(varDataVal(output), varDataVal(input), resLen);
G
Ganlin Zhao 已提交
352

G
Ganlin Zhao 已提交
353
  varDataSetLen(output, resLen);
G
Ganlin Zhao 已提交
354 355
}

356
static int32_t doLengthFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput, _len_fn lenFn) {
G
Ganlin Zhao 已提交
357 358
  int32_t type = GET_PARAM_TYPE(pInput);

H
Hongze Cheng 已提交
359
  SColumnInfoData *pInputData = pInput->columnData;
G
Ganlin Zhao 已提交
360 361
  SColumnInfoData *pOutputData = pOutput->columnData;

362 363
  ASSERT(pOutputData->info.type == TSDB_DATA_TYPE_BIGINT);
  int64_t *out = (int64_t *)pOutputData->pData;
G
Ganlin Zhao 已提交
364 365

  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
366
    if (colDataIsNull_s(pInputData, i)) {
367
      colDataAppendNULL(pOutputData, i);
G
Ganlin Zhao 已提交
368 369 370
      continue;
    }

371
    char *in = colDataGetData(pInputData, i);
G
Ganlin Zhao 已提交
372
    out[i] = lenFn(in, type);
G
Ganlin Zhao 已提交
373 374 375 376 377
  }

  pOutput->numOfRows = pInput->numOfRows;
  return TSDB_CODE_SUCCESS;
}
378

379 380
static int32_t concatCopyHelper(const char *input, char *output, bool hasNchar, int32_t type, int16_t *dataLen) {
  if (hasNchar && type == TSDB_DATA_TYPE_VARCHAR) {
381
    TdUcs4 *newBuf = taosMemoryCalloc((varDataLen(input) + 1) * TSDB_NCHAR_SIZE, 1);
382
    int32_t len = varDataLen(input);
H
Hongze Cheng 已提交
383
    bool    ret = taosMbsToUcs4(varDataVal(input), len, newBuf, (varDataLen(input) + 1) * TSDB_NCHAR_SIZE, &len);
384 385 386 387 388 389 390 391 392 393 394 395
    if (!ret) {
      taosMemoryFree(newBuf);
      return TSDB_CODE_FAILED;
    }
    memcpy(varDataVal(output) + *dataLen, newBuf, varDataLen(input) * TSDB_NCHAR_SIZE);
    *dataLen += varDataLen(input) * TSDB_NCHAR_SIZE;
    taosMemoryFree(newBuf);
  } else {
    memcpy(varDataVal(output) + *dataLen, varDataVal(input), varDataLen(input));
    *dataLen += varDataLen(input);
  }
  return TSDB_CODE_SUCCESS;
396
}
G
Ganlin Zhao 已提交
397

398 399 400 401 402 403 404 405 406 407 408 409 410
static int32_t getNumOfNullEntries(SColumnInfoData *pColumnInfoData, int32_t numOfRows) {
  int32_t numOfNulls = 0;
  if (!pColumnInfoData->hasNull) {
    return numOfNulls;
  }
  for (int i = 0; i < numOfRows; ++i) {
    if (pColumnInfoData->varmeta.offset[i] == -1) {
      numOfNulls++;
    }
  }
  return numOfNulls;
}

G
Ganlin Zhao 已提交
411
int32_t concatFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
412
  int32_t           ret = TSDB_CODE_SUCCESS;
G
Ganlin Zhao 已提交
413
  SColumnInfoData **pInputData = taosMemoryCalloc(inputNum, sizeof(SColumnInfoData *));
H
Hongze Cheng 已提交
414 415 416
  SColumnInfoData  *pOutputData = pOutput->columnData;
  char            **input = taosMemoryCalloc(inputNum, POINTER_BYTES);
  char             *outputBuf = NULL;
G
Ganlin Zhao 已提交
417

418
  int32_t inputLen = 0;
419
  int32_t numOfRows = 0;
H
Hongze Cheng 已提交
420
  bool    hasNchar = (GET_PARAM_TYPE(pOutput) == TSDB_DATA_TYPE_NCHAR) ? true : false;
421 422 423 424 425
  for (int32_t i = 0; i < inputNum; ++i) {
    if (pInput[i].numOfRows > numOfRows) {
      numOfRows = pInput[i].numOfRows;
    }
  }
G
Ganlin Zhao 已提交
426 427
  for (int32_t i = 0; i < inputNum; ++i) {
    pInputData[i] = pInput[i].columnData;
428
    int32_t factor = 1;
429
    if (hasNchar && (GET_PARAM_TYPE(&pInput[i]) == TSDB_DATA_TYPE_VARCHAR)) {
430 431
      factor = TSDB_NCHAR_SIZE;
    }
432 433

    int32_t numOfNulls = getNumOfNullEntries(pInputData[i], pInput[i].numOfRows);
434
    if (pInput[i].numOfRows == 1) {
435
      inputLen += (pInputData[i]->varmeta.length - VARSTR_HEADER_SIZE) * factor * (numOfRows - numOfNulls);
436
    } else {
437
      inputLen += (pInputData[i]->varmeta.length - (numOfRows - numOfNulls) * VARSTR_HEADER_SIZE) * factor;
438
    }
439 440
  }

441 442 443
  int32_t outputLen = inputLen + numOfRows * VARSTR_HEADER_SIZE;
  outputBuf = taosMemoryCalloc(outputLen, 1);
  char *output = outputBuf;
G
Ganlin Zhao 已提交
444

445
  for (int32_t k = 0; k < numOfRows; ++k) {
446
    bool hasNull = false;
G
Ganlin Zhao 已提交
447
    for (int32_t i = 0; i < inputNum; ++i) {
H
Hongze Cheng 已提交
448
      if (colDataIsNull_s(pInputData[i], k) || IS_NULL_TYPE(GET_PARAM_TYPE(&pInput[i]))) {
449
        colDataAppendNULL(pOutputData, k);
G
Ganlin Zhao 已提交
450 451 452 453 454 455 456 457 458 459 460
        hasNull = true;
        break;
      }
    }

    if (hasNull) {
      continue;
    }

    int16_t dataLen = 0;
    for (int32_t i = 0; i < inputNum; ++i) {
461 462
      int32_t rowIdx = (pInput[i].numOfRows == 1) ? 0 : k;
      input[i] = colDataGetData(pInputData[i], rowIdx);
463 464 465 466

      ret = concatCopyHelper(input[i], output, hasNchar, GET_PARAM_TYPE(&pInput[i]), &dataLen);
      if (ret != TSDB_CODE_SUCCESS) {
        goto DONE;
467
      }
G
Ganlin Zhao 已提交
468
    }
469
    varDataSetLen(output, dataLen);
470 471
    colDataAppend(pOutputData, k, output, false);
    output += varDataTLen(output);
G
Ganlin Zhao 已提交
472 473
  }

474
  pOutput->numOfRows = numOfRows;
475 476

DONE:
477
  taosMemoryFree(input);
478
  taosMemoryFree(outputBuf);
G
Ganlin Zhao 已提交
479 480
  taosMemoryFree(pInputData);

481
  return ret;
G
Ganlin Zhao 已提交
482 483 484
}

int32_t concatWsFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
485
  int32_t           ret = TSDB_CODE_SUCCESS;
G
Ganlin Zhao 已提交
486
  SColumnInfoData **pInputData = taosMemoryCalloc(inputNum, sizeof(SColumnInfoData *));
H
Hongze Cheng 已提交
487 488 489
  SColumnInfoData  *pOutputData = pOutput->columnData;
  char            **input = taosMemoryCalloc(inputNum, POINTER_BYTES);
  char             *outputBuf = NULL;
G
Ganlin Zhao 已提交
490

491
  int32_t inputLen = 0;
492
  int32_t numOfRows = 0;
H
Hongze Cheng 已提交
493
  bool    hasNchar = (GET_PARAM_TYPE(pOutput) == TSDB_DATA_TYPE_NCHAR) ? true : false;
494
  for (int32_t i = 1; i < inputNum; ++i) {
495 496 497 498
    if (pInput[i].numOfRows > numOfRows) {
      numOfRows = pInput[i].numOfRows;
    }
  }
G
Ganlin Zhao 已提交
499 500
  for (int32_t i = 0; i < inputNum; ++i) {
    pInputData[i] = pInput[i].columnData;
501
    int32_t factor = 1;
502
    if (hasNchar && (GET_PARAM_TYPE(&pInput[i]) == TSDB_DATA_TYPE_VARCHAR)) {
503 504
      factor = TSDB_NCHAR_SIZE;
    }
505 506

    int32_t numOfNulls = getNumOfNullEntries(pInputData[i], pInput[i].numOfRows);
507 508
    if (i == 0) {
      // calculate required separator space
H
Hongze Cheng 已提交
509 510
      inputLen +=
          (pInputData[0]->varmeta.length - VARSTR_HEADER_SIZE) * (numOfRows - numOfNulls) * (inputNum - 2) * factor;
511
    } else if (pInput[i].numOfRows == 1) {
512
      inputLen += (pInputData[i]->varmeta.length - VARSTR_HEADER_SIZE) * (numOfRows - numOfNulls) * factor;
513
    } else {
514
      inputLen += (pInputData[i]->varmeta.length - (numOfRows - numOfNulls) * VARSTR_HEADER_SIZE) * factor;
515 516 517
    }
  }

518 519 520
  int32_t outputLen = inputLen + numOfRows * VARSTR_HEADER_SIZE;
  outputBuf = taosMemoryCalloc(outputLen, 1);
  char *output = outputBuf;
G
Ganlin Zhao 已提交
521

522
  for (int32_t k = 0; k < numOfRows; ++k) {
H
Hongze Cheng 已提交
523
    if (colDataIsNull_s(pInputData[0], k) || IS_NULL_TYPE(GET_PARAM_TYPE(&pInput[0]))) {
524
      colDataAppendNULL(pOutputData, k);
G
Ganlin Zhao 已提交
525 526 527 528
      continue;
    }

    int16_t dataLen = 0;
H
Hongze Cheng 已提交
529
    bool    hasNull = false;
G
Ganlin Zhao 已提交
530
    for (int32_t i = 1; i < inputNum; ++i) {
H
Hongze Cheng 已提交
531
      if (colDataIsNull_s(pInputData[i], k) || IS_NULL_TYPE(GET_PARAM_TYPE(&pInput[i]))) {
532 533
        hasNull = true;
        break;
G
Ganlin Zhao 已提交
534 535
      }

536 537
      int32_t rowIdx = (pInput[i].numOfRows == 1) ? 0 : k;
      input[i] = colDataGetData(pInputData[i], rowIdx);
538

539 540 541
      ret = concatCopyHelper(input[i], output, hasNchar, GET_PARAM_TYPE(&pInput[i]), &dataLen);
      if (ret != TSDB_CODE_SUCCESS) {
        goto DONE;
542
      }
G
Ganlin Zhao 已提交
543 544

      if (i < inputNum - 1) {
H
Hongze Cheng 已提交
545
        // insert the separator
546
        char *sep = (pInput[0].numOfRows == 1) ? colDataGetData(pInputData[0], 0) : colDataGetData(pInputData[0], k);
H
Hongze Cheng 已提交
547
        ret = concatCopyHelper(sep, output, hasNchar, GET_PARAM_TYPE(&pInput[0]), &dataLen);
548
        if (ret != TSDB_CODE_SUCCESS) {
549
          goto DONE;
550
        }
G
Ganlin Zhao 已提交
551 552
      }
    }
553 554 555 556 557 558 559 560 561

    if (hasNull) {
      colDataAppendNULL(pOutputData, k);
      memset(output, 0, dataLen);
    } else {
      varDataSetLen(output, dataLen);
      colDataAppend(pOutputData, k, output, false);
      output += varDataTLen(output);
    }
G
Ganlin Zhao 已提交
562 563
  }

564
  pOutput->numOfRows = numOfRows;
565 566

DONE:
567
  taosMemoryFree(input);
568
  taosMemoryFree(outputBuf);
G
Ganlin Zhao 已提交
569 570
  taosMemoryFree(pInputData);

571
  return ret;
G
Ganlin Zhao 已提交
572 573
}

574
static int32_t doCaseConvFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput, _conv_fn convFn) {
G
Ganlin Zhao 已提交
575 576
  int32_t type = GET_PARAM_TYPE(pInput);

H
Hongze Cheng 已提交
577
  SColumnInfoData *pInputData = pInput->columnData;
G
Ganlin Zhao 已提交
578 579
  SColumnInfoData *pOutputData = pOutput->columnData;

580
  int32_t outputLen = pInputData->varmeta.length;
H
Hongze Cheng 已提交
581 582
  char   *outputBuf = taosMemoryCalloc(outputLen, 1);
  char   *output = outputBuf;
583

G
Ganlin Zhao 已提交
584
  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
585 586
    if (colDataIsNull_s(pInputData, i)) {
      colDataAppendNULL(pOutputData, i);
G
Ganlin Zhao 已提交
587 588 589
      continue;
    }

H
Hongze Cheng 已提交
590
    char   *input = colDataGetData(pInput[0].columnData, i);
591
    int32_t len = varDataLen(input);
G
Ganlin Zhao 已提交
592 593
    if (type == TSDB_DATA_TYPE_VARCHAR) {
      for (int32_t j = 0; j < len; ++j) {
594
        *(varDataVal(output) + j) = convFn(*(varDataVal(input) + j));
G
Ganlin Zhao 已提交
595
      }
H
Hongze Cheng 已提交
596
    } else {  // NCHAR
G
Ganlin Zhao 已提交
597
      for (int32_t j = 0; j < len / TSDB_NCHAR_SIZE; ++j) {
598
        *((uint32_t *)varDataVal(output) + j) = convFn(*((uint32_t *)varDataVal(input) + j));
G
Ganlin Zhao 已提交
599 600
      }
    }
601
    varDataSetLen(output, len);
602
    colDataAppend(pOutputData, i, output, false);
603
    output += varDataTLen(output);
G
Ganlin Zhao 已提交
604 605 606
  }

  pOutput->numOfRows = pInput->numOfRows;
607
  taosMemoryFree(outputBuf);
G
Ganlin Zhao 已提交
608 609 610 611

  return TSDB_CODE_SUCCESS;
}

612
static int32_t doTrimFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput, _trim_fn trimFn) {
G
Ganlin Zhao 已提交
613 614
  int32_t type = GET_PARAM_TYPE(pInput);

H
Hongze Cheng 已提交
615
  SColumnInfoData *pInputData = pInput->columnData;
G
Ganlin Zhao 已提交
616 617
  SColumnInfoData *pOutputData = pOutput->columnData;

618
  int32_t outputLen = pInputData->varmeta.length;
H
Hongze Cheng 已提交
619 620
  char   *outputBuf = taosMemoryCalloc(outputLen, 1);
  char   *output = outputBuf;
621

G
Ganlin Zhao 已提交
622
  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
623 624
    if (colDataIsNull_s(pInputData, i)) {
      colDataAppendNULL(pOutputData, i);
G
Ganlin Zhao 已提交
625 626 627
      continue;
    }

H
Hongze Cheng 已提交
628
    char   *input = colDataGetData(pInputData, i);
629
    int32_t len = varDataLen(input);
G
Ganlin Zhao 已提交
630
    int32_t charLen = (type == TSDB_DATA_TYPE_VARCHAR) ? len : len / TSDB_NCHAR_SIZE;
631 632
    trimFn(input, output, type, charLen);

633
    colDataAppend(pOutputData, i, output, false);
634
    output += varDataTLen(output);
G
Ganlin Zhao 已提交
635 636 637
  }

  pOutput->numOfRows = pInput->numOfRows;
638
  taosMemoryFree(outputBuf);
G
Ganlin Zhao 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652

  return TSDB_CODE_SUCCESS;
}

int32_t substrFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  int32_t subPos = 0;
  GET_TYPED_DATA(subPos, int32_t, GET_PARAM_TYPE(&pInput[1]), pInput[1].columnData->pData);

  int32_t subLen = INT16_MAX;
  if (inputNum == 3) {
    GET_TYPED_DATA(subLen, int32_t, GET_PARAM_TYPE(&pInput[2]), pInput[2].columnData->pData);
    subLen = (GET_PARAM_TYPE(pInput) == TSDB_DATA_TYPE_VARCHAR) ? subLen : subLen * TSDB_NCHAR_SIZE;
  }

H
Hongze Cheng 已提交
653
  SColumnInfoData *pInputData = pInput->columnData;
G
Ganlin Zhao 已提交
654 655
  SColumnInfoData *pOutputData = pOutput->columnData;

656
  int32_t outputLen = pInputData->varmeta.length * pInput->numOfRows;
H
Hongze Cheng 已提交
657 658
  char   *outputBuf = taosMemoryCalloc(outputLen, 1);
  char   *output = outputBuf;
659 660

  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
661 662
    if (colDataIsNull_s(pInputData, i)) {
      colDataAppendNULL(pOutputData, i);
G
Ganlin Zhao 已提交
663 664
      continue;
    }
H
Hongze Cheng 已提交
665
    char   *input = colDataGetData(pInput[0].columnData, i);
666
    int32_t len = varDataLen(input);
G
Ganlin Zhao 已提交
667 668 669 670
    int32_t startPosBytes;

    if (subPos > 0) {
      startPosBytes = (GET_PARAM_TYPE(pInput) == TSDB_DATA_TYPE_VARCHAR) ? subPos - 1 : (subPos - 1) * TSDB_NCHAR_SIZE;
wafwerar's avatar
wafwerar 已提交
671
      startPosBytes = TMIN(startPosBytes, len);
G
Ganlin Zhao 已提交
672
    } else {
H
Hongze Cheng 已提交
673 674
      startPosBytes =
          (GET_PARAM_TYPE(pInput) == TSDB_DATA_TYPE_VARCHAR) ? len + subPos : len + subPos * TSDB_NCHAR_SIZE;
wafwerar's avatar
wafwerar 已提交
675
      startPosBytes = TMAX(startPosBytes, 0);
G
Ganlin Zhao 已提交
676 677
    }

wafwerar's avatar
wafwerar 已提交
678
    int32_t resLen = TMIN(subLen, len - startPosBytes);
679 680
    if (resLen > 0) {
      memcpy(varDataVal(output), varDataVal(input) + startPosBytes, resLen);
G
Ganlin Zhao 已提交
681 682
    }

683
    varDataSetLen(output, resLen);
H
Hongze Cheng 已提交
684
    colDataAppend(pOutputData, i, output, false);
685
    output += varDataTLen(output);
G
Ganlin Zhao 已提交
686 687 688
  }

  pOutput->numOfRows = pInput->numOfRows;
689
  taosMemoryFree(outputBuf);
G
Ganlin Zhao 已提交
690 691 692 693

  return TSDB_CODE_SUCCESS;
}

694
/** Conversion functions **/
G
Ganlin Zhao 已提交
695
int32_t castFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
696 697
  int16_t inputType = GET_PARAM_TYPE(&pInput[0]);
  int16_t inputLen = GET_PARAM_BYTES(&pInput[0]);
698
  int16_t outputType = GET_PARAM_TYPE(&pOutput[0]);
H
Hongze Cheng 已提交
699
  int64_t outputLen = GET_PARAM_BYTES(&pOutput[0]);
G
Ganlin Zhao 已提交
700

701
  int32_t code = TSDB_CODE_SUCCESS;
H
Hongze Cheng 已提交
702 703
  char   *convBuf = taosMemoryMalloc(inputLen);
  char   *output = taosMemoryCalloc(1, outputLen + TSDB_NCHAR_SIZE);
704 705 706 707 708 709
  char    buf[400] = {0};

  if (convBuf == NULL || output == NULL) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto _end;
  }
G
Ganlin Zhao 已提交
710 711 712 713 714 715

  for (int32_t i = 0; i < pInput[0].numOfRows; ++i) {
    if (colDataIsNull_s(pInput[0].columnData, i)) {
      colDataAppendNULL(pOutput->columnData, i);
      continue;
    }
716

717
    char *input = colDataGetData(pInput[0].columnData, i);
G
Ganlin Zhao 已提交
718

H
Hongze Cheng 已提交
719
    switch (outputType) {
720 721
      case TSDB_DATA_TYPE_TINYINT: {
        if (inputType == TSDB_DATA_TYPE_BINARY) {
722 723 724
          memcpy(buf, varDataVal(input), varDataLen(input));
          buf[varDataLen(input)] = 0;
          *(int8_t *)output = taosStr2Int8(buf, NULL, 10);
725
        } else if (inputType == TSDB_DATA_TYPE_NCHAR) {
H
Hongze Cheng 已提交
726
          int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf);
727
          if (len < 0) {
728 729
            code = TSDB_CODE_FAILED;
            goto _end;
730
          }
731 732 733

          convBuf[len] = 0;
          *(int8_t *)output = taosStr2Int8(convBuf, NULL, 10);
734 735 736 737 738 739 740
        } else {
          GET_TYPED_DATA(*(int8_t *)output, int8_t, inputType, input);
        }
        break;
      }
      case TSDB_DATA_TYPE_SMALLINT: {
        if (inputType == TSDB_DATA_TYPE_BINARY) {
741 742 743
          memcpy(buf, varDataVal(input), varDataLen(input));
          buf[varDataLen(input)] = 0;
          *(int16_t *)output = taosStr2Int16(buf, NULL, 10);
744
        } else if (inputType == TSDB_DATA_TYPE_NCHAR) {
H
Hongze Cheng 已提交
745
          int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf);
746
          if (len < 0) {
747 748
            code = TSDB_CODE_FAILED;
            goto _end;
749
          }
750 751
          convBuf[len] = 0;
          *(int16_t *)output = taosStr2Int16(convBuf, NULL, 10);
752 753 754 755 756 757 758
        } else {
          GET_TYPED_DATA(*(int16_t *)output, int16_t, inputType, input);
        }
        break;
      }
      case TSDB_DATA_TYPE_INT: {
        if (inputType == TSDB_DATA_TYPE_BINARY) {
759 760 761
          memcpy(buf, varDataVal(input), varDataLen(input));
          buf[varDataLen(input)] = 0;
          *(int32_t *)output = taosStr2Int32(buf, NULL, 10);
762
        } else if (inputType == TSDB_DATA_TYPE_NCHAR) {
H
Hongze Cheng 已提交
763
          int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf);
764
          if (len < 0) {
765 766
            code = TSDB_CODE_FAILED;
            goto _end;
767
          }
768 769 770

          convBuf[len] = 0;
          *(int32_t *)output = taosStr2Int32(convBuf, NULL, 10);
771 772 773 774 775
        } else {
          GET_TYPED_DATA(*(int32_t *)output, int32_t, inputType, input);
        }
        break;
      }
G
Ganlin Zhao 已提交
776 777
      case TSDB_DATA_TYPE_BIGINT: {
        if (inputType == TSDB_DATA_TYPE_BINARY) {
778 779 780
          memcpy(buf, varDataVal(input), varDataLen(input));
          buf[varDataLen(input)] = 0;
          *(int64_t *)output = taosStr2Int64(buf, NULL, 10);
G
Ganlin Zhao 已提交
781
        } else if (inputType == TSDB_DATA_TYPE_NCHAR) {
H
Hongze Cheng 已提交
782
          int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf);
G
Ganlin Zhao 已提交
783
          if (len < 0) {
784 785
            code = TSDB_CODE_FAILED;
            goto _end;
G
Ganlin Zhao 已提交
786
          }
787 788
          convBuf[len] = 0;
          *(int64_t *)output = taosStr2Int64(convBuf, NULL, 10);
G
Ganlin Zhao 已提交
789 790 791 792 793
        } else {
          GET_TYPED_DATA(*(int64_t *)output, int64_t, inputType, input);
        }
        break;
      }
794 795
      case TSDB_DATA_TYPE_UTINYINT: {
        if (inputType == TSDB_DATA_TYPE_BINARY) {
796 797 798
          memcpy(buf, varDataVal(input), varDataLen(input));
          buf[varDataLen(input)] = 0;
          *(uint8_t *)output = taosStr2UInt8(buf, NULL, 10);
799
        } else if (inputType == TSDB_DATA_TYPE_NCHAR) {
800
          int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf);
801
          if (len < 0) {
802 803
            code = TSDB_CODE_FAILED;
            goto _end;
804
          }
805 806
          convBuf[len] = 0;
          *(uint8_t *)output = taosStr2UInt8(convBuf, NULL, 10);
807 808 809 810 811 812 813
        } else {
          GET_TYPED_DATA(*(uint8_t *)output, uint8_t, inputType, input);
        }
        break;
      }
      case TSDB_DATA_TYPE_USMALLINT: {
        if (inputType == TSDB_DATA_TYPE_BINARY) {
814 815 816
          memcpy(buf, varDataVal(input), varDataLen(input));
          buf[varDataLen(input)] = 0;
          *(uint16_t *)output = taosStr2UInt16(buf, NULL, 10);
817
        } else if (inputType == TSDB_DATA_TYPE_NCHAR) {
818
          int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf);
819
          if (len < 0) {
820 821
            code = TSDB_CODE_FAILED;
            goto _end;
822
          }
823 824
          convBuf[len] = 0;
          *(uint16_t *)output = taosStr2UInt16(convBuf, NULL, 10);
825 826 827 828 829 830 831
        } else {
          GET_TYPED_DATA(*(uint16_t *)output, uint16_t, inputType, input);
        }
        break;
      }
      case TSDB_DATA_TYPE_UINT: {
        if (inputType == TSDB_DATA_TYPE_BINARY) {
832 833 834
          memcpy(buf, varDataVal(input), varDataLen(input));
          buf[varDataLen(input)] = 0;
          *(uint32_t *)output = taosStr2UInt32(buf, NULL, 10);
835
        } else if (inputType == TSDB_DATA_TYPE_NCHAR) {
836
          int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf);
837
          if (len < 0) {
838 839
            code = TSDB_CODE_FAILED;
            goto _end;
840
          }
841 842
          convBuf[len] = 0;
          *(uint32_t *)output = taosStr2UInt32(convBuf, NULL, 10);
843 844 845 846 847
        } else {
          GET_TYPED_DATA(*(uint32_t *)output, uint32_t, inputType, input);
        }
        break;
      }
G
Ganlin Zhao 已提交
848 849
      case TSDB_DATA_TYPE_UBIGINT: {
        if (inputType == TSDB_DATA_TYPE_BINARY) {
850 851 852
          memcpy(buf, varDataVal(input), varDataLen(input));
          buf[varDataLen(input)] = 0;
          *(uint64_t *)output = taosStr2UInt64(buf, NULL, 10);
G
Ganlin Zhao 已提交
853
        } else if (inputType == TSDB_DATA_TYPE_NCHAR) {
854
          int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf);
G
Ganlin Zhao 已提交
855
          if (len < 0) {
856 857
            code = TSDB_CODE_FAILED;
            goto _end;
G
Ganlin Zhao 已提交
858
          }
859 860 861

          convBuf[len] = 0;
          *(uint64_t *)output = taosStr2UInt64(convBuf, NULL, 10);
G
Ganlin Zhao 已提交
862 863 864 865 866
        } else {
          GET_TYPED_DATA(*(uint64_t *)output, uint64_t, inputType, input);
        }
        break;
      }
867 868
      case TSDB_DATA_TYPE_FLOAT: {
        if (inputType == TSDB_DATA_TYPE_BINARY) {
869 870 871
          memcpy(buf, varDataVal(input), varDataLen(input));
          buf[varDataLen(input)] = 0;
          *(float *)output = taosStr2Float(buf, NULL);
872
        } else if (inputType == TSDB_DATA_TYPE_NCHAR) {
H
Hongze Cheng 已提交
873
          int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf);
874
          if (len < 0) {
875 876
            code = TSDB_CODE_FAILED;
            goto _end;
877
          }
878 879
          convBuf[len] = 0;
          *(float *)output = taosStr2Float(convBuf, NULL);
880 881 882 883 884 885 886
        } else {
          GET_TYPED_DATA(*(float *)output, float, inputType, input);
        }
        break;
      }
      case TSDB_DATA_TYPE_DOUBLE: {
        if (inputType == TSDB_DATA_TYPE_BINARY) {
887 888 889
          memcpy(buf, varDataVal(input), varDataLen(input));
          buf[varDataLen(input)] = 0;
          *(double *)output = taosStr2Double(buf, NULL);
890
        } else if (inputType == TSDB_DATA_TYPE_NCHAR) {
H
Hongze Cheng 已提交
891
          int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf);
892
          if (len < 0) {
893 894
            code = TSDB_CODE_FAILED;
            goto _end;
895
          }
896 897
          convBuf[len] = 0;
          *(double *)output = taosStr2Double(convBuf, NULL);
898 899 900 901 902
        } else {
          GET_TYPED_DATA(*(double *)output, double, inputType, input);
        }
        break;
      }
G
Ganlin Zhao 已提交
903 904
      case TSDB_DATA_TYPE_BOOL: {
        if (inputType == TSDB_DATA_TYPE_BINARY) {
905 906 907
          memcpy(buf, varDataVal(input), varDataLen(input));
          buf[varDataLen(input)] = 0;
          *(bool *)output = taosStr2Int8(buf, NULL, 10);
G
Ganlin Zhao 已提交
908
        } else if (inputType == TSDB_DATA_TYPE_NCHAR) {
H
Hongze Cheng 已提交
909
          int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf);
G
Ganlin Zhao 已提交
910
          if (len < 0) {
911 912
            code = TSDB_CODE_FAILED;
            goto _end;
G
Ganlin Zhao 已提交
913
          }
914 915
          convBuf[len] = 0;
          *(bool *)output = taosStr2Int8(convBuf, NULL, 10);
G
Ganlin Zhao 已提交
916 917 918 919 920
        } else {
          GET_TYPED_DATA(*(bool *)output, bool, inputType, input);
        }
        break;
      }
G
Ganlin Zhao 已提交
921
      case TSDB_DATA_TYPE_TIMESTAMP: {
922
        int64_t timeVal;
G
Ganlin Zhao 已提交
923
        if (inputType == TSDB_DATA_TYPE_BINARY || inputType == TSDB_DATA_TYPE_NCHAR) {
924 925 926
          int64_t timePrec;
          GET_TYPED_DATA(timePrec, int64_t, GET_PARAM_TYPE(&pInput[1]), pInput[1].columnData->pData);
          int32_t ret = convertStringToTimestamp(inputType, input, timePrec, &timeVal);
927 928 929 930 931
          if (ret != TSDB_CODE_SUCCESS) {
            *(int64_t *)output = 0;
          } else {
            *(int64_t *)output = timeVal;
          }
G
Ganlin Zhao 已提交
932 933 934 935 936 937 938
        } else {
          GET_TYPED_DATA(*(int64_t *)output, int64_t, inputType, input);
        }
        break;
      }
      case TSDB_DATA_TYPE_BINARY: {
        if (inputType == TSDB_DATA_TYPE_BOOL) {
H
Haojun Liao 已提交
939
          // NOTE: sprintf will append '\0' at the end of string
H
Hongze Cheng 已提交
940 941
          int32_t len = sprintf(varDataVal(output), "%.*s", (int32_t)(outputLen - VARSTR_HEADER_SIZE),
                                *(int8_t *)input ? "true" : "false");
G
Ganlin Zhao 已提交
942 943
          varDataSetLen(output, len);
        } else if (inputType == TSDB_DATA_TYPE_BINARY) {
wafwerar's avatar
wafwerar 已提交
944
          int32_t len = TMIN(varDataLen(input), outputLen - VARSTR_HEADER_SIZE);
H
Haojun Liao 已提交
945
          memcpy(varDataVal(output), varDataVal(input), len);
G
Ganlin Zhao 已提交
946
          varDataSetLen(output, len);
947
        } else if (inputType == TSDB_DATA_TYPE_NCHAR) {
948
          int32_t len = taosUcs4ToMbs((TdUcs4 *)varDataVal(input), varDataLen(input), convBuf);
949
          if (len < 0) {
950 951
            code = TSDB_CODE_FAILED;
            goto _end;
952 953
          }
          len = TMIN(len, outputLen - VARSTR_HEADER_SIZE);
954
          memcpy(varDataVal(output), convBuf, len);
955
          varDataSetLen(output, len);
G
Ganlin Zhao 已提交
956
        } else {
957 958
          NUM_TO_STRING(inputType, input, sizeof(buf), buf);
          int32_t len = (int32_t)strlen(buf);
G
Ganlin Zhao 已提交
959
          len = (outputLen - VARSTR_HEADER_SIZE) > len ? len : (outputLen - VARSTR_HEADER_SIZE);
960
          memcpy(varDataVal(output), buf, len);
G
Ganlin Zhao 已提交
961 962 963 964 965 966
          varDataSetLen(output, len);
        }
        break;
      }
      case TSDB_DATA_TYPE_NCHAR: {
        int32_t outputCharLen = (outputLen - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE;
967
        int32_t len;
G
Ganlin Zhao 已提交
968 969
        if (inputType == TSDB_DATA_TYPE_BOOL) {
          char tmp[8] = {0};
H
Hongze Cheng 已提交
970
          len = sprintf(tmp, "%.*s", outputCharLen, *(int8_t *)input ? "true" : "false");
G
Ganlin Zhao 已提交
971 972
          bool ret = taosMbsToUcs4(tmp, len, (TdUcs4 *)varDataVal(output), outputLen - VARSTR_HEADER_SIZE, &len);
          if (!ret) {
973 974
            code = TSDB_CODE_FAILED;
            goto _end;
G
Ganlin Zhao 已提交
975
          }
976

G
Ganlin Zhao 已提交
977 978
          varDataSetLen(output, len);
        } else if (inputType == TSDB_DATA_TYPE_BINARY) {
979
          len = outputCharLen > varDataLen(input) ? varDataLen(input) : outputCharLen;
H
Hongze Cheng 已提交
980 981
          bool ret = taosMbsToUcs4(input + VARSTR_HEADER_SIZE, len, (TdUcs4 *)varDataVal(output),
                                   outputLen - VARSTR_HEADER_SIZE, &len);
G
Ganlin Zhao 已提交
982
          if (!ret) {
983 984
            code = TSDB_CODE_FAILED;
            goto _end;
G
Ganlin Zhao 已提交
985 986 987
          }
          varDataSetLen(output, len);
        } else if (inputType == TSDB_DATA_TYPE_NCHAR) {
988 989 990
          len = TMIN(outputLen - VARSTR_HEADER_SIZE, varDataLen(input));
          memcpy(output, input, len + VARSTR_HEADER_SIZE);
          varDataSetLen(output, len);
G
Ganlin Zhao 已提交
991
        } else {
992 993
          NUM_TO_STRING(inputType, input, sizeof(buf), buf);
          len = (int32_t)strlen(buf);
G
Ganlin Zhao 已提交
994
          len = outputCharLen > len ? len : outputCharLen;
995
          bool ret = taosMbsToUcs4(buf, len, (TdUcs4 *)varDataVal(output), outputLen - VARSTR_HEADER_SIZE, &len);
G
Ganlin Zhao 已提交
996
          if (!ret) {
997 998
            code = TSDB_CODE_FAILED;
            goto _end;
G
Ganlin Zhao 已提交
999 1000 1001
          }
          varDataSetLen(output, len);
        }
1002

H
Hongze Cheng 已提交
1003
        // for constant conversion, need to set proper length of pOutput description
G
Ganlin Zhao 已提交
1004
        if (len < outputLen) {
D
dapan1121 已提交
1005
          pOutput->columnData->info.bytes = len + VARSTR_HEADER_SIZE;
1006
        }
1007

G
Ganlin Zhao 已提交
1008 1009 1010
        break;
      }
      default: {
1011 1012
        code = TSDB_CODE_FAILED;
        goto _end;
G
Ganlin Zhao 已提交
1013 1014 1015 1016 1017 1018 1019
      }
    }

    colDataAppend(pOutput->columnData, i, output, false);
  }

  pOutput->numOfRows = pInput->numOfRows;
1020

H
Hongze Cheng 已提交
1021
_end:
1022
  taosMemoryFree(output);
H
Haojun Liao 已提交
1023
  taosMemoryFree(convBuf);
1024
  return code;
G
Ganlin Zhao 已提交
1025
}
G
Ganlin Zhao 已提交
1026

1027 1028 1029
int32_t toISO8601Function(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  int32_t type = GET_PARAM_TYPE(pInput);

H
Hongze Cheng 已提交
1030
  bool    tzPresent = (inputNum == 2) ? true : false;
G
Ganlin Zhao 已提交
1031 1032
  char    tz[20] = {0};
  int32_t tzLen = 0;
1033 1034
  if (tzPresent) {
    tzLen = varDataLen(pInput[1].columnData->pData);
G
Ganlin Zhao 已提交
1035
    memcpy(tz, varDataVal(pInput[1].columnData->pData), tzLen);
1036
  }
1037

1038 1039 1040 1041 1042 1043
  for (int32_t i = 0; i < pInput[0].numOfRows; ++i) {
    if (colDataIsNull_s(pInput[0].columnData, i)) {
      colDataAppendNULL(pOutput->columnData, i);
      continue;
    }

1044
    char *input = colDataGetData(pInput[0].columnData, i);
H
Hongze Cheng 已提交
1045 1046
    char  fraction[20] = {0};
    bool  hasFraction = false;
1047 1048 1049
    NUM_TO_STRING(type, input, sizeof(fraction), fraction);
    int32_t tsDigits = (int32_t)strlen(fraction);

H
Hongze Cheng 已提交
1050
    char    buf[64] = {0};
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
    int64_t timeVal;
    GET_TYPED_DATA(timeVal, int64_t, type, input);
    if (tsDigits > TSDB_TIME_PRECISION_SEC_DIGITS) {
      if (tsDigits == TSDB_TIME_PRECISION_MILLI_DIGITS) {
        timeVal = timeVal / 1000;
      } else if (tsDigits == TSDB_TIME_PRECISION_MICRO_DIGITS) {
        timeVal = timeVal / (1000 * 1000);
      } else if (tsDigits == TSDB_TIME_PRECISION_NANO_DIGITS) {
        timeVal = timeVal / (1000 * 1000 * 1000);
      } else {
1061 1062
        colDataAppendNULL(pOutput->columnData, i);
        continue;
1063 1064 1065 1066 1067
      }
      hasFraction = true;
      memmove(fraction, fraction + TSDB_TIME_PRECISION_SEC_DIGITS, TSDB_TIME_PRECISION_SEC_DIGITS);
    }

1068 1069 1070
    struct tm tmInfo;
    taosLocalTime((const time_t *)&timeVal, &tmInfo);
    strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &tmInfo);
1071 1072
    int32_t len = (int32_t)strlen(buf);

H
Hongze Cheng 已提交
1073
    // add timezone string
G
Ganlin Zhao 已提交
1074 1075 1076 1077
    if (tzLen > 0) {
      snprintf(buf + len, tzLen + 1, "%s", tz);
      len += tzLen;
    }
1078

1079 1080
    if (hasFraction) {
      int32_t fracLen = (int32_t)strlen(fraction) + 1;
1081 1082 1083 1084

      char *tzInfo;
      if (buf[len - 1] == 'z' || buf[len - 1] == 'Z') {
        tzInfo = &buf[len - 1];
1085 1086
        memmove(tzInfo + fracLen, tzInfo, strlen(tzInfo));
      } else {
1087 1088 1089 1090
        tzInfo = strchr(buf, '+');
        if (tzInfo) {
          memmove(tzInfo + fracLen, tzInfo, strlen(tzInfo));
        } else {
H
Hongze Cheng 已提交
1091
          // search '-' backwards
1092 1093 1094 1095 1096
          tzInfo = strrchr(buf, '-');
          if (tzInfo) {
            memmove(tzInfo + fracLen, tzInfo, strlen(tzInfo));
          }
        }
1097 1098
      }

1099
      char tmp[32] = {0};
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
      sprintf(tmp, ".%s", fraction);
      memcpy(tzInfo, tmp, fracLen);
      len += fracLen;
    }

    memmove(buf + VARSTR_HEADER_SIZE, buf, len);
    varDataSetLen(buf, len);

    colDataAppend(pOutput->columnData, i, buf, false);
  }

  pOutput->numOfRows = pInput->numOfRows;

  return TSDB_CODE_SUCCESS;
}

1116 1117
int32_t toUnixtimestampFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  int32_t type = GET_PARAM_TYPE(pInput);
1118 1119
  int64_t timePrec;
  GET_TYPED_DATA(timePrec, int64_t, GET_PARAM_TYPE(&pInput[1]), pInput[1].columnData->pData);
1120 1121 1122 1123 1124 1125

  for (int32_t i = 0; i < pInput[0].numOfRows; ++i) {
    if (colDataIsNull_s(pInput[0].columnData, i)) {
      colDataAppendNULL(pOutput->columnData, i);
      continue;
    }
1126
    char *input = colDataGetData(pInput[0].columnData, i);
1127 1128

    int64_t timeVal = 0;
1129 1130 1131
    int32_t ret = convertStringToTimestamp(type, input, timePrec, &timeVal);
    if (ret != TSDB_CODE_SUCCESS) {
      colDataAppendNULL(pOutput->columnData, i);
1132 1133
    } else {
      colDataAppend(pOutput->columnData, i, (char *)&timeVal, false);
1134
    }
1135 1136 1137 1138 1139 1140 1141
  }

  pOutput->numOfRows = pInput->numOfRows;

  return TSDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
1142 1143 1144
int32_t toJsonFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  int32_t type = GET_PARAM_TYPE(pInput);

wmmhello's avatar
wmmhello 已提交
1145
  char tmp[TSDB_MAX_JSON_TAG_LEN] = {0};
wmmhello's avatar
wmmhello 已提交
1146
  for (int32_t i = 0; i < pInput[0].numOfRows; ++i) {
H
Hongze Cheng 已提交
1147 1148
    SArray *pTagVals = taosArrayInit(8, sizeof(STagVal));
    STag   *pTag = NULL;
wmmhello's avatar
wmmhello 已提交
1149

wmmhello's avatar
wmmhello 已提交
1150 1151
    if (colDataIsNull_s(pInput[0].columnData, i)) {
      tTagNew(pTagVals, 1, true, &pTag);
H
Hongze Cheng 已提交
1152
    } else {
wmmhello's avatar
wmmhello 已提交
1153
      char *input = pInput[0].columnData->pData + pInput[0].columnData->varmeta.offset[i];
H
Hongze Cheng 已提交
1154
      if (varDataLen(input) > (TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE) {
wmmhello's avatar
wmmhello 已提交
1155 1156
        taosArrayDestroy(pTagVals);
        return TSDB_CODE_FAILED;
wmmhello's avatar
wmmhello 已提交
1157 1158
      }
      memcpy(tmp, varDataVal(input), varDataLen(input));
wmmhello's avatar
wmmhello 已提交
1159
      tmp[varDataLen(input)] = 0;
H
Hongze Cheng 已提交
1160
      if (parseJsontoTagData(tmp, pTagVals, &pTag, NULL)) {
wmmhello's avatar
wmmhello 已提交
1161 1162
        tTagNew(pTagVals, 1, true, &pTag);
      }
wmmhello's avatar
wmmhello 已提交
1163 1164
    }

H
Hongze Cheng 已提交
1165
    colDataAppend(pOutput->columnData, i, (const char *)pTag, false);
wmmhello's avatar
wmmhello 已提交
1166 1167
    tTagFree(pTag);
    taosArrayDestroy(pTagVals);
wmmhello's avatar
wmmhello 已提交
1168 1169 1170 1171 1172 1173
  }

  pOutput->numOfRows = pInput->numOfRows;
  return TSDB_CODE_SUCCESS;
}

1174
/** Time functions **/
1175 1176 1177
int32_t timeTruncateFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  int32_t type = GET_PARAM_TYPE(&pInput[0]);

1178
  int64_t timeUnit, timePrec, timeVal = 0;
1179
  GET_TYPED_DATA(timeUnit, int64_t, GET_PARAM_TYPE(&pInput[1]), pInput[1].columnData->pData);
1180
  GET_TYPED_DATA(timePrec, int64_t, GET_PARAM_TYPE(&pInput[2]), pInput[2].columnData->pData);
1181

1182
  int64_t factor = TSDB_TICK_PER_SECOND(timePrec);
1183
  int64_t unit = timeUnit * 1000 / factor;
1184

1185 1186 1187 1188 1189 1190
  for (int32_t i = 0; i < pInput[0].numOfRows; ++i) {
    if (colDataIsNull_s(pInput[0].columnData, i)) {
      colDataAppendNULL(pOutput->columnData, i);
      continue;
    }

1191 1192
    char *input = colDataGetData(pInput[0].columnData, i);

1193
    if (IS_VAR_DATA_TYPE(type)) { /* datetime format strings */
1194 1195 1196 1197 1198
      int32_t ret = convertStringToTimestamp(type, input, TSDB_TIME_PRECISION_NANO, &timeVal);
      if (ret != TSDB_CODE_SUCCESS) {
        colDataAppendNULL(pOutput->columnData, i);
        continue;
      }
H
Hongze Cheng 已提交
1199
      // If converted value is less than 10digits in second, use value in second instead
1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
      int64_t timeValSec = timeVal / 1000000000;
      if (timeValSec < 1000000000) {
        timeVal = timeValSec;
      }
    } else if (type == TSDB_DATA_TYPE_BIGINT) { /* unix timestamp */
      GET_TYPED_DATA(timeVal, int64_t, type, input);
    } else if (type == TSDB_DATA_TYPE_TIMESTAMP) { /* timestamp column*/
      GET_TYPED_DATA(timeVal, int64_t, type, input);
      int64_t timeValSec = timeVal / factor;
      if (timeValSec < 1000000000) {
        timeVal = timeValSec;
      }
    }

    char buf[20] = {0};
    NUM_TO_STRING(TSDB_DATA_TYPE_BIGINT, &timeVal, sizeof(buf), buf);
    int32_t tsDigits = (int32_t)strlen(buf);

1218 1219
    switch (unit) {
      case 0: { /* 1u or 1b */
1220
        if (tsDigits == TSDB_TIME_PRECISION_NANO_DIGITS) {
1221 1222 1223 1224 1225
          if (timePrec == TSDB_TIME_PRECISION_NANO && timeUnit == 1) {
            timeVal = timeVal * 1;
          } else {
            timeVal = timeVal / 1000 * 1000;
          }
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
        } else if (tsDigits <= TSDB_TIME_PRECISION_SEC_DIGITS) {
          timeVal = timeVal * factor;
        } else {
          timeVal = timeVal * 1;
        }
        break;
      }
      case 1: { /* 1a */
        if (tsDigits == TSDB_TIME_PRECISION_MILLI_DIGITS) {
          timeVal = timeVal * 1;
        } else if (tsDigits == TSDB_TIME_PRECISION_MICRO_DIGITS) {
          timeVal = timeVal / 1000 * 1000;
        } else if (tsDigits == TSDB_TIME_PRECISION_NANO_DIGITS) {
          timeVal = timeVal / 1000000 * 1000000;
H
Hongze Cheng 已提交
1240
        } else if (tsDigits <= TSDB_TIME_PRECISION_SEC_DIGITS) {
1241 1242
          timeVal = timeVal * factor;
        } else {
1243 1244
          colDataAppendNULL(pOutput->columnData, i);
          continue;
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
        }
        break;
      }
      case 1000: { /* 1s */
        if (tsDigits == TSDB_TIME_PRECISION_MILLI_DIGITS) {
          timeVal = timeVal / 1000 * 1000;
        } else if (tsDigits == TSDB_TIME_PRECISION_MICRO_DIGITS) {
          timeVal = timeVal / 1000000 * 1000000;
        } else if (tsDigits == TSDB_TIME_PRECISION_NANO_DIGITS) {
          timeVal = timeVal / 1000000000 * 1000000000;
        } else if (tsDigits <= TSDB_TIME_PRECISION_SEC_DIGITS) {
          timeVal = timeVal * factor;
        } else {
1258 1259
          colDataAppendNULL(pOutput->columnData, i);
          continue;
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272
        }
        break;
      }
      case 60000: { /* 1m */
        if (tsDigits == TSDB_TIME_PRECISION_MILLI_DIGITS) {
          timeVal = timeVal / 1000 / 60 * 60 * 1000;
        } else if (tsDigits == TSDB_TIME_PRECISION_MICRO_DIGITS) {
          timeVal = timeVal / 1000000 / 60 * 60 * 1000000;
        } else if (tsDigits == TSDB_TIME_PRECISION_NANO_DIGITS) {
          timeVal = timeVal / 1000000000 / 60 * 60 * 1000000000;
        } else if (tsDigits <= TSDB_TIME_PRECISION_SEC_DIGITS) {
          timeVal = timeVal * factor / factor / 60 * 60 * factor;
        } else {
1273 1274
          colDataAppendNULL(pOutput->columnData, i);
          continue;
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
        }
        break;
      }
      case 3600000: { /* 1h */
        if (tsDigits == TSDB_TIME_PRECISION_MILLI_DIGITS) {
          timeVal = timeVal / 1000 / 3600 * 3600 * 1000;
        } else if (tsDigits == TSDB_TIME_PRECISION_MICRO_DIGITS) {
          timeVal = timeVal / 1000000 / 3600 * 3600 * 1000000;
        } else if (tsDigits == TSDB_TIME_PRECISION_NANO_DIGITS) {
          timeVal = timeVal / 1000000000 / 3600 * 3600 * 1000000000;
        } else if (tsDigits <= TSDB_TIME_PRECISION_SEC_DIGITS) {
          timeVal = timeVal * factor / factor / 3600 * 3600 * factor;
        } else {
1288 1289
          colDataAppendNULL(pOutput->columnData, i);
          continue;
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
        }
        break;
      }
      case 86400000: { /* 1d */
        if (tsDigits == TSDB_TIME_PRECISION_MILLI_DIGITS) {
          timeVal = timeVal / 1000 / 86400 * 86400 * 1000;
        } else if (tsDigits == TSDB_TIME_PRECISION_MICRO_DIGITS) {
          timeVal = timeVal / 1000000 / 86400 * 86400 * 1000000;
        } else if (tsDigits == TSDB_TIME_PRECISION_NANO_DIGITS) {
          timeVal = timeVal / 1000000000 / 86400 * 86400 * 1000000000;
        } else if (tsDigits <= TSDB_TIME_PRECISION_SEC_DIGITS) {
H
Hongze Cheng 已提交
1301
          timeVal = timeVal * factor / factor / 86400 * 86400 * factor;
1302
        } else {
1303 1304
          colDataAppendNULL(pOutput->columnData, i);
          continue;
1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
        }
        break;
      }
      case 604800000: { /* 1w */
        if (tsDigits == TSDB_TIME_PRECISION_MILLI_DIGITS) {
          timeVal = timeVal / 1000 / 604800 * 604800 * 1000;
        } else if (tsDigits == TSDB_TIME_PRECISION_MICRO_DIGITS) {
          timeVal = timeVal / 1000000 / 604800 * 604800 * 1000000;
        } else if (tsDigits == TSDB_TIME_PRECISION_NANO_DIGITS) {
          timeVal = timeVal / 1000000000 / 604800 * 604800 * 1000000000;
        } else if (tsDigits <= TSDB_TIME_PRECISION_SEC_DIGITS) {
H
Hongze Cheng 已提交
1316
          timeVal = timeVal * factor / factor / 604800 * 604800 * factor;
1317
        } else {
1318 1319
          colDataAppendNULL(pOutput->columnData, i);
          continue;
1320 1321 1322 1323 1324 1325 1326 1327 1328
        }
        break;
      }
      default: {
        timeVal = timeVal * 1;
        break;
      }
    }

H
Hongze Cheng 已提交
1329
    // truncate the timestamp to db precision
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
    switch (timePrec) {
      case TSDB_TIME_PRECISION_MILLI: {
        if (tsDigits == TSDB_TIME_PRECISION_MICRO_DIGITS) {
          timeVal = timeVal / 1000;
        } else if (tsDigits == TSDB_TIME_PRECISION_NANO_DIGITS) {
          timeVal = timeVal / 1000000;
        }
        break;
      }
      case TSDB_TIME_PRECISION_MICRO: {
        if (tsDigits == TSDB_TIME_PRECISION_NANO_DIGITS) {
          timeVal = timeVal / 1000;
        } else if (tsDigits == TSDB_TIME_PRECISION_MILLI_DIGITS) {
          timeVal = timeVal * 1000;
        }
        break;
      }
      case TSDB_TIME_PRECISION_NANO: {
        if (tsDigits == TSDB_TIME_PRECISION_MICRO_DIGITS) {
          timeVal = timeVal * 1000;
        } else if (tsDigits == TSDB_TIME_PRECISION_MILLI_DIGITS) {
          timeVal = timeVal * 1000000;
        }
        break;
      }
    }

    colDataAppend(pOutput->columnData, i, (char *)&timeVal, false);
  }

  pOutput->numOfRows = pInput->numOfRows;

  return TSDB_CODE_SUCCESS;
}

G
Ganlin Zhao 已提交
1365
int32_t timeDiffFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
1366 1367
  int64_t timeUnit = -1, timePrec, timeVal[2] = {0};
  if (inputNum == 4) {
G
Ganlin Zhao 已提交
1368
    GET_TYPED_DATA(timeUnit, int64_t, GET_PARAM_TYPE(&pInput[2]), pInput[2].columnData->pData);
1369 1370 1371
    GET_TYPED_DATA(timePrec, int64_t, GET_PARAM_TYPE(&pInput[3]), pInput[3].columnData->pData);
  } else {
    GET_TYPED_DATA(timePrec, int64_t, GET_PARAM_TYPE(&pInput[2]), pInput[2].columnData->pData);
G
Ganlin Zhao 已提交
1372 1373
  }

1374
  int64_t factor = TSDB_TICK_PER_SECOND(timePrec);
G
Ganlin Zhao 已提交
1375 1376 1377 1378
  int32_t numOfRows = 0;
  for (int32_t i = 0; i < inputNum; ++i) {
    if (pInput[i].numOfRows > numOfRows) {
      numOfRows = pInput[i].numOfRows;
G
Ganlin Zhao 已提交
1379 1380 1381
    }
  }

G
Ganlin Zhao 已提交
1382 1383 1384
  char *input[2];
  for (int32_t i = 0; i < numOfRows; ++i) {
    bool hasNull = false;
G
Ganlin Zhao 已提交
1385
    for (int32_t k = 0; k < 2; ++k) {
G
Ganlin Zhao 已提交
1386 1387 1388
      if (colDataIsNull_s(pInput[k].columnData, i)) {
        hasNull = true;
        break;
G
Ganlin Zhao 已提交
1389 1390
      }

1391 1392 1393
      int32_t rowIdx = (pInput[k].numOfRows == 1) ? 0 : i;
      input[k] = colDataGetData(pInput[k].columnData, rowIdx);

G
Ganlin Zhao 已提交
1394 1395
      int32_t type = GET_PARAM_TYPE(&pInput[k]);
      if (IS_VAR_DATA_TYPE(type)) { /* datetime format strings */
1396 1397
        int32_t ret = convertStringToTimestamp(type, input[k], TSDB_TIME_PRECISION_NANO, &timeVal[k]);
        if (ret != TSDB_CODE_SUCCESS) {
1398 1399
          hasNull = true;
          break;
1400
        }
G
Ganlin Zhao 已提交
1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
      } else if (type == TSDB_DATA_TYPE_BIGINT || type == TSDB_DATA_TYPE_TIMESTAMP) { /* unix timestamp or ts column*/
        GET_TYPED_DATA(timeVal[k], int64_t, type, input[k]);
        if (type == TSDB_DATA_TYPE_TIMESTAMP) {
          int64_t timeValSec = timeVal[k] / factor;
          if (timeValSec < 1000000000) {
            timeVal[k] = timeValSec;
          }
        }

        char buf[20] = {0};
        NUM_TO_STRING(TSDB_DATA_TYPE_BIGINT, &timeVal[k], sizeof(buf), buf);
        int32_t tsDigits = (int32_t)strlen(buf);
        if (tsDigits <= TSDB_TIME_PRECISION_SEC_DIGITS) {
          timeVal[k] = timeVal[k] * 1000000000;
        } else if (tsDigits == TSDB_TIME_PRECISION_MILLI_DIGITS) {
          timeVal[k] = timeVal[k] * 1000000;
        } else if (tsDigits == TSDB_TIME_PRECISION_MICRO_DIGITS) {
          timeVal[k] = timeVal[k] * 1000;
        } else if (tsDigits == TSDB_TIME_PRECISION_NANO_DIGITS) {
G
Ganlin Zhao 已提交
1420
          timeVal[k] = timeVal[k] * 1;
G
Ganlin Zhao 已提交
1421
        } else {
1422 1423
          hasNull = true;
          break;
G
Ganlin Zhao 已提交
1424
        }
G
Ganlin Zhao 已提交
1425 1426 1427
      }
    }

G
Ganlin Zhao 已提交
1428 1429 1430 1431 1432
    if (hasNull) {
      colDataAppendNULL(pOutput->columnData, i);
      continue;
    }

H
Hongze Cheng 已提交
1433
    int64_t result = (timeVal[0] >= timeVal[1]) ? (timeVal[0] - timeVal[1]) : (timeVal[1] - timeVal[0]);
G
Ganlin Zhao 已提交
1434

H
Hongze Cheng 已提交
1435 1436
    if (timeUnit < 0) {  // if no time unit given use db precision
      switch (timePrec) {
G
Ganlin Zhao 已提交
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
        case TSDB_TIME_PRECISION_MILLI: {
          result = result / 1000000;
          break;
        }
        case TSDB_TIME_PRECISION_MICRO: {
          result = result / 1000;
          break;
        }
        case TSDB_TIME_PRECISION_NANO: {
          result = result / 1;
          break;
        }
      }
    } else {
1451
      int64_t unit = timeUnit * 1000 / factor;
H
Hongze Cheng 已提交
1452
      switch (unit) {
1453 1454 1455 1456 1457 1458
        case 0: { /* 1u or 1b */
          if (timePrec == TSDB_TIME_PRECISION_NANO && timeUnit == 1) {
            result = result / 1;
          } else {
            result = result / 1000;
          }
G
Ganlin Zhao 已提交
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
          break;
        }
        case 1: { /* 1a */
          result = result / 1000000;
          break;
        }
        case 1000: { /* 1s */
          result = result / 1000000000;
          break;
        }
        case 60000: { /* 1m */
          result = result / 1000000000 / 60;
          break;
        }
        case 3600000: { /* 1h */
          result = result / 1000000000 / 3600;
          break;
        }
        case 86400000: { /* 1d */
          result = result / 1000000000 / 86400;
          break;
        }
        case 604800000: { /* 1w */
          result = result / 1000000000 / 604800;
          break;
        }
        default: {
          break;
        }
      }
    }

    colDataAppend(pOutput->columnData, i, (char *)&result, false);
  }

G
Ganlin Zhao 已提交
1494
  pOutput->numOfRows = numOfRows;
G
Ganlin Zhao 已提交
1495 1496 1497 1498

  return TSDB_CODE_SUCCESS;
}

1499
int32_t nowFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
1500 1501 1502 1503
  int64_t timePrec;
  GET_TYPED_DATA(timePrec, int64_t, GET_PARAM_TYPE(&pInput[0]), pInput[0].columnData->pData);

  int64_t ts = taosGetTimestamp(timePrec);
X
Xiaoyu Wang 已提交
1504 1505
  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    colDataAppendInt64(pOutput->columnData, i, &ts);
1506
  }
X
Xiaoyu Wang 已提交
1507
  pOutput->numOfRows = pInput->numOfRows;
1508 1509 1510 1511
  return TSDB_CODE_SUCCESS;
}

int32_t todayFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
1512
  int64_t timePrec;
1513
  GET_TYPED_DATA(timePrec, int64_t, GET_PARAM_TYPE(&pInput[0]), pInput[0].columnData->pData);
1514 1515

  int64_t ts = taosGetTimestampToday(timePrec);
X
Xiaoyu Wang 已提交
1516 1517
  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    colDataAppendInt64(pOutput->columnData, i, &ts);
1518
  }
X
Xiaoyu Wang 已提交
1519
  pOutput->numOfRows = pInput->numOfRows;
1520 1521 1522
  return TSDB_CODE_SUCCESS;
}

1523
int32_t timezoneFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
1524 1525 1526
  char output[TD_TIMEZONE_LEN + VARSTR_HEADER_SIZE] = {0};
  memcpy(varDataVal(output), tsTimezoneStr, TD_TIMEZONE_LEN);
  varDataSetLen(output, strlen(tsTimezoneStr));
X
Xiaoyu Wang 已提交
1527
  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
1528
    colDataAppend(pOutput->columnData, i, output, false);
1529
  }
X
Xiaoyu Wang 已提交
1530
  pOutput->numOfRows = pInput->numOfRows;
1531 1532 1533
  return TSDB_CODE_SUCCESS;
}

1534 1535 1536
int32_t atanFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doScalarFunctionUnique(pInput, inputNum, pOutput, atan);
}
1537

1538 1539 1540
int32_t sinFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doScalarFunctionUnique(pInput, inputNum, pOutput, sin);
}
1541

1542 1543 1544
int32_t cosFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doScalarFunctionUnique(pInput, inputNum, pOutput, cos);
}
1545

1546 1547 1548
int32_t tanFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doScalarFunctionUnique(pInput, inputNum, pOutput, tan);
}
1549

1550 1551 1552
int32_t asinFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doScalarFunctionUnique(pInput, inputNum, pOutput, asin);
}
1553

1554 1555 1556
int32_t acosFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doScalarFunctionUnique(pInput, inputNum, pOutput, acos);
}
H
Haojun Liao 已提交
1557

G
Ganlin Zhao 已提交
1558 1559 1560 1561 1562
int32_t powFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doScalarFunctionUnique2(pInput, inputNum, pOutput, pow);
}

int32_t logFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
1563 1564 1565 1566 1567
  if (inputNum == 1) {
    return doScalarFunctionUnique(pInput, inputNum, pOutput, tlog);
  } else {
    return doScalarFunctionUnique2(pInput, inputNum, pOutput, tlog2);
  }
G
Ganlin Zhao 已提交
1568 1569
}

1570 1571 1572
int32_t sqrtFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doScalarFunctionUnique(pInput, inputNum, pOutput, sqrt);
}
1573

1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
int32_t ceilFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doScalarFunction(pInput, inputNum, pOutput, ceilf, ceil);
}

int32_t floorFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doScalarFunction(pInput, inputNum, pOutput, floorf, floor);
}

int32_t roundFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doScalarFunction(pInput, inputNum, pOutput, roundf, round);
1584 1585
}

G
Ganlin Zhao 已提交
1586
int32_t lowerFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
wafwerar's avatar
wafwerar 已提交
1587 1588 1589
#ifdef WINDOWS
  return doCaseConvFunction(pInput, inputNum, pOutput, towlower);
#else
G
Ganlin Zhao 已提交
1590
  return doCaseConvFunction(pInput, inputNum, pOutput, tolower);
wafwerar's avatar
wafwerar 已提交
1591
#endif
1592 1593
}

G
Ganlin Zhao 已提交
1594
int32_t upperFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
wafwerar's avatar
wafwerar 已提交
1595 1596 1597
#ifdef WINDOWS
  return doCaseConvFunction(pInput, inputNum, pOutput, towupper);
#else
G
Ganlin Zhao 已提交
1598
  return doCaseConvFunction(pInput, inputNum, pOutput, toupper);
wafwerar's avatar
wafwerar 已提交
1599
#endif
1600 1601
}

G
Ganlin Zhao 已提交
1602 1603
int32_t ltrimFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doTrimFunction(pInput, inputNum, pOutput, tltrim);
1604 1605
}

G
Ganlin Zhao 已提交
1606 1607
int32_t rtrimFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doTrimFunction(pInput, inputNum, pOutput, trtrim);
1608 1609
}

G
Ganlin Zhao 已提交
1610 1611 1612
int32_t lengthFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doLengthFunction(pInput, inputNum, pOutput, tlength);
}
1613

G
Ganlin Zhao 已提交
1614 1615
int32_t charLengthFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doLengthFunction(pInput, inputNum, pOutput, tcharlength);
1616 1617
}

H
Haojun Liao 已提交
1618
#if 0
1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
static void reverseCopy(char* dest, const char* src, int16_t type, int32_t numOfRows) {
  switch(type) {
    case TSDB_DATA_TYPE_TINYINT:
    case TSDB_DATA_TYPE_UTINYINT:{
      int8_t* p = (int8_t*) dest;
      int8_t* pSrc = (int8_t*) src;

      for(int32_t i = 0; i < numOfRows; ++i) {
        p[i] = pSrc[numOfRows - i - 1];
      }
      return;
    }

    case TSDB_DATA_TYPE_SMALLINT:
    case TSDB_DATA_TYPE_USMALLINT:{
      int16_t* p = (int16_t*) dest;
      int16_t* pSrc = (int16_t*) src;

      for(int32_t i = 0; i < numOfRows; ++i) {
        p[i] = pSrc[numOfRows - i - 1];
      }
      return;
    }
    case TSDB_DATA_TYPE_INT:
    case TSDB_DATA_TYPE_UINT: {
      int32_t* p = (int32_t*) dest;
      int32_t* pSrc = (int32_t*) src;

      for(int32_t i = 0; i < numOfRows; ++i) {
        p[i] = pSrc[numOfRows - i - 1];
      }
      return;
    }
    case TSDB_DATA_TYPE_BIGINT:
    case TSDB_DATA_TYPE_UBIGINT: {
      int64_t* p = (int64_t*) dest;
      int64_t* pSrc = (int64_t*) src;

      for(int32_t i = 0; i < numOfRows; ++i) {
        p[i] = pSrc[numOfRows - i - 1];
      }
      return;
    }
    case TSDB_DATA_TYPE_FLOAT: {
      float* p = (float*) dest;
      float* pSrc = (float*) src;

      for(int32_t i = 0; i < numOfRows; ++i) {
        p[i] = pSrc[numOfRows - i - 1];
      }
      return;
    }
    case TSDB_DATA_TYPE_DOUBLE: {
      double* p = (double*) dest;
      double* pSrc = (double*) src;

      for(int32_t i = 0; i < numOfRows; ++i) {
        p[i] = pSrc[numOfRows - i - 1];
      }
      return;
    }
    default: assert(0);
  }
}
H
Haojun Liao 已提交
1683
#endif
1684

H
Hongze Cheng 已提交
1685
bool getTimePseudoFuncEnv(SFunctionNode *UNUSED_PARAM(pFunc), SFuncExecEnv *pEnv) {
1686 1687 1688 1689 1690 1691 1692
  pEnv->calcMemSize = sizeof(int64_t);
  return true;
}

int32_t qStartTsFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  ASSERT(inputNum == 1);
  colDataAppendInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 0));
1693
  return TSDB_CODE_SUCCESS;
1694 1695 1696 1697 1698
}

int32_t qEndTsFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  ASSERT(inputNum == 1);
  colDataAppendInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 1));
1699
  return TSDB_CODE_SUCCESS;
1700 1701 1702 1703 1704
}

int32_t winDurFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  ASSERT(inputNum == 1);
  colDataAppendInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 2));
1705
  return TSDB_CODE_SUCCESS;
1706 1707 1708 1709
}

int32_t winStartTsFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  ASSERT(inputNum == 1);
H
Hongze Cheng 已提交
1710
  colDataAppendInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 3));
1711 1712 1713 1714 1715
  return TSDB_CODE_SUCCESS;
}

int32_t winEndTsFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  ASSERT(inputNum == 1);
H
Hongze Cheng 已提交
1716
  colDataAppendInt64(pOutput->columnData, pOutput->numOfRows, (int64_t *)colDataGetData(pInput->columnData, 4));
1717
  return TSDB_CODE_SUCCESS;
1718
}
1719 1720 1721

int32_t qTbnameFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  ASSERT(inputNum == 1);
H
Haojun Liao 已提交
1722
  char* p = colDataGetVarData(pInput->columnData, 0);
1723

H
Haojun Liao 已提交
1724
  colDataAppendNItems(pOutput->columnData, pOutput->numOfRows, p, pInput->numOfRows);
1725
  pOutput->numOfRows += pInput->numOfRows;
1726 1727
  return TSDB_CODE_SUCCESS;
}
1728 1729 1730

/** Aggregation functions **/
int32_t countScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
1731
  SColumnInfoData *pInputData = pInput->columnData;
1732 1733 1734 1735 1736 1737
  SColumnInfoData *pOutputData = pOutput->columnData;

  int64_t *out = (int64_t *)pOutputData->pData;
  *out = 0;
  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    if (colDataIsNull_s(pInputData, i)) {
G
Ganlin Zhao 已提交
1738
      continue;
1739 1740 1741 1742
    }
    (*out)++;
  }

G
Ganlin Zhao 已提交
1743
  pOutput->numOfRows = 1;
1744 1745
  return TSDB_CODE_SUCCESS;
}
1746 1747

int32_t sumScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
1748
  SColumnInfoData *pInputData = pInput->columnData;
1749 1750 1751
  SColumnInfoData *pOutputData = pOutput->columnData;

  int32_t type = GET_PARAM_TYPE(pInput);
H
Hongze Cheng 已提交
1752
  bool    hasNull = false;
1753 1754
  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    if (colDataIsNull_s(pInputData, i)) {
G
Ganlin Zhao 已提交
1755
      hasNull = true;
1756 1757 1758 1759
      break;
    }

    if (IS_SIGNED_NUMERIC_TYPE(type)) {
H
Hongze Cheng 已提交
1760
      int64_t *in = (int64_t *)pInputData->pData;
1761 1762 1763
      int64_t *out = (int64_t *)pOutputData->pData;
      *out += in[i];
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
H
Hongze Cheng 已提交
1764
      uint64_t *in = (uint64_t *)pInputData->pData;
1765 1766 1767
      uint64_t *out = (uint64_t *)pOutputData->pData;
      *out += in[i];
    } else if (IS_FLOAT_TYPE(type)) {
H
Hongze Cheng 已提交
1768
      double *in = (double *)pInputData->pData;
1769 1770 1771 1772 1773
      double *out = (double *)pOutputData->pData;
      *out += in[i];
    }
  }

G
Ganlin Zhao 已提交
1774 1775 1776 1777 1778
  if (hasNull) {
    colDataAppendNULL(pOutputData, 0);
  }

  pOutput->numOfRows = 1;
1779 1780
  return TSDB_CODE_SUCCESS;
}
1781

1782
static int32_t doMinMaxScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput, bool isMinFunc) {
H
Hongze Cheng 已提交
1783
  SColumnInfoData *pInputData = pInput->columnData;
1784 1785 1786
  SColumnInfoData *pOutputData = pOutput->columnData;

  int32_t type = GET_PARAM_TYPE(pInput);
1787

G
Ganlin Zhao 已提交
1788
  bool hasNull = false;
1789 1790 1791 1792 1793
  if (isMinFunc) {
    SET_TYPED_DATA_MAX(pOutputData->pData, type);
  } else {
    SET_TYPED_DATA_MIN(pOutputData->pData, type);
  }
1794 1795 1796

  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    if (colDataIsNull_s(pInputData, i)) {
G
Ganlin Zhao 已提交
1797
      hasNull = true;
1798 1799 1800
      break;
    }

H
Hongze Cheng 已提交
1801
    switch (type) {
1802 1803
      case TSDB_DATA_TYPE_BOOL:
      case TSDB_DATA_TYPE_TINYINT: {
H
Hongze Cheng 已提交
1804
        int8_t *in = (int8_t *)pInputData->pData;
1805
        int8_t *out = (int8_t *)pOutputData->pData;
H
Hongze Cheng 已提交
1806
        if ((in[i] > *out) ^ isMinFunc) {
1807 1808 1809 1810 1811
          *out = in[i];
        }
        break;
      }
      case TSDB_DATA_TYPE_SMALLINT: {
H
Hongze Cheng 已提交
1812
        int16_t *in = (int16_t *)pInputData->pData;
1813
        int16_t *out = (int16_t *)pOutputData->pData;
H
Hongze Cheng 已提交
1814
        if ((in[i] > *out) ^ isMinFunc) {
1815 1816 1817 1818 1819
          *out = in[i];
        }
        break;
      }
      case TSDB_DATA_TYPE_INT: {
H
Hongze Cheng 已提交
1820
        int32_t *in = (int32_t *)pInputData->pData;
1821
        int32_t *out = (int32_t *)pOutputData->pData;
H
Hongze Cheng 已提交
1822
        if ((in[i] > *out) ^ isMinFunc) {
1823 1824 1825 1826 1827
          *out = in[i];
        }
        break;
      }
      case TSDB_DATA_TYPE_BIGINT: {
H
Hongze Cheng 已提交
1828
        int64_t *in = (int64_t *)pInputData->pData;
1829
        int64_t *out = (int64_t *)pOutputData->pData;
H
Hongze Cheng 已提交
1830
        if ((in[i] > *out) ^ isMinFunc) {
1831 1832 1833 1834 1835
          *out = in[i];
        }
        break;
      }
      case TSDB_DATA_TYPE_UTINYINT: {
H
Hongze Cheng 已提交
1836
        uint8_t *in = (uint8_t *)pInputData->pData;
1837
        uint8_t *out = (uint8_t *)pOutputData->pData;
H
Hongze Cheng 已提交
1838
        if ((in[i] > *out) ^ isMinFunc) {
1839 1840 1841 1842 1843
          *out = in[i];
        }
        break;
      }
      case TSDB_DATA_TYPE_USMALLINT: {
H
Hongze Cheng 已提交
1844
        uint16_t *in = (uint16_t *)pInputData->pData;
1845
        uint16_t *out = (uint16_t *)pOutputData->pData;
H
Hongze Cheng 已提交
1846
        if ((in[i] > *out) ^ isMinFunc) {
1847 1848 1849 1850 1851
          *out = in[i];
        }
        break;
      }
      case TSDB_DATA_TYPE_UINT: {
H
Hongze Cheng 已提交
1852
        uint32_t *in = (uint32_t *)pInputData->pData;
1853
        uint32_t *out = (uint32_t *)pOutputData->pData;
H
Hongze Cheng 已提交
1854
        if ((in[i] > *out) ^ isMinFunc) {
1855 1856 1857 1858 1859
          *out = in[i];
        }
        break;
      }
      case TSDB_DATA_TYPE_UBIGINT: {
H
Hongze Cheng 已提交
1860
        uint64_t *in = (uint64_t *)pInputData->pData;
1861
        uint64_t *out = (uint64_t *)pOutputData->pData;
H
Hongze Cheng 已提交
1862
        if ((in[i] > *out) ^ isMinFunc) {
1863 1864 1865 1866 1867
          *out = in[i];
        }
        break;
      }
      case TSDB_DATA_TYPE_FLOAT: {
H
Hongze Cheng 已提交
1868
        float *in = (float *)pInputData->pData;
1869
        float *out = (float *)pOutputData->pData;
H
Hongze Cheng 已提交
1870
        if ((in[i] > *out) ^ isMinFunc) {
1871 1872 1873 1874 1875
          *out = in[i];
        }
        break;
      }
      case TSDB_DATA_TYPE_DOUBLE: {
H
Hongze Cheng 已提交
1876
        double *in = (double *)pInputData->pData;
1877
        double *out = (double *)pOutputData->pData;
H
Hongze Cheng 已提交
1878
        if ((in[i] > *out) ^ isMinFunc) {
1879 1880 1881 1882 1883 1884 1885
          *out = in[i];
        }
        break;
      }
    }
  }

G
Ganlin Zhao 已提交
1886 1887 1888 1889 1890
  if (hasNull) {
    colDataAppendNULL(pOutputData, 0);
  }

  pOutput->numOfRows = 1;
1891 1892
  return TSDB_CODE_SUCCESS;
}
1893 1894 1895 1896 1897 1898 1899 1900

int32_t minScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doMinMaxScalarFunction(pInput, inputNum, pOutput, true);
}

int32_t maxScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return doMinMaxScalarFunction(pInput, inputNum, pOutput, false);
}
1901

1902
int32_t avgScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
1903
  SColumnInfoData *pInputData = pInput->columnData;
1904 1905 1906
  SColumnInfoData *pOutputData = pOutput->columnData;

  int32_t type = GET_PARAM_TYPE(pInput);
1907
  int64_t count = 0;
H
Hongze Cheng 已提交
1908
  bool    hasNull = false;
1909 1910 1911 1912 1913 1914 1915

  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    if (colDataIsNull_s(pInputData, i)) {
      hasNull = true;
      break;
    }

H
Hongze Cheng 已提交
1916
    switch (type) {
1917
      case TSDB_DATA_TYPE_TINYINT: {
H
Hongze Cheng 已提交
1918
        int8_t  *in = (int8_t *)pInputData->pData;
1919 1920
        int64_t *out = (int64_t *)pOutputData->pData;
        *out += in[i];
1921 1922 1923 1924
        count++;
        break;
      }
      case TSDB_DATA_TYPE_SMALLINT: {
H
Hongze Cheng 已提交
1925
        int16_t *in = (int16_t *)pInputData->pData;
1926 1927
        int64_t *out = (int64_t *)pOutputData->pData;
        *out += in[i];
1928 1929 1930 1931
        count++;
        break;
      }
      case TSDB_DATA_TYPE_INT: {
H
Hongze Cheng 已提交
1932
        int32_t *in = (int32_t *)pInputData->pData;
1933 1934
        int64_t *out = (int64_t *)pOutputData->pData;
        *out += in[i];
1935 1936 1937 1938
        count++;
        break;
      }
      case TSDB_DATA_TYPE_BIGINT: {
H
Hongze Cheng 已提交
1939
        int64_t *in = (int64_t *)pInputData->pData;
1940 1941
        int64_t *out = (int64_t *)pOutputData->pData;
        *out += in[i];
1942 1943 1944 1945
        count++;
        break;
      }
      case TSDB_DATA_TYPE_UTINYINT: {
H
Hongze Cheng 已提交
1946
        uint8_t  *in = (uint8_t *)pInputData->pData;
1947 1948
        uint64_t *out = (uint64_t *)pOutputData->pData;
        *out += in[i];
1949 1950 1951 1952
        count++;
        break;
      }
      case TSDB_DATA_TYPE_USMALLINT: {
H
Hongze Cheng 已提交
1953
        uint16_t *in = (uint16_t *)pInputData->pData;
1954 1955
        uint64_t *out = (uint64_t *)pOutputData->pData;
        *out += in[i];
1956 1957 1958 1959
        count++;
        break;
      }
      case TSDB_DATA_TYPE_UINT: {
H
Hongze Cheng 已提交
1960
        uint32_t *in = (uint32_t *)pInputData->pData;
1961 1962
        uint64_t *out = (uint64_t *)pOutputData->pData;
        *out += in[i];
1963 1964 1965 1966
        count++;
        break;
      }
      case TSDB_DATA_TYPE_UBIGINT: {
H
Hongze Cheng 已提交
1967
        uint64_t *in = (uint64_t *)pInputData->pData;
1968 1969
        uint64_t *out = (uint64_t *)pOutputData->pData;
        *out += in[i];
1970 1971 1972 1973
        count++;
        break;
      }
      case TSDB_DATA_TYPE_FLOAT: {
H
Hongze Cheng 已提交
1974
        float *in = (float *)pInputData->pData;
1975 1976
        float *out = (float *)pOutputData->pData;
        *out += in[i];
1977 1978 1979 1980
        count++;
        break;
      }
      case TSDB_DATA_TYPE_DOUBLE: {
H
Hongze Cheng 已提交
1981
        double *in = (double *)pInputData->pData;
1982 1983
        double *out = (double *)pOutputData->pData;
        *out += in[i];
1984 1985 1986 1987 1988 1989
        count++;
        break;
      }
    }
  }

G
Ganlin Zhao 已提交
1990
  if (hasNull || (count == 0)) {
1991 1992 1993
    colDataAppendNULL(pOutputData, 0);
  } else {
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
H
Hongze Cheng 已提交
1994
      int64_t *out = (int64_t *)pOutputData->pData;
1995
      *(double *)out = *out / (double)count;
1996
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
H
Hongze Cheng 已提交
1997
      uint64_t *out = (uint64_t *)pOutputData->pData;
1998
      *(double *)out = *out / (double)count;
1999
    } else if (IS_FLOAT_TYPE(type)) {
H
Hongze Cheng 已提交
2000
      double *out = (double *)pOutputData->pData;
2001
      *(double *)out = *out / (double)count;
2002 2003 2004 2005 2006 2007 2008
    }
  }

  pOutput->numOfRows = 1;
  return TSDB_CODE_SUCCESS;
}

2009
int32_t stddevScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
2010
  SColumnInfoData *pInputData = pInput->columnData;
2011 2012 2013
  SColumnInfoData *pOutputData = pOutput->columnData;

  int32_t type = GET_PARAM_TYPE(pInput);
H
Hongze Cheng 已提交
2014
  // int64_t count = 0, sum = 0, qSum = 0;
G
Ganlin Zhao 已提交
2015
  bool hasNull = false;
2016 2017 2018

  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    if (colDataIsNull_s(pInputData, i)) {
G
Ganlin Zhao 已提交
2019 2020
      hasNull = true;
      break;
2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097
    }
#if 0
    switch(type) {
      case TSDB_DATA_TYPE_TINYINT: {
        int8_t *in  = (int8_t *)pInputData->pData;
        sum += in[i];
        qSum += in[i] * in[i];
        count++;
        break;
      }
      case TSDB_DATA_TYPE_SMALLINT: {
        int16_t *in  = (int16_t *)pInputData->pData;
        sum += in[i];
        qSum += in[i] * in[i];
        count++;
        break;
      }
      case TSDB_DATA_TYPE_INT: {
        int32_t *in  = (int32_t *)pInputData->pData;
        sum += in[i];
        qSum += in[i] * in[i];
        count++;
        break;
      }
      case TSDB_DATA_TYPE_BIGINT: {
        int64_t *in  = (int64_t *)pInputData->pData;
        sum += in[i];
        qSum += in[i] * in[i];
        count++;
        break;
      }
      case TSDB_DATA_TYPE_UTINYINT: {
        uint8_t *in  = (uint8_t *)pInputData->pData;
        sum += in[i];
        qSum += in[i] * in[i];
        count++;
        break;
      }
      case TSDB_DATA_TYPE_USMALLINT: {
        uint16_t *in  = (uint16_t *)pInputData->pData;
        sum += in[i];
        qSum += in[i] * in[i];
        count++;
        break;
      }
      case TSDB_DATA_TYPE_UINT: {
        uint32_t *in  = (uint32_t *)pInputData->pData;
        sum += in[i];
        qSum += in[i] * in[i];
        count++;
        break;
      }
      case TSDB_DATA_TYPE_UBIGINT: {
        uint64_t *in  = (uint64_t *)pInputData->pData;
        sum += in[i];
        qSum += in[i] * in[i];
        count++;
        break;
      }
      case TSDB_DATA_TYPE_FLOAT: {
        float *in  = (float *)pInputData->pData;
        sum += in[i];
        qSum += in[i] * in[i];
        count++;
        break;
      }
      case TSDB_DATA_TYPE_DOUBLE: {
        double *in  = (double *)pInputData->pData;
        sum += in[i];
        qSum += in[i] * in[i];
        count++;
        break;
      }
    }
#endif
  }

H
Hongze Cheng 已提交
2098
  double *out = (double *)pOutputData->pData;
G
Ganlin Zhao 已提交
2099
  if (hasNull) {
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
    colDataAppendNULL(pOutputData, 0);
  } else {
    *out = 0;
#if 0
    double avg = 0;
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
      avg = (int64_t)sum / (double)count;
      *out =  sqrt(fabs((int64_t)qSum / ((double)count) - avg * avg));
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
      avg = (uint64_t)sum / (double)count;
      *out =  sqrt(fabs((uint64_t)qSum / ((double)count) - avg * avg));
    } else if (IS_FLOAT_TYPE(type)) {
      avg = (double)sum / (double)count;
      *out =  sqrt(fabs((double)qSum / ((double)count) - avg * avg));
    }
#endif
  }

G
Ganlin Zhao 已提交
2118
  pOutput->numOfRows = 1;
2119 2120
  return TSDB_CODE_SUCCESS;
}
2121

2122 2123 2124 2125 2126 2127 2128 2129 2130 2131
#define LEASTSQR_CAL(p, x, y, index, step) \
  do {                                     \
    (p)[0][0] += (double)(x) * (x);        \
    (p)[0][1] += (double)(x);              \
    (p)[0][2] += (double)(x) * (y)[index]; \
    (p)[1][2] += (y)[index];               \
    (x) += step;                           \
  } while (0)

int32_t leastSQRScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
2132
  SColumnInfoData *pInputData = pInput->columnData;
2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
  SColumnInfoData *pOutputData = pOutput->columnData;

  double startVal, stepVal;
  double matrix[2][3] = {0};
  GET_TYPED_DATA(startVal, double, GET_PARAM_TYPE(&pInput[1]), pInput[1].columnData->pData);
  GET_TYPED_DATA(stepVal, double, GET_PARAM_TYPE(&pInput[2]), pInput[2].columnData->pData);

  int32_t type = GET_PARAM_TYPE(pInput);
  int64_t count = 0;

H
Hongze Cheng 已提交
2143
  switch (type) {
2144
    case TSDB_DATA_TYPE_TINYINT: {
H
Hongze Cheng 已提交
2145
      int8_t *in = (int8_t *)pInputData->pData;
2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
        if (colDataIsNull_s(pInputData, i)) {
          continue;
        }

        count++;
        LEASTSQR_CAL(matrix, startVal, in, i, stepVal);
      }
      break;
    }
    case TSDB_DATA_TYPE_SMALLINT: {
H
Hongze Cheng 已提交
2157
      int16_t *in = (int16_t *)pInputData->pData;
2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
        if (colDataIsNull_s(pInputData, i)) {
          continue;
        }

        count++;
        LEASTSQR_CAL(matrix, startVal, in, i, stepVal);
      }
      break;
    }
    case TSDB_DATA_TYPE_INT: {
H
Hongze Cheng 已提交
2169
      int32_t *in = (int32_t *)pInputData->pData;
2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
        if (colDataIsNull_s(pInputData, i)) {
          continue;
        }

        count++;
        LEASTSQR_CAL(matrix, startVal, in, i, stepVal);
      }
      break;
    }
    case TSDB_DATA_TYPE_BIGINT: {
H
Hongze Cheng 已提交
2181
      int64_t *in = (int64_t *)pInputData->pData;
2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
        if (colDataIsNull_s(pInputData, i)) {
          continue;
        }

        count++;
        LEASTSQR_CAL(matrix, startVal, in, i, stepVal);
      }
      break;
    }
    case TSDB_DATA_TYPE_UTINYINT: {
H
Hongze Cheng 已提交
2193
      uint8_t *in = (uint8_t *)pInputData->pData;
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
        if (colDataIsNull_s(pInputData, i)) {
          continue;
        }

        count++;
        LEASTSQR_CAL(matrix, startVal, in, i, stepVal);
      }
      break;
    }
    case TSDB_DATA_TYPE_USMALLINT: {
H
Hongze Cheng 已提交
2205
      uint16_t *in = (uint16_t *)pInputData->pData;
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
        if (colDataIsNull_s(pInputData, i)) {
          continue;
        }

        count++;
        LEASTSQR_CAL(matrix, startVal, in, i, stepVal);
      }
      break;
    }
    case TSDB_DATA_TYPE_UINT: {
H
Hongze Cheng 已提交
2217
      uint32_t *in = (uint32_t *)pInputData->pData;
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
        if (colDataIsNull_s(pInputData, i)) {
          continue;
        }

        count++;
        LEASTSQR_CAL(matrix, startVal, in, i, stepVal);
      }
      break;
    }
    case TSDB_DATA_TYPE_UBIGINT: {
H
Hongze Cheng 已提交
2229
      uint64_t *in = (uint64_t *)pInputData->pData;
2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
        if (colDataIsNull_s(pInputData, i)) {
          continue;
        }

        count++;
        LEASTSQR_CAL(matrix, startVal, in, i, stepVal);
      }
      break;
    }
    case TSDB_DATA_TYPE_FLOAT: {
H
Hongze Cheng 已提交
2241
      float *in = (float *)pInputData->pData;
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
        if (colDataIsNull_s(pInputData, i)) {
          continue;
        }

        count++;
        LEASTSQR_CAL(matrix, startVal, in, i, stepVal);
      }
      break;
    }
    case TSDB_DATA_TYPE_DOUBLE: {
H
Hongze Cheng 已提交
2253
      double *in = (double *)pInputData->pData;
2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
      for (int32_t i = 0; i < pInput->numOfRows; ++i) {
        if (colDataIsNull_s(pInputData, i)) {
          continue;
        }

        count++;
        LEASTSQR_CAL(matrix, startVal, in, i, stepVal);
      }
      break;
    }
  }

  if (count == 0) {
    colDataAppendNULL(pOutputData, 0);
  } else {
    matrix[1][1] = (double)count;
    matrix[1][0] = matrix[0][1];

    double matrix00 = matrix[0][0] - matrix[1][0] * (matrix[0][1] / matrix[1][1]);
    double matrix02 = matrix[0][2] - matrix[1][2] * (matrix[0][1] / matrix[1][1]);
    double matrix12 = matrix[1][2] - matrix02 * (matrix[1][0] / matrix00);
    matrix02 /= matrix00;

    matrix12 /= matrix[1][1];

    char   buf[64] = {0};
H
Hongze Cheng 已提交
2280 2281
    size_t len = snprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE, "{slop:%.6lf, intercept:%.6lf}", matrix02,
                          matrix12);
2282 2283 2284 2285 2286 2287 2288
    varDataSetLen(buf, len);
    colDataAppend(pOutputData, 0, buf, false);
  }

  pOutput->numOfRows = 1;
  return TSDB_CODE_SUCCESS;
}
2289 2290

int32_t percentileScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
2291
  SColumnInfoData *pInputData = pInput->columnData;
2292 2293 2294 2295 2296
  SColumnInfoData *pOutputData = pOutput->columnData;

  int32_t type = GET_PARAM_TYPE(pInput);

  double val;
H
Hongze Cheng 已提交
2297
  bool   hasNull = false;
2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319
  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    if (colDataIsNull_s(pInputData, i)) {
      hasNull = true;
      break;
    }
    char *in = pInputData->pData;
    GET_TYPED_DATA(val, double, type, in);
  }

  if (hasNull) {
    colDataAppendNULL(pOutputData, 0);
  } else {
    colDataAppend(pOutputData, 0, (char *)&val, false);
  }

  pOutput->numOfRows = 1;
  return TSDB_CODE_SUCCESS;
}

int32_t apercentileScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return percentileScalarFunction(pInput, inputNum, pOutput);
}
2320 2321

int32_t spreadScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
2322
  SColumnInfoData *pInputData = pInput->columnData;
2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361
  SColumnInfoData *pOutputData = pOutput->columnData;

  int32_t type = GET_PARAM_TYPE(pInput);

  double min, max;
  SET_DOUBLE_VAL(&min, DBL_MAX);
  SET_DOUBLE_VAL(&max, -DBL_MAX);

  bool hasNull = false;
  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    if (colDataIsNull_s(pInputData, i)) {
      hasNull = true;
      break;
    }

    char *in = pInputData->pData;

    double val = 0;
    GET_TYPED_DATA(val, double, type, in);

    if (val < GET_DOUBLE_VAL(&min)) {
      SET_DOUBLE_VAL(&min, val);
    }

    if (val > GET_DOUBLE_VAL(&max)) {
      SET_DOUBLE_VAL(&max, val);
    }
  }

  if (hasNull) {
    colDataAppendNULL(pOutputData, 0);
  } else {
    double result = max - min;
    colDataAppend(pOutputData, 0, (char *)&result, false);
  }

  pOutput->numOfRows = 1;
  return TSDB_CODE_SUCCESS;
}
2362

G
Ganlin Zhao 已提交
2363
int32_t nonCalcScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
2364
  SColumnInfoData *pInputData = pInput->columnData;
2365 2366 2367
  SColumnInfoData *pOutputData = pOutput->columnData;

  int32_t type = GET_PARAM_TYPE(pInput);
H
Hongze Cheng 已提交
2368
  bool    hasNull = false;
2369 2370 2371 2372 2373 2374 2375 2376

  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    if (colDataIsNull_s(pInputData, i)) {
      hasNull = true;
      break;
    }
  }

H
Hongze Cheng 已提交
2377
  double *out = (double *)pOutputData->pData;
2378 2379 2380 2381 2382 2383 2384 2385 2386
  if (hasNull) {
    colDataAppendNULL(pOutputData, 0);
  } else {
    *out = 0;
  }

  pOutput->numOfRows = 1;
  return TSDB_CODE_SUCCESS;
}
G
Ganlin Zhao 已提交
2387 2388 2389 2390 2391 2392 2393 2394

int32_t derivativeScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return nonCalcScalarFunction(pInput, inputNum, pOutput);
}

int32_t irateScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return nonCalcScalarFunction(pInput, inputNum, pOutput);
}
2395

2396 2397 2398 2399
int32_t diffScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return nonCalcScalarFunction(pInput, inputNum, pOutput);
}

2400 2401 2402
int32_t twaScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return avgScalarFunction(pInput, inputNum, pOutput);
}
2403 2404 2405 2406

int32_t mavgScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return avgScalarFunction(pInput, inputNum, pOutput);
}
2407 2408 2409 2410

int32_t hllScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return countScalarFunction(pInput, inputNum, pOutput);
}
2411 2412 2413 2414

int32_t csumScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return sumScalarFunction(pInput, inputNum, pOutput);
}
2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455

typedef enum {
  STATE_OPER_INVALID = 0,
  STATE_OPER_LT,
  STATE_OPER_GT,
  STATE_OPER_LE,
  STATE_OPER_GE,
  STATE_OPER_NE,
  STATE_OPER_EQ,
} EStateOperType;

#define STATE_COMP(_op, _lval, _rval, _rtype) STATE_COMP_IMPL(_op, _lval, GET_STATE_VAL(_rval, _rtype))

#define GET_STATE_VAL(_val, _type) ((_type == TSDB_DATA_TYPE_BIGINT) ? (*(int64_t *)_val) : (*(double *)_val))

#define STATE_COMP_IMPL(_op, _lval, _rval) \
  do {                                     \
    switch (_op) {                         \
      case STATE_OPER_LT:                  \
        return ((_lval) < (_rval));        \
        break;                             \
      case STATE_OPER_GT:                  \
        return ((_lval) > (_rval));        \
        break;                             \
      case STATE_OPER_LE:                  \
        return ((_lval) <= (_rval));       \
        break;                             \
      case STATE_OPER_GE:                  \
        return ((_lval) >= (_rval));       \
        break;                             \
      case STATE_OPER_NE:                  \
        return ((_lval) != (_rval));       \
        break;                             \
      case STATE_OPER_EQ:                  \
        return ((_lval) == (_rval));       \
        break;                             \
      default:                             \
        break;                             \
    }                                      \
  } while (0)

H
Hongze Cheng 已提交
2456
static int8_t getStateOpType(char *opStr) {
2457
  int8_t opType;
2458
  if (strncasecmp(opStr, "LT", 2) == 0) {
2459
    opType = STATE_OPER_LT;
2460
  } else if (strncasecmp(opStr, "GT", 2) == 0) {
2461
    opType = STATE_OPER_GT;
2462
  } else if (strncasecmp(opStr, "LE", 2) == 0) {
2463
    opType = STATE_OPER_LE;
2464
  } else if (strncasecmp(opStr, "GE", 2) == 0) {
2465
    opType = STATE_OPER_GE;
2466
  } else if (strncasecmp(opStr, "NE", 2) == 0) {
2467
    opType = STATE_OPER_NE;
2468
  } else if (strncasecmp(opStr, "EQ", 2) == 0) {
2469 2470 2471 2472 2473 2474 2475 2476
    opType = STATE_OPER_EQ;
  } else {
    opType = STATE_OPER_INVALID;
  }

  return opType;
}

H
Hongze Cheng 已提交
2477 2478 2479
static bool checkStateOp(int8_t op, SColumnInfoData *pCol, int32_t index, SScalarParam *pCondParam) {
  char   *data = colDataGetData(pCol, index);
  char   *param = pCondParam->columnData->pData;
2480 2481 2482
  int32_t paramType = GET_PARAM_TYPE(pCondParam);
  switch (pCol->info.type) {
    case TSDB_DATA_TYPE_TINYINT: {
H
Hongze Cheng 已提交
2483
      int8_t v = *(int8_t *)data;
2484 2485 2486 2487
      STATE_COMP(op, v, param, paramType);
      break;
    }
    case TSDB_DATA_TYPE_UTINYINT: {
H
Hongze Cheng 已提交
2488
      uint8_t v = *(uint8_t *)data;
2489 2490 2491 2492
      STATE_COMP(op, v, param, paramType);
      break;
    }
    case TSDB_DATA_TYPE_SMALLINT: {
H
Hongze Cheng 已提交
2493
      int16_t v = *(int16_t *)data;
2494 2495 2496 2497
      STATE_COMP(op, v, param, paramType);
      break;
    }
    case TSDB_DATA_TYPE_USMALLINT: {
H
Hongze Cheng 已提交
2498
      uint16_t v = *(uint16_t *)data;
2499 2500 2501 2502
      STATE_COMP(op, v, param, paramType);
      break;
    }
    case TSDB_DATA_TYPE_INT: {
H
Hongze Cheng 已提交
2503
      int32_t v = *(int32_t *)data;
2504 2505 2506 2507
      STATE_COMP(op, v, param, paramType);
      break;
    }
    case TSDB_DATA_TYPE_UINT: {
H
Hongze Cheng 已提交
2508
      uint32_t v = *(uint32_t *)data;
2509 2510 2511 2512
      STATE_COMP(op, v, param, paramType);
      break;
    }
    case TSDB_DATA_TYPE_BIGINT: {
H
Hongze Cheng 已提交
2513
      int64_t v = *(int64_t *)data;
2514 2515 2516 2517
      STATE_COMP(op, v, param, paramType);
      break;
    }
    case TSDB_DATA_TYPE_UBIGINT: {
H
Hongze Cheng 已提交
2518
      uint64_t v = *(uint64_t *)data;
2519 2520 2521 2522
      STATE_COMP(op, v, param, paramType);
      break;
    }
    case TSDB_DATA_TYPE_FLOAT: {
H
Hongze Cheng 已提交
2523
      float v = *(float *)data;
2524 2525 2526 2527
      STATE_COMP(op, v, param, paramType);
      break;
    }
    case TSDB_DATA_TYPE_DOUBLE: {
H
Hongze Cheng 已提交
2528
      double v = *(double *)data;
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539
      STATE_COMP(op, v, param, paramType);
      break;
    }
    default: {
      ASSERT(0);
    }
  }
  return false;
}

int32_t stateCountScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
2540
  SColumnInfoData *pInputData = pInput->columnData;
2541 2542
  SColumnInfoData *pOutputData = pOutput->columnData;

H
Hongze Cheng 已提交
2543
  int8_t  op = getStateOpType(varDataVal(pInput[1].columnData->pData));
2544 2545 2546 2547 2548 2549 2550 2551
  int64_t count = 0;

  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    if (colDataIsNull_s(pInputData, i)) {
      colDataAppendNULL(pOutputData, i);
      continue;
    }

H
Hongze Cheng 已提交
2552
    bool    ret = checkStateOp(op, pInputData, i, &pInput[2]);
2553 2554 2555 2556 2557 2558
    int64_t out = -1;
    if (ret) {
      out = ++count;
    } else {
      count = 0;
    }
H
Hongze Cheng 已提交
2559
    colDataAppend(pOutputData, i, (char *)&out, false);
2560 2561 2562 2563 2564
  }

  pOutput->numOfRows = pInput->numOfRows;
  return TSDB_CODE_SUCCESS;
}
2565 2566

int32_t stateDurationScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
2567
  SColumnInfoData *pInputData = pInput->columnData;
2568 2569 2570 2571 2572 2573 2574 2575 2576 2577
  SColumnInfoData *pOutputData = pOutput->columnData;

  int8_t op = getStateOpType(varDataVal(pInput[1].columnData->pData));

  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    if (colDataIsNull_s(pInputData, i)) {
      colDataAppendNULL(pOutputData, i);
      continue;
    }

H
Hongze Cheng 已提交
2578
    bool    ret = checkStateOp(op, pInputData, i, &pInput[2]);
2579 2580 2581 2582
    int64_t out = -1;
    if (ret) {
      out = 0;
    }
H
Hongze Cheng 已提交
2583
    colDataAppend(pOutputData, i, (char *)&out, false);
2584 2585 2586 2587 2588
  }

  pOutput->numOfRows = pInput->numOfRows;
  return TSDB_CODE_SUCCESS;
}
2589 2590 2591

typedef enum { UNKNOWN_BIN = 0, USER_INPUT_BIN, LINEAR_BIN, LOG_BIN } EHistoBinType;

H
Hongze Cheng 已提交
2592
static int8_t getHistogramBinType(char *binTypeStr) {
2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613
  int8_t binType;
  if (strcasecmp(binTypeStr, "user_input") == 0) {
    binType = USER_INPUT_BIN;
  } else if (strcasecmp(binTypeStr, "linear_bin") == 0) {
    binType = LINEAR_BIN;
  } else if (strcasecmp(binTypeStr, "log_bin") == 0) {
    binType = LOG_BIN;
  } else {
    binType = UNKNOWN_BIN;
  }

  return binType;
}

typedef struct SHistoFuncBin {
  double  lower;
  double  upper;
  int64_t count;
  double  percentage;
} SHistoFuncBin;

H
Hongze Cheng 已提交
2614 2615 2616
static bool getHistogramBinDesc(SHistoFuncBin **bins, int32_t *binNum, char *binDescStr, int8_t binType,
                                bool normalized) {
  cJSON  *binDesc = cJSON_Parse(binDescStr);
2617
  int32_t numOfBins;
H
Hongze Cheng 已提交
2618
  double *intervals;
2619 2620 2621 2622 2623 2624 2625
  if (cJSON_IsObject(binDesc)) { /* linaer/log bins */
    int32_t numOfParams = cJSON_GetArraySize(binDesc);
    int32_t startIndex;
    if (numOfParams != 4) {
      return false;
    }

H
Hongze Cheng 已提交
2626 2627 2628 2629 2630
    cJSON *start = cJSON_GetObjectItem(binDesc, "start");
    cJSON *factor = cJSON_GetObjectItem(binDesc, "factor");
    cJSON *width = cJSON_GetObjectItem(binDesc, "width");
    cJSON *count = cJSON_GetObjectItem(binDesc, "count");
    cJSON *infinity = cJSON_GetObjectItem(binDesc, "infinity");
2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706

    if (!cJSON_IsNumber(start) || !cJSON_IsNumber(count) || !cJSON_IsBool(infinity)) {
      return false;
    }

    if (count->valueint <= 0 || count->valueint > 1000) {  // limit count to 1000
      return false;
    }

    if (isinf(start->valuedouble) || (width != NULL && isinf(width->valuedouble)) ||
        (factor != NULL && isinf(factor->valuedouble)) || (count != NULL && isinf(count->valuedouble))) {
      return false;
    }

    int32_t counter = (int32_t)count->valueint;
    if (infinity->valueint == false) {
      startIndex = 0;
      numOfBins = counter + 1;
    } else {
      startIndex = 1;
      numOfBins = counter + 3;
    }

    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
    if (cJSON_IsNumber(width) && factor == NULL && binType == LINEAR_BIN) {
      // linear bin process
      if (width->valuedouble == 0) {
        taosMemoryFree(intervals);
        return false;
      }
      for (int i = 0; i < counter + 1; ++i) {
        intervals[startIndex] = start->valuedouble + i * width->valuedouble;
        if (isinf(intervals[startIndex])) {
          taosMemoryFree(intervals);
          return false;
        }
        startIndex++;
      }
    } else if (cJSON_IsNumber(factor) && width == NULL && binType == LOG_BIN) {
      // log bin process
      if (start->valuedouble == 0) {
        taosMemoryFree(intervals);
        return false;
      }
      if (factor->valuedouble < 0 || factor->valuedouble == 0 || factor->valuedouble == 1) {
        taosMemoryFree(intervals);
        return false;
      }
      for (int i = 0; i < counter + 1; ++i) {
        intervals[startIndex] = start->valuedouble * pow(factor->valuedouble, i * 1.0);
        if (isinf(intervals[startIndex])) {
          taosMemoryFree(intervals);
          return false;
        }
        startIndex++;
      }
    } else {
      taosMemoryFree(intervals);
      return false;
    }

    if (infinity->valueint == true) {
      intervals[0] = -INFINITY;
      intervals[numOfBins - 1] = INFINITY;
      // in case of desc bin orders, -inf/inf should be swapped
      ASSERT(numOfBins >= 4);
      if (intervals[1] > intervals[numOfBins - 2]) {
        TSWAP(intervals[0], intervals[numOfBins - 1]);
      }
    }
  } else if (cJSON_IsArray(binDesc)) { /* user input bins */
    if (binType != USER_INPUT_BIN) {
      return false;
    }
    numOfBins = cJSON_GetArraySize(binDesc);
    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
H
Hongze Cheng 已提交
2707
    cJSON *bin = binDesc->child;
2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737
    if (bin == NULL) {
      taosMemoryFree(intervals);
      return false;
    }
    int i = 0;
    while (bin) {
      intervals[i] = bin->valuedouble;
      if (!cJSON_IsNumber(bin)) {
        taosMemoryFree(intervals);
        return false;
      }
      if (i != 0 && intervals[i] <= intervals[i - 1]) {
        taosMemoryFree(intervals);
        return false;
      }
      bin = bin->next;
      i++;
    }
  } else {
    return false;
  }

  *binNum = numOfBins - 1;
  *bins = taosMemoryCalloc(numOfBins, sizeof(SHistoFuncBin));
  for (int32_t i = 0; i < *binNum; ++i) {
    (*bins)[i].lower = intervals[i] < intervals[i + 1] ? intervals[i] : intervals[i + 1];
    (*bins)[i].upper = intervals[i + 1] > intervals[i] ? intervals[i + 1] : intervals[i];
    (*bins)[i].count = 0;
  }

2738
  cJSON_Delete(binDesc);
2739 2740 2741 2742 2743
  taosMemoryFree(intervals);
  return true;
}

int32_t histogramScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
2744
  SColumnInfoData *pInputData = pInput->columnData;
2745 2746 2747
  SColumnInfoData *pOutputData = pOutput->columnData;

  SHistoFuncBin *bins;
H
Hongze Cheng 已提交
2748 2749
  int32_t        numOfBins = 0;
  int32_t        totalCount = 0;
2750

H
Hongze Cheng 已提交
2751 2752
  int8_t  binType = getHistogramBinType(varDataVal(pInput[1].columnData->pData));
  char   *binDesc = varDataVal(pInput[2].columnData->pData);
2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764
  int64_t normalized = *(int64_t *)(pInput[3].columnData->pData);

  int32_t type = GET_PARAM_TYPE(pInput);
  if (!getHistogramBinDesc(&bins, &numOfBins, binDesc, binType, (bool)normalized)) {
    return TSDB_CODE_FAILED;
  }

  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    if (colDataIsNull_s(pInputData, i)) {
      continue;
    }

H
Hongze Cheng 已提交
2765
    char  *data = colDataGetData(pInputData, i);
2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
    double v;
    GET_TYPED_DATA(v, double, type, data);

    for (int32_t k = 0; k < numOfBins; ++k) {
      if (v > bins[k].lower && v <= bins[k].upper) {
        bins[k].count++;
        totalCount++;
        break;
      }
    }
  }

  if (normalized) {
    for (int32_t k = 0; k < numOfBins; ++k) {
      if (totalCount != 0) {
        bins[k].percentage = bins[k].count / (double)totalCount;
      } else {
        bins[k].percentage = 0;
      }
    }
  }

  for (int32_t k = 0; k < numOfBins; ++k) {
    int32_t len;
    char    buf[512] = {0};
    if (!normalized) {
H
Hongze Cheng 已提交
2792 2793
      len = sprintf(varDataVal(buf), "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%" PRId64 "}", bins[k].lower,
                    bins[k].upper, bins[k].count);
2794
    } else {
H
Hongze Cheng 已提交
2795 2796
      len = sprintf(varDataVal(buf), "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%lf}", bins[k].lower,
                    bins[k].upper, bins[k].percentage);
2797 2798 2799 2800 2801 2802 2803 2804 2805
    }
    varDataSetLen(buf, len);
    colDataAppend(pOutputData, k, buf, false);
  }

  taosMemoryFree(bins);
  pOutput->numOfRows = numOfBins;
  return TSDB_CODE_SUCCESS;
}
2806 2807

int32_t selectScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
H
Hongze Cheng 已提交
2808
  SColumnInfoData *pInputData = pInput->columnData;
2809 2810 2811 2812 2813 2814 2815 2816 2817 2818
  SColumnInfoData *pOutputData = pOutput->columnData;

  int32_t type = GET_PARAM_TYPE(pInput);

  for (int32_t i = 0; i < pInput->numOfRows; ++i) {
    if (colDataIsNull_s(pInputData, i)) {
      colDataAppendNULL(pOutputData, 0);
      continue;
    }

H
Hongze Cheng 已提交
2819
    char *data = colDataGetData(pInputData, i);
2820 2821 2822 2823 2824 2825 2826
    colDataAppend(pOutputData, i, data, false);
  }

  pOutput->numOfRows = 1;
  return TSDB_CODE_SUCCESS;
}

G
Ganlin Zhao 已提交
2827
int32_t topBotScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
2828 2829
  return selectScalarFunction(pInput, inputNum, pOutput);
}
2830 2831 2832 2833

int32_t firstLastScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return selectScalarFunction(pInput, inputNum, pOutput);
}
2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849

int32_t sampleScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return selectScalarFunction(pInput, inputNum, pOutput);
}

int32_t tailScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return selectScalarFunction(pInput, inputNum, pOutput);
}

int32_t uniqueScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return selectScalarFunction(pInput, inputNum, pOutput);
}

int32_t modeScalarFunction(SScalarParam *pInput, int32_t inputNum, SScalarParam *pOutput) {
  return selectScalarFunction(pInput, inputNum, pOutput);
}