builtinsimpl.c 188.0 KB
Newer Older
H
Haojun Liao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "builtinsimpl.h"
17
#include "cJSON.h"
18
#include "function.h"
X
Xiaoyu Wang 已提交
19
#include "query.h"
20
#include "querynodes.h"
H
Haojun Liao 已提交
21
#include "taggfunction.h"
G
Ganlin Zhao 已提交
22
#include "tcompare.h"
H
Haojun Liao 已提交
23
#include "tdatablock.h"
24
#include "tdigest.h"
X
Xiaoyu Wang 已提交
25
#include "tglobal.h"
26
#include "thistogram.h"
27
#include "tpercentile.h"
H
Haojun Liao 已提交
28

X
Xiaoyu Wang 已提交
29 30 31 32 33
#define HISTOGRAM_MAX_BINS_NUM 1000
#define MAVG_MAX_POINTS_NUM    1000
#define SAMPLE_MAX_POINTS_NUM  1000
#define TAIL_MAX_POINTS_NUM    100
#define TAIL_MAX_OFFSET        100
G
Ganlin Zhao 已提交
34

X
Xiaoyu Wang 已提交
35
#define UNIQUE_MAX_RESULT_SIZE (1024 * 1024 * 10)
G
Ganlin Zhao 已提交
36
#define MODE_MAX_RESULT_SIZE   UNIQUE_MAX_RESULT_SIZE
37

X
Xiaoyu Wang 已提交
38 39 40 41 42
#define HLL_BUCKET_BITS 14  // The bits of the bucket
#define HLL_DATA_BITS   (64 - HLL_BUCKET_BITS)
#define HLL_BUCKETS     (1 << HLL_BUCKET_BITS)
#define HLL_BUCKET_MASK (HLL_BUCKETS - 1)
#define HLL_ALPHA_INF   0.721347520444481703680  // constant for 0.5/ln(2)
G
Ganlin Zhao 已提交
43

G
Ganlin Zhao 已提交
44 45 46 47 48 49 50 51 52 53 54 55
typedef struct SSumRes {
  union {
    int64_t  isum;
    uint64_t usum;
    double   dsum;
  };
} SSumRes;

typedef struct SAvgRes {
  double  result;
  SSumRes sum;
  int64_t count;
G
Ganlin Zhao 已提交
56
  int16_t type;  // store the original input type, used in merge function
G
Ganlin Zhao 已提交
57 58
} SAvgRes;

59
typedef struct STuplePos {
X
Xiaoyu Wang 已提交
60 61
  int32_t pageId;
  int32_t offset;
62 63
} STuplePos;

G
Ganlin Zhao 已提交
64 65 66 67 68 69
typedef struct SMinmaxResInfo {
  bool      assign;  // assign the first value or not
  int64_t   v;
  STuplePos tuplePos;
} SMinmaxResInfo;

70
typedef struct STopBotResItem {
71 72 73
  SVariant  v;
  uint64_t  uid;  // it is a table uid, used to extract tag data during building of the final result for the tag data
  STuplePos tuplePos;  // tuple data of this chosen row
74 75
} STopBotResItem;

G
Ganlin Zhao 已提交
76
typedef struct STopBotRes {
X
Xiaoyu Wang 已提交
77
  int32_t         maxSize;
G
Ganlin Zhao 已提交
78
  int16_t         type;
79
  STopBotResItem* pItems;
G
Ganlin Zhao 已提交
80 81
} STopBotRes;

G
Ganlin Zhao 已提交
82 83
typedef struct SFirstLastRes {
  bool    hasResult;
84
  bool    isNull;  // used for last_row function only
G
Ganlin Zhao 已提交
85 86 87 88
  int32_t bytes;
  char    buf[];
} SFirstLastRes;

G
Ganlin Zhao 已提交
89 90 91
typedef struct SStddevRes {
  double  result;
  int64_t count;
92
  union {
93 94 95
    double   quadraticDSum;
    int64_t  quadraticISum;
    uint64_t quadraticUSum;
96 97
  };
  union {
98 99 100
    double   dsum;
    int64_t  isum;
    uint64_t usum;
101
  };
G
Ganlin Zhao 已提交
102
  int16_t type;
G
Ganlin Zhao 已提交
103 104
} SStddevRes;

105
typedef struct SLeastSQRInfo {
X
Xiaoyu Wang 已提交
106 107 108
  double  matrix[2][3];
  double  startVal;
  double  stepVal;
109 110 111
  int64_t num;
} SLeastSQRInfo;

G
Ganlin Zhao 已提交
112 113
typedef struct SPercentileInfo {
  double      result;
114
  tMemBucket* pMemBucket;
G
Ganlin Zhao 已提交
115 116 117 118 119 120
  int32_t     stage;
  double      minval;
  double      maxval;
  int64_t     numOfElems;
} SPercentileInfo;

121
typedef struct SAPercentileInfo {
X
Xiaoyu Wang 已提交
122 123 124 125 126
  double          result;
  double          percent;
  int8_t          algo;
  SHistogramInfo* pHisto;
  TDigest*        pTDigest;
127 128 129 130 131 132 133 134
} SAPercentileInfo;

typedef enum {
  APERCT_ALGO_UNKNOWN = 0,
  APERCT_ALGO_DEFAULT,
  APERCT_ALGO_TDIGEST,
} EAPerctAlgoType;

G
Ganlin Zhao 已提交
135
typedef struct SDiffInfo {
136 137
  bool hasPrev;
  bool includeNull;
138
  bool ignoreNegative;  // replace the ignore with case when
139 140 141 142 143
  bool firstOutput;
  union {
    int64_t i64;
    double  d64;
  } prev;
144 145

  int64_t prevTs;
G
Ganlin Zhao 已提交
146 147
} SDiffInfo;

G
Ganlin Zhao 已提交
148 149 150 151 152 153 154
typedef struct SSpreadInfo {
  double result;
  bool   hasResult;
  double min;
  double max;
} SSpreadInfo;

G
Ganlin Zhao 已提交
155 156 157 158 159 160 161
typedef struct SElapsedInfo {
  double  result;
  TSKEY   min;
  TSKEY   max;
  int64_t timeUnit;
} SElapsedInfo;

G
Ganlin Zhao 已提交
162 163 164 165 166 167
typedef struct STwaInfo {
  double      dOutput;
  SPoint1     p;
  STimeWindow win;
} STwaInfo;

168
typedef struct SHistoFuncBin {
X
Xiaoyu Wang 已提交
169 170
  double  lower;
  double  upper;
171 172
  int64_t count;
  double  percentage;
173 174 175
} SHistoFuncBin;

typedef struct SHistoFuncInfo {
X
Xiaoyu Wang 已提交
176 177 178
  int32_t       numOfBins;
  int32_t       totalCount;
  bool          normalized;
179 180 181
  SHistoFuncBin bins[];
} SHistoFuncInfo;

X
Xiaoyu Wang 已提交
182
typedef enum { UNKNOWN_BIN = 0, USER_INPUT_BIN, LINEAR_BIN, LOG_BIN } EHistoBinType;
183

184 185
typedef struct SHLLFuncInfo {
  uint64_t result;
X
Xiaoyu Wang 已提交
186
  uint8_t  buckets[HLL_BUCKETS];
187 188
} SHLLInfo;

189
typedef struct SStateInfo {
190 191 192 193
  union {
    int64_t count;
    int64_t durationStart;
  };
194 195 196 197 198 199 200 201 202 203 204
} SStateInfo;

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;
205

G
Ganlin Zhao 已提交
206 207 208 209 210 211 212 213
typedef struct SMavgInfo {
  int32_t pos;
  double  sum;
  int32_t numOfPoints;
  bool    pointsMeet;
  double  points[];
} SMavgInfo;

G
Ganlin Zhao 已提交
214
typedef struct SSampleInfo {
215 216 217 218 219 220 221
  int32_t    samples;
  int32_t    totalPoints;
  int32_t    numSampled;
  uint8_t    colType;
  int16_t    colBytes;
  char*      data;
  STuplePos* tuplePos;
G
Ganlin Zhao 已提交
222 223
} SSampleInfo;

G
Ganlin Zhao 已提交
224
typedef struct STailItem {
G
Ganlin Zhao 已提交
225
  int64_t timestamp;
226
  bool    isNull;
G
Ganlin Zhao 已提交
227
  char    data[];
G
Ganlin Zhao 已提交
228
} STailItem;
G
Ganlin Zhao 已提交
229 230

typedef struct STailInfo {
X
Xiaoyu Wang 已提交
231 232 233 234 235 236
  int32_t     numOfPoints;
  int32_t     numAdded;
  int32_t     offset;
  uint8_t     colType;
  int16_t     colBytes;
  STailItem** pItems;
G
Ganlin Zhao 已提交
237 238
} STailInfo;

G
Ganlin Zhao 已提交
239 240 241 242 243 244 245 246 247 248
typedef struct SUniqueItem {
  int64_t timestamp;
  bool    isNull;
  char    data[];
} SUniqueItem;

typedef struct SUniqueInfo {
  int32_t   numOfPoints;
  uint8_t   colType;
  int16_t   colBytes;
X
Xiaoyu Wang 已提交
249 250
  bool      hasNull;  // null is not hashable, handle separately
  SHashObj* pHash;
G
Ganlin Zhao 已提交
251 252 253
  char      pItems[];
} SUniqueInfo;

G
Ganlin Zhao 已提交
254 255 256 257 258 259 260 261 262 263 264 265 266
typedef struct SModeItem {
  int64_t count;
  char    data[];
} SModeItem;

typedef struct SModeInfo {
  int32_t   numOfPoints;
  uint8_t   colType;
  int16_t   colBytes;
  SHashObj* pHash;
  char      pItems[];
} SModeInfo;

G
Ganlin Zhao 已提交
267 268 269 270 271 272 273 274 275
typedef struct SDerivInfo {
  double  prevValue;       // previous value
  TSKEY   prevTs;          // previous timestamp
  bool    ignoreNegative;  // ignore the negative value
  int64_t tsWindow;        // time window for derivative
  bool    valueSet;        // the value has been set already
} SDerivInfo;

typedef struct SRateInfo {
276 277 278 279 280
  double firstValue;
  TSKEY  firstKey;
  double lastValue;
  TSKEY  lastKey;
  int8_t hasResult;  // flag to denote has value
G
Ganlin Zhao 已提交
281 282
} SRateInfo;

283 284 285 286
typedef struct SGroupKeyInfo {
  bool hasResult;
  bool isNull;
  char data[];
G
Ganlin Zhao 已提交
287 288
} SGroupKeyInfo;

289 290 291 292 293 294
#define SET_VAL(_info, numOfElem, res) \
  do {                                 \
    if ((numOfElem) <= 0) {            \
      break;                           \
    }                                  \
    (_info)->numOfRes = (res);         \
H
Haojun Liao 已提交
295 296
  } while (0)

G
Ganlin Zhao 已提交
297 298 299 300 301 302
#define GET_TS_LIST(x)    ((TSKEY*)((x)->ptsList))
#define GET_TS_DATA(x, y) (GET_TS_LIST(x)[(y)])

#define DO_UPDATE_TAG_COLUMNS_WITHOUT_TS(ctx)                      \
  do {                                                             \
    for (int32_t _i = 0; _i < (ctx)->tagInfo.numOfTagCols; ++_i) { \
303
      SqlFunctionCtx* __ctx = (ctx)->tagInfo.pTagCtxList[_i];      \
G
Ganlin Zhao 已提交
304 305 306 307
      __ctx->fpSet.process(__ctx);                                 \
    }                                                              \
  } while (0);

G
Ganlin Zhao 已提交
308 309 310 311 312 313 314 315 316 317 318 319
#define DO_UPDATE_SUBSID_RES(ctx, ts)                          \
  do {                                                         \
    for (int32_t _i = 0; _i < (ctx)->subsidiaries.num; ++_i) { \
      SqlFunctionCtx* __ctx = (ctx)->subsidiaries.pCtx[_i];    \
      if (__ctx->functionId == FUNCTION_TS_DUMMY) {            \
        __ctx->tag.i = (ts);                                   \
        __ctx->tag.nType = TSDB_DATA_TYPE_BIGINT;              \
      }                                                        \
      __ctx->fpSet.process(__ctx);                             \
    }                                                          \
  } while (0)

G
Ganlin Zhao 已提交
320 321 322 323 324 325 326 327 328 329 330
#define UPDATE_DATA(ctx, left, right, num, sign, _ts) \
  do {                                                \
    if (((left) < (right)) ^ (sign)) {                \
      (left) = (right);                               \
      DO_UPDATE_SUBSID_RES(ctx, _ts);                 \
      (num) += 1;                                     \
    }                                                 \
  } while (0)

#define LOOPCHECK_N(val, _col, ctx, _t, _nrow, _start, sign, num)        \
  do {                                                                   \
331
    _t* d = (_t*)((_col)->pData);                                        \
G
Ganlin Zhao 已提交
332 333 334 335 336 337 338 339 340
    for (int32_t i = (_start); i < (_nrow) + (_start); ++i) {            \
      if (((_col)->hasNull) && colDataIsNull_f((_col)->nullbitmap, i)) { \
        continue;                                                        \
      }                                                                  \
      TSKEY ts = (ctx)->ptsList != NULL ? GET_TS_DATA(ctx, i) : 0;       \
      UPDATE_DATA(ctx, val, d[i], num, sign, ts);                        \
    }                                                                    \
  } while (0)

X
Xiaoyu Wang 已提交
341
bool dummyGetEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* UNUSED_PARAM(pEnv)) { return true; }
342

X
Xiaoyu Wang 已提交
343
bool dummyInit(SqlFunctionCtx* UNUSED_PARAM(pCtx), SResultRowEntryInfo* UNUSED_PARAM(pResultInfo)) { return true; }
344

X
Xiaoyu Wang 已提交
345
int32_t dummyProcess(SqlFunctionCtx* UNUSED_PARAM(pCtx)) { return 0; }
346

X
Xiaoyu Wang 已提交
347
int32_t dummyFinalize(SqlFunctionCtx* UNUSED_PARAM(pCtx), SSDataBlock* UNUSED_PARAM(pBlock)) { return 0; }
348

349
bool functionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
H
Haojun Liao 已提交
350 351 352 353 354 355 356 357 358 359 360 361
  if (pResultInfo->initialized) {
    return false;
  }

  if (pCtx->pOutput != NULL) {
    memset(pCtx->pOutput, 0, (size_t)pCtx->resDataInfo.bytes);
  }

  initResultRowEntry(pResultInfo, pCtx->resDataInfo.interBufSize);
  return true;
}

362
int32_t functionFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
363
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
364
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
365

366
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
367
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
368 369 370 371 372

  char* in = GET_ROWCELL_INTERBUF(pResInfo);
  colDataAppend(pCol, pBlock->info.rows, in, pResInfo->isNullRes);

  return pResInfo->numOfRes;
H
Haojun Liao 已提交
373 374
}

5
54liuyao 已提交
375 376
int32_t firstCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
X
Xiaoyu Wang 已提交
377 378 379
  char*                pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
  int32_t              type = pDestCtx->input.pData[0]->info.type;
  int32_t              bytes = pDestCtx->input.pData[0]->info.bytes;
5
54liuyao 已提交
380 381

  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
X
Xiaoyu Wang 已提交
382
  char*                pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
5
54liuyao 已提交
383

X
Xiaoyu Wang 已提交
384
  if (pSResInfo->numOfRes != 0 && (pDResInfo->numOfRes == 0 || *(TSKEY*)(pDBuf + bytes) > *(TSKEY*)(pSBuf + bytes))) {
5
54liuyao 已提交
385 386 387 388 389 390 391
    memcpy(pDBuf, pSBuf, bytes);
    *(TSKEY*)(pDBuf + bytes) = *(TSKEY*)(pSBuf + bytes);
    pDResInfo->numOfRes = 1;
  }
  return TSDB_CODE_SUCCESS;
}

392
int32_t functionFinalizeWithResultBuf(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, char* finalResult) {
393
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
394 395 396
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
397
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
398 399 400 401 402 403 404 405
  cleanupResultRowEntry(pResInfo);

  char* in = finalResult;
  colDataAppend(pCol, pBlock->info.rows, in, pResInfo->isNullRes);

  return pResInfo->numOfRes;
}

406 407 408
EFuncDataRequired countDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
  SNode* pParam = nodesListGetNode(pFunc->pParameterList, 0);
  if (QUERY_NODE_COLUMN == nodeType(pParam) && PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)pParam)->colId) {
409
    return FUNC_DATA_REQUIRED_NOT_LOAD;
410
  }
411
  return FUNC_DATA_REQUIRED_STATIS_LOAD;
412
}
H
Haojun Liao 已提交
413 414 415 416 417 418

bool getCountFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(int64_t);
  return true;
}

419
static FORCE_INLINE int32_t getNumOfElems(SqlFunctionCtx* pCtx) {
H
Haojun Liao 已提交
420 421 422
  int32_t numOfElem = 0;

  /*
H
Haojun Liao 已提交
423 424 425
   * 1. column data missing (schema modified) causes pInputCol->hasNull == true. pInput->colDataAggIsSet == true;
   * 2. for general non-primary key columns, pInputCol->hasNull may be true or false, pInput->colDataAggIsSet == true;
   * 3. for primary key column, pInputCol->hasNull always be false, pInput->colDataAggIsSet == false;
H
Haojun Liao 已提交
426 427
   */
  SInputColumnInfoData* pInput = &pCtx->input;
428
  SColumnInfoData*      pInputCol = pInput->pData[0];
H
Haojun Liao 已提交
429 430 431 432 433 434 435 436 437 438 439 440
  if (pInput->colDataAggIsSet && pInput->totalRows == pInput->numOfRows) {
    numOfElem = pInput->numOfRows - pInput->pColumnDataAgg[0]->numOfNull;
    ASSERT(numOfElem >= 0);
  } else {
    if (pInputCol->hasNull) {
      for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
        if (colDataIsNull(pInputCol, pInput->totalRows, i, NULL)) {
          continue;
        }
        numOfElem += 1;
      }
    } else {
441 442
      // when counting on the primary time stamp column and no statistics data is presented, use the size value
      // directly.
H
Haojun Liao 已提交
443 444 445
      numOfElem = pInput->numOfRows;
    }
  }
5
54liuyao 已提交
446 447
  return numOfElem;
}
448

5
54liuyao 已提交
449 450 451 452 453
/*
 * count function does need the finalize, if data is missing, the default value, which is 0, is used
 * count function does not use the pCtx->interResBuf to keep the intermediate buffer
 */
int32_t countFunction(SqlFunctionCtx* pCtx) {
454
  int32_t numOfElem = getNumOfElems(pCtx);
455

X
Xiaoyu Wang 已提交
456
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
457
  SInputColumnInfoData* pInput = &pCtx->input;
458 459

  int32_t type = pInput->pData[0]->info.type;
460 461 462

  char* buf = GET_ROWCELL_INTERBUF(pResInfo);
  if (IS_NULL_TYPE(type)) {
X
Xiaoyu Wang 已提交
463
    // select count(NULL) returns 0
464 465 466 467 468
    numOfElem = 1;
    *((int64_t*)buf) = 0;
  } else {
    *((int64_t*)buf) += numOfElem;
  }
H
Haojun Liao 已提交
469

470 471 472 473 474 475
  if (tsCountAlwaysReturnValue) {
    pResInfo->numOfRes = 1;
  } else {
    SET_VAL(pResInfo, 1, 1);
  }

wmmhello's avatar
wmmhello 已提交
476
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
477 478
}

5
54liuyao 已提交
479
int32_t countInvertFunction(SqlFunctionCtx* pCtx) {
480
  int32_t numOfElem = getNumOfElems(pCtx);
5
54liuyao 已提交
481 482 483 484 485 486 487 488 489

  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  char*                buf = GET_ROWCELL_INTERBUF(pResInfo);
  *((int64_t*)buf) -= numOfElem;

  SET_VAL(pResInfo, *((int64_t*)buf), 1);
  return TSDB_CODE_SUCCESS;
}

5
54liuyao 已提交
490 491
int32_t combineFunction(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
X
Xiaoyu Wang 已提交
492
  char*                pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
5
54liuyao 已提交
493 494 495 496 497 498 499 500 501

  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
  char*                pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
  *((int64_t*)pDBuf) += *((int64_t*)pSBuf);

  SET_VAL(pDResInfo, *((int64_t*)pDBuf), 1);
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
502 503
#define LIST_ADD_N(_res, _col, _start, _rows, _t, numOfElem)             \
  do {                                                                   \
504
    _t* d = (_t*)(_col->pData);                                          \
H
Haojun Liao 已提交
505 506 507 508 509 510 511 512 513
    for (int32_t i = (_start); i < (_rows) + (_start); ++i) {            \
      if (((_col)->hasNull) && colDataIsNull_f((_col)->nullbitmap, i)) { \
        continue;                                                        \
      };                                                                 \
      (_res) += (d)[i];                                                  \
      (numOfElem)++;                                                     \
    }                                                                    \
  } while (0)

5
54liuyao 已提交
514 515 516 517 518 519 520 521 522 523 524 525
#define LIST_SUB_N(_res, _col, _start, _rows, _t, numOfElem)             \
  do {                                                                   \
    _t* d = (_t*)(_col->pData);                                          \
    for (int32_t i = (_start); i < (_rows) + (_start); ++i) {            \
      if (((_col)->hasNull) && colDataIsNull_f((_col)->nullbitmap, i)) { \
        continue;                                                        \
      };                                                                 \
      (_res) -= (d)[i];                                                  \
      (numOfElem)++;                                                     \
    }                                                                    \
  } while (0)

526
int32_t sumFunction(SqlFunctionCtx* pCtx) {
H
Haojun Liao 已提交
527 528 529 530
  int32_t numOfElem = 0;

  // Only the pre-computing information loaded and actual data does not loaded
  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
531 532
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
  int32_t               type = pInput->pData[0]->info.type;
H
Haojun Liao 已提交
533

534
  SSumRes* pSumRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
G
Ganlin Zhao 已提交
535

536 537 538 539 540 541
  if (IS_NULL_TYPE(type)) {
    GET_RES_INFO(pCtx)->isNullRes = 1;
    numOfElem = 1;
    goto _sum_over;
  }

H
Haojun Liao 已提交
542 543 544 545 546
  if (pInput->colDataAggIsSet) {
    numOfElem = pInput->numOfRows - pAgg->numOfNull;
    ASSERT(numOfElem >= 0);

    if (IS_SIGNED_NUMERIC_TYPE(type)) {
547
      pSumRes->isum += pAgg->sum;
H
Haojun Liao 已提交
548
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
549
      pSumRes->usum += pAgg->sum;
H
Haojun Liao 已提交
550
    } else if (IS_FLOAT_TYPE(type)) {
551
      pSumRes->dsum += GET_DOUBLE_VAL((const char*)&(pAgg->sum));
H
Haojun Liao 已提交
552 553 554 555
    }
  } else {  // computing based on the true data block
    SColumnInfoData* pCol = pInput->pData[0];

556
    int32_t start = pInput->startRowIndex;
H
Haojun Liao 已提交
557 558
    int32_t numOfRows = pInput->numOfRows;

559 560
    if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
      if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
561 562 563 564 565 566 567
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int8_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_SMALLINT) {
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int16_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_INT) {
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int32_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_BIGINT) {
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int64_t, numOfElem);
H
Haojun Liao 已提交
568
      }
569 570 571 572 573 574 575 576 577
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
      if (type == TSDB_DATA_TYPE_UTINYINT) {
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint8_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_USMALLINT) {
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint16_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_UINT) {
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint32_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_UBIGINT) {
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint64_t, numOfElem);
H
Haojun Liao 已提交
578
      }
579 580 581 582
    } else if (type == TSDB_DATA_TYPE_DOUBLE) {
      LIST_ADD_N(pSumRes->dsum, pCol, start, numOfRows, double, numOfElem);
    } else if (type == TSDB_DATA_TYPE_FLOAT) {
      LIST_ADD_N(pSumRes->dsum, pCol, start, numOfRows, float, numOfElem);
H
Haojun Liao 已提交
583 584 585
    }
  }

X
Xiaoyu Wang 已提交
586
  // check for overflow
587
  if (IS_FLOAT_TYPE(type) && (isinf(pSumRes->dsum) || isnan(pSumRes->dsum))) {
G
Ganlin Zhao 已提交
588
    numOfElem = 0;
589 590
  }

591
_sum_over:
H
Haojun Liao 已提交
592 593
  // data in the check operation are all null, not output
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
wmmhello's avatar
wmmhello 已提交
594
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
595 596
}

5
54liuyao 已提交
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
int32_t sumInvertFunction(SqlFunctionCtx* pCtx) {
  int32_t numOfElem = 0;

  // Only the pre-computing information loaded and actual data does not loaded
  SInputColumnInfoData* pInput = &pCtx->input;
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
  int32_t               type = pInput->pData[0]->info.type;

  SSumRes* pSumRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

  if (pInput->colDataAggIsSet) {
    numOfElem = pInput->numOfRows - pAgg->numOfNull;
    ASSERT(numOfElem >= 0);

    if (IS_SIGNED_NUMERIC_TYPE(type)) {
      pSumRes->isum -= pAgg->sum;
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
      pSumRes->usum -= pAgg->sum;
    } else if (IS_FLOAT_TYPE(type)) {
      pSumRes->dsum -= GET_DOUBLE_VAL((const char*)&(pAgg->sum));
    }
  } else {  // computing based on the true data block
    SColumnInfoData* pCol = pInput->pData[0];

    int32_t start = pInput->startRowIndex;
    int32_t numOfRows = pInput->numOfRows;

    if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
      if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
        LIST_SUB_N(pSumRes->isum, pCol, start, numOfRows, int8_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_SMALLINT) {
        LIST_SUB_N(pSumRes->isum, pCol, start, numOfRows, int16_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_INT) {
        LIST_SUB_N(pSumRes->isum, pCol, start, numOfRows, int32_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_BIGINT) {
        LIST_SUB_N(pSumRes->isum, pCol, start, numOfRows, int64_t, numOfElem);
      }
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
      if (type == TSDB_DATA_TYPE_UTINYINT) {
        LIST_SUB_N(pSumRes->usum, pCol, start, numOfRows, uint8_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_USMALLINT) {
        LIST_SUB_N(pSumRes->usum, pCol, start, numOfRows, uint16_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_UINT) {
        LIST_SUB_N(pSumRes->usum, pCol, start, numOfRows, uint32_t, numOfElem);
      } else if (type == TSDB_DATA_TYPE_UBIGINT) {
        LIST_SUB_N(pSumRes->usum, pCol, start, numOfRows, uint64_t, numOfElem);
      }
    } else if (type == TSDB_DATA_TYPE_DOUBLE) {
      LIST_SUB_N(pSumRes->dsum, pCol, start, numOfRows, double, numOfElem);
    } else if (type == TSDB_DATA_TYPE_FLOAT) {
      LIST_SUB_N(pSumRes->dsum, pCol, start, numOfRows, float, numOfElem);
    }
  }

  // data in the check operation are all null, not output
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
  return TSDB_CODE_SUCCESS;
}

5
54liuyao 已提交
656 657
int32_t sumCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
X
Xiaoyu Wang 已提交
658 659
  SSumRes*             pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
  int32_t              type = pDestCtx->input.pData[0]->info.type;
5
54liuyao 已提交
660 661

  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
X
Xiaoyu Wang 已提交
662
  SSumRes*             pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
663

5
54liuyao 已提交
664 665 666 667 668 669 670
  if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
    pDBuf->isum += pSBuf->isum;
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
    pDBuf->usum += pSBuf->usum;
  } else if (type == TSDB_DATA_TYPE_DOUBLE || type == TSDB_DATA_TYPE_FLOAT) {
    pDBuf->dsum += pSBuf->dsum;
  }
5
54liuyao 已提交
671
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
5
54liuyao 已提交
672 673 674
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
675
bool getSumFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
H
Haojun Liao 已提交
676 677 678 679
  pEnv->calcMemSize = sizeof(SSumRes);
  return true;
}

680 681
int32_t getAvgInfoSize() { return (int32_t)sizeof(SAvgRes); }

G
Ganlin Zhao 已提交
682
bool getAvgFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
683
  pEnv->calcMemSize = sizeof(SAvgRes);
G
Ganlin Zhao 已提交
684 685 686
  return true;
}

687
bool avgFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
G
Ganlin Zhao 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  SAvgRes* pRes = GET_ROWCELL_INTERBUF(pResultInfo);
  memset(pRes, 0, sizeof(SAvgRes));
  return true;
}

int32_t avgFunction(SqlFunctionCtx* pCtx) {
  int32_t numOfElem = 0;

  SInputColumnInfoData* pInput = &pCtx->input;
701
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
G
Ganlin Zhao 已提交
702 703 704
  int32_t               type = pInput->pData[0]->info.type;

  SAvgRes* pAvgRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
G
Ganlin Zhao 已提交
705
  pAvgRes->type = type;
G
Ganlin Zhao 已提交
706 707 708 709 710 711 712

  // computing based on the true data block
  SColumnInfoData* pCol = pInput->pData[0];

  int32_t start = pInput->startRowIndex;
  int32_t numOfRows = pInput->numOfRows;

713 714 715 716 717 718
  if (IS_NULL_TYPE(type)) {
    GET_RES_INFO(pCtx)->isNullRes = 1;
    numOfElem = 1;
    goto _avg_over;
  }

719 720 721 722 723
  if (pInput->colDataAggIsSet) {
    numOfElem = numOfRows - pAgg->numOfNull;
    ASSERT(numOfElem >= 0);

    pAvgRes->count += numOfElem;
724
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
725
      pAvgRes->sum.isum += pAgg->sum;
726 727
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
      pAvgRes->sum.usum += pAgg->sum;
728 729 730 731 732 733 734 735 736 737 738 739 740 741 742
    } else if (IS_FLOAT_TYPE(type)) {
      pAvgRes->sum.dsum += GET_DOUBLE_VAL((const char*)&(pAgg->sum));
    }
  } else {  // computing based on the true data block
    switch (type) {
      case TSDB_DATA_TYPE_TINYINT: {
        int8_t* plist = (int8_t*)pCol->pData;
        for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
          if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
            continue;
          }

          numOfElem += 1;
          pAvgRes->count += 1;
          pAvgRes->sum.isum += plist[i];
G
Ganlin Zhao 已提交
743 744
        }

745
        break;
G
Ganlin Zhao 已提交
746 747
      }

748 749 750 751 752 753
      case TSDB_DATA_TYPE_SMALLINT: {
        int16_t* plist = (int16_t*)pCol->pData;
        for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
          if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
            continue;
          }
754

755 756 757
          numOfElem += 1;
          pAvgRes->count += 1;
          pAvgRes->sum.isum += plist[i];
G
Ganlin Zhao 已提交
758
        }
759
        break;
G
Ganlin Zhao 已提交
760 761
      }

762 763 764 765 766 767 768 769 770 771
      case TSDB_DATA_TYPE_INT: {
        int32_t* plist = (int32_t*)pCol->pData;
        for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
          if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
            continue;
          }

          numOfElem += 1;
          pAvgRes->count += 1;
          pAvgRes->sum.isum += plist[i];
G
Ganlin Zhao 已提交
772 773
        }

774
        break;
G
Ganlin Zhao 已提交
775 776
      }

777 778 779 780 781 782
      case TSDB_DATA_TYPE_BIGINT: {
        int64_t* plist = (int64_t*)pCol->pData;
        for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
          if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
            continue;
          }
G
Ganlin Zhao 已提交
783

784 785 786
          numOfElem += 1;
          pAvgRes->count += 1;
          pAvgRes->sum.isum += plist[i];
G
Ganlin Zhao 已提交
787
        }
788
        break;
G
Ganlin Zhao 已提交
789 790
      }

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848
      case TSDB_DATA_TYPE_UTINYINT: {
        uint8_t* plist = (uint8_t*)pCol->pData;
        for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
          if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
            continue;
          }

          numOfElem += 1;
          pAvgRes->count += 1;
          pAvgRes->sum.usum += plist[i];
        }

        break;
      }

      case TSDB_DATA_TYPE_USMALLINT: {
        uint16_t* plist = (uint16_t*)pCol->pData;
        for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
          if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
            continue;
          }

          numOfElem += 1;
          pAvgRes->count += 1;
          pAvgRes->sum.usum += plist[i];
        }
        break;
      }

      case TSDB_DATA_TYPE_UINT: {
        uint32_t* plist = (uint32_t*)pCol->pData;
        for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
          if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
            continue;
          }

          numOfElem += 1;
          pAvgRes->count += 1;
          pAvgRes->sum.usum += plist[i];
        }

        break;
      }

      case TSDB_DATA_TYPE_UBIGINT: {
        uint64_t* plist = (uint64_t*)pCol->pData;
        for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
          if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
            continue;
          }

          numOfElem += 1;
          pAvgRes->count += 1;
          pAvgRes->sum.usum += plist[i];
        }
        break;
      }

849 850 851 852 853 854
      case TSDB_DATA_TYPE_FLOAT: {
        float* plist = (float*)pCol->pData;
        for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
          if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
            continue;
          }
G
Ganlin Zhao 已提交
855

856 857 858 859 860
          numOfElem += 1;
          pAvgRes->count += 1;
          pAvgRes->sum.dsum += plist[i];
        }
        break;
G
Ganlin Zhao 已提交
861 862
      }

863 864 865 866 867 868
      case TSDB_DATA_TYPE_DOUBLE: {
        double* plist = (double*)pCol->pData;
        for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
          if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
            continue;
          }
G
Ganlin Zhao 已提交
869

870 871 872 873 874
          numOfElem += 1;
          pAvgRes->count += 1;
          pAvgRes->sum.dsum += plist[i];
        }
        break;
G
Ganlin Zhao 已提交
875 876
      }

877 878 879
      default:
        break;
    }
G
Ganlin Zhao 已提交
880 881
  }

882
_avg_over:
G
Ganlin Zhao 已提交
883 884 885 886 887
  // data in the check operation are all null, not output
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
  return TSDB_CODE_SUCCESS;
}

G
Ganlin Zhao 已提交
888
static void avgTransferInfo(SAvgRes* pInput, SAvgRes* pOutput) {
G
Ganlin Zhao 已提交
889
  pOutput->type = pInput->type;
890
  if (IS_SIGNED_NUMERIC_TYPE(pOutput->type)) {
G
Ganlin Zhao 已提交
891
    pOutput->sum.isum += pInput->sum.isum;
892 893
  } else if (IS_UNSIGNED_NUMERIC_TYPE(pOutput->type)) {
    pOutput->sum.usum += pInput->sum.usum;
G
Ganlin Zhao 已提交
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909
  } else {
    pOutput->sum.dsum += pInput->sum.dsum;
  }

  pOutput->count += pInput->count;

  return;
}

int32_t avgFunctionMerge(SqlFunctionCtx* pCtx) {
  SInputColumnInfoData* pInput = &pCtx->input;
  SColumnInfoData*      pCol = pInput->pData[0];
  ASSERT(pCol->info.type == TSDB_DATA_TYPE_BINARY);

  SAvgRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

910
  int32_t start = pInput->startRowIndex;
G
Ganlin Zhao 已提交
911

912 913 914 915 916
  for(int32_t i = start; i < start + pInput->numOfRows; ++i) {
    char* data = colDataGetData(pCol, i);
    SAvgRes* pInputInfo = (SAvgRes*)varDataVal(data);
    avgTransferInfo(pInputInfo, pInfo);
  }
G
Ganlin Zhao 已提交
917 918 919 920 921 922

  SET_VAL(GET_RES_INFO(pCtx), 1, 1);

  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
923 924 925 926 927 928 929 930 931 932 933 934
#define LIST_AVG_N(sumT, T)                                               \
  do {                                                                    \
    T* plist = (T*)pCol->pData;                                           \
    for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) { \
      if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {        \
        continue;                                                         \
      }                                                                   \
                                                                          \
      numOfElem += 1;                                                     \
      pAvgRes->count -= 1;                                                \
      sumT -= plist[i];                                                   \
    }                                                                     \
5
54liuyao 已提交
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968
  } while (0)

int32_t avgInvertFunction(SqlFunctionCtx* pCtx) {
  int32_t numOfElem = 0;

  // Only the pre-computing information loaded and actual data does not loaded
  SInputColumnInfoData* pInput = &pCtx->input;
  int32_t               type = pInput->pData[0]->info.type;

  SAvgRes* pAvgRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

  // computing based on the true data block
  SColumnInfoData* pCol = pInput->pData[0];

  int32_t start = pInput->startRowIndex;
  int32_t numOfRows = pInput->numOfRows;

  switch (type) {
    case TSDB_DATA_TYPE_TINYINT: {
      LIST_AVG_N(pAvgRes->sum.isum, int8_t);
      break;
    }
    case TSDB_DATA_TYPE_SMALLINT: {
      LIST_AVG_N(pAvgRes->sum.isum, int16_t);
      break;
    }
    case TSDB_DATA_TYPE_INT: {
      LIST_AVG_N(pAvgRes->sum.isum, int32_t);
      break;
    }
    case TSDB_DATA_TYPE_BIGINT: {
      LIST_AVG_N(pAvgRes->sum.isum, int64_t);
      break;
    }
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
    case TSDB_DATA_TYPE_UTINYINT: {
      LIST_AVG_N(pAvgRes->sum.usum, uint8_t);
      break;
    }
    case TSDB_DATA_TYPE_USMALLINT: {
      LIST_AVG_N(pAvgRes->sum.usum, uint16_t);
      break;
    }
    case TSDB_DATA_TYPE_UINT: {
      LIST_AVG_N(pAvgRes->sum.usum, uint32_t);
      break;
    }
    case TSDB_DATA_TYPE_UBIGINT: {
      LIST_AVG_N(pAvgRes->sum.usum, uint64_t);
      break;
    }
5
54liuyao 已提交
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
    case TSDB_DATA_TYPE_FLOAT: {
      LIST_AVG_N(pAvgRes->sum.dsum, float);
      break;
    }
    case TSDB_DATA_TYPE_DOUBLE: {
      LIST_AVG_N(pAvgRes->sum.dsum, double);
      break;
    }
    default:
      break;
  }

  // data in the check operation are all null, not output
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
  return TSDB_CODE_SUCCESS;
}

5
54liuyao 已提交
1002 1003
int32_t avgCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
X
Xiaoyu Wang 已提交
1004 1005
  SAvgRes*             pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
  int32_t              type = pDestCtx->input.pData[0]->info.type;
5
54liuyao 已提交
1006 1007

  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
X
Xiaoyu Wang 已提交
1008
  SAvgRes*             pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
5
54liuyao 已提交
1009

1010
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
5
54liuyao 已提交
1011
    pDBuf->sum.isum += pSBuf->sum.isum;
1012 1013
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
    pDBuf->sum.usum += pSBuf->sum.usum;
5
54liuyao 已提交
1014 1015 1016 1017 1018 1019 1020 1021
  } else {
    pDBuf->sum.dsum += pSBuf->sum.dsum;
  }
  pDBuf->count += pSBuf->count;

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1022
int32_t avgFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
G
Ganlin Zhao 已提交
1023
  SInputColumnInfoData* pInput = &pCtx->input;
1024 1025

  SAvgRes* pAvgRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
G
Ganlin Zhao 已提交
1026
  int32_t  type = pAvgRes->type;
1027

1028
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
1029
    pAvgRes->result = pAvgRes->sum.isum / ((double)pAvgRes->count);
1030 1031
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
    pAvgRes->result = pAvgRes->sum.usum / ((double)pAvgRes->count);
G
Ganlin Zhao 已提交
1032
  } else {
1033
    pAvgRes->result = pAvgRes->sum.dsum / ((double)pAvgRes->count);
G
Ganlin Zhao 已提交
1034
  }
1035

X
Xiaoyu Wang 已提交
1036
  // check for overflow
1037
  if (isinf(pAvgRes->result) || isnan(pAvgRes->result)) {
1038
    GET_RES_INFO(pCtx)->numOfRes = 0;
1039 1040
  }

H
Haojun Liao 已提交
1041
  return functionFinalize(pCtx, pBlock);
G
Ganlin Zhao 已提交
1042 1043
}

G
Ganlin Zhao 已提交
1044 1045
int32_t avgPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1046 1047 1048
  SAvgRes*             pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  int32_t              resultBytes = getAvgInfoSize();
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
G
Ganlin Zhao 已提交
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061

  memcpy(varDataVal(res), pInfo, resultBytes);
  varDataSetLen(res, resultBytes);

  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  colDataAppend(pCol, pBlock->info.rows, res, false);

  taosMemoryFree(res);
  return pResInfo->numOfRes;
}

1062
EFuncDataRequired statisDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
1063 1064 1065
  return FUNC_DATA_REQUIRED_STATIS_LOAD;
}

1066
bool minmaxFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
1067 1068 1069 1070
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;  // not initialized since it has been initialized
  }

1071 1072 1073
  SMinmaxResInfo* buf = GET_ROWCELL_INTERBUF(pResultInfo);
  buf->assign = false;
  buf->tuplePos.pageId = -1;
1074 1075 1076
  return true;
}

H
Haojun Liao 已提交
1077
bool getMinmaxFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
1078
  pEnv->calcMemSize = sizeof(SMinmaxResInfo);
1079 1080 1081
  return true;
}

1082 1083 1084
static void saveTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos);
static void copyTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos);

1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
static int32_t findRowIndex(int32_t start, int32_t num, SColumnInfoData* pCol, const char* tval) {
  // the data is loaded, not only the block SMA value
  for(int32_t i = start; i < num + start; ++i) {
    char* p = colDataGetData(pCol, i);
    if (memcpy((void*)tval, p, pCol->info.bytes) == 0)  {
      return i;
    }
  }

  ASSERT(0);
}


1098
int32_t doMinMaxHelper(SqlFunctionCtx* pCtx, int32_t isMinFunc) {
1099 1100 1101
  int32_t numOfElems = 0;

  SInputColumnInfoData* pInput = &pCtx->input;
1102
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
1103 1104

  SColumnInfoData* pCol = pInput->pData[0];
1105
  int32_t          type = pCol->info.type;
1106 1107

  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
X
Xiaoyu Wang 已提交
1108
  SMinmaxResInfo*      pBuf = GET_ROWCELL_INTERBUF(pResInfo);
1109

1110 1111 1112 1113 1114 1115
  if (IS_NULL_TYPE(type)) {
    GET_RES_INFO(pCtx)->isNullRes = 1;
    numOfElems = 1;
    goto _min_max_over;
  }

1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
  // data in current data block are qualified to the query
  if (pInput->colDataAggIsSet) {
    numOfElems = pInput->numOfRows - pAgg->numOfNull;
    ASSERT(pInput->numOfRows == pInput->totalRows && numOfElems >= 0);
    if (numOfElems == 0) {
      return numOfElems;
    }

    void*   tval = NULL;
    int16_t index = 0;

    if (isMinFunc) {
1128
      tval = &pInput->pColumnDataAgg[0]->min;
1129
    } else {
1130
      tval = &pInput->pColumnDataAgg[0]->max;
1131 1132
    }

1133 1134 1135
    if (!pBuf->assign) {
      pBuf->v = *(int64_t*)tval;
      if (pCtx->subsidiaries.num > 0) {
1136
        index = findRowIndex(pInput->startRowIndex, pInput->numOfRows, pCol, tval);
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147
        saveTupleData(pCtx, index, pCtx->pSrcBlock, &pBuf->tuplePos);
      }
    } else {
      if (IS_SIGNED_NUMERIC_TYPE(type)) {
        int64_t prev = 0;
        GET_TYPED_DATA(prev, int64_t, type, &pBuf->v);

        int64_t val = GET_INT64_VAL(tval);
        if ((prev < val) ^ isMinFunc) {
          pBuf->v = val;
          if (pCtx->subsidiaries.num > 0) {
1148
            index = findRowIndex(pInput->startRowIndex, pInput->numOfRows, pCol, tval);
1149
            saveTupleData(pCtx, index, pCtx->pSrcBlock, &pBuf->tuplePos);
1150
          }
1151
        }
1152

1153 1154 1155 1156 1157 1158 1159 1160
      } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
        uint64_t prev = 0;
        GET_TYPED_DATA(prev, uint64_t, type, &pBuf->v);

        uint64_t val = GET_UINT64_VAL(tval);
        if ((prev < val) ^ isMinFunc) {
          pBuf->v = val;
          if (pCtx->subsidiaries.num > 0) {
1161
            index = findRowIndex(pInput->startRowIndex, pInput->numOfRows, pCol, tval);
1162 1163
            saveTupleData(pCtx, index, pCtx->pSrcBlock, &pBuf->tuplePos);
          }
1164
        }
1165 1166 1167
      } else if (type == TSDB_DATA_TYPE_DOUBLE) {
        double prev = 0;
        GET_TYPED_DATA(prev, int64_t, type, &pBuf->v);
1168

1169 1170 1171 1172
        double val = GET_DOUBLE_VAL(tval);
        if ((prev < val) ^ isMinFunc) {
          pBuf->v = val;
          if (pCtx->subsidiaries.num > 0) {
1173
            index = findRowIndex(pInput->startRowIndex, pInput->numOfRows, pCol, tval);
1174
            saveTupleData(pCtx, index, pCtx->pSrcBlock, &pBuf->tuplePos);
H
Haojun Liao 已提交
1175
          }
1176 1177 1178 1179
        }
      } else if (type == TSDB_DATA_TYPE_FLOAT) {
        double prev = 0;
        GET_TYPED_DATA(prev, int64_t, type, &pBuf->v);
1180

1181 1182 1183 1184 1185 1186
        double val = GET_DOUBLE_VAL(tval);
        if ((prev < val) ^ isMinFunc) {
          pBuf->v = val;
        }

        if (pCtx->subsidiaries.num > 0) {
1187
          index = findRowIndex(pInput->startRowIndex, pInput->numOfRows, pCol, tval);
1188
          saveTupleData(pCtx, index, pCtx->pSrcBlock, &pBuf->tuplePos);
H
Haojun Liao 已提交
1189 1190
        }
      }
1191 1192
    }

1193
    pBuf->assign = true;
1194 1195 1196 1197 1198 1199
    return numOfElems;
  }

  int32_t start = pInput->startRowIndex;
  int32_t numOfRows = pInput->numOfRows;

1200 1201
  if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
    if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
      int8_t* pData = (int8_t*)pCol->pData;
      int8_t* val = (int8_t*)&pBuf->v;

      for (int32_t i = start; i < start + numOfRows; ++i) {
        if ((pCol->hasNull) && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        if (!pBuf->assign) {
          *val = pData[i];
          if (pCtx->subsidiaries.num > 0) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
          }
          pBuf->assign = true;
        } else {
          // ignore the equivalent data value
          if ((*val) == pData[i]) {
            continue;
          }

          if ((*val < pData[i]) ^ isMinFunc) {
            *val = pData[i];
            if (pCtx->subsidiaries.num > 0) {
              copyTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
            }
          }
        }

        numOfElems += 1;
      }
1232
    } else if (type == TSDB_DATA_TYPE_SMALLINT) {
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
      int16_t* pData = (int16_t*)pCol->pData;
      int16_t* val = (int16_t*)&pBuf->v;

      for (int32_t i = start; i < start + numOfRows; ++i) {
        if ((pCol->hasNull) && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        if (!pBuf->assign) {
          *val = pData[i];
          if (pCtx->subsidiaries.num > 0) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
          }
          pBuf->assign = true;
        } else {
          // ignore the equivalent data value
          if ((*val) == pData[i]) {
            continue;
          }

          if ((*val < pData[i]) ^ isMinFunc) {
            *val = pData[i];
            if (pCtx->subsidiaries.num > 0) {
              copyTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
            }
          }
        }

        numOfElems += 1;
      }
1263
    } else if (type == TSDB_DATA_TYPE_INT) {
1264
      int32_t* pData = (int32_t*)pCol->pData;
1265
      int32_t* val = (int32_t*)&pBuf->v;
1266

H
Haojun Liao 已提交
1267
      for (int32_t i = start; i < start + numOfRows; ++i) {
1268 1269 1270 1271
        if ((pCol->hasNull) && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

1272
        if (!pBuf->assign) {
1273
          *val = pData[i];
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
          if (pCtx->subsidiaries.num > 0) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
          }
          pBuf->assign = true;
        } else {
          // ignore the equivalent data value
          if ((*val) == pData[i]) {
            continue;
          }

          if ((*val < pData[i]) ^ isMinFunc) {
            *val = pData[i];
            if (pCtx->subsidiaries.num > 0) {
              copyTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
            }
          }
1290 1291 1292 1293
        }

        numOfElems += 1;
      }
1294
    } else if (type == TSDB_DATA_TYPE_BIGINT) {
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
      int64_t* pData = (int64_t*)pCol->pData;
      int64_t* val = (int64_t*)&pBuf->v;

      for (int32_t i = start; i < start + numOfRows; ++i) {
        if ((pCol->hasNull) && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        if (!pBuf->assign) {
          *val = pData[i];
          if (pCtx->subsidiaries.num > 0) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
          }
          pBuf->assign = true;
        } else {
          // ignore the equivalent data value
          if ((*val) == pData[i]) {
            continue;
          }

          if ((*val < pData[i]) ^ isMinFunc) {
            *val = pData[i];
            if (pCtx->subsidiaries.num > 0) {
              copyTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
            }
          }
        }

        numOfElems += 1;
      }
1325
    }
1326 1327
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
    if (type == TSDB_DATA_TYPE_UTINYINT) {
1328 1329 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
      uint8_t* pData = (uint8_t*)pCol->pData;
      uint8_t* val = (uint8_t*)&pBuf->v;

      for (int32_t i = start; i < start + numOfRows; ++i) {
        if ((pCol->hasNull) && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        if (!pBuf->assign) {
          *val = pData[i];
          if (pCtx->subsidiaries.num > 0) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
          }
          pBuf->assign = true;
        } else {
          // ignore the equivalent data value
          if ((*val) == pData[i]) {
            continue;
          }

          if ((*val < pData[i]) ^ isMinFunc) {
            *val = pData[i];
            if (pCtx->subsidiaries.num > 0) {
              copyTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
            }
          }
        }

        numOfElems += 1;
      }
1358
    } else if (type == TSDB_DATA_TYPE_USMALLINT) {
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
      uint16_t* pData = (uint16_t*)pCol->pData;
      uint16_t* val = (uint16_t*)&pBuf->v;

      for (int32_t i = start; i < start + numOfRows; ++i) {
        if ((pCol->hasNull) && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        if (!pBuf->assign) {
          *val = pData[i];
          if (pCtx->subsidiaries.num > 0) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
          }
          pBuf->assign = true;
        } else {
          // ignore the equivalent data value
          if ((*val) == pData[i]) {
            continue;
          }

          if ((*val < pData[i]) ^ isMinFunc) {
            *val = pData[i];
            if (pCtx->subsidiaries.num > 0) {
              copyTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
            }
          }
        }

        numOfElems += 1;
      }
1389
    } else if (type == TSDB_DATA_TYPE_UINT) {
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
      uint32_t* pData = (uint32_t*)pCol->pData;
      uint32_t* val = (uint32_t*)&pBuf->v;

      for (int32_t i = start; i < start + numOfRows; ++i) {
        if ((pCol->hasNull) && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        if (!pBuf->assign) {
          *val = pData[i];
          if (pCtx->subsidiaries.num > 0) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
          }
          pBuf->assign = true;
        } else {
          // ignore the equivalent data value
          if ((*val) == pData[i]) {
            continue;
          }

          if ((*val < pData[i]) ^ isMinFunc) {
            *val = pData[i];
            if (pCtx->subsidiaries.num > 0) {
              copyTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
            }
          }
        }

        numOfElems += 1;
      }
1420
    } else if (type == TSDB_DATA_TYPE_UBIGINT) {
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
      uint64_t* pData = (uint64_t*)pCol->pData;
      uint64_t* val = (uint64_t*)&pBuf->v;

      for (int32_t i = start; i < start + numOfRows; ++i) {
        if ((pCol->hasNull) && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        if (!pBuf->assign) {
          *val = pData[i];
          if (pCtx->subsidiaries.num > 0) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
          }
          pBuf->assign = true;
        } else {
          // ignore the equivalent data value
          if ((*val) == pData[i]) {
            continue;
          }

          if ((*val < pData[i]) ^ isMinFunc) {
            *val = pData[i];
            if (pCtx->subsidiaries.num > 0) {
              copyTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
            }
          }
        }

        numOfElems += 1;
      }
1451
    }
1452
  } else if (type == TSDB_DATA_TYPE_DOUBLE) {
1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482
    double* pData = (double*)pCol->pData;
    double* val = (double*)&pBuf->v;

    for (int32_t i = start; i < start + numOfRows; ++i) {
      if ((pCol->hasNull) && colDataIsNull_f(pCol->nullbitmap, i)) {
        continue;
      }

      if (!pBuf->assign) {
        *val = pData[i];
        if (pCtx->subsidiaries.num > 0) {
          saveTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
        }
        pBuf->assign = true;
      } else {
        // ignore the equivalent data value
        if ((*val) == pData[i]) {
          continue;
        }

        if ((*val < pData[i]) ^ isMinFunc) {
          *val = pData[i];
          if (pCtx->subsidiaries.num > 0) {
            copyTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
          }
        }
      }

      numOfElems += 1;
    }
1483
  } else if (type == TSDB_DATA_TYPE_FLOAT) {
X
Xiaoyu Wang 已提交
1484
    float*  pData = (float*)pCol->pData;
1485
    double* val = (double*)&pBuf->v;
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513

    for (int32_t i = start; i < start + numOfRows; ++i) {
      if ((pCol->hasNull) && colDataIsNull_f(pCol->nullbitmap, i)) {
        continue;
      }

      if (!pBuf->assign) {
        *val = pData[i];
        if (pCtx->subsidiaries.num > 0) {
          saveTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
        }
        pBuf->assign = true;
      } else {
        // ignore the equivalent data value
        if ((*val) == pData[i]) {
          continue;
        }

        if ((*val < pData[i]) ^ isMinFunc) {
          *val = pData[i];
          if (pCtx->subsidiaries.num > 0) {
            copyTupleData(pCtx, i, pCtx->pSrcBlock, &pBuf->tuplePos);
          }
        }
      }

      numOfElems += 1;
    }
1514 1515
  }

1516
_min_max_over:
1517
  return numOfElems;
H
Haojun Liao 已提交
1518
}
1519

1520
int32_t minFunction(SqlFunctionCtx* pCtx) {
1521 1522
  int32_t numOfElems = doMinMaxHelper(pCtx, 1);
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
wmmhello's avatar
wmmhello 已提交
1523
  return TSDB_CODE_SUCCESS;
1524 1525
}

1526
int32_t maxFunction(SqlFunctionCtx* pCtx) {
1527 1528
  int32_t numOfElems = doMinMaxHelper(pCtx, 0);
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
wmmhello's avatar
wmmhello 已提交
1529
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1530 1531
}

1532 1533 1534
static void setNullSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t rowIndex);

static void setSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, const STuplePos* pTuplePos, int32_t rIndex);
1535

1536 1537 1538 1539 1540 1541
int32_t minmaxFunctionFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);

  SMinmaxResInfo* pRes = GET_ROWCELL_INTERBUF(pEntryInfo);

  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
1542
  int32_t currentRow = pBlock->info.rows;
1543 1544

  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
1545
  pEntryInfo->isNullRes = (pEntryInfo->numOfRes == 0);
1546

1547
  if (pCol->info.type == TSDB_DATA_TYPE_FLOAT) {
X
Xiaoyu Wang 已提交
1548
    float v = *(double*)&pRes->v;
1549
    colDataAppend(pCol, currentRow, (const char*)&v, pEntryInfo->isNullRes);
1550
  } else {
1551
    colDataAppend(pCol, currentRow, (const char*)&pRes->v, pEntryInfo->isNullRes);
1552
  }
1553

1554 1555
  if (pEntryInfo->numOfRes > 0) {
    setSelectivityValue(pCtx, pBlock, &pRes->tuplePos, currentRow);
1556 1557
  } else {
    setNullSelectivityValue(pCtx, pBlock, currentRow);
1558 1559
  }

1560 1561
  return pEntryInfo->numOfRes;
}
1562

1563 1564 1565
void setNullSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t rowIndex) {
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
1566
    int32_t         dstSlotId = pc->pExpr->base.resSchema.slotId;
1567 1568 1569 1570 1571 1572

    SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId);
    colDataAppendNULL(pDstCol, rowIndex);
  }
}

X
Xiaoyu Wang 已提交
1573
void setSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, const STuplePos* pTuplePos, int32_t rowIndex) {
1574 1575
  int32_t pageId = pTuplePos->pageId;
  int32_t offset = pTuplePos->offset;
1576

wmmhello's avatar
wmmhello 已提交
1577
  if (pTuplePos->pageId != -1 && pCtx->subsidiaries.num > 0) {
X
Xiaoyu Wang 已提交
1578
    int32_t    numOfCols = pCtx->subsidiaries.num;
1579 1580 1581
    SFilePage* pPage = getBufPage(pCtx->pBuf, pageId);

    bool* nullList = (bool*)((char*)pPage + offset);
1582
    char* pStart = (char*)(nullList + numOfCols * sizeof(bool));
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593

    // todo set the offset value to optimize the performance.
    for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
      SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];

      SFunctParam* pFuncParam = &pc->pExpr->base.pParam[0];
      int32_t      dstSlotId = pc->pExpr->base.resSchema.slotId;

      int32_t ps = 0;

      SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId);
wmmhello's avatar
wmmhello 已提交
1594 1595
      ASSERT(pc->pExpr->base.resSchema.bytes == pDstCol->info.bytes);
      if (nullList[j]) {
1596
        colDataAppendNULL(pDstCol, rowIndex);
1597
      } else {
wmmhello's avatar
wmmhello 已提交
1598
        colDataAppend(pDstCol, rowIndex, pStart, false);
1599
      }
wmmhello's avatar
wmmhello 已提交
1600
      pStart += pDstCol->info.bytes;
1601
    }
wmmhello's avatar
wmmhello 已提交
1602 1603

    releaseBufPage(pCtx->pBuf, pPage);
1604 1605 1606
  }
}

1607 1608
void releaseSource(STuplePos* pPos) {
  if (pPos->pageId == -1) {
X
Xiaoyu Wang 已提交
1609
    return;
1610 1611 1612 1613 1614 1615 1616 1617 1618
  }
  // Todo(liuyao) relase row
}

void replaceTupleData(STuplePos* pDestPos, STuplePos* pSourcePos) {
  releaseSource(pDestPos);
  *pDestPos = *pSourcePos;
}

5
54liuyao 已提交
1619 1620 1621
int32_t minMaxCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx, int32_t isMinFunc) {
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
  SMinmaxResInfo*      pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
X
Xiaoyu Wang 已提交
1622
  int32_t              type = pDestCtx->input.pData[0]->info.type;
5
54liuyao 已提交
1623 1624 1625 1626

  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
  SMinmaxResInfo*      pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
  if (IS_FLOAT_TYPE(type)) {
X
Xiaoyu Wang 已提交
1627 1628
    if (pSBuf->assign && ((((*(double*)&pDBuf->v) < (*(double*)&pSBuf->v)) ^ isMinFunc) || !pDBuf->assign)) {
      *(double*)&pDBuf->v = *(double*)&pSBuf->v;
1629
      replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
5
54liuyao 已提交
1630
      pDBuf->assign = true;
5
54liuyao 已提交
1631 1632
    }
  } else {
X
Xiaoyu Wang 已提交
1633
    if (pSBuf->assign && (((pDBuf->v < pSBuf->v) ^ isMinFunc) || !pDBuf->assign)) {
5
54liuyao 已提交
1634
      pDBuf->v = pSBuf->v;
1635
      replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
5
54liuyao 已提交
1636
      pDBuf->assign = true;
5
54liuyao 已提交
1637 1638
    }
  }
5
54liuyao 已提交
1639
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
5
54liuyao 已提交
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649
  return TSDB_CODE_SUCCESS;
}

int32_t minCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  return minMaxCombine(pDestCtx, pSourceCtx, 1);
}
int32_t maxCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  return minMaxCombine(pDestCtx, pSourceCtx, 0);
}

1650 1651
int32_t getStddevInfoSize() { return (int32_t)sizeof(SStddevRes); }

H
Haojun Liao 已提交
1652 1653 1654 1655 1656
bool getStddevFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SStddevRes);
  return true;
}

1657
bool stddevFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
H
Haojun Liao 已提交
1658 1659 1660 1661 1662 1663 1664 1665 1666
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  SStddevRes* pRes = GET_ROWCELL_INTERBUF(pResultInfo);
  memset(pRes, 0, sizeof(SStddevRes));
  return true;
}

H
Haojun Liao 已提交
1667
int32_t stddevFunction(SqlFunctionCtx* pCtx) {
H
Haojun Liao 已提交
1668 1669 1670 1671
  int32_t numOfElem = 0;

  // Only the pre-computing information loaded and actual data does not loaded
  SInputColumnInfoData* pInput = &pCtx->input;
H
Haojun Liao 已提交
1672
  int32_t               type = pInput->pData[0]->info.type;
H
Haojun Liao 已提交
1673 1674

  SStddevRes* pStddevRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
G
Ganlin Zhao 已提交
1675
  pStddevRes->type = type;
H
Haojun Liao 已提交
1676

H
Haojun Liao 已提交
1677 1678
  // computing based on the true data block
  SColumnInfoData* pCol = pInput->pData[0];
H
Haojun Liao 已提交
1679

H
Haojun Liao 已提交
1680 1681
  int32_t start = pInput->startRowIndex;
  int32_t numOfRows = pInput->numOfRows;
H
Haojun Liao 已提交
1682

1683 1684 1685 1686 1687 1688
  if (IS_NULL_TYPE(type)) {
    GET_RES_INFO(pCtx)->isNullRes = 1;
    numOfElem = 1;
    goto _stddev_over;
  }

H
Haojun Liao 已提交
1689 1690
  switch (type) {
    case TSDB_DATA_TYPE_TINYINT: {
1691 1692 1693 1694
      int8_t* plist = (int8_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + start; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
H
Haojun Liao 已提交
1695
        }
H
Haojun Liao 已提交
1696

1697 1698 1699 1700
        numOfElem += 1;
        pStddevRes->count += 1;
        pStddevRes->isum += plist[i];
        pStddevRes->quadraticISum += plist[i] * plist[i];
H
Haojun Liao 已提交
1701 1702
      }

1703 1704 1705 1706
      break;
    }

    case TSDB_DATA_TYPE_SMALLINT: {
H
Haojun Liao 已提交
1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
      int16_t* plist = (int16_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
        pStddevRes->isum += plist[i];
        pStddevRes->quadraticISum += plist[i] * plist[i];
      }
      break;
    }

    case TSDB_DATA_TYPE_INT: {
      int32_t* plist = (int32_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
        pStddevRes->isum += plist[i];
        pStddevRes->quadraticISum += plist[i] * plist[i];
      }

      break;
    }

    case TSDB_DATA_TYPE_BIGINT: {
      int64_t* plist = (int64_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
        pStddevRes->isum += plist[i];
        pStddevRes->quadraticISum += plist[i] * plist[i];
      }
      break;
    }

1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
    case TSDB_DATA_TYPE_UTINYINT: {
      uint8_t* plist = (uint8_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + start; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
        pStddevRes->usum += plist[i];
        pStddevRes->quadraticISum += plist[i] * plist[i];
      }

      break;
    }

    case TSDB_DATA_TYPE_USMALLINT: {
      uint16_t* plist = (uint16_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
        pStddevRes->usum += plist[i];
        pStddevRes->quadraticISum += plist[i] * plist[i];
      }
      break;
    }

    case TSDB_DATA_TYPE_UINT: {
      uint32_t* plist = (uint32_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
        pStddevRes->usum += plist[i];
        pStddevRes->quadraticISum += plist[i] * plist[i];
      }

      break;
    }

    case TSDB_DATA_TYPE_UBIGINT: {
      uint64_t* plist = (uint64_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
        pStddevRes->usum += plist[i];
        pStddevRes->quadraticISum += plist[i] * plist[i];
      }
      break;
    }

H
Haojun Liao 已提交
1814 1815 1816 1817 1818 1819 1820 1821 1822
    case TSDB_DATA_TYPE_FLOAT: {
      float* plist = (float*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
G
Ganlin Zhao 已提交
1823 1824
        pStddevRes->dsum += plist[i];
        pStddevRes->quadraticDSum += plist[i] * plist[i];
H
Haojun Liao 已提交
1825 1826 1827 1828
      }
      break;
    }

H
Haojun Liao 已提交
1829 1830 1831 1832 1833 1834 1835 1836 1837
    case TSDB_DATA_TYPE_DOUBLE: {
      double* plist = (double*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem += 1;
        pStddevRes->count += 1;
G
Ganlin Zhao 已提交
1838 1839
        pStddevRes->dsum += plist[i];
        pStddevRes->quadraticDSum += plist[i] * plist[i];
H
Haojun Liao 已提交
1840 1841 1842 1843 1844 1845 1846 1847
      }
      break;
    }

    default:
      break;
  }

1848
_stddev_over:
H
Haojun Liao 已提交
1849 1850
  // data in the check operation are all null, not output
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
wmmhello's avatar
wmmhello 已提交
1851
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1852 1853
}

G
Ganlin Zhao 已提交
1854 1855
static void stddevTransferInfo(SStddevRes* pInput, SStddevRes* pOutput) {
  pOutput->type = pInput->type;
1856
  if (IS_SIGNED_NUMERIC_TYPE(pOutput->type)) {
G
Ganlin Zhao 已提交
1857 1858
    pOutput->quadraticISum += pInput->quadraticISum;
    pOutput->isum += pInput->isum;
1859 1860 1861
  } else if (IS_UNSIGNED_NUMERIC_TYPE(pOutput->type)) {
    pOutput->quadraticUSum += pInput->quadraticUSum;
    pOutput->usum += pInput->usum;
G
Ganlin Zhao 已提交
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
  } else {
    pOutput->quadraticDSum += pInput->quadraticDSum;
    pOutput->dsum += pInput->dsum;
  }

  pOutput->count += pInput->count;
}

int32_t stddevFunctionMerge(SqlFunctionCtx* pCtx) {
  SInputColumnInfoData* pInput = &pCtx->input;
  SColumnInfoData*      pCol = pInput->pData[0];
  ASSERT(pCol->info.type == TSDB_DATA_TYPE_BINARY);

  SStddevRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

1877 1878 1879 1880 1881
  for(int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
    char*       data = colDataGetData(pCol, i);
    SStddevRes* pInputInfo = (SStddevRes*)varDataVal(data);
    stddevTransferInfo(pInputInfo, pInfo);
  }
G
Ganlin Zhao 已提交
1882 1883 1884 1885 1886

  SET_VAL(GET_RES_INFO(pCtx), 1, 1);
  return TSDB_CODE_SUCCESS;
}

5
54liuyao 已提交
1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899
#define LIST_STDDEV_SUB_N(sumT, T)                                 \
  do {                                                             \
    T* plist = (T*)pCol->pData;                                    \
    for (int32_t i = start; i < numOfRows + start; ++i) {          \
      if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) { \
        continue;                                                  \
      }                                                            \
      numOfElem += 1;                                              \
      pStddevRes->count -= 1;                                      \
      sumT -= plist[i];                                            \
      pStddevRes->quadraticISum -= plist[i] * plist[i];            \
    }                                                              \
  } while (0)
X
Xiaoyu Wang 已提交
1900

5
54liuyao 已提交
1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932
int32_t stddevInvertFunction(SqlFunctionCtx* pCtx) {
  int32_t numOfElem = 0;

  // Only the pre-computing information loaded and actual data does not loaded
  SInputColumnInfoData* pInput = &pCtx->input;
  int32_t               type = pInput->pData[0]->info.type;

  SStddevRes* pStddevRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

  // computing based on the true data block
  SColumnInfoData* pCol = pInput->pData[0];

  int32_t start = pInput->startRowIndex;
  int32_t numOfRows = pInput->numOfRows;

  switch (type) {
    case TSDB_DATA_TYPE_TINYINT: {
      LIST_STDDEV_SUB_N(pStddevRes->isum, int8_t);
      break;
    }
    case TSDB_DATA_TYPE_SMALLINT: {
      LIST_STDDEV_SUB_N(pStddevRes->isum, int16_t);
      break;
    }
    case TSDB_DATA_TYPE_INT: {
      LIST_STDDEV_SUB_N(pStddevRes->isum, int32_t);
      break;
    }
    case TSDB_DATA_TYPE_BIGINT: {
      LIST_STDDEV_SUB_N(pStddevRes->isum, int64_t);
      break;
    }
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
    case TSDB_DATA_TYPE_UTINYINT: {
      LIST_STDDEV_SUB_N(pStddevRes->isum, uint8_t);
      break;
    }
    case TSDB_DATA_TYPE_USMALLINT: {
      LIST_STDDEV_SUB_N(pStddevRes->isum, uint16_t);
      break;
    }
    case TSDB_DATA_TYPE_UINT: {
      LIST_STDDEV_SUB_N(pStddevRes->isum, uint32_t);
      break;
    }
    case TSDB_DATA_TYPE_UBIGINT: {
      LIST_STDDEV_SUB_N(pStddevRes->isum, uint64_t);
      break;
    }
5
54liuyao 已提交
1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965
    case TSDB_DATA_TYPE_FLOAT: {
      LIST_STDDEV_SUB_N(pStddevRes->dsum, float);
      break;
    }
    case TSDB_DATA_TYPE_DOUBLE: {
      LIST_STDDEV_SUB_N(pStddevRes->dsum, double);
      break;
    }
    default:
      break;
  }

  // data in the check operation are all null, not output
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1966
int32_t stddevFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
G
Ganlin Zhao 已提交
1967
  SInputColumnInfoData* pInput = &pCtx->input;
1968
  SStddevRes*           pStddevRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
G
Ganlin Zhao 已提交
1969
  int32_t               type = pStddevRes->type;
1970
  double                avg;
G
Ganlin Zhao 已提交
1971

1972
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
1973
    avg = pStddevRes->isum / ((double)pStddevRes->count);
1974
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticISum / ((double)pStddevRes->count) - avg * avg));
1975 1976 1977
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
    avg = pStddevRes->usum / ((double)pStddevRes->count);
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticUSum / ((double)pStddevRes->count) - avg * avg));
G
Ganlin Zhao 已提交
1978
  } else {
1979
    avg = pStddevRes->dsum / ((double)pStddevRes->count);
1980
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticDSum / ((double)pStddevRes->count) - avg * avg));
G
Ganlin Zhao 已提交
1981
  }
1982

1983 1984 1985 1986 1987
  // check for overflow
  if (isinf(pStddevRes->result) || isnan(pStddevRes->result)) {
    GET_RES_INFO(pCtx)->numOfRes = 0;
  }

1988
  return functionFinalize(pCtx, pBlock);
H
Haojun Liao 已提交
1989 1990
}

G
Ganlin Zhao 已提交
1991 1992
int32_t stddevPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1993 1994 1995
  SStddevRes*          pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  int32_t              resultBytes = getStddevInfoSize();
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
G
Ganlin Zhao 已提交
1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008

  memcpy(varDataVal(res), pInfo, resultBytes);
  varDataSetLen(res, resultBytes);

  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  colDataAppend(pCol, pBlock->info.rows, res, false);

  taosMemoryFree(res);
  return pResInfo->numOfRes;
}

5
54liuyao 已提交
2009 2010
int32_t stddevCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
X
Xiaoyu Wang 已提交
2011 2012
  SStddevRes*          pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
  int32_t              type = pDestCtx->input.pData[0]->info.type;
5
54liuyao 已提交
2013 2014

  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
X
Xiaoyu Wang 已提交
2015
  SStddevRes*          pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
5
54liuyao 已提交
2016

2017
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
5
54liuyao 已提交
2018 2019
    pDBuf->isum += pSBuf->isum;
    pDBuf->quadraticISum += pSBuf->quadraticISum;
2020 2021 2022
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
    pDBuf->usum += pSBuf->usum;
    pDBuf->quadraticUSum += pSBuf->quadraticUSum;
5
54liuyao 已提交
2023 2024 2025 2026 2027
  } else {
    pDBuf->dsum += pSBuf->dsum;
    pDBuf->quadraticDSum += pSBuf->quadraticDSum;
  }
  pDBuf->count += pSBuf->count;
5
54liuyao 已提交
2028
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
5
54liuyao 已提交
2029 2030 2031
  return TSDB_CODE_SUCCESS;
}

2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043
bool getLeastSQRFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SLeastSQRInfo);
  return true;
}

bool leastSQRFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);

X
Xiaoyu Wang 已提交
2044 2045
  pInfo->startVal = IS_FLOAT_TYPE(pCtx->param[1].param.nType) ? pCtx->param[1].param.d : (double)pCtx->param[1].param.i;
  pInfo->stepVal = IS_FLOAT_TYPE(pCtx->param[2].param.nType) ? pCtx->param[2].param.d : (double)pCtx->param[2].param.i;
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
  return true;
}

#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 leastSQRFunction(SqlFunctionCtx* pCtx) {
  int32_t numOfElem = 0;

  SInputColumnInfoData* pInput = &pCtx->input;
  int32_t               type = pInput->pData[0]->info.type;

  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

  SColumnInfoData* pCol = pInput->pData[0];

  double(*param)[3] = pInfo->matrix;
  double x = pInfo->startVal;

  int32_t start = pInput->startRowIndex;
  int32_t numOfRows = pInput->numOfRows;

  switch (type) {
    case TSDB_DATA_TYPE_TINYINT: {
      int8_t* plist = (int8_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }
        numOfElem++;
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
      }
2084
      break;
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149
    }
    case TSDB_DATA_TYPE_SMALLINT: {
      int16_t* plist = (int16_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem++;
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
      }
      break;
    }

    case TSDB_DATA_TYPE_INT: {
      int32_t* plist = (int32_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem++;
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
      }
      break;
    }

    case TSDB_DATA_TYPE_BIGINT: {
      int64_t* plist = (int64_t*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem++;
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
      }
      break;
    }

    case TSDB_DATA_TYPE_FLOAT: {
      float* plist = (float*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem++;
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
      }
      break;
    }

    case TSDB_DATA_TYPE_DOUBLE: {
      double* plist = (double*)pCol->pData;
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
          continue;
        }

        numOfElem++;
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
      }
      break;
    }
2150 2151 2152 2153 2154
    case TSDB_DATA_TYPE_NULL: {
      GET_RES_INFO(pCtx)->isNullRes = 1;
      numOfElem = 1;
      break;
    }
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169

    default:
      break;
  }

  pInfo->startVal = x;
  pInfo->num += numOfElem;

  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);

  return TSDB_CODE_SUCCESS;
}

int32_t leastSQRFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
X
Xiaoyu Wang 已提交
2170 2171 2172
  SLeastSQRInfo*       pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
2173 2174 2175

  int32_t currentRow = pBlock->info.rows;

2176
  if (0 == pInfo->num) {
2177 2178 2179 2180 2181 2182 2183 2184
    return 0;
  }

  double(*param)[3] = pInfo->matrix;

  param[1][1] = (double)pInfo->num;
  param[1][0] = param[0][1];

5
54liuyao 已提交
2185 2186 2187 2188 2189 2190
  double param00 = param[0][0] - param[1][0] * (param[0][1] / param[1][1]);
  double param02 = param[0][2] - param[1][2] * (param[0][1] / param[1][1]);
  // param[0][1] = 0;
  double param12 = param[1][2] - param02 * (param[1][0] / param00);
  // param[1][0] = 0;
  param02 /= param00;
2191

5
54liuyao 已提交
2192
  param12 /= param[1][1];
2193

X
Xiaoyu Wang 已提交
2194 2195 2196
  char   buf[64] = {0};
  size_t len =
      snprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE, "{slop:%.6lf, intercept:%.6lf}", param02, param12);
2197 2198
  varDataSetLen(buf, len);

2199
  colDataAppend(pCol, currentRow, buf, pResInfo->isNullRes);
2200 2201 2202 2203 2204

  return pResInfo->numOfRes;
}

int32_t leastSQRInvertFunction(SqlFunctionCtx* pCtx) {
X
Xiaoyu Wang 已提交
2205
  // TODO
2206 2207 2208
  return TSDB_CODE_SUCCESS;
}

5
54liuyao 已提交
2209 2210 2211 2212
int32_t leastSQRCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
  SLeastSQRInfo*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
  int32_t              type = pDestCtx->input.pData[0]->info.type;
X
Xiaoyu Wang 已提交
2213
  double(*pDparam)[3] = pDBuf->matrix;
5
54liuyao 已提交
2214 2215 2216

  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
  SLeastSQRInfo*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
X
Xiaoyu Wang 已提交
2217
  double(*pSparam)[3] = pSBuf->matrix;
5
54liuyao 已提交
2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
  for (int32_t i = 0; i < pSBuf->num; i++) {
    pDparam[0][0] += pDBuf->startVal * pDBuf->startVal;
    pDparam[0][1] += pDBuf->startVal;
    pDBuf->startVal += pDBuf->stepVal;
  }
  pDparam[0][2] += pSparam[0][2] + pDBuf->num * pDBuf->stepVal * pSparam[1][2];
  pDparam[1][2] += pSparam[1][2];
  pDBuf->num += pSBuf->num;
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
2230 2231 2232 2233 2234
bool getPercentileFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SPercentileInfo);
  return true;
}

2235
bool percentileFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
H
Haojun Liao 已提交
2236 2237 2238 2239 2240
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  // in the first round, get the min-max value of all involved data
2241
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
H
Haojun Liao 已提交
2242 2243 2244 2245 2246
  SET_DOUBLE_VAL(&pInfo->minval, DBL_MAX);
  SET_DOUBLE_VAL(&pInfo->maxval, -DBL_MAX);
  pInfo->numOfElems = 0;

  return true;
H
Haojun Liao 已提交
2247 2248
}

2249
int32_t percentileFunction(SqlFunctionCtx* pCtx) {
2250
  int32_t              numOfElems = 0;
2251
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2252 2253

  SInputColumnInfoData* pInput = &pCtx->input;
2254
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
H
Haojun Liao 已提交
2255

2256 2257
  SColumnInfoData* pCol = pInput->pData[0];
  int32_t          type = pCol->info.type;
2258

2259
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2260
  if (pCtx->scanFlag == REPEAT_SCAN && pInfo->stage == 0) {
H
Haojun Liao 已提交
2261
    pInfo->stage += 1;
H
Haojun Liao 已提交
2262

H
Haojun Liao 已提交
2263 2264 2265
    // all data are null, set it completed
    if (pInfo->numOfElems == 0) {
      pResInfo->complete = true;
H
Haojun Liao 已提交
2266
      return 0;
H
Haojun Liao 已提交
2267
    } else {
2268
      pInfo->pMemBucket = tMemBucketCreate(pCol->info.bytes, type, pInfo->minval, pInfo->maxval);
H
Haojun Liao 已提交
2269 2270 2271 2272 2273
    }
  }

  // the first stage, only acquire the min/max value
  if (pInfo->stage == 0) {
2274
    if (pCtx->input.colDataAggIsSet) {
H
Haojun Liao 已提交
2275
      double tmin = 0.0, tmax = 0.0;
2276 2277 2278 2279 2280 2281 2282 2283 2284
      if (IS_SIGNED_NUMERIC_TYPE(type)) {
        tmin = (double)GET_INT64_VAL(&pAgg->min);
        tmax = (double)GET_INT64_VAL(&pAgg->max);
      } else if (IS_FLOAT_TYPE(type)) {
        tmin = GET_DOUBLE_VAL(&pAgg->min);
        tmax = GET_DOUBLE_VAL(&pAgg->max);
      } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
        tmin = (double)GET_UINT64_VAL(&pAgg->min);
        tmax = (double)GET_UINT64_VAL(&pAgg->max);
H
Haojun Liao 已提交
2285 2286 2287 2288 2289 2290 2291 2292 2293 2294
      }

      if (GET_DOUBLE_VAL(&pInfo->minval) > tmin) {
        SET_DOUBLE_VAL(&pInfo->minval, tmin);
      }

      if (GET_DOUBLE_VAL(&pInfo->maxval) < tmax) {
        SET_DOUBLE_VAL(&pInfo->maxval, tmax);
      }

2295
      pInfo->numOfElems += (pInput->numOfRows - pAgg->numOfNull);
H
Haojun Liao 已提交
2296
    } else {
2297 2298 2299 2300
      // check the valid data one by one
      int32_t start = pInput->startRowIndex;
      for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
        if (colDataIsNull_f(pCol->nullbitmap, i)) {
H
Haojun Liao 已提交
2301 2302 2303
          continue;
        }

2304
        char* data = colDataGetData(pCol, i);
2305

H
Haojun Liao 已提交
2306
        double v = 0;
2307
        GET_TYPED_DATA(v, double, type, data);
H
Haojun Liao 已提交
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318
        if (v < GET_DOUBLE_VAL(&pInfo->minval)) {
          SET_DOUBLE_VAL(&pInfo->minval, v);
        }

        if (v > GET_DOUBLE_VAL(&pInfo->maxval)) {
          SET_DOUBLE_VAL(&pInfo->maxval, v);
        }

        pInfo->numOfElems += 1;
      }
    }
2319 2320 2321 2322 2323 2324 2325
  } else {
    // the second stage, calculate the true percentile value
    int32_t start = pInput->startRowIndex;
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
        continue;
      }
H
Haojun Liao 已提交
2326

2327
      char* data = colDataGetData(pCol, i);
2328
      numOfElems += 1;
2329
      tMemBucketPut(pInfo->pMemBucket, data, 1);
H
Haojun Liao 已提交
2330 2331
    }

2332
    SET_VAL(pResInfo, numOfElems, 1);
H
Haojun Liao 已提交
2333 2334
  }

wmmhello's avatar
wmmhello 已提交
2335
  return TSDB_CODE_SUCCESS;
2336 2337
}

2338
int32_t percentileFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
2339
  SVariant* pVal = &pCtx->param[1].param;
2340
  double    v = (pVal->nType == TSDB_DATA_TYPE_BIGINT) ? pVal->i : pVal->d;
H
Haojun Liao 已提交
2341

2342 2343
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SPercentileInfo*     ppInfo = (SPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
2344

2345
  tMemBucket* pMemBucket = ppInfo->pMemBucket;
2346 2347 2348 2349 2350
  if (pMemBucket != NULL && pMemBucket->total > 0) {  // check for null
    SET_DOUBLE_VAL(&ppInfo->result, getPercentile(pMemBucket, v));
  }

  tMemBucketDestroy(pMemBucket);
2351
  return functionFinalize(pCtx, pBlock);
H
Haojun Liao 已提交
2352
}
H
Haojun Liao 已提交
2353

2354
bool getApercentileFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
X
Xiaoyu Wang 已提交
2355 2356
  int32_t bytesHist =
      (int32_t)(sizeof(SAPercentileInfo) + sizeof(SHistogramInfo) + sizeof(SHistBin) * (MAX_HISTOGRAM_BIN + 1));
2357
  int32_t bytesDigest = (int32_t)(sizeof(SAPercentileInfo) + TDIGEST_SIZE(COMPRESSION));
G
Ganlin Zhao 已提交
2358
  pEnv->calcMemSize = TMAX(bytesHist, bytesDigest);
2359 2360 2361
  return true;
}

G
Ganlin Zhao 已提交
2362
int32_t getApercentileMaxSize() {
X
Xiaoyu Wang 已提交
2363 2364
  int32_t bytesHist =
      (int32_t)(sizeof(SAPercentileInfo) + sizeof(SHistogramInfo) + sizeof(SHistBin) * (MAX_HISTOGRAM_BIN + 1));
G
Ganlin Zhao 已提交
2365 2366 2367 2368
  int32_t bytesDigest = (int32_t)(sizeof(SAPercentileInfo) + TDIGEST_SIZE(COMPRESSION));
  return TMAX(bytesHist, bytesDigest);
}

X
Xiaoyu Wang 已提交
2369
static int8_t getApercentileAlgo(char* algoStr) {
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
  int8_t algoType;
  if (strcasecmp(algoStr, "default") == 0) {
    algoType = APERCT_ALGO_DEFAULT;
  } else if (strcasecmp(algoStr, "t-digest") == 0) {
    algoType = APERCT_ALGO_TDIGEST;
  } else {
    algoType = APERCT_ALGO_UNKNOWN;
  }

  return algoType;
}

static void buildHistogramInfo(SAPercentileInfo* pInfo) {
X
Xiaoyu Wang 已提交
2383 2384
  pInfo->pHisto = (SHistogramInfo*)((char*)pInfo + sizeof(SAPercentileInfo));
  pInfo->pHisto->elems = (SHistBin*)((char*)pInfo->pHisto + sizeof(SHistogramInfo));
2385 2386
}

2387 2388 2389 2390
static void buildTDigestInfo(SAPercentileInfo* pInfo) {
  pInfo->pTDigest = (TDigest*)((char*)pInfo + sizeof(SAPercentileInfo));
}

2391 2392 2393 2394 2395 2396
bool apercentileFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
2397 2398 2399 2400

  SVariant* pVal = &pCtx->param[1].param;
  pInfo->percent = (pVal->nType == TSDB_DATA_TYPE_BIGINT) ? pVal->i : pVal->d;

2401 2402 2403
  if (pCtx->numOfParams == 2) {
    pInfo->algo = APERCT_ALGO_DEFAULT;
  } else if (pCtx->numOfParams == 3) {
2404
    pInfo->algo = getApercentileAlgo(varDataVal(pCtx->param[2].param.pz));
2405 2406 2407 2408 2409
    if (pInfo->algo == APERCT_ALGO_UNKNOWN) {
      return false;
    }
  }

X
Xiaoyu Wang 已提交
2410
  char* tmp = (char*)pInfo + sizeof(SAPercentileInfo);
2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
    pInfo->pTDigest = tdigestNewFrom(tmp, COMPRESSION);
  } else {
    buildHistogramInfo(pInfo);
    pInfo->pHisto = tHistogramCreateFrom(tmp, MAX_HISTOGRAM_BIN);
  }

  return true;
}

int32_t apercentileFunction(SqlFunctionCtx* pCtx) {
2422
  int32_t              numOfElems = 0;
2423 2424 2425
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);

  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
2426
  // SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438

  SColumnInfoData* pCol = pInput->pData[0];
  int32_t          type = pCol->info.type;

  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);

  int32_t start = pInput->startRowIndex;
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
        continue;
      }
2439
      numOfElems += 1;
2440 2441
      char* data = colDataGetData(pCol, i);

X
Xiaoyu Wang 已提交
2442 2443
      double  v = 0;  // value
      int64_t w = 1;  // weigth
2444 2445 2446 2447 2448 2449 2450 2451
      GET_TYPED_DATA(v, double, type, data);
      tdigestAdd(pInfo->pTDigest, v, w);
    }
  } else {
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
        continue;
      }
2452
      numOfElems += 1;
2453 2454 2455 2456 2457 2458 2459 2460
      char* data = colDataGetData(pCol, i);

      double v = 0;
      GET_TYPED_DATA(v, double, type, data);
      tHistogramAdd(&pInfo->pHisto, v);
    }
  }

2461
  SET_VAL(pResInfo, numOfElems, 1);
2462 2463 2464
  return TSDB_CODE_SUCCESS;
}

2465 2466 2467 2468 2469 2470
static void apercentileTransferInfo(SAPercentileInfo* pInput, SAPercentileInfo* pOutput) {
  pOutput->percent = pInput->percent;
  pOutput->algo = pInput->algo;
  if (pOutput->algo == APERCT_ALGO_TDIGEST) {
    buildTDigestInfo(pInput);
    tdigestAutoFill(pInput->pTDigest, COMPRESSION);
2471

X
Xiaoyu Wang 已提交
2472
    if (pInput->pTDigest->num_centroids == 0 && pInput->pTDigest->num_buffered_pts == 0) {
2473
      return;
2474 2475
    }

2476
    buildTDigestInfo(pOutput);
X
Xiaoyu Wang 已提交
2477
    TDigest* pTDigest = pOutput->pTDigest;
2478

X
Xiaoyu Wang 已提交
2479
    if (pTDigest->num_centroids <= 0) {
2480
      memcpy(pTDigest, pInput->pTDigest, (size_t)TDIGEST_SIZE(COMPRESSION));
2481 2482
      tdigestAutoFill(pTDigest, COMPRESSION);
    } else {
2483
      tdigestMerge(pTDigest, pInput->pTDigest);
2484
    }
2485
  } else {
2486 2487 2488
    buildHistogramInfo(pInput);
    if (pInput->pHisto->numOfElems <= 0) {
      return;
2489 2490
    }

2491
    buildHistogramInfo(pOutput);
X
Xiaoyu Wang 已提交
2492
    SHistogramInfo* pHisto = pOutput->pHisto;
2493 2494

    if (pHisto->numOfElems <= 0) {
2495
      memcpy(pHisto, pInput->pHisto, sizeof(SHistogramInfo) + sizeof(SHistBin) * (MAX_HISTOGRAM_BIN + 1));
X
Xiaoyu Wang 已提交
2496
      pHisto->elems = (SHistBin*)((char*)pHisto + sizeof(SHistogramInfo));
2497
    } else {
X
Xiaoyu Wang 已提交
2498 2499
      pHisto->elems = (SHistBin*)((char*)pHisto + sizeof(SHistogramInfo));
      SHistogramInfo* pRes = tHistogramMerge(pHisto, pInput->pHisto, MAX_HISTOGRAM_BIN);
2500
      memcpy(pHisto, pRes, sizeof(SHistogramInfo) + sizeof(SHistBin) * MAX_HISTOGRAM_BIN);
X
Xiaoyu Wang 已提交
2501
      pHisto->elems = (SHistBin*)((char*)pHisto + sizeof(SHistogramInfo));
2502 2503 2504
      tHistogramDestroy(&pRes);
    }
  }
2505
}
2506

2507 2508 2509 2510 2511 2512 2513 2514 2515 2516
int32_t apercentileFunctionMerge(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);

  SInputColumnInfoData* pInput = &pCtx->input;

  SColumnInfoData* pCol = pInput->pData[0];
  ASSERT(pCol->info.type == TSDB_DATA_TYPE_BINARY);

  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);

2517
  int32_t start = pInput->startRowIndex;
2518

2519 2520 2521 2522 2523
  for(int32_t i = start; i < start + pInput->numOfRows; ++i) {
    char* data = colDataGetData(pCol, i);
    SAPercentileInfo* pInputInfo = (SAPercentileInfo*)varDataVal(data);
    apercentileTransferInfo(pInputInfo, pInfo);
  }
2524 2525

  SET_VAL(pResInfo, 1, 1);
2526 2527 2528
  return TSDB_CODE_SUCCESS;
}

2529 2530
int32_t apercentileFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
X
Xiaoyu Wang 已提交
2531
  SAPercentileInfo*    pInfo = (SAPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
2532 2533 2534

  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
    if (pInfo->pTDigest->size > 0) {
2535
      pInfo->result = tdigestQuantile(pInfo->pTDigest, pInfo->percent / 100);
2536
    } else {  // no need to free
X
Xiaoyu Wang 已提交
2537
      // setNull(pCtx->pOutput, pCtx->outputType, pCtx->outputBytes);
2538 2539 2540 2541
      return TSDB_CODE_SUCCESS;
    }
  } else {
    if (pInfo->pHisto->numOfElems > 0) {
X
Xiaoyu Wang 已提交
2542 2543
      double  ratio[] = {pInfo->percent};
      double* res = tHistogramUniform(pInfo->pHisto, ratio, 1);
2544
      pInfo->result = *res;
X
Xiaoyu Wang 已提交
2545
      // memcpy(pCtx->pOutput, res, sizeof(double));
2546 2547
      taosMemoryFree(res);
    } else {  // no need to free
X
Xiaoyu Wang 已提交
2548
      // setNull(pCtx->pOutput, pCtx->outputType, pCtx->outputBytes);
2549 2550 2551 2552 2553 2554 2555
      return TSDB_CODE_SUCCESS;
    }
  }

  return functionFinalize(pCtx, pBlock);
}

2556 2557
int32_t apercentilePartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
X
Xiaoyu Wang 已提交
2558
  SAPercentileInfo*    pInfo = (SAPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
2559

2560
  int32_t resultBytes = getApercentileMaxSize();
X
Xiaoyu Wang 已提交
2561
  char*   res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
2562 2563 2564

  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
    if (pInfo->pTDigest->size > 0) {
2565 2566
      memcpy(varDataVal(res), pInfo, resultBytes);
      varDataSetLen(res, resultBytes);
2567 2568 2569 2570 2571
    } else {
      return TSDB_CODE_SUCCESS;
    }
  } else {
    if (pInfo->pHisto->numOfElems > 0) {
2572 2573
      memcpy(varDataVal(res), pInfo, resultBytes);
      varDataSetLen(res, resultBytes);
2574 2575 2576 2577 2578 2579 2580 2581
    } else {
      return TSDB_CODE_SUCCESS;
    }
  }

  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

2582
  colDataAppend(pCol, pBlock->info.rows, res, false);
2583

2584
  taosMemoryFree(res);
2585 2586 2587
  return pResInfo->numOfRes;
}

2588 2589 2590 2591 2592 2593 2594
int32_t apercentileCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
  SAPercentileInfo*    pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);

  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
  SAPercentileInfo*    pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
  ASSERT(pDBuf->algo == pSBuf->algo);
2595
  apercentileTransferInfo(pSBuf, pDBuf);
2596 2597 2598 2599
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
  return TSDB_CODE_SUCCESS;
}

2600 2601 2602
int32_t getFirstLastInfoSize(int32_t resBytes) {
  return sizeof(SFirstLastRes) + resBytes + sizeof(int64_t) + sizeof(STuplePos);
}
2603

H
Haojun Liao 已提交
2604
bool getFirstLastFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
2605
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
2606
  pEnv->calcMemSize = getFirstLastInfoSize(pNode->node.resType.bytes);
H
Haojun Liao 已提交
2607 2608 2609
  return true;
}

2610
bool getSelectivityFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
2611
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
2612 2613 2614 2615
  pEnv->calcMemSize = pNode->node.resType.bytes;
  return true;
}

2616 2617
bool getGroupKeyFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
G
Ganlin Zhao 已提交
2618
  pEnv->calcMemSize = sizeof(SGroupKeyInfo) + pNode->node.resType.bytes;
2619 2620 2621
  return true;
}

2622 2623 2624 2625 2626
static FORCE_INLINE TSKEY getRowPTs(SColumnInfoData* pTsColInfo, int32_t rowIndex) {
  if (pTsColInfo == NULL) {
    return 0;
  }

2627
  return *(TSKEY*)colDataGetData(pTsColInfo, rowIndex);
2628 2629
}

2630 2631
// This ordinary first function does not care if current scan is ascending order or descending order scan
// the OPTIMIZED version of first function will only handle the ascending order scan
2632
int32_t firstFunction(SqlFunctionCtx* pCtx) {
H
Haojun Liao 已提交
2633 2634
  int32_t numOfElems = 0;

2635
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2636
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
H
Haojun Liao 已提交
2637 2638

  SInputColumnInfoData* pInput = &pCtx->input;
2639
  SColumnInfoData*      pInputCol = pInput->pData[0];
H
Haojun Liao 已提交
2640

2641
  int32_t type = pInputCol->info.type;
2642
  int32_t bytes = pInputCol->info.bytes;
2643
  pInfo->bytes = bytes;
2644

H
Haojun Liao 已提交
2645
  // All null data column, return directly.
H
Haojun Liao 已提交
2646
  if (pInput->colDataAggIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows)) {
H
Haojun Liao 已提交
2647
    ASSERT(pInputCol->hasNull == true);
H
Haojun Liao 已提交
2648
    return 0;
H
Haojun Liao 已提交
2649 2650
  }

2651
  SColumnDataAgg* pColAgg = (pInput->colDataAggIsSet) ? pInput->pColumnDataAgg[0] : NULL;
2652

2653 2654
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
2655

2656
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
2657 2658 2659 2660

  if (blockDataOrder == TSDB_ORDER_ASC) {
    // filter according to current result firstly
    if (pResInfo->numOfRes > 0) {
G
Ganlin Zhao 已提交
2661
      TSKEY ts = *(TSKEY*)(pInfo->buf + bytes);
2662 2663 2664 2665 2666 2667 2668 2669 2670 2671
      if (ts < startKey) {
        return TSDB_CODE_SUCCESS;
      }
    }

    for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
        continue;
      }

2672 2673
      numOfElems++;

2674
      char* data = colDataGetData(pInputCol, i);
2675
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2676

G
Ganlin Zhao 已提交
2677
      if (pResInfo->numOfRes == 0 || *(TSKEY*)(pInfo->buf + bytes) > cts) {
G
Ganlin Zhao 已提交
2678 2679 2680 2681
        if (IS_VAR_DATA_TYPE(type)) {
          bytes = varDataTLen(data);
          pInfo->bytes = bytes;
        }
G
Ganlin Zhao 已提交
2682 2683
        memcpy(pInfo->buf, data, bytes);
        *(TSKEY*)(pInfo->buf + bytes) = cts;
2684
        // handle selectivity
G
Ganlin Zhao 已提交
2685 2686 2687 2688 2689 2690 2691
        if (pCtx->subsidiaries.num > 0) {
          STuplePos* pTuplePos = (STuplePos*)(pInfo->buf + bytes + sizeof(TSKEY));
          if (!pInfo->hasResult) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, pTuplePos);
          } else {
            copyTupleData(pCtx, i, pCtx->pSrcBlock, pTuplePos);
          }
2692
        }
G
Ganlin Zhao 已提交
2693
        pInfo->hasResult = true;
2694
        // DO_UPDATE_TAG_COLUMNS(pCtx, ts);
2695
        pResInfo->numOfRes = 1;
2696
        break;
2697 2698 2699 2700 2701 2702
      }
    }
  } else {
    // in case of descending order time stamp serial, which usually happens as the results of the nest query,
    // all data needs to be check.
    if (pResInfo->numOfRes > 0) {
G
Ganlin Zhao 已提交
2703
      TSKEY ts = *(TSKEY*)(pInfo->buf + bytes);
2704 2705 2706
      if (ts < endKey) {
        return TSDB_CODE_SUCCESS;
      }
H
Haojun Liao 已提交
2707 2708
    }

2709 2710 2711 2712 2713
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
        continue;
      }

2714 2715
      numOfElems++;

2716
      char* data = colDataGetData(pInputCol, i);
2717
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2718

G
Ganlin Zhao 已提交
2719
      if (pResInfo->numOfRes == 0 || *(TSKEY*)(pInfo->buf + bytes) > cts) {
G
Ganlin Zhao 已提交
2720 2721 2722 2723
        if (IS_VAR_DATA_TYPE(type)) {
          bytes = varDataTLen(data);
          pInfo->bytes = bytes;
        }
G
Ganlin Zhao 已提交
2724 2725
        memcpy(pInfo->buf, data, bytes);
        *(TSKEY*)(pInfo->buf + bytes) = cts;
2726
        // handle selectivity
G
Ganlin Zhao 已提交
2727 2728 2729 2730 2731 2732 2733
        if (pCtx->subsidiaries.num > 0) {
          STuplePos* pTuplePos = (STuplePos*)(pInfo->buf + bytes + sizeof(TSKEY));
          if (!pInfo->hasResult) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, pTuplePos);
          } else {
            copyTupleData(pCtx, i, pCtx->pSrcBlock, pTuplePos);
          }
2734
        }
G
Ganlin Zhao 已提交
2735
        pInfo->hasResult = true;
2736
        // DO_UPDATE_TAG_COLUMNS(pCtx, ts);
2737
        pResInfo->numOfRes = 1;
2738
        break;
2739 2740
      }
    }
H
Haojun Liao 已提交
2741 2742 2743
  }

  SET_VAL(pResInfo, numOfElems, 1);
wmmhello's avatar
wmmhello 已提交
2744
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2745 2746
}

2747
int32_t lastFunction(SqlFunctionCtx* pCtx) {
H
Haojun Liao 已提交
2748 2749
  int32_t numOfElems = 0;

2750
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2751
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
H
Haojun Liao 已提交
2752 2753

  SInputColumnInfoData* pInput = &pCtx->input;
2754
  SColumnInfoData*      pInputCol = pInput->pData[0];
H
Haojun Liao 已提交
2755

2756
  int32_t type = pInputCol->info.type;
2757
  int32_t bytes = pInputCol->info.bytes;
2758
  pInfo->bytes = bytes;
2759

H
Haojun Liao 已提交
2760
  // All null data column, return directly.
2761
  if (pInput->colDataAggIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows)) {
H
Haojun Liao 已提交
2762
    ASSERT(pInputCol->hasNull == true);
H
Haojun Liao 已提交
2763
    return 0;
H
Haojun Liao 已提交
2764 2765
  }

2766
  SColumnDataAgg* pColAgg = (pInput->colDataAggIsSet) ? pInput->pColumnDataAgg[0] : NULL;
2767 2768 2769 2770

  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);

2771
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
2772 2773

  if (blockDataOrder == TSDB_ORDER_ASC) {
H
Haojun Liao 已提交
2774
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
2775
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
H
Haojun Liao 已提交
2776 2777 2778 2779
        continue;
      }

      numOfElems++;
2780 2781 2782

      char* data = colDataGetData(pInputCol, i);
      TSKEY cts = getRowPTs(pInput->pPTS, i);
G
Ganlin Zhao 已提交
2783
      if (pResInfo->numOfRes == 0 || *(TSKEY*)(pInfo->buf + bytes) < cts) {
G
Ganlin Zhao 已提交
2784 2785 2786 2787
        if (IS_VAR_DATA_TYPE(type)) {
          bytes = varDataTLen(data);
          pInfo->bytes = bytes;
        }
G
Ganlin Zhao 已提交
2788 2789
        memcpy(pInfo->buf, data, bytes);
        *(TSKEY*)(pInfo->buf + bytes) = cts;
2790
        // handle selectivity
G
Ganlin Zhao 已提交
2791 2792 2793 2794 2795 2796 2797
        if (pCtx->subsidiaries.num > 0) {
          STuplePos* pTuplePos = (STuplePos*)(pInfo->buf + bytes + sizeof(TSKEY));
          if (!pInfo->hasResult) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, pTuplePos);
          } else {
            copyTupleData(pCtx, i, pCtx->pSrcBlock, pTuplePos);
          }
2798
        }
G
Ganlin Zhao 已提交
2799
        pInfo->hasResult = true;
2800
        // DO_UPDATE_TAG_COLUMNS(pCtx, ts);
2801 2802
        pResInfo->numOfRes = 1;
      }
H
Haojun Liao 已提交
2803 2804
      break;
    }
2805
  } else {  // descending order
H
Haojun Liao 已提交
2806
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
2807
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
H
Haojun Liao 已提交
2808 2809 2810
        continue;
      }

2811
      numOfElems++;
H
Haojun Liao 已提交
2812

2813 2814
      char* data = colDataGetData(pInputCol, i);
      TSKEY cts = getRowPTs(pInput->pPTS, i);
G
Ganlin Zhao 已提交
2815
      if (pResInfo->numOfRes == 0 || *(TSKEY*)(pInfo->buf + bytes) < cts) {
G
Ganlin Zhao 已提交
2816 2817 2818 2819
        if (IS_VAR_DATA_TYPE(type)) {
          bytes = varDataTLen(data);
          pInfo->bytes = bytes;
        }
G
Ganlin Zhao 已提交
2820 2821
        memcpy(pInfo->buf, data, bytes);
        *(TSKEY*)(pInfo->buf + bytes) = cts;
2822
        // handle selectivity
G
Ganlin Zhao 已提交
2823 2824 2825 2826 2827 2828 2829
        if (pCtx->subsidiaries.num > 0) {
          STuplePos* pTuplePos = (STuplePos*)(pInfo->buf + bytes + sizeof(TSKEY));
          if (!pInfo->hasResult) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, pTuplePos);
          } else {
            copyTupleData(pCtx, i, pCtx->pSrcBlock, pTuplePos);
          }
2830
        }
G
Ganlin Zhao 已提交
2831
        pInfo->hasResult = true;
2832
        pResInfo->numOfRes = 1;
2833
        // DO_UPDATE_TAG_COLUMNS(pCtx, ts);
H
Haojun Liao 已提交
2834 2835 2836 2837 2838 2839
      }
      break;
    }
  }

  SET_VAL(pResInfo, numOfElems, 1);
wmmhello's avatar
wmmhello 已提交
2840
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2841
}
H
Haojun Liao 已提交
2842

2843 2844
static void firstLastTransferInfo(SqlFunctionCtx* pCtx, SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst) {
  SInputColumnInfoData* pColInfo = &pCtx->input;
2845
  int32_t               start = pColInfo->startRowIndex;
2846

G
Ganlin Zhao 已提交
2847
  pOutput->bytes = pInput->bytes;
2848 2849
  TSKEY* tsIn = (TSKEY*)(pInput->buf + pInput->bytes);
  TSKEY* tsOut = (TSKEY*)(pOutput->buf + pInput->bytes);
G
Ganlin Zhao 已提交
2850
  if (pOutput->hasResult) {
2851 2852 2853 2854 2855 2856 2857 2858
    if (isFirst) {
      if (*tsIn > *tsOut) {
        return;
      }
    } else {
      if (*tsIn < *tsOut) {
        return;
      }
G
Ganlin Zhao 已提交
2859 2860 2861 2862
    }
  }
  *tsOut = *tsIn;
  memcpy(pOutput->buf, pInput->buf, pOutput->bytes);
2863
  // handle selectivity
2864
  STuplePos* pTuplePos = (STuplePos*)(pOutput->buf + pOutput->bytes + sizeof(TSKEY));
G
Ganlin Zhao 已提交
2865 2866 2867 2868 2869 2870
  if (pCtx->subsidiaries.num > 0) {
    if (!pOutput->hasResult) {
      saveTupleData(pCtx, start, pCtx->pSrcBlock, pTuplePos);
    } else {
      copyTupleData(pCtx, start, pCtx->pSrcBlock, pTuplePos);
    }
2871
  }
G
Ganlin Zhao 已提交
2872
  pOutput->hasResult = true;
G
Ganlin Zhao 已提交
2873

G
Ganlin Zhao 已提交
2874 2875 2876
  return;
}

2877
static int32_t firstLastFunctionMergeImpl(SqlFunctionCtx* pCtx, bool isFirstQuery) {
G
Ganlin Zhao 已提交
2878
  SInputColumnInfoData* pInput = &pCtx->input;
2879
  SColumnInfoData*      pCol = pInput->pData[0];
G
Ganlin Zhao 已提交
2880 2881 2882 2883
  ASSERT(pCol->info.type == TSDB_DATA_TYPE_BINARY);

  SFirstLastRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

2884 2885
  int32_t start = pInput->startRowIndex;
  int32_t numOfElems = 0;
G
Ganlin Zhao 已提交
2886

2887 2888 2889 2890 2891 2892 2893 2894
  for(int32_t i = start; i < start + pInput->numOfRows; ++i) {
    char* data = colDataGetData(pCol, i);
    SFirstLastRes* pInputInfo = (SFirstLastRes*)varDataVal(data);
    firstLastTransferInfo(pCtx, pInputInfo, pInfo, isFirstQuery);
    if (!numOfElems) {
      numOfElems = pInputInfo->hasResult ? 1 : 0;
    }
  }
2895 2896

  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
G
Ganlin Zhao 已提交
2897 2898 2899 2900

  return TSDB_CODE_SUCCESS;
}

2901
int32_t firstFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, true); }
2902

2903
int32_t lastFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, false); }
2904

2905
int32_t firstLastFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
G
Ganlin Zhao 已提交
2906 2907 2908 2909 2910 2911
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;

G
Ganlin Zhao 已提交
2912 2913
  SFirstLastRes* pRes = GET_ROWCELL_INTERBUF(pResInfo);
  colDataAppend(pCol, pBlock->info.rows, pRes->buf, pResInfo->isNullRes);
2914
  // handle selectivity
2915 2916
  STuplePos* pTuplePos = (STuplePos*)(pRes->buf + pRes->bytes + sizeof(TSKEY));
  setSelectivityValue(pCtx, pBlock, pTuplePos, pBlock->info.rows);
G
Ganlin Zhao 已提交
2917 2918 2919 2920

  return pResInfo->numOfRes;
}

G
Ganlin Zhao 已提交
2921 2922
int32_t firstLastPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
2923
  SFirstLastRes*       pRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2924

2925 2926
  int32_t resultBytes = getFirstLastInfoSize(pRes->bytes);
  char*   res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
G
Ganlin Zhao 已提交
2927 2928 2929 2930 2931 2932 2933 2934

  memcpy(varDataVal(res), pRes, resultBytes);
  varDataSetLen(res, resultBytes);

  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  colDataAppend(pCol, pBlock->info.rows, res, false);
2935
  // handle selectivity
2936 2937
  STuplePos* pTuplePos = (STuplePos*)(pRes->buf + pRes->bytes + sizeof(TSKEY));
  setSelectivityValue(pCtx, pBlock, pTuplePos, pBlock->info.rows);
G
Ganlin Zhao 已提交
2938 2939 2940 2941 2942

  taosMemoryFree(res);
  return 1;
}

5
54liuyao 已提交
2943 2944
int32_t lastCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
X
Xiaoyu Wang 已提交
2945 2946 2947
  char*                pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
  int32_t              type = pDestCtx->input.pData[0]->info.type;
  int32_t              bytes = pDestCtx->input.pData[0]->info.bytes;
5
54liuyao 已提交
2948 2949

  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
X
Xiaoyu Wang 已提交
2950
  char*                pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
5
54liuyao 已提交
2951

X
Xiaoyu Wang 已提交
2952
  if (pSResInfo->numOfRes != 0 && (pDResInfo->numOfRes == 0 || *(TSKEY*)(pDBuf + bytes) < *(TSKEY*)(pSBuf + bytes))) {
5
54liuyao 已提交
2953 2954 2955 2956 2957 2958 2959
    memcpy(pDBuf, pSBuf, bytes);
    *(TSKEY*)(pDBuf + bytes) = *(TSKEY*)(pSBuf + bytes);
    pDResInfo->numOfRes = 1;
  }
  return TSDB_CODE_SUCCESS;
}

2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996
int32_t lastRowFunction(SqlFunctionCtx* pCtx) {
  int32_t numOfElems = 0;

  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);

  SInputColumnInfoData* pInput = &pCtx->input;
  SColumnInfoData*      pInputCol = pInput->pData[0];

  int32_t type = pInputCol->info.type;
  int32_t bytes = pInputCol->info.bytes;
  pInfo->bytes = bytes;

  SColumnDataAgg* pColAgg = (pInput->colDataAggIsSet) ? pInput->pColumnDataAgg[0] : NULL;

  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);

  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;

  if (blockDataOrder == TSDB_ORDER_ASC) {
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
      char* data = colDataGetData(pInputCol, i);
      TSKEY cts = getRowPTs(pInput->pPTS, i);
      if (pResInfo->numOfRes == 0 || *(TSKEY*)(pInfo->buf) < cts) {
        if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
          pInfo->isNull = true;
        } else {
          pInfo->isNull = false;
          if (IS_VAR_DATA_TYPE(type)) {
            bytes = varDataTLen(data);
            pInfo->bytes = bytes;
          }
          memcpy(pInfo->buf + sizeof(TSKEY), data, bytes);
        }
        *(TSKEY*)(pInfo->buf) = cts;
        numOfElems++;
2997
        // handle selectivity
2998 2999 3000 3001 3002 3003 3004 3005 3006
        if (pCtx->subsidiaries.num > 0) {
          STuplePos* pTuplePos = (STuplePos*)(pInfo->buf + bytes + sizeof(TSKEY));
          if (!pInfo->hasResult) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, pTuplePos);
          } else {
            copyTupleData(pCtx, i, pCtx->pSrcBlock, pTuplePos);
          }
        }
        pInfo->hasResult = true;
3007
        // DO_UPDATE_TAG_COLUMNS(pCtx, ts);
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
        pResInfo->numOfRes = 1;
      }
      break;
    }
  } else {  // descending order
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
      char* data = colDataGetData(pInputCol, i);
      TSKEY cts = getRowPTs(pInput->pPTS, i);
      if (pResInfo->numOfRes == 0 || *(TSKEY*)(pInfo->buf) < cts) {
        if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
          pInfo->isNull = true;
        } else {
          pInfo->isNull = false;
          if (IS_VAR_DATA_TYPE(type)) {
            bytes = varDataTLen(data);
            pInfo->bytes = bytes;
          }
          memcpy(pInfo->buf + sizeof(TSKEY), data, bytes);
        }
        *(TSKEY*)(pInfo->buf) = cts;
        numOfElems++;
3029
        // handle selectivity
3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
        if (pCtx->subsidiaries.num > 0) {
          STuplePos* pTuplePos = (STuplePos*)(pInfo->buf + bytes + sizeof(TSKEY));
          if (!pInfo->hasResult) {
            saveTupleData(pCtx, i, pCtx->pSrcBlock, pTuplePos);
          } else {
            copyTupleData(pCtx, i, pCtx->pSrcBlock, pTuplePos);
          }
        }
        pInfo->hasResult = true;
        pResInfo->numOfRes = 1;
3040
        // DO_UPDATE_TAG_COLUMNS(pCtx, ts);
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057
      }
      break;
    }
  }

  SET_VAL(pResInfo, numOfElems, 1);
  return TSDB_CODE_SUCCESS;
}

int32_t lastRowFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);

  SFirstLastRes* pRes = GET_ROWCELL_INTERBUF(pResInfo);
  colDataAppend(pCol, pBlock->info.rows, pRes->buf + sizeof(TSKEY), pRes->isNull);
3058
  // handle selectivity
3059 3060 3061 3062 3063 3064
  STuplePos* pTuplePos = (STuplePos*)(pRes->buf + pRes->bytes + sizeof(TSKEY));
  setSelectivityValue(pCtx, pBlock, pTuplePos, pBlock->info.rows);

  return pResInfo->numOfRes;
}

H
Haojun Liao 已提交
3065 3066 3067 3068 3069
bool getDiffFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SDiffInfo);
  return true;
}

3070
bool diffFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
H
Haojun Liao 已提交
3071 3072 3073 3074 3075
  if (!functionSetup(pCtx, pResInfo)) {
    return false;
  }

  SDiffInfo* pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
3076
  pDiffInfo->hasPrev = false;
H
Haojun Liao 已提交
3077
  pDiffInfo->prev.i64 = 0;
3078 3079 3080 3081 3082
  if (pCtx->numOfParams > 1) {
    pDiffInfo->ignoreNegative = pCtx->param[1].param.i;  // TODO set correct param
  } else {
    pDiffInfo->ignoreNegative = false;
  }
H
Haojun Liao 已提交
3083 3084
  pDiffInfo->includeNull = false;
  pDiffInfo->firstOutput = false;
H
Haojun Liao 已提交
3085 3086 3087
  return true;
}

3088
static void doSetPrevVal(SDiffInfo* pDiffInfo, int32_t type, const char* pv) {
X
Xiaoyu Wang 已提交
3089
  switch (type) {
3090 3091
    case TSDB_DATA_TYPE_BOOL:
    case TSDB_DATA_TYPE_TINYINT:
X
Xiaoyu Wang 已提交
3092 3093
      pDiffInfo->prev.i64 = *(int8_t*)pv;
      break;
3094
    case TSDB_DATA_TYPE_INT:
X
Xiaoyu Wang 已提交
3095 3096
      pDiffInfo->prev.i64 = *(int32_t*)pv;
      break;
3097
    case TSDB_DATA_TYPE_SMALLINT:
X
Xiaoyu Wang 已提交
3098 3099
      pDiffInfo->prev.i64 = *(int16_t*)pv;
      break;
3100
    case TSDB_DATA_TYPE_BIGINT:
X
Xiaoyu Wang 已提交
3101 3102
      pDiffInfo->prev.i64 = *(int64_t*)pv;
      break;
3103
    case TSDB_DATA_TYPE_FLOAT:
X
Xiaoyu Wang 已提交
3104 3105
      pDiffInfo->prev.d64 = *(float*)pv;
      break;
3106
    case TSDB_DATA_TYPE_DOUBLE:
X
Xiaoyu Wang 已提交
3107 3108
      pDiffInfo->prev.d64 = *(double*)pv;
      break;
3109 3110 3111 3112 3113
    default:
      ASSERT(0);
  }
}

X
Xiaoyu Wang 已提交
3114 3115 3116
static void doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, SColumnInfoData* pOutput, int32_t pos,
                         int32_t order) {
  int32_t factor = (order == TSDB_ORDER_ASC) ? 1 : -1;
3117 3118 3119
  switch (type) {
    case TSDB_DATA_TYPE_INT: {
      int32_t v = *(int32_t*)pv;
X
Xiaoyu Wang 已提交
3120
      int64_t delta = factor * (v - pDiffInfo->prev.i64);  // direct previous may be null
3121 3122 3123
      if (delta < 0 && pDiffInfo->ignoreNegative) {
        colDataSetNull_f(pOutput->nullbitmap, pos);
      } else {
3124
        colDataAppendInt64(pOutput, pos, &delta);
3125 3126 3127 3128 3129 3130
      }
      pDiffInfo->prev.i64 = v;
      break;
    }
    case TSDB_DATA_TYPE_BOOL:
    case TSDB_DATA_TYPE_TINYINT: {
X
Xiaoyu Wang 已提交
3131 3132
      int8_t  v = *(int8_t*)pv;
      int64_t delta = factor * (v - pDiffInfo->prev.i64);  // direct previous may be null
3133 3134 3135
      if (delta < 0 && pDiffInfo->ignoreNegative) {
        colDataSetNull_f(pOutput->nullbitmap, pos);
      } else {
3136
        colDataAppendInt64(pOutput, pos, &delta);
3137 3138 3139 3140 3141 3142
      }
      pDiffInfo->prev.i64 = v;
      break;
    }
    case TSDB_DATA_TYPE_SMALLINT: {
      int16_t v = *(int16_t*)pv;
X
Xiaoyu Wang 已提交
3143
      int64_t delta = factor * (v - pDiffInfo->prev.i64);  // direct previous may be null
3144 3145 3146
      if (delta < 0 && pDiffInfo->ignoreNegative) {
        colDataSetNull_f(pOutput->nullbitmap, pos);
      } else {
3147
        colDataAppendInt64(pOutput, pos, &delta);
3148 3149 3150 3151 3152 3153
      }
      pDiffInfo->prev.i64 = v;
      break;
    }
    case TSDB_DATA_TYPE_BIGINT: {
      int64_t v = *(int64_t*)pv;
X
Xiaoyu Wang 已提交
3154
      int64_t delta = factor * (v - pDiffInfo->prev.i64);  // direct previous may be null
3155 3156 3157 3158 3159 3160 3161 3162 3163
      if (delta < 0 && pDiffInfo->ignoreNegative) {
        colDataSetNull_f(pOutput->nullbitmap, pos);
      } else {
        colDataAppendInt64(pOutput, pos, &delta);
      }
      pDiffInfo->prev.i64 = v;
      break;
    }
    case TSDB_DATA_TYPE_FLOAT: {
X
Xiaoyu Wang 已提交
3164 3165 3166
      float  v = *(float*)pv;
      double delta = factor * (v - pDiffInfo->prev.d64);                               // direct previous may be null
      if ((delta < 0 && pDiffInfo->ignoreNegative) || isinf(delta) || isnan(delta)) {  // check for overflow
3167 3168
        colDataSetNull_f(pOutput->nullbitmap, pos);
      } else {
3169
        colDataAppendDouble(pOutput, pos, &delta);
3170 3171 3172 3173 3174 3175
      }
      pDiffInfo->prev.d64 = v;
      break;
    }
    case TSDB_DATA_TYPE_DOUBLE: {
      double v = *(double*)pv;
X
Xiaoyu Wang 已提交
3176 3177
      double delta = factor * (v - pDiffInfo->prev.d64);                               // direct previous may be null
      if ((delta < 0 && pDiffInfo->ignoreNegative) || isinf(delta) || isnan(delta)) {  // check for overflow
3178 3179 3180 3181 3182 3183 3184 3185 3186 3187
        colDataSetNull_f(pOutput->nullbitmap, pos);
      } else {
        colDataAppendDouble(pOutput, pos, &delta);
      }
      pDiffInfo->prev.d64 = v;
      break;
    }
    default:
      ASSERT(0);
  }
G
Ganlin Zhao 已提交
3188
}
3189

3190 3191 3192
int32_t diffFunction(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
H
Haojun Liao 已提交
3193 3194 3195

  SInputColumnInfoData* pInput = &pCtx->input;

3196
  SColumnInfoData* pInputCol = pInput->pData[0];
H
Haojun Liao 已提交
3197

3198
  int32_t numOfElems = 0;
H
Haojun Liao 已提交
3199
  int32_t startOffset = pCtx->offset;
H
Haojun Liao 已提交
3200

3201
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
H
Haojun Liao 已提交
3202

3203 3204 3205
  if (pCtx->order == TSDB_ORDER_ASC) {
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
      int32_t pos = startOffset + numOfElems;
H
Haojun Liao 已提交
3206

3207 3208 3209
      if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
        if (pDiffInfo->includeNull) {
          colDataSetNull_f(pOutput->nullbitmap, pos);
H
Haojun Liao 已提交
3210

3211
          numOfElems += 1;
H
Haojun Liao 已提交
3212
        }
3213
        continue;
H
Haojun Liao 已提交
3214 3215
      }

3216
      char* pv = colDataGetData(pInputCol, i);
H
Haojun Liao 已提交
3217

3218 3219
      if (pDiffInfo->hasPrev) {
        doHandleDiff(pDiffInfo, pInputCol->info.type, pv, pOutput, pos, pCtx->order);
H
Haojun Liao 已提交
3220 3221

        numOfElems++;
3222 3223
      } else {
        doSetPrevVal(pDiffInfo, pInputCol->info.type, pv);
H
Haojun Liao 已提交
3224 3225
      }

3226 3227 3228 3229 3230 3231 3232 3233 3234
      pDiffInfo->hasPrev = true;
    }
  } else {
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
      int32_t pos = startOffset + numOfElems;

      if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
        if (pDiffInfo->includeNull) {
          colDataSetNull_f(pOutput->nullbitmap, pos);
H
Haojun Liao 已提交
3235

3236
          numOfElems += 1;
H
Haojun Liao 已提交
3237
        }
3238
        continue;
H
Haojun Liao 已提交
3239 3240
      }

3241
      char* pv = colDataGetData(pInputCol, i);
H
Haojun Liao 已提交
3242

3243 3244 3245
      // there is a row of previous data block to be handled in the first place.
      if (pDiffInfo->hasPrev) {
        doHandleDiff(pDiffInfo, pInputCol->info.type, pv, pOutput, pos, pCtx->order);
H
Haojun Liao 已提交
3246 3247

        numOfElems++;
3248 3249
      } else {
        doSetPrevVal(pDiffInfo, pInputCol->info.type, pv);
H
Haojun Liao 已提交
3250 3251
      }

3252
      pDiffInfo->hasPrev = true;
H
Haojun Liao 已提交
3253 3254 3255 3256
    }
  }

  // initial value is not set yet
3257
  return numOfElems;
H
Haojun Liao 已提交
3258
}
H
Haojun Liao 已提交
3259

X
Xiaoyu Wang 已提交
3260
int32_t getTopBotInfoSize(int64_t numOfItems) { return sizeof(STopBotRes) + numOfItems * sizeof(STopBotResItem); }
G
Ganlin Zhao 已提交
3261

3262
bool getTopBotFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
3263
  SValueNode* pkNode = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
3264
  pEnv->calcMemSize = sizeof(STopBotRes) + pkNode->datum.i * sizeof(STopBotResItem);
3265 3266 3267
  return true;
}

G
Ganlin Zhao 已提交
3268 3269 3270 3271 3272
bool topBotFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
  if (!functionSetup(pCtx, pResInfo)) {
    return false;
  }

X
Xiaoyu Wang 已提交
3273
  STopBotRes*           pRes = GET_ROWCELL_INTERBUF(pResInfo);
3274 3275 3276 3277
  SInputColumnInfoData* pInput = &pCtx->input;

  pRes->maxSize = pCtx->param[1].param.i;

G
Ganlin Zhao 已提交
3278 3279 3280
  return true;
}

3281 3282 3283 3284
static STopBotRes* getTopBotOutputInfo(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  STopBotRes*          pRes = GET_ROWCELL_INTERBUF(pResInfo);
  pRes->pItems = (STopBotResItem*)((char*)pRes + sizeof(STopBotRes));
3285 3286

  return pRes;
3287 3288
}

3289
static void doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, uint16_t type,
3290
                            uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery);
3291

G
Ganlin Zhao 已提交
3292 3293
static void addResult(SqlFunctionCtx* pCtx, STopBotResItem* pSourceItem, int16_t type, bool isTopQuery);

3294 3295 3296
int32_t topFunction(SqlFunctionCtx* pCtx) {
  int32_t              numOfElems = 0;
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
3297 3298

  SInputColumnInfoData* pInput = &pCtx->input;
3299
  SColumnInfoData*      pCol = pInput->pData[0];
3300

G
Ganlin Zhao 已提交
3301 3302
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
  pRes->type = pInput->pData[0]->info.type;
3303 3304

  int32_t start = pInput->startRowIndex;
3305
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
3306 3307 3308
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
      continue;
    }
3309

3310
    numOfElems++;
3311
    char* data = colDataGetData(pCol, i);
G
Ganlin Zhao 已提交
3312
    doAddIntoResult(pCtx, data, i, pCtx->pSrcBlock, pRes->type, pInput->uid, pResInfo, true);
3313 3314 3315 3316 3317
  }

  return TSDB_CODE_SUCCESS;
}

3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341
int32_t bottomFunction(SqlFunctionCtx* pCtx) {
  int32_t              numOfElems = 0;
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);

  SInputColumnInfoData* pInput = &pCtx->input;
  SColumnInfoData*      pCol = pInput->pData[0];

  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
  pRes->type = pInput->pData[0]->info.type;

  int32_t start = pInput->startRowIndex;
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
      continue;
    }

    numOfElems++;
    char* data = colDataGetData(pCol, i);
    doAddIntoResult(pCtx, data, i, pCtx->pSrcBlock, pRes->type, pInput->uid, pResInfo, false);
  }

  return TSDB_CODE_SUCCESS;
}

3342 3343
static int32_t topBotResComparFn(const void* p1, const void* p2, const void* param) {
  uint16_t type = *(uint16_t*)param;
3344

3345 3346
  STopBotResItem* val1 = (STopBotResItem*)p1;
  STopBotResItem* val2 = (STopBotResItem*)p2;
3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368

  if (IS_SIGNED_NUMERIC_TYPE(type)) {
    if (val1->v.i == val2->v.i) {
      return 0;
    }

    return (val1->v.i > val2->v.i) ? 1 : -1;
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
    if (val1->v.u == val2->v.u) {
      return 0;
    }

    return (val1->v.u > val2->v.u) ? 1 : -1;
  }

  if (val1->v.d == val2->v.d) {
    return 0;
  }

  return (val1->v.d > val2->v.d) ? 1 : -1;
}

3369
void doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, uint16_t type,
3370
                     uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery) {
3371
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
3372

3373 3374 3375
  SVariant val = {0};
  taosVariantCreateFromBinary(&val, pData, tDataTypes[type].bytes, type);

3376
  STopBotResItem* pItems = pRes->pItems;
3377 3378 3379
  assert(pItems != NULL);

  // not full yet
G
Ganlin Zhao 已提交
3380
  if (pEntryInfo->numOfRes < pRes->maxSize) {
3381
    STopBotResItem* pItem = &pItems[pEntryInfo->numOfRes];
3382
    pItem->v = val;
3383
    pItem->uid = uid;
3384

3385
    // save the data of this tuple
G
Ganlin Zhao 已提交
3386 3387 3388
    if (pCtx->subsidiaries.num > 0) {
      saveTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
    }
3389
#ifdef BUF_PAGE_DEBUG
X
Xiaoyu Wang 已提交
3390 3391
    qDebug("page_saveTuple i:%d, item:%p,pageId:%d, offset:%d\n", pEntryInfo->numOfRes, pItem, pItem->tuplePos.pageId,
           pItem->tuplePos.offset);
3392
#endif
3393 3394
    // allocate the buffer and keep the data of this row into the new allocated buffer
    pEntryInfo->numOfRes++;
3395
    taosheapsort((void*)pItems, sizeof(STopBotResItem), pEntryInfo->numOfRes, (const void*)&type, topBotResComparFn,
3396
                 !isTopQuery);
3397
  } else {  // replace the minimum value in the result
X
Xiaoyu Wang 已提交
3398 3399 3400 3401 3402 3403
    if ((isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i > pItems[0].v.i) ||
                        (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u > pItems[0].v.u) ||
                        (IS_FLOAT_TYPE(type) && val.d > pItems[0].v.d))) ||
        (!isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i < pItems[0].v.i) ||
                         (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u < pItems[0].v.u) ||
                         (IS_FLOAT_TYPE(type) && val.d < pItems[0].v.d)))) {
3404
      // replace the old data and the coresponding tuple data
3405
      STopBotResItem* pItem = &pItems[0];
3406
      pItem->v = val;
3407
      pItem->uid = uid;
3408 3409

      // save the data of this tuple by over writing the old data
G
Ganlin Zhao 已提交
3410 3411 3412
      if (pCtx->subsidiaries.num > 0) {
        copyTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
      }
3413
#ifdef BUF_PAGE_DEBUG
wmmhello's avatar
wmmhello 已提交
3414
      qDebug("page_copyTuple pageId:%d, offset:%d", pItem->tuplePos.pageId, pItem->tuplePos.offset);
3415
#endif
3416
      taosheapadjust((void*)pItems, sizeof(STopBotResItem), 0, pEntryInfo->numOfRes - 1, (const void*)&type,
3417
                     topBotResComparFn, NULL, !isTopQuery);
3418
    }
3419 3420
  }
}
3421

3422
void saveTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
3423 3424
  SFilePage* pPage = NULL;

wmmhello's avatar
wmmhello 已提交
3425 3426 3427 3428 3429
  int32_t completeRowSize = pCtx->subsidiaries.num * sizeof(bool);
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
    completeRowSize += pc->pExpr->base.resSchema.bytes;
  }
3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441

  if (pCtx->curBufPage == -1) {
    pPage = getNewBufPage(pCtx->pBuf, 0, &pCtx->curBufPage);
    pPage->num = sizeof(SFilePage);
  } else {
    pPage = getBufPage(pCtx->pBuf, pCtx->curBufPage);
    if (pPage->num + completeRowSize > getBufPageSize(pCtx->pBuf)) {
      pPage = getNewBufPage(pCtx->pBuf, 0, &pCtx->curBufPage);
      pPage->num = sizeof(SFilePage);
    }
  }

3442
  pPos->pageId = pCtx->curBufPage;
3443 3444 3445 3446

  // keep the current row data, extract method
  int32_t offset = 0;
  bool*   nullList = (bool*)((char*)pPage + pPage->num);
wmmhello's avatar
wmmhello 已提交
3447 3448 3449 3450 3451 3452 3453 3454 3455
  char*   pStart = (char*)(nullList + sizeof(bool) * pCtx->subsidiaries.num);
  for (int32_t i = 0; i < pCtx->subsidiaries.num; ++i) {
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[i];

    SFunctParam* pFuncParam = &pc->pExpr->base.pParam[0];
    int32_t      srcSlotId = pFuncParam->pCol->slotId;

    SColumnInfoData* pCol = taosArrayGet(pSrcBlock->pDataBlock, srcSlotId);
    if ((nullList[i] = colDataIsNull_s(pCol, rowIndex)) == true) {
3456
      offset += pCol->info.bytes;
3457 3458 3459 3460 3461
      continue;
    }

    char* p = colDataGetData(pCol, rowIndex);
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
X
Xiaoyu Wang 已提交
3462
      memcpy(pStart + offset, p, (pCol->info.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(p) : varDataTLen(p));
3463 3464 3465 3466 3467 3468 3469
    } else {
      memcpy(pStart + offset, p, pCol->info.bytes);
    }

    offset += pCol->info.bytes;
  }

3470
  pPos->offset = pPage->num;
3471 3472 3473 3474
  pPage->num += completeRowSize;

  setBufPageDirty(pPage, true);
  releaseBufPage(pCtx->pBuf, pPage);
wmmhello's avatar
wmmhello 已提交
3475 3476 3477 3478
#ifdef BUF_PAGE_DEBUG
  qDebug("page_saveTuple pos:%p,pageId:%d, offset:%d\n", pPos, pPos->pageId,
           pPos->offset);
#endif
3479 3480
}

3481 3482
void copyTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
  SFilePage* pPage = getBufPage(pCtx->pBuf, pPos->pageId);
3483

wmmhello's avatar
wmmhello 已提交
3484
  int32_t numOfCols = pCtx->subsidiaries.num;
3485

3486
  bool* nullList = (bool*)((char*)pPage + pPos->offset);
3487
  char* pStart = (char*)(nullList + numOfCols * sizeof(bool));
3488 3489

  int32_t offset = 0;
3490
  for (int32_t i = 0; i < numOfCols; ++i) {
wmmhello's avatar
wmmhello 已提交
3491
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[i];
X
Xiaoyu Wang 已提交
3492 3493
    SFunctParam*    pFuncParam = &pc->pExpr->base.pParam[0];
    int32_t         srcSlotId = pFuncParam->pCol->slotId;
wmmhello's avatar
wmmhello 已提交
3494 3495

    SColumnInfoData* pCol = taosArrayGet(pSrcBlock->pDataBlock, srcSlotId);
3496
    if ((nullList[i] = colDataIsNull_s(pCol, rowIndex)) == true) {
3497
      offset += pCol->info.bytes;
3498 3499 3500 3501 3502
      continue;
    }

    char* p = colDataGetData(pCol, rowIndex);
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
X
Xiaoyu Wang 已提交
3503
      memcpy(pStart + offset, p, (pCol->info.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(p) : varDataTLen(p));
3504 3505 3506 3507 3508 3509 3510 3511 3512
    } else {
      memcpy(pStart + offset, p, pCol->info.bytes);
    }

    offset += pCol->info.bytes;
  }

  setBufPageDirty(pPage, true);
  releaseBufPage(pCtx->pBuf, pPage);
wmmhello's avatar
wmmhello 已提交
3513 3514 3515
#ifdef BUF_PAGE_DEBUG
  qDebug("page_copyTuple pos:%p, pageId:%d, offset:%d", pPos, pPos->pageId, pPos->offset);
#endif
3516 3517
}

3518
int32_t topBotFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
3519
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
3520
  STopBotRes*          pRes = getTopBotOutputInfo(pCtx);
3521

3522
  int16_t type = pCtx->input.pData[0]->info.type;
3523 3524
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;

3525 3526 3527 3528
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  // todo assign the tag value and the corresponding row data
  int32_t currentRow = pBlock->info.rows;
3529 3530 3531 3532 3533 3534 3535
  for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
    STopBotResItem* pItem = &pRes->pItems[i];
    if (type == TSDB_DATA_TYPE_FLOAT) {
      float v = pItem->v.d;
      colDataAppend(pCol, currentRow, (const char*)&v, false);
    } else {
      colDataAppend(pCol, currentRow, (const char*)&pItem->v.i, false);
3536
    }
3537
#ifdef BUF_PAGE_DEBUG
X
Xiaoyu Wang 已提交
3538 3539
    qDebug("page_finalize i:%d,item:%p,pageId:%d, offset:%d\n", i, pItem, pItem->tuplePos.pageId,
           pItem->tuplePos.offset);
3540
#endif
3541
    setSelectivityValue(pCtx, pBlock, &pRes->pItems[i].tuplePos, currentRow);
3542
    currentRow += 1;
3543 3544 3545
  }

  return pEntryInfo->numOfRes;
3546
}
G
Ganlin Zhao 已提交
3547

X
Xiaoyu Wang 已提交
3548
void addResult(SqlFunctionCtx* pCtx, STopBotResItem* pSourceItem, int16_t type, bool isTopQuery) {
3549
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
X
Xiaoyu Wang 已提交
3550 3551
  STopBotRes*          pRes = getTopBotOutputInfo(pCtx);
  STopBotResItem*      pItems = pRes->pItems;
3552 3553 3554
  assert(pItems != NULL);

  // not full yet
G
Ganlin Zhao 已提交
3555
  if (pEntryInfo->numOfRes < pRes->maxSize) {
3556 3557 3558 3559 3560 3561 3562 3563 3564
    STopBotResItem* pItem = &pItems[pEntryInfo->numOfRes];
    pItem->v = pSourceItem->v;
    pItem->uid = pSourceItem->uid;
    pItem->tuplePos.pageId = -1;
    replaceTupleData(&pItem->tuplePos, &pSourceItem->tuplePos);
    pEntryInfo->numOfRes++;
    taosheapsort((void*)pItems, sizeof(STopBotResItem), pEntryInfo->numOfRes, (const void*)&type, topBotResComparFn,
                 !isTopQuery);
  } else {  // replace the minimum value in the result
X
Xiaoyu Wang 已提交
3565 3566 3567 3568 3569 3570
    if ((isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && pSourceItem->v.i > pItems[0].v.i) ||
                        (IS_UNSIGNED_NUMERIC_TYPE(type) && pSourceItem->v.u > pItems[0].v.u) ||
                        (IS_FLOAT_TYPE(type) && pSourceItem->v.d > pItems[0].v.d))) ||
        (!isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && pSourceItem->v.i < pItems[0].v.i) ||
                         (IS_UNSIGNED_NUMERIC_TYPE(type) && pSourceItem->v.u < pItems[0].v.u) ||
                         (IS_FLOAT_TYPE(type) && pSourceItem->v.d < pItems[0].v.d)))) {
3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584
      // replace the old data and the coresponding tuple data
      STopBotResItem* pItem = &pItems[0];
      pItem->v = pSourceItem->v;
      pItem->uid = pSourceItem->uid;

      // save the data of this tuple by over writing the old data
      replaceTupleData(&pItem->tuplePos, &pSourceItem->tuplePos);
      taosheapadjust((void*)pItems, sizeof(STopBotResItem), 0, pEntryInfo->numOfRes - 1, (const void*)&type,
                     topBotResComparFn, NULL, !isTopQuery);
    }
  }
}

int32_t topCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
X
Xiaoyu Wang 已提交
3585
  int32_t              type = pDestCtx->input.pData[0]->info.type;
3586 3587 3588 3589 3590 3591 3592 3593 3594
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
  STopBotRes*          pSBuf = getTopBotOutputInfo(pSourceCtx);
  for (int32_t i = 0; i < pSResInfo->numOfRes; i++) {
    addResult(pDestCtx, pSBuf->pItems + i, type, true);
  }
  return TSDB_CODE_SUCCESS;
}

int32_t bottomCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
X
Xiaoyu Wang 已提交
3595
  int32_t              type = pDestCtx->input.pData[0]->info.type;
3596 3597 3598 3599 3600 3601 3602 3603
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
  STopBotRes*          pSBuf = getTopBotOutputInfo(pSourceCtx);
  for (int32_t i = 0; i < pSResInfo->numOfRes; i++) {
    addResult(pDestCtx, pSBuf->pItems + i, type, false);
  }
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
3604
int32_t getSpreadInfoSize() { return (int32_t)sizeof(SSpreadInfo); }
G
Ganlin Zhao 已提交
3605

G
Ganlin Zhao 已提交
3606 3607 3608 3609 3610
bool getSpreadFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SSpreadInfo);
  return true;
}

X
Xiaoyu Wang 已提交
3611
bool spreadFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
G
Ganlin Zhao 已提交
3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
  SET_DOUBLE_VAL(&pInfo->min, DBL_MAX);
  SET_DOUBLE_VAL(&pInfo->max, -DBL_MAX);
  pInfo->hasResult = false;
  return true;
}

X
Xiaoyu Wang 已提交
3623
int32_t spreadFunction(SqlFunctionCtx* pCtx) {
G
Ganlin Zhao 已提交
3624 3625 3626 3627
  int32_t numOfElems = 0;

  // Only the pre-computing information loaded and actual data does not loaded
  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
3628 3629
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
  int32_t               type = pInput->pData[0]->info.type;
G
Ganlin Zhao 已提交
3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660

  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

  if (pInput->colDataAggIsSet) {
    numOfElems = pInput->numOfRows - pAgg->numOfNull;
    if (numOfElems == 0) {
      goto _spread_over;
    }
    double tmin = 0.0, tmax = 0.0;
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
      tmin = (double)GET_INT64_VAL(&pAgg->min);
      tmax = (double)GET_INT64_VAL(&pAgg->max);
    } else if (IS_FLOAT_TYPE(type)) {
      tmin = GET_DOUBLE_VAL(&pAgg->min);
      tmax = GET_DOUBLE_VAL(&pAgg->max);
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
      tmin = (double)GET_UINT64_VAL(&pAgg->min);
      tmax = (double)GET_UINT64_VAL(&pAgg->max);
    }

    if (GET_DOUBLE_VAL(&pInfo->min) > tmin) {
      SET_DOUBLE_VAL(&pInfo->min, tmin);
    }

    if (GET_DOUBLE_VAL(&pInfo->max) < tmax) {
      SET_DOUBLE_VAL(&pInfo->max, tmax);
    }

  } else {  // computing based on the true data block
    SColumnInfoData* pCol = pInput->pData[0];

X
Xiaoyu Wang 已提交
3661
    int32_t start = pInput->startRowIndex;
G
Ganlin Zhao 已提交
3662 3663 3664 3665 3666 3667 3668 3669
    int32_t numOfRows = pInput->numOfRows;

    // check the valid data one by one
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
        continue;
      }

X
Xiaoyu Wang 已提交
3670
      char* data = colDataGetData(pCol, i);
G
Ganlin Zhao 已提交
3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695

      double v = 0;
      GET_TYPED_DATA(v, double, type, data);
      if (v < GET_DOUBLE_VAL(&pInfo->min)) {
        SET_DOUBLE_VAL(&pInfo->min, v);
      }

      if (v > GET_DOUBLE_VAL(&pInfo->max)) {
        SET_DOUBLE_VAL(&pInfo->max, v);
      }

      numOfElems += 1;
    }
  }

_spread_over:
  // data in the check operation are all null, not output
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
  if (numOfElems > 0) {
    pInfo->hasResult = true;
  }

  return TSDB_CODE_SUCCESS;
}

3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706
static void spreadTransferInfo(SSpreadInfo* pInput, SSpreadInfo* pOutput) {
  pOutput->hasResult = pInput->hasResult;
  if (pInput->max > pOutput->max) {
    pOutput->max = pInput->max;
  }

  if (pInput->min < pOutput->min) {
    pOutput->min = pInput->min;
  }
}

X
Xiaoyu Wang 已提交
3707
int32_t spreadFunctionMerge(SqlFunctionCtx* pCtx) {
3708
  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
3709
  SColumnInfoData*      pCol = pInput->pData[0];
3710 3711 3712 3713
  ASSERT(pCol->info.type == TSDB_DATA_TYPE_BINARY);

  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

3714
  int32_t start = pInput->startRowIndex;
3715

3716 3717 3718 3719 3720
  for(int32_t i = start; i < start + pInput->numOfRows; ++i) {
    char* data = colDataGetData(pCol, i);
    SSpreadInfo* pInputInfo = (SSpreadInfo*)varDataVal(data);
    spreadTransferInfo(pInputInfo, pInfo);
  }
3721 3722 3723 3724 3725 3726

  SET_VAL(GET_RES_INFO(pCtx), 1, 1);

  return TSDB_CODE_SUCCESS;
}

G
Ganlin Zhao 已提交
3727 3728 3729 3730 3731 3732 3733
int32_t spreadFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  if (pInfo->hasResult == true) {
    SET_DOUBLE_VAL(&pInfo->result, pInfo->max - pInfo->min);
  }
  return functionFinalize(pCtx, pBlock);
}
3734

3735 3736
int32_t spreadPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
3737 3738 3739
  SSpreadInfo*         pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  int32_t              resultBytes = getSpreadInfoSize();
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752

  memcpy(varDataVal(res), pInfo, resultBytes);
  varDataSetLen(res, resultBytes);

  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  colDataAppend(pCol, pBlock->info.rows, res, false);

  taosMemoryFree(res);
  return pResInfo->numOfRes;
}

3753 3754
int32_t spreadCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
X
Xiaoyu Wang 已提交
3755
  SSpreadInfo*         pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
3756 3757

  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
X
Xiaoyu Wang 已提交
3758
  SSpreadInfo*         pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
3759
  spreadTransferInfo(pSBuf, pDBuf);
3760 3761 3762 3763
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
3764
int32_t getElapsedInfoSize() { return (int32_t)sizeof(SElapsedInfo); }
3765

G
Ganlin Zhao 已提交
3766 3767 3768 3769 3770
bool getElapsedFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SElapsedInfo);
  return true;
}

X
Xiaoyu Wang 已提交
3771
bool elapsedFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
G
Ganlin Zhao 已提交
3772 3773 3774 3775 3776 3777 3778 3779 3780
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
  pInfo->result = 0;
  pInfo->min = MAX_TS_KEY;
  pInfo->max = 0;

3781
  if (pCtx->numOfParams > 1) {
G
Ganlin Zhao 已提交
3782 3783 3784 3785 3786 3787 3788 3789
    pInfo->timeUnit = pCtx->param[1].param.i;
  } else {
    pInfo->timeUnit = 1;
  }

  return true;
}

X
Xiaoyu Wang 已提交
3790
int32_t elapsedFunction(SqlFunctionCtx* pCtx) {
G
Ganlin Zhao 已提交
3791 3792 3793 3794
  int32_t numOfElems = 0;

  // Only the pre-computing information loaded and actual data does not loaded
  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
3795
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
G
Ganlin Zhao 已提交
3796 3797 3798

  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

X
Xiaoyu Wang 已提交
3799
  numOfElems = pInput->numOfRows;  // since this is the primary timestamp, no need to exclude NULL values
G
Ganlin Zhao 已提交
3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815
  if (numOfElems == 0) {
    goto _elapsed_over;
  }

  if (pInput->colDataAggIsSet) {
    if (pInfo->min == MAX_TS_KEY) {
      pInfo->min = GET_INT64_VAL(&pAgg->min);
      pInfo->max = GET_INT64_VAL(&pAgg->max);
    } else {
      if (pCtx->order == TSDB_ORDER_ASC) {
        pInfo->max = GET_INT64_VAL(&pAgg->max);
      } else {
        pInfo->min = GET_INT64_VAL(&pAgg->min);
      }
    }
  } else {  // computing based on the true data block
H
Haojun Liao 已提交
3816
    if (0 == pInput->numOfRows) {
G
Ganlin Zhao 已提交
3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830
      if (pCtx->order == TSDB_ORDER_DESC) {
        if (pCtx->end.key != INT64_MIN) {
          pInfo->min = pCtx->end.key;
        }
      } else {
        if (pCtx->end.key != INT64_MIN) {
          pInfo->max = pCtx->end.key + 1;
        }
      }
      goto _elapsed_over;
    }

    SColumnInfoData* pCol = pInput->pData[0];

3831 3832
    int32_t start = pInput->startRowIndex;
    TSKEY*  ptsList = (int64_t*)colDataGetData(pCol, 0);
G
Ganlin Zhao 已提交
3833 3834
    if (pCtx->order == TSDB_ORDER_DESC) {
      if (pCtx->start.key == INT64_MIN) {
X
Xiaoyu Wang 已提交
3835 3836
        pInfo->max =
            (pInfo->max < ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->max;
G
Ganlin Zhao 已提交
3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855
      } else {
        pInfo->max = pCtx->start.key + 1;
      }

      if (pCtx->end.key != INT64_MIN) {
        pInfo->min = pCtx->end.key;
      } else {
        pInfo->min = ptsList[0];
      }
    } else {
      if (pCtx->start.key == INT64_MIN) {
        pInfo->min = (pInfo->min > ptsList[0]) ? ptsList[0] : pInfo->min;
      } else {
        pInfo->min = pCtx->start.key;
      }

      if (pCtx->end.key != INT64_MIN) {
        pInfo->max = pCtx->end.key + 1;
      } else {
H
Haojun Liao 已提交
3856
        pInfo->max = ptsList[start + pInput->numOfRows - 1];
G
Ganlin Zhao 已提交
3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867
      }
    }
  }

_elapsed_over:
  // data in the check operation are all null, not output
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);

  return TSDB_CODE_SUCCESS;
}

3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878
static void elapsedTransferInfo(SElapsedInfo* pInput, SElapsedInfo* pOutput) {
  pOutput->timeUnit = pInput->timeUnit;
  if (pOutput->min > pInput->min) {
    pOutput->min = pInput->min;
  }

  if (pOutput->max < pInput->max) {
    pOutput->max = pInput->max;
  }
}

X
Xiaoyu Wang 已提交
3879
int32_t elapsedFunctionMerge(SqlFunctionCtx* pCtx) {
3880
  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
3881
  SColumnInfoData*      pCol = pInput->pData[0];
3882 3883 3884 3885
  ASSERT(pCol->info.type == TSDB_DATA_TYPE_BINARY);

  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

3886
  int32_t start = pInput->startRowIndex;
3887

3888 3889 3890 3891 3892
  for(int32_t i = start; i < start + pInput->numOfRows; ++i) {
    char* data = colDataGetData(pCol, i);
    SElapsedInfo* pInputInfo = (SElapsedInfo*)varDataVal(data);
    elapsedTransferInfo(pInputInfo, pInfo);
  }
3893 3894 3895 3896 3897

  SET_VAL(GET_RES_INFO(pCtx), 1, 1);
  return TSDB_CODE_SUCCESS;
}

G
Ganlin Zhao 已提交
3898 3899
int32_t elapsedFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
X
Xiaoyu Wang 已提交
3900
  double        result = (double)pInfo->max - (double)pInfo->min;
G
Ganlin Zhao 已提交
3901 3902 3903 3904 3905
  result = (result >= 0) ? result : -result;
  pInfo->result = result / pInfo->timeUnit;
  return functionFinalize(pCtx, pBlock);
}

3906 3907
int32_t elapsedPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
X
Xiaoyu Wang 已提交
3908 3909 3910
  SElapsedInfo*        pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  int32_t              resultBytes = getElapsedInfoSize();
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923

  memcpy(varDataVal(res), pInfo, resultBytes);
  varDataSetLen(res, resultBytes);

  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  colDataAppend(pCol, pBlock->info.rows, res, false);

  taosMemoryFree(res);
  return pResInfo->numOfRes;
}

3924 3925
int32_t elapsedCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
X
Xiaoyu Wang 已提交
3926
  SElapsedInfo*        pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
3927 3928

  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
X
Xiaoyu Wang 已提交
3929
  SElapsedInfo*        pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
3930

3931
  elapsedTransferInfo(pSBuf, pDBuf);
3932 3933 3934 3935
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
  return TSDB_CODE_SUCCESS;
}

3936 3937 3938 3939
int32_t getHistogramInfoSize() {
  return (int32_t)sizeof(SHistoFuncInfo) + HISTOGRAM_MAX_BINS_NUM * sizeof(SHistoFuncBin);
}

3940 3941 3942 3943 3944
bool getHistogramFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SHistoFuncInfo) + HISTOGRAM_MAX_BINS_NUM * sizeof(SHistoFuncBin);
  return true;
}

X
Xiaoyu Wang 已提交
3945
static int8_t getHistogramBinType(char* binTypeStr) {
3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959
  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;
}

X
Xiaoyu Wang 已提交
3960
static bool getHistogramBinDesc(SHistoFuncInfo* pInfo, char* binDescStr, int8_t binType, bool normalized) {
3961 3962 3963 3964 3965 3966 3967 3968 3969 3970
  cJSON*  binDesc = cJSON_Parse(binDescStr);
  int32_t numOfBins;
  double* intervals;
  if (cJSON_IsObject(binDesc)) { /* linaer/log bins */
    int32_t numOfParams = cJSON_GetArraySize(binDesc);
    int32_t startIndex;
    if (numOfParams != 4) {
      return false;
    }

X
Xiaoyu Wang 已提交
3971 3972 3973 3974
    cJSON* start = cJSON_GetObjectItem(binDesc, "start");
    cJSON* factor = cJSON_GetObjectItem(binDesc, "factor");
    cJSON* width = cJSON_GetObjectItem(binDesc, "width");
    cJSON* count = cJSON_GetObjectItem(binDesc, "count");
3975 3976 3977 3978 3979 3980
    cJSON* infinity = cJSON_GetObjectItem(binDesc, "infinity");

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

X
Xiaoyu Wang 已提交
3981
    if (count->valueint <= 0 || count->valueint > 1000) {  // limit count to 1000
3982 3983 3984 3985 3986 3987 3988 3989
      return false;
    }

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

3990
    int32_t counter = (int32_t)count->valueint;
3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049
    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;
    }
4050
    numOfBins = cJSON_GetArraySize(binDesc);
4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074
    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
    cJSON* bin = binDesc->child;
    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;
  }

X
Xiaoyu Wang 已提交
4075
  pInfo->numOfBins = numOfBins - 1;
4076
  pInfo->normalized = normalized;
4077
  for (int32_t i = 0; i < pInfo->numOfBins; ++i) {
4078 4079 4080 4081 4082 4083 4084 4085 4086
    pInfo->bins[i].lower = intervals[i] < intervals[i + 1] ? intervals[i] : intervals[i + 1];
    pInfo->bins[i].upper = intervals[i + 1] > intervals[i] ? intervals[i + 1] : intervals[i];
    pInfo->bins[i].count = 0;
  }

  taosMemoryFree(intervals);
  return true;
}

X
Xiaoyu Wang 已提交
4087
bool histogramFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
4088 4089 4090 4091
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

X
Xiaoyu Wang 已提交
4092
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
4093 4094 4095
  pInfo->numOfBins = 0;
  pInfo->totalCount = 0;
  pInfo->normalized = 0;
4096

4097 4098 4099 4100
  int8_t binType = getHistogramBinType(varDataVal(pCtx->param[1].param.pz));
  if (binType == UNKNOWN_BIN) {
    return false;
  }
X
Xiaoyu Wang 已提交
4101
  char*   binDesc = varDataVal(pCtx->param[2].param.pz);
4102
  int64_t normalized = pCtx->param[3].param.i;
4103 4104 4105
  if (normalized != 0 && normalized != 1) {
    return false;
  }
4106 4107 4108
  if (!getHistogramBinDesc(pInfo, binDesc, binType, (bool)normalized)) {
    return false;
  }
4109 4110 4111 4112

  return true;
}

4113
static int32_t histogramFunctionImpl(SqlFunctionCtx* pCtx, bool isPartial) {
4114 4115 4116 4117 4118 4119 4120 4121 4122 4123
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

  SInputColumnInfoData* pInput = &pCtx->input;
  SColumnInfoData*      pCol = pInput->pData[0];

  int32_t type = pInput->pData[0]->info.type;

  int32_t start = pInput->startRowIndex;
  int32_t numOfRows = pInput->numOfRows;

4124
  int32_t numOfElems = 0;
4125 4126 4127 4128 4129
  for (int32_t i = start; i < numOfRows + start; ++i) {
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
      continue;
    }

4130 4131
    numOfElems++;

X
Xiaoyu Wang 已提交
4132
    char*  data = colDataGetData(pCol, i);
4133 4134 4135 4136 4137 4138
    double v;
    GET_TYPED_DATA(v, double, type, data);

    for (int32_t k = 0; k < pInfo->numOfBins; ++k) {
      if (v > pInfo->bins[k].lower && v <= pInfo->bins[k].upper) {
        pInfo->bins[k].count++;
4139
        pInfo->totalCount++;
4140 4141 4142
        break;
      }
    }
4143 4144
  }

4145 4146 4147 4148 4149
  if (!isPartial) {
    SET_VAL(GET_RES_INFO(pCtx), numOfElems, pInfo->numOfBins);
  } else {
    SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
  }
4150 4151 4152
  return TSDB_CODE_SUCCESS;
}

4153 4154 4155 4156 4157 4158 4159 4160
int32_t histogramFunction(SqlFunctionCtx* pCtx) {
  return histogramFunctionImpl(pCtx, false);
}

int32_t histogramFunctionPartial(SqlFunctionCtx* pCtx) {
  return histogramFunctionImpl(pCtx, true);
}

4161 4162
static void histogramTransferInfo(SHistoFuncInfo* pInput, SHistoFuncInfo* pOutput) {
  pOutput->normalized = pInput->normalized;
X
Xiaoyu Wang 已提交
4163
  pOutput->numOfBins = pInput->numOfBins;
4164 4165 4166 4167 4168 4169 4170 4171
  pOutput->totalCount += pInput->totalCount;
  for (int32_t k = 0; k < pOutput->numOfBins; ++k) {
    pOutput->bins[k].lower = pInput->bins[k].lower;
    pOutput->bins[k].upper = pInput->bins[k].upper;
    pOutput->bins[k].count += pInput->bins[k].count;
  }
}

X
Xiaoyu Wang 已提交
4172
int32_t histogramFunctionMerge(SqlFunctionCtx* pCtx) {
4173
  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
4174
  SColumnInfoData*      pCol = pInput->pData[0];
4175 4176 4177 4178
  ASSERT(pCol->info.type == TSDB_DATA_TYPE_BINARY);

  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

4179
  int32_t start = pInput->startRowIndex;
4180

4181
  for(int32_t i = start; i < start + pInput->numOfRows; ++i) {
4182
    char* data = colDataGetData(pCol, i);
4183 4184 4185
    SHistoFuncInfo* pInputInfo = (SHistoFuncInfo*)varDataVal(data);
    histogramTransferInfo(pInputInfo, pInfo);
  }
4186

G
Ganlin Zhao 已提交
4187
  SET_VAL(GET_RES_INFO(pCtx), pInfo->numOfBins, pInfo->numOfBins);
4188 4189 4190
  return TSDB_CODE_SUCCESS;
}

4191
int32_t histogramFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
4192
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
X
Xiaoyu Wang 已提交
4193 4194 4195
  SHistoFuncInfo*      pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
4196 4197 4198

  int32_t currentRow = pBlock->info.rows;

4199 4200
  if (pInfo->normalized) {
    for (int32_t k = 0; k < pResInfo->numOfRes; ++k) {
X
Xiaoyu Wang 已提交
4201
      if (pInfo->totalCount != 0) {
4202 4203 4204 4205 4206 4207 4208
        pInfo->bins[k].percentage = pInfo->bins[k].count / (double)pInfo->totalCount;
      } else {
        pInfo->bins[k].percentage = 0;
      }
    }
  }

4209
  for (int32_t i = 0; i < pResInfo->numOfRes; ++i) {
4210
    int32_t len;
X
Xiaoyu Wang 已提交
4211
    char    buf[512] = {0};
4212
    if (!pInfo->normalized) {
X
Xiaoyu Wang 已提交
4213 4214
      len = sprintf(varDataVal(buf), "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%" PRId64 "}",
                    pInfo->bins[i].lower, pInfo->bins[i].upper, pInfo->bins[i].count);
4215
    } else {
X
Xiaoyu Wang 已提交
4216 4217
      len = sprintf(varDataVal(buf), "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%lf}", pInfo->bins[i].lower,
                    pInfo->bins[i].upper, pInfo->bins[i].percentage);
4218 4219 4220 4221 4222 4223
    }
    varDataSetLen(buf, len);
    colDataAppend(pCol, currentRow, buf, false);
    currentRow++;
  }

4224
  return pResInfo->numOfRes;
4225
}
4226

4227
int32_t histogramPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
4228
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
4229
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
X
Xiaoyu Wang 已提交
4230 4231
  int32_t         resultBytes = getHistogramInfoSize();
  char*           res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
4232 4233 4234 4235 4236 4237 4238 4239 4240 4241

  memcpy(varDataVal(res), pInfo, resultBytes);
  varDataSetLen(res, resultBytes);

  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  colDataAppend(pCol, pBlock->info.rows, res, false);

  taosMemoryFree(res);
4242
  return pResInfo->numOfRes;
4243 4244
}

4245 4246 4247 4248 4249 4250 4251
int32_t histogramCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
  SHistoFuncInfo*      pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);

  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
  SHistoFuncInfo*      pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);

4252
  histogramTransferInfo(pSBuf, pDBuf);
4253 4254 4255 4256
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
4257
int32_t getHLLInfoSize() { return (int32_t)sizeof(SHLLInfo); }
4258

4259 4260 4261 4262 4263
bool getHLLFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SHLLInfo);
  return true;
}

X
Xiaoyu Wang 已提交
4264
static uint8_t hllCountNum(void* data, int32_t bytes, int32_t* buk) {
4265
  uint64_t hash = MurmurHash3_64(data, bytes);
X
Xiaoyu Wang 已提交
4266
  int32_t  index = hash & HLL_BUCKET_MASK;
4267 4268 4269
  hash >>= HLL_BUCKET_BITS;
  hash |= ((uint64_t)1 << HLL_DATA_BITS);
  uint64_t bit = 1;
X
Xiaoyu Wang 已提交
4270 4271
  uint8_t  count = 1;
  while ((hash & bit) == 0) {
4272 4273 4274 4275 4276 4277 4278
    count++;
    bit <<= 1;
  }
  *buk = index;
  return count;
}

X
Xiaoyu Wang 已提交
4279 4280 4281
static void hllBucketHisto(uint8_t* buckets, int32_t* bucketHisto) {
  uint64_t* word = (uint64_t*)buckets;
  uint8_t*  bytes;
4282

X
Xiaoyu Wang 已提交
4283
  for (int32_t j = 0; j < HLL_BUCKETS >> 3; j++) {
4284 4285 4286
    if (*word == 0) {
      bucketHisto[0] += 8;
    } else {
X
Xiaoyu Wang 已提交
4287
      bytes = (uint8_t*)word;
4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308
      bucketHisto[bytes[0]]++;
      bucketHisto[bytes[1]]++;
      bucketHisto[bytes[2]]++;
      bucketHisto[bytes[3]]++;
      bucketHisto[bytes[4]]++;
      bucketHisto[bytes[5]]++;
      bucketHisto[bytes[6]]++;
      bucketHisto[bytes[7]]++;
    }
    word++;
  }
}
static double hllTau(double x) {
  if (x == 0. || x == 1.) return 0.;
  double zPrime;
  double y = 1.0;
  double z = 1 - x;
  do {
    x = sqrt(x);
    zPrime = z;
    y *= 0.5;
X
Xiaoyu Wang 已提交
4309 4310
    z -= pow(1 - x, 2) * y;
  } while (zPrime != z);
4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323
  return z / 3;
}

static double hllSigma(double x) {
  if (x == 1.0) return INFINITY;
  double zPrime;
  double y = 1;
  double z = x;
  do {
    x *= x;
    zPrime = z;
    z += x * y;
    y += y;
X
Xiaoyu Wang 已提交
4324
  } while (zPrime != z);
4325 4326 4327
  return z;
}

X
Xiaoyu Wang 已提交
4328 4329 4330 4331
// estimate the cardinality, the algorithm refer this paper: "New cardinality estimation algorithms for HyperLogLog
// sketches"
static uint64_t hllCountCnt(uint8_t* buckets) {
  double  m = HLL_BUCKETS;
4332
  int32_t buckethisto[64] = {0};
X
Xiaoyu Wang 已提交
4333
  hllBucketHisto(buckets, buckethisto);
4334

X
Xiaoyu Wang 已提交
4335
  double z = m * hllTau((m - buckethisto[HLL_DATA_BITS + 1]) / (double)m);
4336 4337 4338 4339
  for (int j = HLL_DATA_BITS; j >= 1; --j) {
    z += buckethisto[j];
    z *= 0.5;
  }
4340

X
Xiaoyu Wang 已提交
4341 4342
  z += m * hllSigma(buckethisto[0] / (double)m);
  double E = (double)llroundl(HLL_ALPHA_INF * m * m / z);
4343

X
Xiaoyu Wang 已提交
4344
  return (uint64_t)E;
4345 4346
}

X
Xiaoyu Wang 已提交
4347
int32_t hllFunction(SqlFunctionCtx* pCtx) {
4348 4349 4350 4351 4352
  SHLLInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

  SInputColumnInfoData* pInput = &pCtx->input;
  SColumnInfoData*      pCol = pInput->pData[0];

X
Xiaoyu Wang 已提交
4353
  int32_t type = pCol->info.type;
4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368
  int32_t bytes = pCol->info.bytes;

  int32_t start = pInput->startRowIndex;
  int32_t numOfRows = pInput->numOfRows;

  int32_t numOfElems = 0;
  for (int32_t i = start; i < numOfRows + start; ++i) {
    if (pCol->hasNull && colDataIsNull_s(pCol, i)) {
      continue;
    }

    numOfElems++;

    char* data = colDataGetData(pCol, i);
    if (IS_VAR_DATA_TYPE(type)) {
G
Ganlin Zhao 已提交
4369
      bytes = varDataLen(data);
4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384
      data = varDataVal(data);
    }

    int32_t index = 0;
    uint8_t count = hllCountNum(data, bytes, &index);
    uint8_t oldcount = pInfo->buckets[index];
    if (count > oldcount) {
      pInfo->buckets[index] = count;
    }
  }

  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
  return TSDB_CODE_SUCCESS;
}

4385 4386 4387 4388 4389 4390 4391 4392
static void hllTransferInfo(SHLLInfo* pInput, SHLLInfo* pOutput) {
  for (int32_t k = 0; k < HLL_BUCKETS; ++k) {
    if (pOutput->buckets[k] < pInput->buckets[k]) {
      pOutput->buckets[k] = pInput->buckets[k];
    }
  }
}

X
Xiaoyu Wang 已提交
4393
int32_t hllFunctionMerge(SqlFunctionCtx* pCtx) {
G
Ganlin Zhao 已提交
4394
  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
4395
  SColumnInfoData*      pCol = pInput->pData[0];
G
Ganlin Zhao 已提交
4396 4397 4398 4399
  ASSERT(pCol->info.type == TSDB_DATA_TYPE_BINARY);

  SHLLInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));

4400
  int32_t start = pInput->startRowIndex;
G
Ganlin Zhao 已提交
4401

4402 4403 4404 4405 4406
  for(int32_t i = start; i < start + pInput->numOfRows; ++i) {
    char* data = colDataGetData(pCol, i);
    SHLLInfo* pInputInfo = (SHLLInfo*)varDataVal(data);
    hllTransferInfo(pInputInfo, pInfo);
  }
G
Ganlin Zhao 已提交
4407 4408 4409 4410 4411

  SET_VAL(GET_RES_INFO(pCtx), 1, 1);
  return TSDB_CODE_SUCCESS;
}

4412
int32_t hllFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
X
Xiaoyu Wang 已提交
4413
  SResultRowEntryInfo* pInfo = GET_RES_INFO(pCtx);
4414

4415 4416 4417 4418 4419
  SHLLInfo* pHllInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  pHllInfo->result = hllCountCnt(pHllInfo->buckets);
  if (tsCountAlwaysReturnValue && pHllInfo->result == 0) {
    pInfo->numOfRes = 1;
  }
4420 4421 4422 4423

  return functionFinalize(pCtx, pBlock);
}

G
Ganlin Zhao 已提交
4424 4425
int32_t hllPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
X
Xiaoyu Wang 已提交
4426 4427 4428
  SHLLInfo*            pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  int32_t              resultBytes = getHLLInfoSize();
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
G
Ganlin Zhao 已提交
4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441

  memcpy(varDataVal(res), pInfo, resultBytes);
  varDataSetLen(res, resultBytes);

  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  colDataAppend(pCol, pBlock->info.rows, res, false);

  taosMemoryFree(res);
  return pResInfo->numOfRes;
}

4442 4443
int32_t hllCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
X
Xiaoyu Wang 已提交
4444
  SHLLInfo*            pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
4445 4446

  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
X
Xiaoyu Wang 已提交
4447
  SHLLInfo*            pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
4448

4449
  hllTransferInfo(pSBuf, pDBuf);
4450 4451 4452 4453
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
  return TSDB_CODE_SUCCESS;
}

4454 4455 4456 4457 4458
bool getStateFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SStateInfo);
  return true;
}

X
Xiaoyu Wang 已提交
4459
static int8_t getStateOpType(char* opStr) {
4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479
  int8_t opType;
  if (strcasecmp(opStr, "LT") == 0) {
    opType = STATE_OPER_LT;
  } else if (strcasecmp(opStr, "GT") == 0) {
    opType = STATE_OPER_GT;
  } else if (strcasecmp(opStr, "LE") == 0) {
    opType = STATE_OPER_LE;
  } else if (strcasecmp(opStr, "GE") == 0) {
    opType = STATE_OPER_GE;
  } else if (strcasecmp(opStr, "NE") == 0) {
    opType = STATE_OPER_NE;
  } else if (strcasecmp(opStr, "EQ") == 0) {
    opType = STATE_OPER_EQ;
  } else {
    opType = STATE_OPER_INVALID;
  }

  return opType;
}

X
Xiaoyu Wang 已提交
4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507
#define GET_STATE_VAL(param) ((param.nType == TSDB_DATA_TYPE_BIGINT) ? (param.i) : (param.d))

#define STATE_COMP(_op, _lval, _param) STATE_COMP_IMPL(_op, _lval, GET_STATE_VAL(_param))

#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;                             \
    }                                      \
G
Ganlin Zhao 已提交
4508
  } while (0)
4509 4510 4511

static bool checkStateOp(int8_t op, SColumnInfoData* pCol, int32_t index, SVariant param) {
  char* data = colDataGetData(pCol, index);
X
Xiaoyu Wang 已提交
4512
  switch (pCol->info.type) {
4513
    case TSDB_DATA_TYPE_TINYINT: {
X
Xiaoyu Wang 已提交
4514
      int8_t v = *(int8_t*)data;
4515 4516 4517 4518
      STATE_COMP(op, v, param);
      break;
    }
    case TSDB_DATA_TYPE_UTINYINT: {
X
Xiaoyu Wang 已提交
4519
      uint8_t v = *(uint8_t*)data;
4520 4521 4522 4523
      STATE_COMP(op, v, param);
      break;
    }
    case TSDB_DATA_TYPE_SMALLINT: {
X
Xiaoyu Wang 已提交
4524
      int16_t v = *(int16_t*)data;
4525 4526 4527 4528
      STATE_COMP(op, v, param);
      break;
    }
    case TSDB_DATA_TYPE_USMALLINT: {
X
Xiaoyu Wang 已提交
4529
      uint16_t v = *(uint16_t*)data;
4530 4531 4532 4533
      STATE_COMP(op, v, param);
      break;
    }
    case TSDB_DATA_TYPE_INT: {
X
Xiaoyu Wang 已提交
4534
      int32_t v = *(int32_t*)data;
4535 4536 4537 4538
      STATE_COMP(op, v, param);
      break;
    }
    case TSDB_DATA_TYPE_UINT: {
X
Xiaoyu Wang 已提交
4539
      uint32_t v = *(uint32_t*)data;
4540 4541 4542 4543
      STATE_COMP(op, v, param);
      break;
    }
    case TSDB_DATA_TYPE_BIGINT: {
X
Xiaoyu Wang 已提交
4544
      int64_t v = *(int64_t*)data;
4545 4546 4547 4548
      STATE_COMP(op, v, param);
      break;
    }
    case TSDB_DATA_TYPE_UBIGINT: {
X
Xiaoyu Wang 已提交
4549
      uint64_t v = *(uint64_t*)data;
4550 4551 4552 4553
      STATE_COMP(op, v, param);
      break;
    }
    case TSDB_DATA_TYPE_FLOAT: {
X
Xiaoyu Wang 已提交
4554
      float v = *(float*)data;
4555 4556 4557 4558
      STATE_COMP(op, v, param);
      break;
    }
    case TSDB_DATA_TYPE_DOUBLE: {
X
Xiaoyu Wang 已提交
4559
      double v = *(double*)data;
4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577
      STATE_COMP(op, v, param);
      break;
    }
    default: {
      ASSERT(0);
    }
  }
  return false;
}

int32_t stateCountFunction(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SStateInfo*          pInfo = GET_ROWCELL_INTERBUF(pResInfo);

  SInputColumnInfoData* pInput = &pCtx->input;

  SColumnInfoData* pInputCol = pInput->pData[0];

X
Xiaoyu Wang 已提交
4578
  int32_t          numOfElems = 0;
4579 4580 4581
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;

  int8_t op = getStateOpType(varDataVal(pCtx->param[1].param.pz));
4582 4583 4584 4585
  if (STATE_OPER_INVALID == op) {
    return 0;
  }

4586 4587 4588 4589 4590 4591 4592
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
    numOfElems++;
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
      colDataAppendNULL(pOutput, i);
      continue;
    }

X
Xiaoyu Wang 已提交
4593
    bool    ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
4594 4595 4596 4597 4598 4599
    int64_t output = -1;
    if (ret) {
      output = ++pInfo->count;
    } else {
      pInfo->count = 0;
    }
X
Xiaoyu Wang 已提交
4600
    colDataAppend(pOutput, i, (char*)&output, false);
4601 4602 4603 4604
  }

  return numOfElems;
}
4605 4606 4607 4608 4609 4610

int32_t stateDurationFunction(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SStateInfo*          pInfo = GET_ROWCELL_INTERBUF(pResInfo);

  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
4611
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
4612 4613 4614

  SColumnInfoData* pInputCol = pInput->pData[0];

X
Xiaoyu Wang 已提交
4615
  int32_t          numOfElems = 0;
4616 4617
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;

X
Xiaoyu Wang 已提交
4618
  // TODO: process timeUnit for different db precisions
4619
  int32_t timeUnit = 1;
X
Xiaoyu Wang 已提交
4620
  if (pCtx->numOfParams == 5) {  // TODO: param number incorrect
4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635
    timeUnit = pCtx->param[3].param.i;
  }

  int8_t op = getStateOpType(varDataVal(pCtx->param[1].param.pz));
  if (STATE_OPER_INVALID == op) {
    return 0;
  }

  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
    numOfElems++;
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
      colDataAppendNULL(pOutput, i);
      continue;
    }

X
Xiaoyu Wang 已提交
4636
    bool    ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647
    int64_t output = -1;
    if (ret) {
      if (pInfo->durationStart == 0) {
        output = 0;
        pInfo->durationStart = tsList[i];
      } else {
        output = (tsList[i] - pInfo->durationStart) / timeUnit;
      }
    } else {
      pInfo->durationStart = 0;
    }
X
Xiaoyu Wang 已提交
4648
    colDataAppend(pOutput, i, (char*)&output, false);
4649 4650 4651 4652
  }

  return numOfElems;
}
G
Ganlin Zhao 已提交
4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663

bool getCsumFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SSumRes);
  return true;
}

int32_t csumFunction(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SSumRes*             pSumRes = GET_ROWCELL_INTERBUF(pResInfo);

  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
4664
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
G
Ganlin Zhao 已提交
4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675

  SColumnInfoData* pInputCol = pInput->pData[0];
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;

  int32_t numOfElems = 0;
  int32_t type = pInputCol->info.type;
  int32_t startOffset = pCtx->offset;
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
    int32_t pos = startOffset + numOfElems;
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
X
Xiaoyu Wang 已提交
4676
      // colDataAppendNULL(pOutput, i);
G
Ganlin Zhao 已提交
4677 4678 4679 4680 4681 4682 4683 4684
      continue;
    }

    char* data = colDataGetData(pInputCol, i);
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
      int64_t v;
      GET_TYPED_DATA(v, int64_t, type, data);
      pSumRes->isum += v;
X
Xiaoyu Wang 已提交
4685
      colDataAppend(pOutput, pos, (char*)&pSumRes->isum, false);
G
Ganlin Zhao 已提交
4686 4687 4688 4689
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
      uint64_t v;
      GET_TYPED_DATA(v, uint64_t, type, data);
      pSumRes->usum += v;
X
Xiaoyu Wang 已提交
4690
      colDataAppend(pOutput, pos, (char*)&pSumRes->usum, false);
G
Ganlin Zhao 已提交
4691 4692 4693 4694
    } else if (IS_FLOAT_TYPE(type)) {
      double v;
      GET_TYPED_DATA(v, double, type, data);
      pSumRes->dsum += v;
X
Xiaoyu Wang 已提交
4695
      // check for overflow
4696 4697
      if (isinf(pSumRes->dsum) || isnan(pSumRes->dsum)) {
        colDataAppendNULL(pOutput, pos);
X
Xiaoyu Wang 已提交
4698 4699
      } else {
        colDataAppend(pOutput, pos, (char*)&pSumRes->dsum, false);
4700
      }
G
Ganlin Zhao 已提交
4701 4702
    }

X
Xiaoyu Wang 已提交
4703
    // TODO: remove this after pTsOutput is handled
G
Ganlin Zhao 已提交
4704 4705 4706 4707 4708 4709 4710 4711 4712
    if (pTsOutput != NULL) {
      colDataAppendInt64(pTsOutput, pos, &tsList[i]);
    }

    numOfElems++;
  }

  return numOfElems;
}
G
Ganlin Zhao 已提交
4713 4714 4715 4716 4717 4718

bool getMavgFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SMavgInfo) + MAVG_MAX_POINTS_NUM * sizeof(double);
  return true;
}

X
Xiaoyu Wang 已提交
4719
bool mavgFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
G
Ganlin Zhao 已提交
4720 4721 4722 4723
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

X
Xiaoyu Wang 已提交
4724
  SMavgInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
G
Ganlin Zhao 已提交
4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751
  pInfo->pos = 0;
  pInfo->sum = 0;
  pInfo->numOfPoints = pCtx->param[1].param.i;
  if (pInfo->numOfPoints < 1 || pInfo->numOfPoints > MAVG_MAX_POINTS_NUM) {
    return false;
  }
  pInfo->pointsMeet = false;

  return true;
}

int32_t mavgFunction(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SMavgInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);

  SInputColumnInfoData* pInput = &pCtx->input;

  SColumnInfoData* pInputCol = pInput->pData[0];
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;

  int32_t numOfElems = 0;
  int32_t type = pInputCol->info.type;
  int32_t startOffset = pCtx->offset;
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
    int32_t pos = startOffset + numOfElems;
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
X
Xiaoyu Wang 已提交
4752
      // colDataAppendNULL(pOutput, i);
G
Ganlin Zhao 已提交
4753 4754 4755
      continue;
    }

X
Xiaoyu Wang 已提交
4756
    char*  data = colDataGetData(pInputCol, i);
G
Ganlin Zhao 已提交
4757 4758 4759 4760 4761 4762 4763 4764
    double v;
    GET_TYPED_DATA(v, double, type, data);

    if (!pInfo->pointsMeet && (pInfo->pos < pInfo->numOfPoints - 1)) {
      pInfo->points[pInfo->pos] = v;
      pInfo->sum += v;
    } else {
      if (!pInfo->pointsMeet && (pInfo->pos == pInfo->numOfPoints - 1)) {
X
Xiaoyu Wang 已提交
4765
        pInfo->sum += v;
G
Ganlin Zhao 已提交
4766 4767 4768 4769 4770
        pInfo->pointsMeet = true;
      } else {
        pInfo->sum = pInfo->sum + v - pInfo->points[pInfo->pos];
      }

G
Ganlin Zhao 已提交
4771 4772
      pInfo->points[pInfo->pos] = v;
      double result = pInfo->sum / pInfo->numOfPoints;
X
Xiaoyu Wang 已提交
4773
      // check for overflow
4774 4775
      if (isinf(result) || isnan(result)) {
        colDataAppendNULL(pOutput, pos);
X
Xiaoyu Wang 已提交
4776 4777
      } else {
        colDataAppend(pOutput, pos, (char*)&result, false);
4778
      }
G
Ganlin Zhao 已提交
4779

G
Ganlin Zhao 已提交
4780
      numOfElems++;
G
Ganlin Zhao 已提交
4781 4782
    }

G
Ganlin Zhao 已提交
4783 4784 4785 4786
    pInfo->pos++;
    if (pInfo->pos == pInfo->numOfPoints) {
      pInfo->pos = 0;
    }
G
Ganlin Zhao 已提交
4787 4788 4789 4790
  }

  return numOfElems;
}
G
Ganlin Zhao 已提交
4791 4792 4793

bool getSampleFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  SColumnNode* pCol = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
X
Xiaoyu Wang 已提交
4794 4795
  SValueNode*  pVal = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
  int32_t      numOfSamples = pVal->datum.i;
4796
  pEnv->calcMemSize = sizeof(SSampleInfo) + numOfSamples * (pCol->node.resType.bytes + sizeof(STuplePos));
G
Ganlin Zhao 已提交
4797 4798 4799
  return true;
}

X
Xiaoyu Wang 已提交
4800
bool sampleFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
G
Ganlin Zhao 已提交
4801 4802 4803 4804 4805 4806
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  taosSeedRand(taosSafeRand());

X
Xiaoyu Wang 已提交
4807
  SSampleInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
G
Ganlin Zhao 已提交
4808 4809 4810
  pInfo->samples = pCtx->param[1].param.i;
  pInfo->totalPoints = 0;
  pInfo->numSampled = 0;
G
Ganlin Zhao 已提交
4811 4812
  pInfo->colType = pCtx->resDataInfo.type;
  pInfo->colBytes = pCtx->resDataInfo.bytes;
G
Ganlin Zhao 已提交
4813 4814 4815
  if (pInfo->samples < 1 || pInfo->samples > SAMPLE_MAX_POINTS_NUM) {
    return false;
  }
X
Xiaoyu Wang 已提交
4816
  pInfo->data = (char*)pInfo + sizeof(SSampleInfo);
4817
  pInfo->tuplePos = (STuplePos*)((char*)pInfo + sizeof(SSampleInfo) + pInfo->samples * pInfo->colBytes);
G
Ganlin Zhao 已提交
4818 4819 4820 4821

  return true;
}

4822
static void sampleAssignResult(SSampleInfo* pInfo, char* data, int32_t index) {
G
Ganlin Zhao 已提交
4823
  assignVal(pInfo->data + index * pInfo->colBytes, data, pInfo->colBytes, pInfo->colType);
G
Ganlin Zhao 已提交
4824 4825
}

4826
static void doReservoirSample(SqlFunctionCtx* pCtx, SSampleInfo* pInfo, char* data, int32_t index) {
G
Ganlin Zhao 已提交
4827 4828
  pInfo->totalPoints++;
  if (pInfo->numSampled < pInfo->samples) {
4829 4830 4831 4832
    sampleAssignResult(pInfo, data, pInfo->numSampled);
    if (pCtx->subsidiaries.num > 0) {
      saveTupleData(pCtx, index, pCtx->pSrcBlock, pInfo->tuplePos + pInfo->numSampled * sizeof(STuplePos));
    }
G
Ganlin Zhao 已提交
4833 4834 4835 4836
    pInfo->numSampled++;
  } else {
    int32_t j = taosRand() % (pInfo->totalPoints);
    if (j < pInfo->samples) {
4837 4838 4839 4840
      sampleAssignResult(pInfo, data, j);
      if (pCtx->subsidiaries.num > 0) {
        copyTupleData(pCtx, index, pCtx->pSrcBlock, pInfo->tuplePos + j * sizeof(STuplePos));
      }
G
Ganlin Zhao 已提交
4841 4842 4843 4844 4845 4846 4847 4848 4849 4850
    }
  }
}

int32_t sampleFunction(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SSampleInfo*         pInfo = GET_ROWCELL_INTERBUF(pResInfo);

  SInputColumnInfoData* pInput = &pCtx->input;

4851
  SColumnInfoData* pInputCol = pInput->pData[0];
G
Ganlin Zhao 已提交
4852
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
4853
    if (colDataIsNull_s(pInputCol, i)) {
G
Ganlin Zhao 已提交
4854 4855 4856 4857
      continue;
    }

    char* data = colDataGetData(pInputCol, i);
4858
    doReservoirSample(pCtx, pInfo, data, i);
G
Ganlin Zhao 已提交
4859 4860
  }

4861 4862 4863 4864 4865 4866 4867 4868 4869 4870
  SET_VAL(pResInfo, pInfo->numSampled, pInfo->numSampled);
  return TSDB_CODE_SUCCESS;
}

int32_t sampleFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);

  SSampleInfo* pInfo = GET_ROWCELL_INTERBUF(pEntryInfo);
  pEntryInfo->complete = true;

X
Xiaoyu Wang 已提交
4871
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
4872 4873 4874
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  int32_t currentRow = pBlock->info.rows;
G
Ganlin Zhao 已提交
4875
  for (int32_t i = 0; i < pInfo->numSampled; ++i) {
4876
    colDataAppend(pCol, currentRow + i, pInfo->data + i * pInfo->colBytes, false);
4877
    setSelectivityValue(pCtx, pBlock, pInfo->tuplePos + i * sizeof(STuplePos), currentRow + i);
G
Ganlin Zhao 已提交
4878 4879
  }

G
Ganlin Zhao 已提交
4880 4881 4882
  return pInfo->numSampled;
}

G
Ganlin Zhao 已提交
4883 4884 4885
bool getTailFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  SColumnNode* pCol = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
  SValueNode*  pVal = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
X
Xiaoyu Wang 已提交
4886
  int32_t      numOfPoints = pVal->datum.i;
G
Ganlin Zhao 已提交
4887
  pEnv->calcMemSize = sizeof(STailInfo) + numOfPoints * (POINTER_BYTES + sizeof(STailItem) + pCol->node.resType.bytes);
G
Ganlin Zhao 已提交
4888 4889 4890
  return true;
}

X
Xiaoyu Wang 已提交
4891
bool tailFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
G
Ganlin Zhao 已提交
4892 4893 4894 4895
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

X
Xiaoyu Wang 已提交
4896
  STailInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
G
Ganlin Zhao 已提交
4897 4898
  pInfo->numAdded = 0;
  pInfo->numOfPoints = pCtx->param[1].param.i;
4899 4900 4901 4902 4903
  if (pCtx->numOfParams == 4) {
    pInfo->offset = pCtx->param[2].param.i;
  } else {
    pInfo->offset = 0;
  }
G
Ganlin Zhao 已提交
4904 4905 4906 4907 4908 4909 4910
  pInfo->colType = pCtx->resDataInfo.type;
  pInfo->colBytes = pCtx->resDataInfo.bytes;
  if ((pInfo->numOfPoints < 1 || pInfo->numOfPoints > TAIL_MAX_POINTS_NUM) ||
      (pInfo->numOfPoints < 0 || pInfo->numOfPoints > TAIL_MAX_OFFSET)) {
    return false;
  }

X
Xiaoyu Wang 已提交
4911 4912
  pInfo->pItems = (STailItem**)((char*)pInfo + sizeof(STailInfo));
  char* pItem = (char*)pInfo->pItems + pInfo->numOfPoints * POINTER_BYTES;
G
Ganlin Zhao 已提交
4913

G
Ganlin Zhao 已提交
4914
  size_t unitSize = sizeof(STailItem) + pInfo->colBytes;
G
Ganlin Zhao 已提交
4915
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
X
Xiaoyu Wang 已提交
4916
    pInfo->pItems[i] = (STailItem*)(pItem + i * unitSize);
4917
    pInfo->pItems[i]->isNull = false;
G
Ganlin Zhao 已提交
4918 4919 4920 4921 4922
  }

  return true;
}

X
Xiaoyu Wang 已提交
4923
static void tailAssignResult(STailItem* pItem, char* data, int32_t colBytes, TSKEY ts, bool isNull) {
G
Ganlin Zhao 已提交
4924
  pItem->timestamp = ts;
4925 4926 4927
  if (isNull) {
    pItem->isNull = true;
  } else {
4928
    pItem->isNull = false;
4929 4930
    memcpy(pItem->data, data, colBytes);
  }
G
Ganlin Zhao 已提交
4931 4932
}

X
Xiaoyu Wang 已提交
4933 4934 4935
static int32_t tailCompFn(const void* p1, const void* p2, const void* param) {
  STailItem* d1 = *(STailItem**)p1;
  STailItem* d2 = *(STailItem**)p2;
G
Ganlin Zhao 已提交
4936 4937 4938
  return compareInt64Val(&d1->timestamp, &d2->timestamp);
}

X
Xiaoyu Wang 已提交
4939 4940
static void doTailAdd(STailInfo* pInfo, char* data, TSKEY ts, bool isNull) {
  STailItem** pList = pInfo->pItems;
G
Ganlin Zhao 已提交
4941
  if (pInfo->numAdded < pInfo->numOfPoints) {
4942
    tailAssignResult(pList[pInfo->numAdded], data, pInfo->colBytes, ts, isNull);
X
Xiaoyu Wang 已提交
4943
    taosheapsort((void*)pList, sizeof(STailItem**), pInfo->numAdded + 1, NULL, tailCompFn, 0);
G
Ganlin Zhao 已提交
4944
    pInfo->numAdded++;
G
Ganlin Zhao 已提交
4945
  } else if (pList[0]->timestamp < ts) {
4946
    tailAssignResult(pList[0], data, pInfo->colBytes, ts, isNull);
X
Xiaoyu Wang 已提交
4947
    taosheapadjust((void*)pList, sizeof(STailItem**), 0, pInfo->numOfPoints - 1, NULL, tailCompFn, NULL, 0);
G
Ganlin Zhao 已提交
4948 4949 4950 4951 4952
  }
}

int32_t tailFunction(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
X
Xiaoyu Wang 已提交
4953
  STailInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
G
Ganlin Zhao 已提交
4954 4955

  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
4956
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
G
Ganlin Zhao 已提交
4957 4958 4959 4960 4961

  SColumnInfoData* pInputCol = pInput->pData[0];
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;

  int32_t startOffset = pCtx->offset;
4962 4963 4964
  if (pInfo->offset >= pInput->numOfRows) {
    return 0;
  } else {
wafwerar's avatar
wafwerar 已提交
4965
    pInfo->numOfPoints = TMIN(pInfo->numOfPoints, pInput->numOfRows - pInfo->offset);
4966 4967
  }
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex - pInfo->offset; i += 1) {
G
Ganlin Zhao 已提交
4968
    char* data = colDataGetData(pInputCol, i);
4969
    doTailAdd(pInfo, data, tsList[i], colDataIsNull_s(pInputCol, i));
G
Ganlin Zhao 已提交
4970 4971
  }

4972 4973
  taosqsort(pInfo->pItems, pInfo->numOfPoints, POINTER_BYTES, NULL, tailCompFn);

G
Ganlin Zhao 已提交
4974
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
X
Xiaoyu Wang 已提交
4975 4976
    int32_t    pos = startOffset + i;
    STailItem* pItem = pInfo->pItems[i];
4977 4978 4979 4980 4981
    if (pItem->isNull) {
      colDataAppendNULL(pOutput, pos);
    } else {
      colDataAppend(pOutput, pos, pItem->data, false);
    }
G
Ganlin Zhao 已提交
4982 4983
  }

G
Ganlin Zhao 已提交
4984 4985
  return pInfo->numOfPoints;
}
G
Ganlin Zhao 已提交
4986 4987 4988

int32_t tailFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
X
Xiaoyu Wang 已提交
4989
  STailInfo*           pInfo = GET_ROWCELL_INTERBUF(pEntryInfo);
G
Ganlin Zhao 已提交
4990 4991 4992 4993 4994 4995 4996 4997 4998 4999
  pEntryInfo->complete = true;

  int32_t type = pCtx->input.pData[0]->info.type;
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;

  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  // todo assign the tag value and the corresponding row data
  int32_t currentRow = pBlock->info.rows;
  for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
X
Xiaoyu Wang 已提交
5000
    STailItem* pItem = pInfo->pItems[i];
G
Ganlin Zhao 已提交
5001 5002 5003 5004 5005 5006
    colDataAppend(pCol, currentRow, pItem->data, false);
    currentRow += 1;
  }

  return pEntryInfo->numOfRes;
}
5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029

bool getUniqueFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SUniqueInfo) + UNIQUE_MAX_RESULT_SIZE;
  return true;
}

bool uniqueFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
  if (!functionSetup(pCtx, pResInfo)) {
    return false;
  }

  SUniqueInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
  pInfo->numOfPoints = 0;
  pInfo->colType = pCtx->resDataInfo.type;
  pInfo->colBytes = pCtx->resDataInfo.bytes;
  if (pInfo->pHash != NULL) {
    taosHashClear(pInfo->pHash);
  } else {
    pInfo->pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
  }
  return true;
}

X
Xiaoyu Wang 已提交
5030 5031
static void doUniqueAdd(SUniqueInfo* pInfo, char* data, TSKEY ts, bool isNull) {
  // handle null elements
5032
  if (isNull == true) {
X
Xiaoyu Wang 已提交
5033 5034
    int32_t      size = sizeof(SUniqueItem) + pInfo->colBytes;
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + pInfo->numOfPoints * size);
5035
    if (pInfo->hasNull == false && pItem->isNull == false) {
5036 5037 5038
      pItem->timestamp = ts;
      pItem->isNull = true;
      pInfo->numOfPoints++;
5039
      pInfo->hasNull = true;
5040 5041 5042 5043 5044
    } else if (pItem->timestamp > ts && pItem->isNull == true) {
      pItem->timestamp = ts;
    }
    return;
  }
5045

X
Xiaoyu Wang 已提交
5046 5047
  int32_t      hashKeyBytes = IS_VAR_DATA_TYPE(pInfo->colType) ? varDataTLen(data) : pInfo->colBytes;
  SUniqueItem* pHashItem = taosHashGet(pInfo->pHash, data, hashKeyBytes);
5048
  if (pHashItem == NULL) {
X
Xiaoyu Wang 已提交
5049 5050
    int32_t      size = sizeof(SUniqueItem) + pInfo->colBytes;
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + pInfo->numOfPoints * size);
5051 5052 5053
    pItem->timestamp = ts;
    memcpy(pItem->data, data, pInfo->colBytes);

X
Xiaoyu Wang 已提交
5054
    taosHashPut(pInfo->pHash, data, hashKeyBytes, (char*)pItem, sizeof(SUniqueItem*));
5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065
    pInfo->numOfPoints++;
  } else if (pHashItem->timestamp > ts) {
    pHashItem->timestamp = ts;
  }
}

int32_t uniqueFunction(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SUniqueInfo*         pInfo = GET_ROWCELL_INTERBUF(pResInfo);

  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
5066
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083

  SColumnInfoData* pInputCol = pInput->pData[0];
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;

  int32_t startOffset = pCtx->offset;
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
    char* data = colDataGetData(pInputCol, i);
    doUniqueAdd(pInfo, data, tsList[i], colDataIsNull_s(pInputCol, i));

    if (sizeof(SUniqueInfo) + pInfo->numOfPoints * (sizeof(SUniqueItem) + pInfo->colBytes) >= UNIQUE_MAX_RESULT_SIZE) {
      taosHashCleanup(pInfo->pHash);
      return 0;
    }
  }

  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
X
Xiaoyu Wang 已提交
5084
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + i * (sizeof(SUniqueItem) + pInfo->colBytes));
5085 5086 5087 5088 5089
    if (pItem->isNull == true) {
      colDataAppendNULL(pOutput, i);
    } else {
      colDataAppend(pOutput, i, pItem->data, false);
    }
5090 5091 5092 5093 5094 5095 5096 5097
    if (pTsOutput != NULL) {
      colDataAppendInt64(pTsOutput, i, &pItem->timestamp);
    }
  }

  return pInfo->numOfPoints;
}

G
Ganlin Zhao 已提交
5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125
bool getModeFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SModeInfo) + MODE_MAX_RESULT_SIZE;
  return true;
}

bool modeFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
  if (!functionSetup(pCtx, pResInfo)) {
    return false;
  }

  SModeInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
  pInfo->numOfPoints = 0;
  pInfo->colType = pCtx->resDataInfo.type;
  pInfo->colBytes = pCtx->resDataInfo.bytes;
  if (pInfo->pHash != NULL) {
    taosHashClear(pInfo->pHash);
  } else {
    pInfo->pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
  }
  return true;
}

static void doModeAdd(SModeInfo* pInfo, char* data, bool isNull) {
  // ignore null elements
  if (isNull) {
    return;
  }

5126 5127
  int32_t     hashKeyBytes = IS_VAR_DATA_TYPE(pInfo->colType) ? varDataTLen(data) : pInfo->colBytes;
  SModeItem** pHashItem = taosHashGet(pInfo->pHash, data, hashKeyBytes);
G
Ganlin Zhao 已提交
5128
  if (pHashItem == NULL) {
5129 5130
    int32_t    size = sizeof(SModeItem) + pInfo->colBytes;
    SModeItem* pItem = (SModeItem*)(pInfo->pItems + pInfo->numOfPoints * size);
G
Ganlin Zhao 已提交
5131 5132 5133
    memcpy(pItem->data, data, pInfo->colBytes);
    pItem->count += 1;

G
Ganlin Zhao 已提交
5134
    taosHashPut(pInfo->pHash, data, hashKeyBytes, &pItem, sizeof(SModeItem*));
G
Ganlin Zhao 已提交
5135 5136
    pInfo->numOfPoints++;
  } else {
G
Ganlin Zhao 已提交
5137
    (*pHashItem)->count += 1;
G
Ganlin Zhao 已提交
5138 5139 5140 5141
  }
}

int32_t modeFunction(SqlFunctionCtx* pCtx) {
5142
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5143
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
G
Ganlin Zhao 已提交
5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160

  SInputColumnInfoData* pInput = &pCtx->input;

  SColumnInfoData* pInputCol = pInput->pData[0];
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;

  int32_t startOffset = pCtx->offset;
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
    char* data = colDataGetData(pInputCol, i);
    doModeAdd(pInfo, data, colDataIsNull_s(pInputCol, i));

    if (sizeof(SModeInfo) + pInfo->numOfPoints * (sizeof(SModeItem) + pInfo->colBytes) >= MODE_MAX_RESULT_SIZE) {
      taosHashCleanup(pInfo->pHash);
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }

G
Ganlin Zhao 已提交
5161 5162
  SET_VAL(pResInfo, 1, 1);

G
Ganlin Zhao 已提交
5163 5164 5165 5166 5167 5168
  return TSDB_CODE_SUCCESS;
}

int32_t modeFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
X
Xiaoyu Wang 已提交
5169 5170
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
G
Ganlin Zhao 已提交
5171
  int32_t              currentRow = pBlock->info.rows;
5172

G
Ganlin Zhao 已提交
5173 5174 5175 5176 5177 5178 5179 5180
  int32_t resIndex;
  int32_t maxCount = 0;
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
    SModeItem* pItem = (SModeItem*)(pInfo->pItems + i * (sizeof(SModeItem) + pInfo->colBytes));
    if (pItem->count > maxCount) {
      maxCount = pItem->count;
      resIndex = i;
    } else if (pItem->count == maxCount) {
G
Ganlin Zhao 已提交
5181
      resIndex = -1;
G
Ganlin Zhao 已提交
5182
    }
5183 5184
  }

G
Ganlin Zhao 已提交
5185
  SModeItem* pResItem = (SModeItem*)(pInfo->pItems + resIndex * (sizeof(SModeItem) + pInfo->colBytes));
G
Ganlin Zhao 已提交
5186
  colDataAppend(pCol, currentRow, pResItem->data, (resIndex == -1) ? true : false);
G
Ganlin Zhao 已提交
5187

5188 5189 5190
  return pResInfo->numOfRes;
}

5191 5192 5193 5194 5195
bool getTwaFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(STwaInfo);
  return true;
}

X
Xiaoyu Wang 已提交
5196
bool twaFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
5197 5198 5199 5200
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

X
Xiaoyu Wang 已提交
5201 5202 5203
  STwaInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  pInfo->p.key = INT64_MIN;
  pInfo->win = TSWINDOW_INITIALIZER;
5204 5205 5206 5207
  return true;
}

static double twa_get_area(SPoint1 s, SPoint1 e) {
X
Xiaoyu Wang 已提交
5208
  if ((s.val >= 0 && e.val >= 0) || (s.val <= 0 && e.val <= 0)) {
5209 5210 5211
    return (s.val + e.val) * (e.key - s.key) / 2;
  }

X
Xiaoyu Wang 已提交
5212
  double x = (s.key * e.val - e.key * s.val) / (e.val - s.val);
5213 5214 5215 5216
  double val = (s.val * (x - s.key) + e.val * (e.key - x)) / 2;
  return val;
}

5217
#define INIT_INTP_POINT(_p, _k, _v) \
X
Xiaoyu Wang 已提交
5218 5219 5220
  do {                              \
    (_p).key = (_k);                \
    (_p).val = (_v);                \
5221 5222
  } while (0)

5223 5224
int32_t twaFunction(SqlFunctionCtx* pCtx) {
  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
5225
  SColumnInfoData*      pInputCol = pInput->pData[0];
5226 5227 5228

  TSKEY* tsList = (int64_t*)pInput->pPTS->pData;

X
Xiaoyu Wang 已提交
5229
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5230

X
Xiaoyu Wang 已提交
5231 5232
  STwaInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
  SPoint1*  last = &pInfo->p;
5233
  int32_t   numOfElems = 0;
5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247

  int32_t i = pInput->startRowIndex;
  if (pCtx->start.key != INT64_MIN) {
    ASSERT((pCtx->start.key < tsList[i] && pCtx->order == TSDB_ORDER_ASC) ||
           (pCtx->start.key > tsList[i] && pCtx->order == TSDB_ORDER_DESC));

    ASSERT(last->key == INT64_MIN);
    last->key = tsList[i];

    GET_TYPED_DATA(last->val, double, pInputCol->info.type, colDataGetData(pInputCol, i));

    pInfo->dOutput += twa_get_area(pCtx->start, *last);
    pInfo->win.skey = pCtx->start.key;
    numOfElems++;
5248
    i += 1;
5249 5250 5251 5252 5253 5254
  } else if (pInfo->p.key == INT64_MIN) {
    last->key = tsList[i];
    GET_TYPED_DATA(last->val, double, pInputCol->info.type, colDataGetData(pInputCol, i));

    pInfo->win.skey = last->key;
    numOfElems++;
5255
    i += 1;
5256 5257
  }

5258 5259
  SPoint1 st = {0};

5260
  // calculate the value of
X
Xiaoyu Wang 已提交
5261
  switch (pInputCol->info.type) {
5262
    case TSDB_DATA_TYPE_TINYINT: {
X
Xiaoyu Wang 已提交
5263
      int8_t* val = (int8_t*)colDataGetData(pInputCol, 0);
5264
      for (; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
5265 5266 5267 5268
        if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
          continue;
        }

5269
        INIT_INTP_POINT(st, tsList[i], val[i]);
5270 5271 5272 5273 5274 5275 5276
        pInfo->dOutput += twa_get_area(pInfo->p, st);
        pInfo->p = st;
      }
      break;
    }

    case TSDB_DATA_TYPE_SMALLINT: {
X
Xiaoyu Wang 已提交
5277
      int16_t* val = (int16_t*)colDataGetData(pInputCol, 0);
5278
      for (; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
5279 5280 5281 5282
        if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
          continue;
        }

5283
        INIT_INTP_POINT(st, tsList[i], val[i]);
5284 5285 5286 5287 5288 5289
        pInfo->dOutput += twa_get_area(pInfo->p, st);
        pInfo->p = st;
      }
      break;
    }
    case TSDB_DATA_TYPE_INT: {
X
Xiaoyu Wang 已提交
5290
      int32_t* val = (int32_t*)colDataGetData(pInputCol, 0);
5291
      for (; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
5292 5293 5294 5295
        if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
          continue;
        }

5296
        INIT_INTP_POINT(st, tsList[i], val[i]);
5297 5298 5299 5300 5301 5302
        pInfo->dOutput += twa_get_area(pInfo->p, st);
        pInfo->p = st;
      }
      break;
    }
    case TSDB_DATA_TYPE_BIGINT: {
X
Xiaoyu Wang 已提交
5303
      int64_t* val = (int64_t*)colDataGetData(pInputCol, 0);
5304
      for (; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
5305 5306 5307 5308
        if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
          continue;
        }

5309
        INIT_INTP_POINT(st, tsList[i], val[i]);
5310 5311 5312 5313 5314 5315
        pInfo->dOutput += twa_get_area(pInfo->p, st);
        pInfo->p = st;
      }
      break;
    }
    case TSDB_DATA_TYPE_FLOAT: {
X
Xiaoyu Wang 已提交
5316
      float* val = (float*)colDataGetData(pInputCol, 0);
5317
      for (; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
5318 5319 5320 5321
        if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
          continue;
        }

5322
        INIT_INTP_POINT(st, tsList[i], val[i]);
5323 5324 5325 5326 5327 5328
        pInfo->dOutput += twa_get_area(pInfo->p, st);
        pInfo->p = st;
      }
      break;
    }
    case TSDB_DATA_TYPE_DOUBLE: {
X
Xiaoyu Wang 已提交
5329
      double* val = (double*)colDataGetData(pInputCol, 0);
5330
      for (; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
5331 5332 5333 5334
        if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
          continue;
        }

5335
        INIT_INTP_POINT(st, tsList[i], val[i]);
5336 5337 5338 5339 5340 5341
        pInfo->dOutput += twa_get_area(pInfo->p, st);
        pInfo->p = st;
      }
      break;
    }
    case TSDB_DATA_TYPE_UTINYINT: {
X
Xiaoyu Wang 已提交
5342
      uint8_t* val = (uint8_t*)colDataGetData(pInputCol, 0);
5343
      for (; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
5344 5345 5346 5347
        if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
          continue;
        }

5348
        INIT_INTP_POINT(st, tsList[i], val[i]);
5349 5350 5351 5352 5353 5354
        pInfo->dOutput += twa_get_area(pInfo->p, st);
        pInfo->p = st;
      }
      break;
    }
    case TSDB_DATA_TYPE_USMALLINT: {
X
Xiaoyu Wang 已提交
5355
      uint16_t* val = (uint16_t*)colDataGetData(pInputCol, 0);
5356
      for (; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
5357 5358 5359 5360
        if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
          continue;
        }

5361
        INIT_INTP_POINT(st, tsList[i], val[i]);
5362 5363 5364 5365 5366 5367
        pInfo->dOutput += twa_get_area(pInfo->p, st);
        pInfo->p = st;
      }
      break;
    }
    case TSDB_DATA_TYPE_UINT: {
X
Xiaoyu Wang 已提交
5368
      uint32_t* val = (uint32_t*)colDataGetData(pInputCol, 0);
5369
      for (; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
5370 5371 5372 5373
        if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
          continue;
        }

5374
        INIT_INTP_POINT(st, tsList[i], val[i]);
5375 5376 5377 5378 5379 5380
        pInfo->dOutput += twa_get_area(pInfo->p, st);
        pInfo->p = st;
      }
      break;
    }
    case TSDB_DATA_TYPE_UBIGINT: {
X
Xiaoyu Wang 已提交
5381
      uint64_t* val = (uint64_t*)colDataGetData(pInputCol, 0);
5382
      for (; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
5383 5384 5385 5386
        if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
          continue;
        }

5387
        INIT_INTP_POINT(st, tsList[i], val[i]);
5388 5389 5390 5391 5392 5393
        pInfo->dOutput += twa_get_area(pInfo->p, st);
        pInfo->p = st;
      }
      break;
    }

X
Xiaoyu Wang 已提交
5394 5395
    default:
      ASSERT(0);
5396 5397 5398 5399
  }

  // the last interpolated time window value
  if (pCtx->end.key != INT64_MIN) {
X
Xiaoyu Wang 已提交
5400
    pInfo->dOutput += twa_get_area(pInfo->p, pCtx->end);
5401 5402 5403
    pInfo->p = pCtx->end;
  }

X
Xiaoyu Wang 已提交
5404
  pInfo->win.ekey = pInfo->p.key;
5405

5406
  SET_VAL(pResInfo, numOfElems, 1);
5407 5408 5409 5410 5411 5412 5413 5414
  return TSDB_CODE_SUCCESS;
}

/*
 * To copy the input to interResBuf to avoid the input buffer space be over writen
 * by next input data. The TWA function only applies to each table, so no merge procedure
 * is required, we simply copy to the resut ot interResBuffer.
 */
X
Xiaoyu Wang 已提交
5415 5416 5417
// void twa_function_copy(SQLFunctionCtx *pCtx) {
//   assert(pCtx->inputType == TSDB_DATA_TYPE_BINARY);
//   SResultRowEntryInfo *pResInfo = GET_RES_INFO(pCtx);
5418
//
X
Xiaoyu Wang 已提交
5419 5420 5421
//   memcpy(GET_ROWCELL_INTERBUF(pResInfo), pCtx->pInput, (size_t)pCtx->inputBytes);
//   pResInfo->hasResult = ((STwaInfo *)pCtx->pInput)->hasResult;
// }
5422

X
Xiaoyu Wang 已提交
5423 5424
int32_t twaFinalize(struct SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5425

X
Xiaoyu Wang 已提交
5426
  STwaInfo* pInfo = (STwaInfo*)GET_ROWCELL_INTERBUF(pResInfo);
5427
  if (pResInfo->numOfRes == 0) {
5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441
    pResInfo->isNullRes = 1;
  } else {
    if (pInfo->win.ekey == pInfo->win.skey) {
      pInfo->dOutput = pInfo->p.val;
    } else {
      pInfo->dOutput = pInfo->dOutput / (pInfo->win.ekey - pInfo->win.skey);
    }

    pResInfo->numOfRes = 1;
  }

  return functionFinalize(pCtx, pBlock);
}

5442
bool blockDistSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
5443 5444 5445 5446 5447 5448 5449 5450 5451
  if (!functionSetup(pCtx, pResultInfo)) {
    return false;
  }

  STableBlockDistInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
  pInfo->minRows = INT32_MAX;
  return true;
}

X
Xiaoyu Wang 已提交
5452
int32_t blockDistFunction(SqlFunctionCtx* pCtx) {
5453 5454
  const int32_t BLOCK_DIST_RESULT_ROWS = 24;

5455
  SInputColumnInfoData* pInput = &pCtx->input;
X
Xiaoyu Wang 已提交
5456
  SColumnInfoData*      pInputCol = pInput->pData[0];
5457

X
Xiaoyu Wang 已提交
5458
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5459

5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471
  STableBlockDistInfo* pDistInfo = GET_ROWCELL_INTERBUF(pResInfo);

  STableBlockDistInfo p1 = {0};
  tDeserializeBlockDistInfo(varDataVal(pInputCol->pData), varDataLen(pInputCol->pData), &p1);

  pDistInfo->numOfBlocks += p1.numOfBlocks;
  pDistInfo->numOfTables += p1.numOfTables;
  pDistInfo->numOfInmemRows += p1.numOfInmemRows;
  pDistInfo->totalSize += p1.totalSize;
  pDistInfo->totalRows += p1.totalRows;
  pDistInfo->numOfFiles += p1.numOfFiles;

5472 5473
  pDistInfo->defMinRows = p1.defMinRows;
  pDistInfo->defMaxRows = p1.defMaxRows;
5474
  pDistInfo->rowSize = p1.rowSize;
5475 5476
  pDistInfo->numOfSmallBlocks = p1.numOfSmallBlocks;

5477 5478 5479 5480 5481 5482 5483
  if (pDistInfo->minRows > p1.minRows) {
    pDistInfo->minRows = p1.minRows;
  }
  if (pDistInfo->maxRows < p1.maxRows) {
    pDistInfo->maxRows = p1.maxRows;
  }

X
Xiaoyu Wang 已提交
5484
  for (int32_t i = 0; i < tListLen(pDistInfo->blockRowsHisto); ++i) {
5485 5486 5487
    pDistInfo->blockRowsHisto[i] += p1.blockRowsHisto[i];
  }

5488
  pResInfo->numOfRes = BLOCK_DIST_RESULT_ROWS;  // default output rows
5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499
  return TSDB_CODE_SUCCESS;
}

int32_t tSerializeBlockDistInfo(void* buf, int32_t bufLen, const STableBlockDistInfo* pInfo) {
  SEncoder encoder = {0};
  tEncoderInit(&encoder, buf, bufLen);

  if (tStartEncode(&encoder) < 0) return -1;
  if (tEncodeU32(&encoder, pInfo->rowSize) < 0) return -1;

  if (tEncodeU16(&encoder, pInfo->numOfFiles) < 0) return -1;
5500
  if (tEncodeU32(&encoder, pInfo->numOfBlocks) < 0) return -1;
5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511
  if (tEncodeU32(&encoder, pInfo->numOfTables) < 0) return -1;

  if (tEncodeU64(&encoder, pInfo->totalSize) < 0) return -1;
  if (tEncodeU64(&encoder, pInfo->totalRows) < 0) return -1;
  if (tEncodeI32(&encoder, pInfo->maxRows) < 0) return -1;
  if (tEncodeI32(&encoder, pInfo->minRows) < 0) return -1;
  if (tEncodeI32(&encoder, pInfo->defMaxRows) < 0) return -1;
  if (tEncodeI32(&encoder, pInfo->defMinRows) < 0) return -1;
  if (tEncodeU32(&encoder, pInfo->numOfInmemRows) < 0) return -1;
  if (tEncodeU32(&encoder, pInfo->numOfSmallBlocks) < 0) return -1;

X
Xiaoyu Wang 已提交
5512
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530
    if (tEncodeI32(&encoder, pInfo->blockRowsHisto[i]) < 0) return -1;
  }

  tEndEncode(&encoder);

  int32_t tlen = encoder.pos;
  tEncoderClear(&encoder);
  return tlen;
}

int32_t tDeserializeBlockDistInfo(void* buf, int32_t bufLen, STableBlockDistInfo* pInfo) {
  SDecoder decoder = {0};
  tDecoderInit(&decoder, buf, bufLen);

  if (tStartDecode(&decoder) < 0) return -1;
  if (tDecodeU32(&decoder, &pInfo->rowSize) < 0) return -1;

  if (tDecodeU16(&decoder, &pInfo->numOfFiles) < 0) return -1;
5531
  if (tDecodeU32(&decoder, &pInfo->numOfBlocks) < 0) return -1;
5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542
  if (tDecodeU32(&decoder, &pInfo->numOfTables) < 0) return -1;

  if (tDecodeU64(&decoder, &pInfo->totalSize) < 0) return -1;
  if (tDecodeU64(&decoder, &pInfo->totalRows) < 0) return -1;
  if (tDecodeI32(&decoder, &pInfo->maxRows) < 0) return -1;
  if (tDecodeI32(&decoder, &pInfo->minRows) < 0) return -1;
  if (tDecodeI32(&decoder, &pInfo->defMaxRows) < 0) return -1;
  if (tDecodeI32(&decoder, &pInfo->defMinRows) < 0) return -1;
  if (tDecodeU32(&decoder, &pInfo->numOfInmemRows) < 0) return -1;
  if (tDecodeU32(&decoder, &pInfo->numOfSmallBlocks) < 0) return -1;

X
Xiaoyu Wang 已提交
5543
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
5544 5545 5546 5547 5548 5549 5550 5551
    if (tDecodeI32(&decoder, &pInfo->blockRowsHisto[i]) < 0) return -1;
  }

  tDecoderClear(&decoder);
  return 0;
}

int32_t blockDistFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
X
Xiaoyu Wang 已提交
5552
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5553
  STableBlockDistInfo* pData = GET_ROWCELL_INTERBUF(pResInfo);
5554

5555 5556 5557
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);

  int32_t row = 0;
X
Xiaoyu Wang 已提交
5558
  char    st[256] = {0};
5559
  double  totalRawSize = pData->totalRows * pData->rowSize;
5560 5561 5562 5563
  int32_t len = sprintf(st + VARSTR_HEADER_SIZE,
                        "Total_Blocks=[%d] Total_Size=[%.2f Kb] Average_size=[%.2f Kb] Compression_Ratio=[%.2f %c]",
                        pData->numOfBlocks, pData->totalSize / 1024.0, ((double)pData->totalSize) / pData->numOfBlocks,
                        pData->totalSize * 100 / totalRawSize, '%');
5564 5565 5566

  varDataSetLen(st, len);
  colDataAppend(pColInfo, row++, st, false);
5567

5568 5569 5570 5571
  len = sprintf(st + VARSTR_HEADER_SIZE,
                "Total_Rows=[%" PRId64 "] Inmem_Rows=[%d] MinRows=[%d] MaxRows=[%d] Average_Rows=[%" PRId64 "]",
                pData->totalRows, pData->numOfInmemRows, pData->minRows, pData->maxRows,
                pData->totalRows / pData->numOfBlocks);
5572

5573 5574
  varDataSetLen(st, len);
  colDataAppend(pColInfo, row++, st, false);
5575

5576 5577
  len = sprintf(st + VARSTR_HEADER_SIZE, "Total_Tables=[%d] Total_Files=[%d] Total_Vgroups=[%d]", pData->numOfTables,
                pData->numOfFiles, 0);
5578 5579 5580 5581

  varDataSetLen(st, len);
  colDataAppend(pColInfo, row++, st, false);

X
Xiaoyu Wang 已提交
5582 5583
  len = sprintf(st + VARSTR_HEADER_SIZE,
                "--------------------------------------------------------------------------------");
5584 5585
  varDataSetLen(st, len);
  colDataAppend(pColInfo, row++, st, false);
5586 5587 5588

  int32_t maxVal = 0;
  int32_t minVal = INT32_MAX;
5589 5590 5591
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
    if (maxVal < pData->blockRowsHisto[i]) {
      maxVal = pData->blockRowsHisto[i];
5592 5593
    }

5594 5595
    if (minVal > pData->blockRowsHisto[i]) {
      minVal = pData->blockRowsHisto[i];
5596 5597 5598
    }
  }

5599 5600
  // maximum number of step is 80
  double factor = pData->numOfBlocks / 80.0;
5601 5602

  int32_t numOfBuckets = sizeof(pData->blockRowsHisto) / sizeof(pData->blockRowsHisto[0]);
5603
  int32_t bucketRange = (pData->defMaxRows - pData->defMinRows) / numOfBuckets;
5604

5605
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
5606
    len = sprintf(st + VARSTR_HEADER_SIZE, "%04d |", pData->defMinRows + bucketRange * i);
5607

5608
    int32_t num = 0;
5609 5610
    if (pData->blockRowsHisto[i] > 0) {
      num = (pData->blockRowsHisto[i]) / factor;
5611
    }
5612 5613 5614

    for (int32_t j = 0; j < num; ++j) {
      int32_t x = sprintf(st + VARSTR_HEADER_SIZE + len, "%c", '|');
5615 5616 5617
      len += x;
    }

5618 5619 5620 5621
    if (num > 0) {
      double v = pData->blockRowsHisto[i] * 100.0 / pData->numOfBlocks;
      len += sprintf(st + VARSTR_HEADER_SIZE + len, "  %d (%.2f%c)", pData->blockRowsHisto[i], v, '%');
    }
5622 5623 5624

    varDataSetLen(st, len);
    colDataAppend(pColInfo, row++, st, false);
5625 5626
  }

5627
  return TSDB_CODE_SUCCESS;
5628
}
5629 5630 5631 5632 5633 5634

bool getDerivativeFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SDerivInfo);
  return true;
}

5635
bool derivativeFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
5636 5637 5638 5639 5640 5641 5642
  if (!functionSetup(pCtx, pResInfo)) {
    return false;  // not initialized since it has been initialized
  }

  SDerivInfo* pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);

  pDerivInfo->ignoreNegative = pCtx->param[2].param.i;
5643
  pDerivInfo->prevTs = -1;
5644 5645 5646 5647 5648
  pDerivInfo->tsWindow = pCtx->param[1].param.i;
  pDerivInfo->valueSet = false;
  return true;
}

5649 5650 5651
int32_t derivativeFunction(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SDerivInfo*          pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
5652 5653

  SInputColumnInfoData* pInput = &pCtx->input;
5654
  SColumnInfoData*      pInputCol = pInput->pData[0];
H
Haojun Liao 已提交
5655

5656
  int32_t          numOfElems = 0;
5657 5658 5659 5660
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;

  int32_t i = pInput->startRowIndex;
5661
  TSKEY*  tsList = (int64_t*)pInput->pPTS->pData;
5662

5663
  double v = 0;
5664

5665 5666
  if (pCtx->order == TSDB_ORDER_ASC) {
    for (; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
5667 5668 5669 5670
      if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
        continue;
      }

5671
      char* d = (char*)pInputCol->pData + pInputCol->info.bytes * i;
5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692
      GET_TYPED_DATA(v, double, pInputCol->info.type, d);

      int32_t pos = pCtx->offset + numOfElems;
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
        pDerivInfo->valueSet = true;
      } else {
        double r = ((v - pDerivInfo->prevValue) * pDerivInfo->tsWindow) / (tsList[i] - pDerivInfo->prevTs);
        if (pDerivInfo->ignoreNegative && r < 0) {
        } else {
          colDataAppend(pOutput, pos, (const char*)&r, false);
          if (pTsOutput != NULL) {
            colDataAppendInt64(pTsOutput, pos, &tsList[i]);
          }
          numOfElems++;
        }
      }

      pDerivInfo->prevValue = v;
      pDerivInfo->prevTs = tsList[i];
    }
  } else {
5693 5694 5695 5696 5697
    for (; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
      if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
        continue;
      }

5698
      char* d = (char*)pInputCol->pData + pInputCol->info.bytes * i;
5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714
      GET_TYPED_DATA(v, double, pInputCol->info.type, d);

      int32_t pos = pCtx->offset + numOfElems;
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
        pDerivInfo->valueSet = true;
      } else {
        double r = ((pDerivInfo->prevValue - v) * pDerivInfo->tsWindow) / (pDerivInfo->prevTs - tsList[i]);
        if (pDerivInfo->ignoreNegative && r < 0) {
        } else {
          colDataAppend(pOutput, pos, (const char*)&r, false);
          if (pTsOutput != NULL) {
            colDataAppendInt64(pTsOutput, pos, &pDerivInfo->prevTs);
          }
          numOfElems++;
        }
      }
5715

5716 5717 5718
      pDerivInfo->prevValue = v;
      pDerivInfo->prevTs = tsList[i];
    }
5719 5720 5721
  }

  return numOfElems;
H
Haojun Liao 已提交
5722 5723
}

G
Ganlin Zhao 已提交
5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735
bool getIrateFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
  pEnv->calcMemSize = sizeof(SRateInfo);
  return true;
}

bool irateFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
  if (!functionSetup(pCtx, pResInfo)) {
    return false;  // not initialized since it has been initialized
  }

  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);

5736 5737
  pInfo->firstKey = INT64_MIN;
  pInfo->lastKey = INT64_MIN;
G
Ganlin Zhao 已提交
5738
  pInfo->firstValue = (double)INT64_MIN;
5739
  pInfo->lastValue = (double)INT64_MIN;
G
Ganlin Zhao 已提交
5740

5741
  pInfo->hasResult = 0;
G
Ganlin Zhao 已提交
5742 5743 5744 5745 5746
  return true;
}

int32_t irateFunction(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5747
  SRateInfo*           pRateInfo = GET_ROWCELL_INTERBUF(pResInfo);
G
Ganlin Zhao 已提交
5748 5749 5750 5751 5752 5753

  SInputColumnInfoData* pInput = &pCtx->input;
  SColumnInfoData*      pInputCol = pInput->pData[0];

  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;

5754
  TSKEY* tsList = (int64_t*)pInput->pPTS->pData;
G
Ganlin Zhao 已提交
5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765

  int32_t numOfElems = 0;
  int32_t type = pInputCol->info.type;

  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
      continue;
    }

    numOfElems++;

5766 5767
    char*  data = colDataGetData(pInputCol, i);
    double v = 0;
G
Ganlin Zhao 已提交
5768 5769 5770 5771
    GET_TYPED_DATA(v, double, type, data);

    if (INT64_MIN == pRateInfo->lastKey) {
      pRateInfo->lastValue = v;
5772
      pRateInfo->lastKey = tsList[i];
G
Ganlin Zhao 已提交
5773 5774 5775 5776 5777 5778 5779 5780 5781 5782
      continue;
    }

    if (tsList[i] > pRateInfo->lastKey) {
      if ((INT64_MIN == pRateInfo->firstKey) || pRateInfo->lastKey > pRateInfo->firstKey) {
        pRateInfo->firstValue = pRateInfo->lastValue;
        pRateInfo->firstKey = pRateInfo->lastKey;
      }

      pRateInfo->lastValue = v;
5783
      pRateInfo->lastKey = tsList[i];
G
Ganlin Zhao 已提交
5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816

      continue;
    }

    if ((INT64_MIN == pRateInfo->firstKey) || tsList[i] > pRateInfo->firstKey) {
      pRateInfo->firstValue = v;
      pRateInfo->firstKey = tsList[i];
    }
  }

  SET_VAL(pResInfo, numOfElems, 1);
  return TSDB_CODE_SUCCESS;
}

static double doCalcRate(const SRateInfo* pRateInfo, double tickPerSec) {
  if ((INT64_MIN == pRateInfo->lastKey) || (INT64_MIN == pRateInfo->firstKey) ||
      (pRateInfo->firstKey >= pRateInfo->lastKey)) {
    return 0.0;
  }

  double diff = 0;
  // If the previous value of the last is greater than the last value, only keep the last point instead of the delta
  // value between two values.
  diff = pRateInfo->lastValue;
  if (diff >= pRateInfo->firstValue) {
    diff -= pRateInfo->firstValue;
  }

  int64_t duration = pRateInfo->lastKey - pRateInfo->firstKey;
  if (duration == 0) {
    return 0;
  }

5817
  return (duration > 0) ? ((double)diff) / (duration / tickPerSec) : 0.0;
G
Ganlin Zhao 已提交
5818 5819 5820 5821 5822 5823 5824 5825 5826 5827
}

int32_t irateFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;

  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5828
  double     result = doCalcRate(pInfo, (double)TSDB_TICK_PER_SECOND(pCtx->param[1].param.i));
G
Ganlin Zhao 已提交
5829 5830 5831 5832 5833
  colDataAppend(pCol, pBlock->info.rows, (const char*)&result, pResInfo->isNullRes);

  return pResInfo->numOfRes;
}

5834 5835
int32_t groupKeyFunction(SqlFunctionCtx* pCtx) {
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5836
  SGroupKeyInfo*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5837 5838

  SInputColumnInfoData* pInput = &pCtx->input;
5839
  SColumnInfoData*      pInputCol = pInput->pData[0];
5840 5841

  int32_t startIndex = pInput->startRowIndex;
5842

5843
  // escape rest of data blocks to avoid first entry to be overwritten.
5844 5845 5846 5847
  if (pInfo->hasResult) {
    goto _group_key_over;
  }

5848
  if (colDataIsNull_s(pInputCol, startIndex)) {
5849 5850
    pInfo->isNull = true;
    pInfo->hasResult = true;
G
Ganlin Zhao 已提交
5851
    goto _group_key_over;
5852 5853 5854
  }

  char* data = colDataGetData(pInputCol, startIndex);
5855
  if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
X
Xiaoyu Wang 已提交
5856 5857
    memcpy(pInfo->data, data,
           (pInputCol->info.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(data) : varDataTLen(data));
5858 5859 5860
  } else {
    memcpy(pInfo->data, data, pInputCol->info.bytes);
  }
5861
  pInfo->hasResult = true;
G
Ganlin Zhao 已提交
5862 5863

_group_key_over:
5864

G
Ganlin Zhao 已提交
5865
  SET_VAL(pResInfo, 1, 1);
5866 5867 5868
  return TSDB_CODE_SUCCESS;
}

G
Ganlin Zhao 已提交
5869 5870 5871 5872 5873 5874 5875
int32_t groupKeyFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);

  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);

  SGroupKeyInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5876 5877 5878 5879 5880 5881

  if (pInfo->hasResult) {
    colDataAppend(pCol, pBlock->info.rows, pInfo->data, pInfo->isNull ? true : false);
  } else {
    pResInfo->numOfRes = 0;
  }
G
Ganlin Zhao 已提交
5882 5883 5884 5885

  return pResInfo->numOfRes;
}

5886
int32_t interpFunction(SqlFunctionCtx* pCtx) {
H
Haojun Liao 已提交
5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976
#if 0
  int32_t fillType = (int32_t) pCtx->param[2].i64;
  //bool ascQuery = (pCtx->order == TSDB_ORDER_ASC);

  if (pCtx->start.key == pCtx->startTs) {
    assert(pCtx->start.key != INT64_MIN);

    COPY_TYPED_DATA(pCtx->pOutput, pCtx->inputType, &pCtx->start.val);

    goto interp_success_exit;
  } else if (pCtx->end.key == pCtx->startTs && pCtx->end.key != INT64_MIN && fillType == TSDB_FILL_NEXT) {
    COPY_TYPED_DATA(pCtx->pOutput, pCtx->inputType, &pCtx->end.val);

    goto interp_success_exit;
  }

  switch (fillType) {
    case TSDB_FILL_NULL:
      setNull(pCtx->pOutput, pCtx->outputType, pCtx->outputBytes);
      break;

    case TSDB_FILL_SET_VALUE:
      tVariantDump(&pCtx->param[1], pCtx->pOutput, pCtx->inputType, true);
      break;

    case TSDB_FILL_LINEAR:
      if (pCtx->start.key == INT64_MIN || pCtx->start.key > pCtx->startTs
          || pCtx->end.key == INT64_MIN || pCtx->end.key < pCtx->startTs) {
        goto interp_exit;
      }

      double v1 = -1, v2 = -1;
      GET_TYPED_DATA(v1, double, pCtx->inputType, &pCtx->start.val);
      GET_TYPED_DATA(v2, double, pCtx->inputType, &pCtx->end.val);

      SPoint point1 = {.key = pCtx->start.key, .val = &v1};
      SPoint point2 = {.key = pCtx->end.key, .val = &v2};
      SPoint point  = {.key = pCtx->startTs, .val = pCtx->pOutput};

      int32_t srcType = pCtx->inputType;
      if (isNull((char *)&pCtx->start.val, srcType) || isNull((char *)&pCtx->end.val, srcType)) {
        setNull(pCtx->pOutput, srcType, pCtx->inputBytes);
      } else {
        bool exceedMax = false, exceedMin = false;
        taosGetLinearInterpolationVal(&point, pCtx->outputType, &point1, &point2, TSDB_DATA_TYPE_DOUBLE, &exceedMax, &exceedMin);
        if (exceedMax || exceedMin) {
          __compar_fn_t func = getComparFunc((int32_t)pCtx->inputType, 0);
          if (func(&pCtx->start.val, &pCtx->end.val) <= 0) {
            COPY_TYPED_DATA(pCtx->pOutput, pCtx->inputType, exceedMax ? &pCtx->start.val : &pCtx->end.val);
          } else {
            COPY_TYPED_DATA(pCtx->pOutput, pCtx->inputType, exceedMax ? &pCtx->end.val : &pCtx->start.val);
          }
        }
      }
      break;

    case TSDB_FILL_PREV:
      if (pCtx->start.key == INT64_MIN || pCtx->start.key > pCtx->startTs) {
        goto interp_exit;
      }

      COPY_TYPED_DATA(pCtx->pOutput, pCtx->inputType, &pCtx->start.val);
      break;

    case TSDB_FILL_NEXT:
      if (pCtx->end.key == INT64_MIN || pCtx->end.key < pCtx->startTs) {
        goto interp_exit;
      }

      COPY_TYPED_DATA(pCtx->pOutput, pCtx->inputType, &pCtx->end.val);
      break;

    case TSDB_FILL_NONE:
      // do nothing
    default:
      goto interp_exit;
  }


  interp_success_exit:
  *(TSKEY*)pCtx->ptsOutputBuf = pCtx->startTs;
  INC_INIT_VAL(pCtx, 1);

  interp_exit:
  pCtx->start.key = INT64_MIN;
  pCtx->end.key = INT64_MIN;
  pCtx->endTs = pCtx->startTs;
#endif

  return TSDB_CODE_SUCCESS;
5977
}
5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017

int32_t lastrowFunction(SqlFunctionCtx* pCtx) {
  int32_t numOfElems = 0;

  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);

  SInputColumnInfoData* pInput = &pCtx->input;
  SColumnInfoData*      pInputCol = pInput->pData[0];

  int32_t type = pInputCol->info.type;
  int32_t bytes = pInputCol->info.bytes;
  pInfo->bytes = bytes;

  for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
    if (pInputCol->hasNull && colDataIsNull_s(pInputCol, i)) {
      continue;
    }

    numOfElems++;

    char* data = colDataGetData(pInputCol, i);
    TSKEY cts = getRowPTs(pInput->pPTS, i);
    if (pResInfo->numOfRes == 0 || *(TSKEY*)(pInfo->buf + bytes) < cts) {
      if (IS_VAR_DATA_TYPE(type)) {
        bytes = varDataTLen(data);
        pInfo->bytes = bytes;
      }

      memcpy(pInfo->buf, data, bytes);
      *(TSKEY*)(pInfo->buf + bytes) = cts;

      pInfo->hasResult = true;
      pResInfo->numOfRes = 1;
    }
  }

  SET_VAL(pResInfo, numOfElems, 1);
  return TSDB_CODE_SUCCESS;
}