• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

taosdata / TDengine / #3529

14 Nov 2024 01:56PM UTC coverage: 60.888% (-0.02%) from 60.905%
#3529

push

travis-ci

web-flow
Merge pull request #28764 from taosdata/docs/TS-4937

doc(arch/last): new section for last/last_row cache

119990 of 252020 branches covered (47.61%)

Branch coverage included in aggregate %.

200800 of 274829 relevant lines covered (73.06%)

15624555.39 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

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

16
#include "builtinsimpl.h"
17
#include "cJSON.h"
18
#include "function.h"
19
#include "functionResInfoInt.h"
20
#include "query.h"
21
#include "querynodes.h"
22
#include "tanalytics.h"
23
#include "tcompare.h"
24
#include "tdatablock.h"
25
#include "tdigest.h"
26
#include "tfunctionInt.h"
27
#include "tglobal.h"
28
#include "thistogram.h"
29
#include "tpercentile.h"
30

31
bool ignoreNegative(int8_t ignoreOption){
49,483,879✔
32
  return (ignoreOption & 0x1) == 0x1;
49,483,879✔
33
}
34
bool ignoreNull(int8_t ignoreOption){
423,931✔
35
  return (ignoreOption & 0x2) == 0x2;
423,931✔
36
}
37

38
typedef enum {
39
  APERCT_ALGO_UNKNOWN = 0,
40
  APERCT_ALGO_DEFAULT,
41
  APERCT_ALGO_TDIGEST,
42
} EAPerctAlgoType;
43

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

46
typedef enum {
47
  STATE_OPER_INVALID = 0,
48
  STATE_OPER_LT,
49
  STATE_OPER_GT,
50
  STATE_OPER_LE,
51
  STATE_OPER_GE,
52
  STATE_OPER_NE,
53
  STATE_OPER_EQ,
54
} EStateOperType;
55

56
#define SET_VAL(_info, numOfElem, res) \
57
  do {                                 \
58
    if ((numOfElem) <= 0) {            \
59
      break;                           \
60
    }                                  \
61
    (_info)->numOfRes = (res);         \
62
  } while (0)
63

64
#define GET_TS_LIST(x)    ((TSKEY*)((x)->ptsList))
65
#define GET_TS_DATA(x, y) (GET_TS_LIST(x)[(y)])
66

67
#define DO_UPDATE_SUBSID_RES(ctx, ts)                          \
68
  do {                                                         \
69
    for (int32_t _i = 0; _i < (ctx)->subsidiaries.num; ++_i) { \
70
      SqlFunctionCtx* __ctx = (ctx)->subsidiaries.pCtx[_i];    \
71
      if (__ctx->functionId == FUNCTION_TS_DUMMY) {            \
72
        __ctx->tag.i = (ts);                                   \
73
        __ctx->tag.nType = TSDB_DATA_TYPE_BIGINT;              \
74
      }                                                        \
75
      __ctx->fpSet.process(__ctx);                             \
76
    }                                                          \
77
  } while (0)
78

79
#define UPDATE_DATA(ctx, left, right, num, sign, _ts) \
80
  do {                                                \
81
    if (((left) < (right)) ^ (sign)) {                \
82
      (left) = (right);                               \
83
      DO_UPDATE_SUBSID_RES(ctx, _ts);                 \
84
      (num) += 1;                                     \
85
    }                                                 \
86
  } while (0)
87

88
#define LOOPCHECK_N(val, _col, ctx, _t, _nrow, _start, sign, num)        \
89
  do {                                                                   \
90
    _t* d = (_t*)((_col)->pData);                                        \
91
    for (int32_t i = (_start); i < (_nrow) + (_start); ++i) {            \
92
      if (((_col)->hasNull) && colDataIsNull_f((_col)->nullbitmap, i)) { \
93
        continue;                                                        \
94
      }                                                                  \
95
      TSKEY ts = (ctx)->ptsList != NULL ? GET_TS_DATA(ctx, i) : 0;       \
96
      UPDATE_DATA(ctx, val, d[i], num, sign, ts);                        \
97
    }                                                                    \
98
  } while (0)
99

100
#define LIST_ADD_N(_res, _col, _start, _rows, _t, numOfElem)             \
101
  do {                                                                   \
102
    _t* d = (_t*)(_col->pData);                                          \
103
    for (int32_t i = (_start); i < (_rows) + (_start); ++i) {            \
104
      if (((_col)->hasNull) && colDataIsNull_f((_col)->nullbitmap, i)) { \
105
        continue;                                                        \
106
      };                                                                 \
107
      (_res) += (d)[i];                                                  \
108
      (numOfElem)++;                                                     \
109
    }                                                                    \
110
  } while (0)
111

112
#define LIST_SUB_N(_res, _col, _start, _rows, _t, numOfElem)             \
113
  do {                                                                   \
114
    _t* d = (_t*)(_col->pData);                                          \
115
    for (int32_t i = (_start); i < (_rows) + (_start); ++i) {            \
116
      if (((_col)->hasNull) && colDataIsNull_f((_col)->nullbitmap, i)) { \
117
        continue;                                                        \
118
      };                                                                 \
119
      (_res) -= (d)[i];                                                  \
120
      (numOfElem)++;                                                     \
121
    }                                                                    \
122
  } while (0)
123

124
//#define LIST_AVG_N(sumT, T)                                               \
125
//  do {                                                                    \
126
//    T* plist = (T*)pCol->pData;                                           \
127
//    for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) { \
128
//      if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {        \
129
//        continue;                                                         \
130
//      }                                                                   \
131
//                                                                          \
132
//      numOfElem += 1;                                                     \
133
//      pAvgRes->count -= 1;                                                \
134
//      sumT -= plist[i];                                                   \
135
//    }                                                                     \
136
//  } while (0)
137

138
#define LIST_STDDEV_SUB_N(sumT, T)                                 \
139
  do {                                                             \
140
    T* plist = (T*)pCol->pData;                                    \
141
    for (int32_t i = start; i < numOfRows + start; ++i) {          \
142
      if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) { \
143
        continue;                                                  \
144
      }                                                            \
145
      numOfElem += 1;                                              \
146
      pStddevRes->count -= 1;                                      \
147
      sumT -= plist[i];                                            \
148
      pStddevRes->quadraticISum -= (int64_t)(plist[i] * plist[i]); \
149
    }                                                              \
150
  } while (0)
151

152
#define LEASTSQR_CAL(p, x, y, index, step) \
153
  do {                                     \
154
    (p)[0][0] += (double)(x) * (x);        \
155
    (p)[0][1] += (double)(x);              \
156
    (p)[0][2] += (double)(x) * (y)[index]; \
157
    (p)[1][2] += (y)[index];               \
158
    (x) += step;                           \
159
  } while (0)
160

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

163
#define GET_STATE_VAL(param) ((param.nType == TSDB_DATA_TYPE_BIGINT) ? (param.i) : (param.d))
164

165
#define STATE_COMP_IMPL(_op, _lval, _rval) \
166
  do {                                     \
167
    switch (_op) {                         \
168
      case STATE_OPER_LT:                  \
169
        return ((_lval) < (_rval));        \
170
        break;                             \
171
      case STATE_OPER_GT:                  \
172
        return ((_lval) > (_rval));        \
173
        break;                             \
174
      case STATE_OPER_LE:                  \
175
        return ((_lval) <= (_rval));       \
176
        break;                             \
177
      case STATE_OPER_GE:                  \
178
        return ((_lval) >= (_rval));       \
179
        break;                             \
180
      case STATE_OPER_NE:                  \
181
        return ((_lval) != (_rval));       \
182
        break;                             \
183
      case STATE_OPER_EQ:                  \
184
        return ((_lval) == (_rval));       \
185
        break;                             \
186
      default:                             \
187
        break;                             \
188
    }                                      \
189
  } while (0)
190

191
#define INIT_INTP_POINT(_p, _k, _v) \
192
  do {                              \
193
    (_p).key = (_k);                \
194
    (_p).val = (_v);                \
195
  } while (0)
196

197
void funcInputUpdate(SqlFunctionCtx* pCtx) {
15,224,645✔
198
  SFuncInputRowIter* pIter = &pCtx->rowIter;
15,224,645✔
199

200
  if (!pCtx->bInputFinished) {
15,224,645!
201
    pIter->pInput = &pCtx->input;
15,224,664✔
202
    pIter->tsList = (TSKEY*)pIter->pInput->pPTS->pData;
15,224,664✔
203
    pIter->pDataCol = pIter->pInput->pData[0];
15,224,664✔
204
    pIter->pPkCol = pIter->pInput->pPrimaryKey;
15,224,664✔
205
    pIter->rowIndex = pIter->pInput->startRowIndex;
15,224,664✔
206
    pIter->inputEndIndex = pIter->rowIndex + pIter->pInput->numOfRows - 1;
15,224,664✔
207
    pIter->pSrcBlock = pCtx->pSrcBlock;
15,224,664✔
208
    if (!pIter->hasGroupId || pIter->groupId != pIter->pSrcBlock->info.id.groupId) {
15,224,664✔
209
      pIter->hasGroupId = true;
199,681✔
210
      pIter->groupId = pIter->pSrcBlock->info.id.groupId;
199,681✔
211
      pIter->hasPrev = false;
199,681✔
212
    }
213
  } else {
214
    pIter->finalRow = true;
×
215
  }
216
}
15,224,645✔
217

218
int32_t funcInputGetNextRowDescPk(SFuncInputRowIter* pIter, SFuncInputRow* pRow, bool *res) {
×
219
  if (pIter->finalRow) {
×
220
    if (pIter->hasPrev) {
×
221
      pRow->ts = pIter->prevBlockTsEnd;
×
222
      pRow->isDataNull = pIter->prevIsDataNull;
×
223
      pRow->pData = pIter->pPrevData;
×
224
      pRow->block = pIter->pPrevRowBlock;
×
225
      pRow->rowIndex = 0;
×
226
      
227
      pIter->hasPrev = false;
×
228
      *res = true;
×
229
      return TSDB_CODE_SUCCESS;
×
230
    } else {
231
      *res = false;
×
232
      return TSDB_CODE_SUCCESS;
×
233
    }
234
  }
235
  if (pIter->hasPrev) {
×
236
    if (pIter->prevBlockTsEnd == pIter->tsList[pIter->inputEndIndex]) {
×
237
      blockDataDestroy(pIter->pPrevRowBlock);
×
238
      int32_t code = blockDataExtractBlock(pIter->pSrcBlock, pIter->inputEndIndex, 1, &pIter->pPrevRowBlock);
×
239
      if (code) {
×
240
        return code;
×
241
      }
242

243
      pIter->prevIsDataNull = colDataIsNull_f(pIter->pDataCol->nullbitmap, pIter->inputEndIndex);
×
244

245
      pIter->pPrevData = taosMemoryMalloc(pIter->pDataCol->info.bytes);
×
246
      if (NULL == pIter->pPrevData) {
×
247
        qError("out of memory when function get input row.");
×
248
        return terrno;
×
249
      }
250
      char* srcData = colDataGetData(pIter->pDataCol, pIter->inputEndIndex);
×
251
      (void)memcpy(pIter->pPrevData, srcData, pIter->pDataCol->info.bytes);
×
252

253
      pIter->pPrevPk = taosMemoryMalloc(pIter->pPkCol->info.bytes);
×
254
      if (NULL == pIter->pPrevPk) {
×
255
        qError("out of memory when function get input row.");
×
256
        taosMemoryFree(pIter->pPrevData);
×
257
        return terrno;
×
258
      }
259
      char* pkData = colDataGetData(pIter->pPkCol, pIter->inputEndIndex);
×
260
      (void)memcpy(pIter->pPrevPk, pkData, pIter->pPkCol->info.bytes);
×
261

262
      code = blockDataExtractBlock(pIter->pSrcBlock, pIter->inputEndIndex, 1, &pIter->pPrevRowBlock);
×
263
      pIter->hasPrev = true;
×
264
      *res = false;
×
265
      return code;
×
266
    } else {
267
      int32_t idx = pIter->rowIndex;
×
268
      while (pIter->tsList[idx] == pIter->prevBlockTsEnd) {
×
269
        ++idx;
×
270
      }
271
      pRow->ts = pIter->prevBlockTsEnd;
×
272
      if (idx == pIter->pInput->startRowIndex) {
×
273
        pRow->isDataNull = pIter->prevIsDataNull;
×
274
        pRow->pData = pIter->pPrevData;
×
275
        pRow->block = pIter->pPrevRowBlock;
×
276
        pRow->rowIndex = 0;
×
277
      } else {
278
        pRow->ts = pIter->tsList[idx - 1];
×
279
        pRow->isDataNull = colDataIsNull_f(pIter->pDataCol->nullbitmap, idx - 1);
×
280
        pRow->pData = colDataGetData(pIter->pDataCol, idx - 1);
×
281
        pRow->pPk = colDataGetData(pIter->pPkCol, idx - 1);
×
282
        pRow->block = pIter->pSrcBlock;
×
283
        pRow->rowIndex = idx - 1;
×
284
      }
285
      pIter->hasPrev = false;
×
286
      pIter->rowIndex = idx;
×
287
      *res = true;
×
288
      return TSDB_CODE_SUCCESS;
×
289
    }
290
  } else {
291
    TSKEY tsEnd = pIter->tsList[pIter->inputEndIndex];
×
292
    if (pIter->tsList[pIter->rowIndex] != tsEnd) {
×
293
      int32_t idx = pIter->rowIndex;
×
294
      while (pIter->tsList[idx + 1] == pIter->tsList[pIter->rowIndex]) {
×
295
        ++idx;
×
296
      }
297
      pRow->ts = pIter->tsList[idx];
×
298
      pRow->isDataNull = colDataIsNull_f(pIter->pDataCol->nullbitmap, idx);
×
299
      pRow->pData = colDataGetData(pIter->pDataCol, idx);
×
300
      pRow->pPk = colDataGetData(pIter->pPkCol, idx);
×
301
      pRow->block = pIter->pSrcBlock;
×
302

303
      pIter->rowIndex = idx + 1;
×
304
      *res = true;
×
305
      return TSDB_CODE_SUCCESS;
×
306
    } else {
307
      pIter->hasPrev = true;
×
308
      pIter->prevBlockTsEnd = tsEnd;
×
309
      pIter->prevIsDataNull = colDataIsNull_f(pIter->pDataCol->nullbitmap, pIter->inputEndIndex);
×
310
      pIter->pPrevData = taosMemoryMalloc(pIter->pDataCol->info.bytes);
×
311
      if (NULL == pIter->pPrevData) {
×
312
        qError("out of memory when function get input row.");
×
313
        return terrno;
×
314
      }
315
      (void)memcpy(pIter->pPrevData, colDataGetData(pIter->pDataCol, pIter->inputEndIndex), pIter->pDataCol->info.bytes);
×
316
      pIter->pPrevPk = taosMemoryMalloc(pIter->pPkCol->info.bytes);
×
317
      if (NULL == pIter->pPrevPk) {
×
318
        qError("out of memory when function get input row.");
×
319
        taosMemoryFree(pIter->pPrevData);
×
320
        return terrno;
×
321
      }
322
      (void)memcpy(pIter->pPrevPk, colDataGetData(pIter->pPkCol, pIter->inputEndIndex), pIter->pPkCol->info.bytes);
×
323

324
      int32_t code = blockDataExtractBlock(pIter->pSrcBlock, pIter->inputEndIndex, 1, &pIter->pPrevRowBlock);
×
325
      *res = false;
×
326
      return code;
×
327
    }
328
  }
329
}
330

331
static void forwardToNextDiffTsRow(SFuncInputRowIter* pIter, int32_t rowIndex) {
27,710✔
332
  int32_t idx = rowIndex + 1;
27,710✔
333
  while (idx <= pIter->inputEndIndex && pIter->tsList[idx] == pIter->tsList[rowIndex]) {
399,678!
334
    ++idx;
371,968✔
335
  }
336
  pIter->rowIndex = idx;
27,710✔
337
}
27,710✔
338

339
static void setInputRowInfo(SFuncInputRow* pRow, SFuncInputRowIter* pIter, int32_t rowIndex, bool setPk) {
92,545,460✔
340
  pRow->ts = pIter->tsList[rowIndex];
92,545,460✔
341
  pRow->ts = pIter->tsList[rowIndex];
92,545,460✔
342
  pRow->isDataNull = colDataIsNull_f(pIter->pDataCol->nullbitmap, rowIndex);
92,545,460✔
343
  pRow->pData = colDataGetData(pIter->pDataCol, rowIndex);
92,545,460!
344
  pRow->pPk = setPk? colDataGetData(pIter->pPkCol, rowIndex):NULL;
92,545,460!
345
  pRow->block = pIter->pSrcBlock;
92,545,460✔
346
  pRow->rowIndex = rowIndex;
92,545,460✔
347
}
92,545,460✔
348

349
bool funcInputGetNextRowAscPk(SFuncInputRowIter *pIter, SFuncInputRow* pRow) {
36,184✔
350
  if (pIter->hasPrev) {
36,184✔
351
    if (pIter->prevBlockTsEnd == pIter->tsList[pIter->inputEndIndex]) {
2,826!
352
      pIter->hasPrev = true;
×
353
      return false;
×
354
    } else {
355
      int32_t idx = pIter->rowIndex;
2,826✔
356
      while (pIter->tsList[idx] == pIter->prevBlockTsEnd) {
2,826!
357
        ++idx;
×
358
      }
359

360
      pIter->hasPrev = false;
2,826✔
361
      setInputRowInfo(pRow, pIter, idx, true);
2,826✔
362
      forwardToNextDiffTsRow(pIter, idx);
2,826✔
363
      return true;
2,826✔
364
    }
365
  } else {
366
    if (pIter->rowIndex <= pIter->inputEndIndex) { 
33,358✔
367
      setInputRowInfo(pRow, pIter, pIter->rowIndex, true);
29,126✔
368

369
      TSKEY tsEnd = pIter->tsList[pIter->inputEndIndex];
29,126✔
370
      if (pIter->tsList[pIter->rowIndex] != tsEnd) {
29,126✔
371
        forwardToNextDiffTsRow(pIter, pIter->rowIndex);
24,884✔
372
      } else {
373
        pIter->rowIndex = pIter->inputEndIndex + 1;
4,242✔
374
      }
375
      return true;
29,126✔
376
    } else {
377
      TSKEY tsEnd = pIter->tsList[pIter->inputEndIndex];
4,232✔
378
      pIter->hasPrev = true;
4,232✔
379
      pIter->prevBlockTsEnd = tsEnd;
4,232✔
380
      return false;
4,232✔
381
    }
382
  }
383
}
384

385
bool funcInputGetNextRowNoPk(SFuncInputRowIter *pIter, SFuncInputRow* pRow) {
107,741,500✔
386
  if (pIter->rowIndex <= pIter->inputEndIndex) {
107,741,500✔
387
    setInputRowInfo(pRow, pIter, pIter->rowIndex, false);
92,513,747✔
388
    ++pIter->rowIndex;
92,515,024✔
389
    return true;    
92,515,024✔
390
  } else {
391
    return false;    
15,227,753✔
392
  }
393
}
394

395
int32_t funcInputGetNextRow(SqlFunctionCtx* pCtx, SFuncInputRow* pRow, bool *res) {
107,779,813✔
396
  SFuncInputRowIter* pIter = &pCtx->rowIter;
107,779,813✔
397
  if (pCtx->hasPrimaryKey) {
107,779,813✔
398
    if (pCtx->order == TSDB_ORDER_ASC) {
36,184!
399
      *res = funcInputGetNextRowAscPk(pIter, pRow);
36,184✔
400
      return TSDB_CODE_SUCCESS;
36,184✔
401
    } else {
402
      return funcInputGetNextRowDescPk(pIter, pRow, res);
×
403
    }
404
  } else {
405
    *res = funcInputGetNextRowNoPk(pIter, pRow);
107,743,629✔
406
    return TSDB_CODE_SUCCESS;
107,742,603✔
407
  }
408
  return TSDB_CODE_SUCCESS;
409
}
410

411
// This function append the selectivity to subsidiaries function context directly, without fetching data
412
// from intermediate disk based buf page
413
int32_t appendSelectivityCols(SqlFunctionCtx* pCtx, SSDataBlock* pSrcBlock, int32_t rowIndex, int32_t pos) {
37,334,379✔
414
  if (pCtx->subsidiaries.num <= 0) {
37,334,379!
415
    return TSDB_CODE_SUCCESS;
×
416
  }
417

418
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
100,374,638✔
419
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
63,040,259✔
420

421
    // get data from source col
422
    SFunctParam* pFuncParam = &pc->pExpr->base.pParam[0];
63,040,259✔
423
    int32_t      srcSlotId = pFuncParam->pCol->slotId;
63,040,259✔
424

425
    SColumnInfoData* pSrcCol = taosArrayGet(pSrcBlock->pDataBlock, srcSlotId);
63,040,259✔
426
    if (NULL == pSrcCol) {
63,040,259!
427
      return TSDB_CODE_OUT_OF_RANGE;
×
428
    }
429

430
    char* pData = colDataGetData(pSrcCol, rowIndex);
63,040,259!
431

432
    // append to dest col
433
    int32_t dstSlotId = pc->pExpr->base.resSchema.slotId;
63,040,259✔
434

435
    SColumnInfoData* pDstCol = taosArrayGet(pCtx->pDstBlock->pDataBlock, dstSlotId);
63,040,259✔
436
    if (NULL == pDstCol) {
63,040,259!
437
      return TSDB_CODE_OUT_OF_RANGE;
×
438
    }
439
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
126,080,518✔
440
      colDataSetNULL(pDstCol, pos);
2,580,095✔
441
    } else {
442
      int32_t code = colDataSetVal(pDstCol, pos, pData, false);
60,460,164✔
443
      if (TSDB_CODE_SUCCESS != code) {
60,460,164!
444
        return code;
×
445
      }
446
    }
447
  }
448
  return TSDB_CODE_SUCCESS;
37,334,379✔
449
}
450

451
bool funcInputGetNextRowIndex(SInputColumnInfoData* pInput, int32_t from, bool firstOccur, int32_t* pRowIndex, int32_t* nextFrom);
452

453
static bool firstLastTransferInfoImpl(SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst);
454

455
int32_t functionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
691,610,199✔
456
  if (pResultInfo->initialized) {
691,610,199✔
457
    return TSDB_CODE_SUCCESS;  // already initialized
44,297✔
458
  }
459

460
  if (pCtx->pOutput != NULL) {
691,565,902!
461
    (void)memset(pCtx->pOutput, 0, (size_t)pCtx->resDataInfo.bytes);
×
462
  }
463

464
  initResultRowEntry(pResultInfo, pCtx->resDataInfo.interBufSize);
691,565,902✔
465
  return TSDB_CODE_SUCCESS;
691,565,902✔
466
}
467

468
int32_t functionFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
185,171,964✔
469
  int32_t          code = TSDB_CODE_SUCCESS;
185,171,964✔
470
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
185,171,964✔
471
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
185,171,964✔
472
  if (NULL == pCol) {
184,656,228!
473
    return TSDB_CODE_OUT_OF_RANGE;
×
474
  }
475
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
184,656,228✔
476
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
184,656,228✔
477

478
  char* in = GET_ROWCELL_INTERBUF(pResInfo);
184,656,228✔
479
  code = colDataSetVal(pCol, pBlock->info.rows, in, pResInfo->isNullRes);
184,656,228✔
480

481
  return code;
186,199,378✔
482
}
483

484
int32_t firstCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
3✔
485
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
3✔
486
  SFirstLastRes*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
3✔
487
  int32_t              bytes = pDBuf->bytes;
3✔
488

489
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
3✔
490
  SFirstLastRes*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
3✔
491

492
  pDBuf->hasResult = firstLastTransferInfoImpl(pSBuf, pDBuf, true);
3✔
493

494
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
3✔
495
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
3✔
496
  return TSDB_CODE_SUCCESS;
3✔
497
}
498

499
int32_t functionFinalizeWithResultBuf(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, char* finalResult) {
1,083✔
500
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
1,083✔
501
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
1,083✔
502
  if (NULL == pCol) {
1,083!
503
    return TSDB_CODE_OUT_OF_RANGE;
×
504
  }
505
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,083✔
506
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
1,083✔
507

508
  char* in = finalResult;
1,083✔
509
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, in, pResInfo->isNullRes);
1,083✔
510

511
  return code;
1,083✔
512
}
513

514
EFuncDataRequired countDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
205,015✔
515
  SNode* pParam = nodesListGetNode(pFunc->pParameterList, 0);
205,015✔
516
  if (QUERY_NODE_COLUMN == nodeType(pParam) && PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)pParam)->colId) {
205,089!
517
    return FUNC_DATA_REQUIRED_NOT_LOAD;
147,759✔
518
  }
519
  return FUNC_DATA_REQUIRED_SMA_LOAD;
57,330✔
520
}
521

522
bool getCountFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
658,430✔
523
  pEnv->calcMemSize = sizeof(int64_t);
658,430✔
524
  return true;
658,430✔
525
}
526

527
static int64_t getNumOfElems(SqlFunctionCtx* pCtx) {
121,328,551✔
528
  int64_t numOfElem = 0;
121,328,551✔
529

530
  /*
531
   * 1. column data missing (schema modified) causes pInputCol->hasNull == true. pInput->colDataSMAIsSet == true;
532
   * 2. for general non-primary key columns, pInputCol->hasNull may be true or false, pInput->colDataSMAIsSet == true;
533
   * 3. for primary key column, pInputCol->hasNull always be false, pInput->colDataSMAIsSet == false;
534
   */
535
  SInputColumnInfoData* pInput = &pCtx->input;
121,328,551✔
536
  SColumnInfoData*      pInputCol = pInput->pData[0];
121,328,551✔
537
  if(1 == pInput->numOfRows && pInput->blankFill) {
121,328,551✔
538
    return 0;
453,987✔
539
  }
540
  if (pInput->colDataSMAIsSet && pInput->totalRows == pInput->numOfRows) {
120,874,564!
541
    numOfElem = pInput->numOfRows - pInput->pColumnDataAgg[0]->numOfNull;
4,468✔
542
  } else {
543
    if (pInputCol->hasNull) {
120,870,096✔
544
      for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
295,412,572✔
545
        if (colDataIsNull(pInputCol, pInput->totalRows, i, NULL)) {
527,129,688!
546
          continue;
4,375,771✔
547
        }
548
        numOfElem += 1;
259,189,073✔
549
      }
550
    } else {
551
      // when counting on the primary time stamp column and no statistics data is presented, use the size value
552
      // directly.
553
      numOfElem = pInput->numOfRows;
89,022,368✔
554
    }
555
  }
556
  return numOfElem;
120,874,564✔
557
}
558

559
/*
560
 * count function does need the finalize, if data is missing, the default value, which is 0, is used
561
 * count function does not use the pCtx->interResBuf to keep the intermediate buffer
562
 */
563
int32_t countFunction(SqlFunctionCtx* pCtx) {
121,334,676✔
564
  int64_t numOfElem = 0;
121,334,676✔
565

566
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
121,334,676✔
567
  SInputColumnInfoData* pInput = &pCtx->input;
121,334,676✔
568

569
  int32_t type = pInput->pData[0]->info.type;
121,334,676✔
570

571
  char* buf = GET_ROWCELL_INTERBUF(pResInfo);
121,334,676✔
572
  if (IS_NULL_TYPE(type)) {
121,334,676✔
573
    // select count(NULL) returns 0
574
    numOfElem = 1;
18,337✔
575
    *((int64_t*)buf) += 0;
18,337✔
576
  } else {
577
    numOfElem = getNumOfElems(pCtx);
121,316,339✔
578
    *((int64_t*)buf) += numOfElem;
120,911,421✔
579
  }
580

581
  if (tsCountAlwaysReturnValue) {
120,929,758!
582
    pResInfo->numOfRes = 1;
121,011,837✔
583
  } else {
584
    SET_VAL(pResInfo, *((int64_t*)buf), 1);
×
585
  }
586

587
  return TSDB_CODE_SUCCESS;
120,929,758✔
588
}
589

590
#ifdef BUILD_NO_CALL
591
int32_t countInvertFunction(SqlFunctionCtx* pCtx) {
592
  int64_t numOfElem = getNumOfElems(pCtx);
593

594
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
595
  char*                buf = GET_ROWCELL_INTERBUF(pResInfo);
596
  *((int64_t*)buf) -= numOfElem;
597

598
  SET_VAL(pResInfo, *((int64_t*)buf), 1);
599
  return TSDB_CODE_SUCCESS;
600
}
601
#endif
602

603
int32_t combineFunction(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
18✔
604
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
18✔
605
  char*                pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
18✔
606

607
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
18✔
608
  char*                pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
18✔
609
  *((int64_t*)pDBuf) += *((int64_t*)pSBuf);
18✔
610

611
  SET_VAL(pDResInfo, *((int64_t*)pDBuf), 1);
18!
612
  return TSDB_CODE_SUCCESS;
18✔
613
}
614

615
int32_t sumFunction(SqlFunctionCtx* pCtx) {
90,129,729✔
616
  int32_t numOfElem = 0;
90,129,729✔
617

618
  // Only the pre-computing information loaded and actual data does not loaded
619
  SInputColumnInfoData* pInput = &pCtx->input;
90,129,729✔
620
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
90,129,729✔
621
  int32_t               type = pInput->pData[0]->info.type;
90,129,729✔
622

623
  SSumRes* pSumRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
90,129,729✔
624
  pSumRes->type = type;
90,129,729✔
625

626
  if (IS_NULL_TYPE(type)) {
90,129,729✔
627
    numOfElem = 0;
260✔
628
    goto _sum_over;
260✔
629
  }
630

631
  if (pInput->colDataSMAIsSet) {
90,129,469✔
632
    numOfElem = pInput->numOfRows - pAgg->numOfNull;
3,050✔
633

634
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
3,050!
635
      pSumRes->isum += pAgg->sum;
3,050✔
636
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
637
      pSumRes->usum += pAgg->sum;
×
638
    } else if (IS_FLOAT_TYPE(type)) {
×
639
      pSumRes->dsum += GET_DOUBLE_VAL((const char*)&(pAgg->sum));
×
640
    }
641
  } else {  // computing based on the true data block
642
    SColumnInfoData* pCol = pInput->pData[0];
90,126,419✔
643

644
    int32_t start = pInput->startRowIndex;
90,126,419✔
645
    int32_t numOfRows = pInput->numOfRows;
90,126,419✔
646

647
    if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
90,126,419!
648
      if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
89,932,402!
649
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int8_t, numOfElem);
1,851,846✔
650
      } else if (type == TSDB_DATA_TYPE_SMALLINT) {
89,552,536✔
651
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int16_t, numOfElem);
5,919,863✔
652
      } else if (type == TSDB_DATA_TYPE_INT) {
87,559,483✔
653
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int32_t, numOfElem);
400,177,694✔
654
      } else if (type == TSDB_DATA_TYPE_BIGINT) {
21,687,299✔
655
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int64_t, numOfElem);
81,509,268✔
656
      }
657
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
194,017!
658
      if (type == TSDB_DATA_TYPE_UTINYINT) {
689✔
659
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint8_t, numOfElem);
130,039!
660
      } else if (type == TSDB_DATA_TYPE_USMALLINT) {
650✔
661
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint16_t, numOfElem);
130,047✔
662
      } else if (type == TSDB_DATA_TYPE_UINT) {
610✔
663
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint32_t, numOfElem);
133,526!
664
      } else if (type == TSDB_DATA_TYPE_UBIGINT) {
384!
665
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint64_t, numOfElem);
134,252✔
666
      }
667
    } else if (type == TSDB_DATA_TYPE_DOUBLE) {
193,328✔
668
      LIST_ADD_N(pSumRes->dsum, pCol, start, numOfRows, double, numOfElem);
2,189,980✔
669
    } else if (type == TSDB_DATA_TYPE_FLOAT) {
101,285✔
670
      LIST_ADD_N(pSumRes->dsum, pCol, start, numOfRows, float, numOfElem);
440,877✔
671
    }
672
  }
673

674
  // check for overflow
675
  if (IS_FLOAT_TYPE(type) && (isinf(pSumRes->dsum) || isnan(pSumRes->dsum))) {
90,129,469!
676
    numOfElem = 0;
×
677
  }
678

679
_sum_over:
90,436,242✔
680
  if (numOfElem == 0) {
90,129,729✔
681
    if (tsCountAlwaysReturnValue && pCtx->pExpr->pExpr->_function.pFunctNode->hasOriginalFunc &&
98,195✔
682
        fmIsCountLikeFunc(pCtx->pExpr->pExpr->_function.pFunctNode->originalFuncId)) {
11,861✔
683
      numOfElem = 1;
17✔
684
    }
685
  }
686
  // data in the check operation are all null, not output
687
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
90,129,729✔
688
  return TSDB_CODE_SUCCESS;
90,129,729✔
689
}
690

691
#ifdef BUILD_NO_CALL
692
int32_t sumInvertFunction(SqlFunctionCtx* pCtx) {
693
  int32_t numOfElem = 0;
694

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

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

702
  if (pInput->colDataSMAIsSet) {
703
    numOfElem = pInput->numOfRows - pAgg->numOfNull;
704

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

715
    int32_t start = pInput->startRowIndex;
716
    int32_t numOfRows = pInput->numOfRows;
717

718
    if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
719
      if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
720
        LIST_SUB_N(pSumRes->isum, pCol, start, numOfRows, int8_t, numOfElem);
721
      } else if (type == TSDB_DATA_TYPE_SMALLINT) {
722
        LIST_SUB_N(pSumRes->isum, pCol, start, numOfRows, int16_t, numOfElem);
723
      } else if (type == TSDB_DATA_TYPE_INT) {
724
        LIST_SUB_N(pSumRes->isum, pCol, start, numOfRows, int32_t, numOfElem);
725
      } else if (type == TSDB_DATA_TYPE_BIGINT) {
726
        LIST_SUB_N(pSumRes->isum, pCol, start, numOfRows, int64_t, numOfElem);
727
      }
728
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
729
      if (type == TSDB_DATA_TYPE_UTINYINT) {
730
        LIST_SUB_N(pSumRes->usum, pCol, start, numOfRows, uint8_t, numOfElem);
731
      } else if (type == TSDB_DATA_TYPE_USMALLINT) {
732
        LIST_SUB_N(pSumRes->usum, pCol, start, numOfRows, uint16_t, numOfElem);
733
      } else if (type == TSDB_DATA_TYPE_UINT) {
734
        LIST_SUB_N(pSumRes->usum, pCol, start, numOfRows, uint32_t, numOfElem);
735
      } else if (type == TSDB_DATA_TYPE_UBIGINT) {
736
        LIST_SUB_N(pSumRes->usum, pCol, start, numOfRows, uint64_t, numOfElem);
737
      }
738
    } else if (type == TSDB_DATA_TYPE_DOUBLE) {
739
      LIST_SUB_N(pSumRes->dsum, pCol, start, numOfRows, double, numOfElem);
740
    } else if (type == TSDB_DATA_TYPE_FLOAT) {
741
      LIST_SUB_N(pSumRes->dsum, pCol, start, numOfRows, float, numOfElem);
742
    }
743
  }
744

745
  // data in the check operation are all null, not output
746
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
747
  return TSDB_CODE_SUCCESS;
748
}
749
#endif
750

751
int32_t sumCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
45✔
752
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
45✔
753
  SSumRes*             pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
45✔
754

755
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
45✔
756
  SSumRes*             pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
45✔
757
  int16_t              type = pDBuf->type == TSDB_DATA_TYPE_NULL ? pSBuf->type : pDBuf->type;
45✔
758

759
  if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
45!
760
    pDBuf->isum += pSBuf->isum;
45✔
761
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
762
    pDBuf->usum += pSBuf->usum;
×
763
  } else if (type == TSDB_DATA_TYPE_DOUBLE || type == TSDB_DATA_TYPE_FLOAT) {
×
764
    pDBuf->dsum += pSBuf->dsum;
×
765
  }
766
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
45✔
767
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
45✔
768
  return TSDB_CODE_SUCCESS;
45✔
769
}
770

771
bool getSumFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
261,937✔
772
  pEnv->calcMemSize = sizeof(SSumRes);
261,937✔
773
  return true;
261,937✔
774
}
775

776
EFuncDataRequired statisDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
175,863✔
777
  return FUNC_DATA_REQUIRED_SMA_LOAD;
175,863✔
778
}
779

780
int32_t minmaxFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
49,920,777✔
781
  if (pResultInfo->initialized) {
49,920,777!
782
    return TSDB_CODE_SUCCESS;
×
783
  }
784
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
49,920,777!
785
    return TSDB_CODE_FUNC_SETUP_ERROR;  // not initialized since it has been initialized
×
786
  }
787

788
  SMinmaxResInfo* buf = GET_ROWCELL_INTERBUF(pResultInfo);
49,934,847✔
789
  buf->assign = false;
49,934,847✔
790
  buf->tuplePos.pageId = -1;
49,934,847✔
791

792
  buf->nullTupleSaved = false;
49,934,847✔
793
  buf->nullTuplePos.pageId = -1;
49,934,847✔
794
  buf->str = NULL;
49,934,847✔
795
  return TSDB_CODE_SUCCESS;
49,934,847✔
796
}
797

798
bool getMinmaxFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
494,351✔
799
  pEnv->calcMemSize = sizeof(SMinmaxResInfo);
494,351✔
800
  return true;
494,351✔
801
}
802

803
int32_t minFunction(SqlFunctionCtx* pCtx) {
23,436,067✔
804
  int32_t numOfElems = 0;
23,436,067✔
805
  int32_t code = doMinMaxHelper(pCtx, 1, &numOfElems);
23,436,067✔
806
  if (code != TSDB_CODE_SUCCESS) {
23,533,095!
807
    return code;
×
808
  }
809
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
23,533,095✔
810
  return TSDB_CODE_SUCCESS;
23,533,095✔
811
}
812

813
int32_t maxFunction(SqlFunctionCtx* pCtx) {
31,004,262✔
814
  int32_t numOfElems = 0;
31,004,262✔
815
  int32_t code = doMinMaxHelper(pCtx, 0, &numOfElems);
31,004,262✔
816
  if (code != TSDB_CODE_SUCCESS) {
31,095,868!
817
    return code;
×
818
  }
819
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
31,095,868✔
820
  return TSDB_CODE_SUCCESS;
31,095,868✔
821
}
822

823
static int32_t setNullSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t rowIndex);
824
static int32_t setSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, const STuplePos* pTuplePos,
825
                                   int32_t rowIndex);
826

827
int32_t minmaxFunctionFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
49,782,887✔
828
  int32_t code = TSDB_CODE_SUCCESS;
49,782,887✔
829

830
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
49,782,887✔
831
  SMinmaxResInfo*      pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
49,782,887✔
832

833
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
49,782,887✔
834
  int32_t currentRow = pBlock->info.rows;
49,782,887✔
835

836
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
49,782,887✔
837
  if (NULL == pCol) {
49,788,743!
838
    return TSDB_CODE_OUT_OF_RANGE;
×
839
  }
840
  pEntryInfo->isNullRes = (pEntryInfo->numOfRes == 0) ? 1 : 0;
49,788,743✔
841

842
  // NOTE: do nothing change it, for performance issue
843
  if (!pEntryInfo->isNullRes) {
49,788,743✔
844
    switch (pCol->info.type) {
42,963,724!
845
      case TSDB_DATA_TYPE_UBIGINT:
15,722,902✔
846
      case TSDB_DATA_TYPE_BIGINT:
847
        ((int64_t*)pCol->pData)[currentRow] = pRes->v;
15,722,902✔
848
        break;
15,722,902✔
849
      case TSDB_DATA_TYPE_UINT:
18,008,685✔
850
      case TSDB_DATA_TYPE_INT:
851
        colDataSetInt32(pCol, currentRow, (int32_t*)&pRes->v);
18,008,685✔
852
        break;
18,008,685✔
853
      case TSDB_DATA_TYPE_USMALLINT:
3,415,338✔
854
      case TSDB_DATA_TYPE_SMALLINT:
855
        colDataSetInt16(pCol, currentRow, (int16_t*)&pRes->v);
3,415,338✔
856
        break;
3,415,338✔
857
      case TSDB_DATA_TYPE_BOOL:
188,760✔
858
      case TSDB_DATA_TYPE_UTINYINT:
859
      case TSDB_DATA_TYPE_TINYINT:
860
        colDataSetInt8(pCol, currentRow, (int8_t*)&pRes->v);
188,760✔
861
        break;
188,760✔
862
      case TSDB_DATA_TYPE_DOUBLE:
218,061✔
863
        colDataSetDouble(pCol, currentRow, (double*)&pRes->v);
218,061✔
864
        break;
218,061✔
865
      case TSDB_DATA_TYPE_FLOAT: {
2,460,697✔
866
        float v = GET_FLOAT_VAL(&pRes->v);
2,460,697✔
867
        colDataSetFloat(pCol, currentRow, &v);
2,460,697✔
868
        break;
2,460,697✔
869
      }
870
      case TSDB_DATA_TYPE_VARBINARY:
2,981,106✔
871
      case TSDB_DATA_TYPE_VARCHAR:
872
      case TSDB_DATA_TYPE_NCHAR: {
873
        code = colDataSetVal(pCol, currentRow, pRes->str, false);
2,981,106✔
874
        if (TSDB_CODE_SUCCESS != code) {
2,981,106!
875
          return code;
×
876
        }
877
        break;
2,981,106✔
878
      }
879
    }
880
  } else {
881
    colDataSetNULL(pCol, currentRow);
6,825,019!
882
  }
883

884
  taosMemoryFreeClear(pRes->str);
49,788,743✔
885
  if (pCtx->subsidiaries.num > 0) {
49,788,743✔
886
    if (pEntryInfo->numOfRes > 0) {
10,712,300✔
887
      code = setSelectivityValue(pCtx, pBlock, &pRes->tuplePos, currentRow);
10,709,729✔
888
    } else {
889
      code = setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, currentRow);
2,571✔
890
    }
891
  }
892

893
  return code;
49,804,964✔
894
}
895

896
#ifdef BUILD_NO_CALL
897
int32_t setNullSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t rowIndex) {
898
  if (pCtx->subsidiaries.num <= 0) {
899
    return TSDB_CODE_SUCCESS;
900
  }
901

902
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
903
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
904
    int32_t         dstSlotId = pc->pExpr->base.resSchema.slotId;
905

906
    SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId);
907
    colDataSetNULL(pDstCol, rowIndex);
908
  }
909

910
  return TSDB_CODE_SUCCESS;
911
}
912
#endif
913

914
int32_t setSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, const STuplePos* pTuplePos, int32_t rowIndex) {
253,809,763✔
915
  if (pCtx->subsidiaries.num <= 0) {
253,809,763✔
916
    return TSDB_CODE_SUCCESS;
139,248,894✔
917
  }
918

919
  if ((pCtx->saveHandle.pBuf != NULL && pTuplePos->pageId != -1) ||
114,560,869!
920
      (pCtx->saveHandle.pState && pTuplePos->streamTupleKey.ts > 0)) {
×
921
    int32_t     numOfCols = pCtx->subsidiaries.num;
114,587,568✔
922
    char* p = NULL;
114,587,568✔
923
    int32_t code = loadTupleData(pCtx, pTuplePos, &p);
114,587,568✔
924
    if (p == NULL || TSDB_CODE_SUCCESS != code) {
115,200,929!
925
      qError("Load tuple data failed since %s, groupId:%" PRIu64 ", ts:%" PRId64, terrstr(),
×
926
             pTuplePos->streamTupleKey.groupId, pTuplePos->streamTupleKey.ts);
927
      return TSDB_CODE_NOT_FOUND;
×
928
    }
929

930
    bool* nullList = (bool*)p;
115,205,350✔
931
    char* pStart = (char*)(nullList + numOfCols * sizeof(bool));
115,205,350✔
932

933
    // todo set the offset value to optimize the performance.
934
    for (int32_t j = 0; j < numOfCols; ++j) {
230,169,713✔
935
      SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
115,232,479✔
936
      int32_t         dstSlotId = pc->pExpr->base.resSchema.slotId;
115,232,479✔
937

938
      // group_key function has its own process function
939
      // do not process there
940
      if (fmIsGroupKeyFunc(pc->functionId)) {
115,232,479✔
941
        continue;
38,835✔
942
      }
943

944
      SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId);
115,201,106✔
945
      if (NULL == pDstCol) {
115,065,630!
946
        return TSDB_CODE_OUT_OF_RANGE;
×
947
      }
948
      if (nullList[j]) {
115,065,630✔
949
        colDataSetNULL(pDstCol, rowIndex);
320!
950
      } else {
951
        code = colDataSetVal(pDstCol, rowIndex, pStart, false);
115,065,310✔
952
        if (TSDB_CODE_SUCCESS != code) {
114,925,208!
953
          return code;
×
954
        }
955
      }
956
      pStart += pDstCol->info.bytes;
114,925,528✔
957
    }
958
  }
959

960
  return TSDB_CODE_SUCCESS;
114,910,535✔
961
}
962

963
// This function append the selectivity to subsidiaries function context directly, without fetching data
964
// from intermediate disk based buf page
965
int32_t appendSelectivityValue(SqlFunctionCtx* pCtx, int32_t rowIndex, int32_t pos) {
34,807,244✔
966
  if (pCtx->subsidiaries.num <= 0) {
34,807,244!
967
    return TSDB_CODE_SUCCESS;
×
968
  }
969

970
  int32_t code = TSDB_CODE_SUCCESS;
34,807,244✔
971
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
69,617,442✔
972
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
34,810,198✔
973

974
    // get data from source col
975
    SFunctParam* pFuncParam = &pc->pExpr->base.pParam[0];
34,810,198✔
976
    int32_t      srcSlotId = pFuncParam->pCol->slotId;
34,810,198✔
977

978
    SColumnInfoData* pSrcCol = taosArrayGet(pCtx->pSrcBlock->pDataBlock, srcSlotId);
34,810,198✔
979
    if (NULL == pSrcCol) {
34,810,198!
980
      return TSDB_CODE_OUT_OF_RANGE;
×
981
    }
982

983
    char* pData = colDataGetData(pSrcCol, rowIndex);
34,810,198!
984

985
    // append to dest col
986
    int32_t dstSlotId = pc->pExpr->base.resSchema.slotId;
34,810,198✔
987

988
    SColumnInfoData* pDstCol = taosArrayGet(pCtx->pDstBlock->pDataBlock, dstSlotId);
34,810,198✔
989
    if (NULL == pDstCol) {
34,810,198!
990
      return TSDB_CODE_OUT_OF_RANGE;
×
991
    }
992

993
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
69,620,396✔
994
      colDataSetNULL(pDstCol, pos);
560✔
995
    } else {
996
      code = colDataSetVal(pDstCol, pos, pData, false);
34,809,638✔
997
      if (TSDB_CODE_SUCCESS != code) {
34,809,638!
998
        return code;
×
999
      }
1000
    }
1001
  }
1002
  return code;
34,807,244✔
1003
}
1004

1005
void replaceTupleData(STuplePos* pDestPos, STuplePos* pSourcePos) { *pDestPos = *pSourcePos; }
32✔
1006

1007
#define COMPARE_MINMAX_DATA(type) (( (*(type*)&pDBuf->v) < (*(type*)&pSBuf->v) ) ^ isMinFunc)
1008
int32_t minMaxCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx, int32_t isMinFunc) {
57✔
1009
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
57✔
1010
  SMinmaxResInfo*      pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
57✔
1011

1012
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
57✔
1013
  SMinmaxResInfo*      pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
57✔
1014
  int16_t              type = pDBuf->type == TSDB_DATA_TYPE_NULL ? pSBuf->type : pDBuf->type;
57✔
1015

1016
  switch (type) {
57!
1017
    case TSDB_DATA_TYPE_DOUBLE:
3✔
1018
    case TSDB_DATA_TYPE_UBIGINT:
1019
    case TSDB_DATA_TYPE_BIGINT:
1020
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(int64_t) || !pDBuf->assign)) {
3!
1021
        pDBuf->v = pSBuf->v;
1✔
1022
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
1✔
1023
        pDBuf->assign = true;
1✔
1024
      }
1025
      break;
3✔
1026
    case TSDB_DATA_TYPE_UINT:
54✔
1027
    case TSDB_DATA_TYPE_INT:
1028
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(int32_t) || !pDBuf->assign)) {
54!
1029
        pDBuf->v = pSBuf->v;
31✔
1030
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
31✔
1031
        pDBuf->assign = true;
31✔
1032
      }
1033
      break;
54✔
1034
    case TSDB_DATA_TYPE_USMALLINT:
×
1035
    case TSDB_DATA_TYPE_SMALLINT:
1036
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(int16_t) || !pDBuf->assign)) {
×
1037
        pDBuf->v = pSBuf->v;
×
1038
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1039
        pDBuf->assign = true;
×
1040
      }
1041
      break;
×
1042
    case TSDB_DATA_TYPE_BOOL:
×
1043
    case TSDB_DATA_TYPE_UTINYINT:
1044
    case TSDB_DATA_TYPE_TINYINT:
1045
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(int8_t) || !pDBuf->assign)) {
×
1046
        pDBuf->v = pSBuf->v;
×
1047
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1048
        pDBuf->assign = true;
×
1049
      }
1050
      break;
×
1051
    case TSDB_DATA_TYPE_FLOAT: {
×
1052
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(double) || !pDBuf->assign)) {
×
1053
        pDBuf->v = pSBuf->v;
×
1054
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1055
        pDBuf->assign = true;
×
1056
      }
1057
      break;
×
1058
    }
1059
    default:
×
1060
      if (pSBuf->assign && (strcmp((char*)&pDBuf->v, (char*)&pSBuf->v) || !pDBuf->assign)) {
×
1061
        pDBuf->v = pSBuf->v;
×
1062
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1063
        pDBuf->assign = true;
×
1064
      }
1065
      break;
×
1066
  }
1067
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
57✔
1068
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
57✔
1069
  return TSDB_CODE_SUCCESS;
57✔
1070
}
1071

1072
int32_t minCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
11✔
1073
  return minMaxCombine(pDestCtx, pSourceCtx, 1);
11✔
1074
}
1075
int32_t maxCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
46✔
1076
  return minMaxCombine(pDestCtx, pSourceCtx, 0);
46✔
1077
}
1078

1079
int32_t getStdInfoSize() { return (int32_t)sizeof(SStdRes); }
499,914✔
1080

1081
bool getStdFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
98,893✔
1082
  pEnv->calcMemSize = sizeof(SStdRes);
98,893✔
1083
  return true;
98,893✔
1084
}
1085

1086
int32_t stdFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
2,675,160✔
1087
  if (pResultInfo->initialized) {
2,675,160!
1088
    return TSDB_CODE_SUCCESS;
×
1089
  }
1090
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
2,675,160!
1091
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1092
  }
1093

1094
  SStdRes* pRes = GET_ROWCELL_INTERBUF(pResultInfo);
2,675,168✔
1095
  (void)memset(pRes, 0, sizeof(SStdRes));
2,675,168✔
1096
  return TSDB_CODE_SUCCESS;
2,675,168✔
1097
}
1098

1099
int32_t stdFunction(SqlFunctionCtx* pCtx) {
2,200,981✔
1100
  int32_t numOfElem = 0;
2,200,981✔
1101

1102
  // Only the pre-computing information loaded and actual data does not loaded
1103
  SInputColumnInfoData* pInput = &pCtx->input;
2,200,981✔
1104
  int32_t               type = pInput->pData[0]->info.type;
2,200,981✔
1105

1106
  SStdRes* pStdRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,200,981✔
1107
  pStdRes->type = type;
2,200,981✔
1108

1109
  // computing based on the true data block
1110
  SColumnInfoData* pCol = pInput->pData[0];
2,200,981✔
1111

1112
  int32_t start = pInput->startRowIndex;
2,200,981✔
1113
  int32_t numOfRows = pInput->numOfRows;
2,200,981✔
1114

1115
  if (IS_NULL_TYPE(type)) {
2,200,981✔
1116
    numOfElem = 0;
57✔
1117
    goto _stddev_over;
57✔
1118
  }
1119

1120
  switch (type) {
2,200,924✔
1121
    case TSDB_DATA_TYPE_TINYINT: {
823,806✔
1122
      int8_t* plist = (int8_t*)pCol->pData;
823,806✔
1123
      for (int32_t i = start; i < numOfRows + start; ++i) {
3,090,569✔
1124
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
2,266,763✔
1125
          continue;
168,751✔
1126
        }
1127

1128
        numOfElem += 1;
2,098,012✔
1129
        pStdRes->count += 1;
2,098,012✔
1130
        pStdRes->isum += plist[i];
2,098,012✔
1131
        pStdRes->quadraticISum += plist[i] * plist[i];
2,098,012✔
1132
      }
1133

1134
      break;
823,806✔
1135
    }
1136

1137
    case TSDB_DATA_TYPE_SMALLINT: {
240,704✔
1138
      int16_t* plist = (int16_t*)pCol->pData;
240,704✔
1139
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
1,739,829✔
1140
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
1,499,125✔
1141
          continue;
41,871✔
1142
        }
1143

1144
        numOfElem += 1;
1,457,254✔
1145
        pStdRes->count += 1;
1,457,254✔
1146
        pStdRes->isum += plist[i];
1,457,254✔
1147
        pStdRes->quadraticISum += plist[i] * plist[i];
1,457,254✔
1148
      }
1149
      break;
240,704✔
1150
    }
1151

1152
    case TSDB_DATA_TYPE_INT: {
1,042,627✔
1153
      int32_t* plist = (int32_t*)pCol->pData;
1,042,627✔
1154
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
3,698,594✔
1155
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
2,655,967✔
1156
          continue;
90,366✔
1157
        }
1158

1159
        numOfElem += 1;
2,565,601✔
1160
        pStdRes->count += 1;
2,565,601✔
1161
        pStdRes->isum += plist[i];
2,565,601✔
1162
        pStdRes->quadraticISum += plist[i] * plist[i];
2,565,601✔
1163
      }
1164

1165
      break;
1,042,627✔
1166
    }
1167

1168
    case TSDB_DATA_TYPE_BIGINT: {
26,656✔
1169
      int64_t* plist = (int64_t*)pCol->pData;
26,656✔
1170
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
1,056,390✔
1171
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
1,029,734✔
1172
          continue;
106,155✔
1173
        }
1174

1175
        numOfElem += 1;
923,579✔
1176
        pStdRes->count += 1;
923,579✔
1177
        pStdRes->isum += plist[i];
923,579✔
1178
        pStdRes->quadraticISum += plist[i] * plist[i];
923,579✔
1179
      }
1180
      break;
26,656✔
1181
    }
1182

1183
    case TSDB_DATA_TYPE_UTINYINT: {
25✔
1184
      uint8_t* plist = (uint8_t*)pCol->pData;
25✔
1185
      for (int32_t i = start; i < numOfRows + start; ++i) {
80,032✔
1186
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
80,007!
1187
          continue;
4✔
1188
        }
1189

1190
        numOfElem += 1;
80,003✔
1191
        pStdRes->count += 1;
80,003✔
1192
        pStdRes->usum += plist[i];
80,003✔
1193
        pStdRes->quadraticUSum += plist[i] * plist[i];
80,003✔
1194
      }
1195

1196
      break;
25✔
1197
    }
1198

1199
    case TSDB_DATA_TYPE_USMALLINT: {
24✔
1200
      uint16_t* plist = (uint16_t*)pCol->pData;
24✔
1201
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
80,024✔
1202
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
80,000!
1203
          continue;
×
1204
        }
1205

1206
        numOfElem += 1;
80,000✔
1207
        pStdRes->count += 1;
80,000✔
1208
        pStdRes->usum += plist[i];
80,000✔
1209
        pStdRes->quadraticUSum += plist[i] * plist[i];
80,000✔
1210
      }
1211
      break;
24✔
1212
    }
1213

1214
    case TSDB_DATA_TYPE_UINT: {
25✔
1215
      uint32_t* plist = (uint32_t*)pCol->pData;
25✔
1216
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
80,030✔
1217
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
80,005!
1218
          continue;
×
1219
        }
1220

1221
        numOfElem += 1;
80,005✔
1222
        pStdRes->count += 1;
80,005✔
1223
        pStdRes->usum += plist[i];
80,005✔
1224
        pStdRes->quadraticUSum += plist[i] * plist[i];
80,005✔
1225
      }
1226

1227
      break;
25✔
1228
    }
1229

1230
    case TSDB_DATA_TYPE_UBIGINT: {
24✔
1231
      uint64_t* plist = (uint64_t*)pCol->pData;
24✔
1232
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
80,024✔
1233
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
80,000!
1234
          continue;
×
1235
        }
1236

1237
        numOfElem += 1;
80,000✔
1238
        pStdRes->count += 1;
80,000✔
1239
        pStdRes->usum += plist[i];
80,000✔
1240
        pStdRes->quadraticUSum += plist[i] * plist[i];
80,000✔
1241
      }
1242
      break;
24✔
1243
    }
1244

1245
    case TSDB_DATA_TYPE_FLOAT: {
16,091✔
1246
      float* plist = (float*)pCol->pData;
16,091✔
1247
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
1,901,090✔
1248
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
1,884,999✔
1249
          continue;
27,599✔
1250
        }
1251

1252
        numOfElem += 1;
1,857,400✔
1253
        pStdRes->count += 1;
1,857,400✔
1254
        pStdRes->dsum += plist[i];
1,857,400✔
1255
        pStdRes->quadraticDSum += plist[i] * plist[i];
1,857,400✔
1256
      }
1257
      break;
16,091✔
1258
    }
1259

1260
    case TSDB_DATA_TYPE_DOUBLE: {
50,940✔
1261
      double* plist = (double*)pCol->pData;
50,940✔
1262
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
2,184,821✔
1263
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
2,133,881✔
1264
          continue;
582,022✔
1265
        }
1266

1267
        numOfElem += 1;
1,551,859✔
1268
        pStdRes->count += 1;
1,551,859✔
1269
        pStdRes->dsum += plist[i];
1,551,859✔
1270
        pStdRes->quadraticDSum += plist[i] * plist[i];
1,551,859✔
1271
      }
1272
      break;
50,940✔
1273
    }
1274

1275
    default:
2✔
1276
      break;
2✔
1277
  }
1278

1279
_stddev_over:
2,200,981✔
1280
  // data in the check operation are all null, not output
1281
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
2,200,981✔
1282
  return TSDB_CODE_SUCCESS;
2,200,981✔
1283
}
1284

1285
static void stdTransferInfo(SStdRes* pInput, SStdRes* pOutput) {
498,674✔
1286
  if (IS_NULL_TYPE(pInput->type)) {
498,674!
1287
    return;
×
1288
  }
1289
  pOutput->type = pInput->type;
498,674✔
1290
  if (IS_SIGNED_NUMERIC_TYPE(pOutput->type)) {
498,674!
1291
    pOutput->quadraticISum += pInput->quadraticISum;
496,462✔
1292
    pOutput->isum += pInput->isum;
496,462✔
1293
  } else if (IS_UNSIGNED_NUMERIC_TYPE(pOutput->type)) {
2,212!
1294
    pOutput->quadraticUSum += pInput->quadraticUSum;
1✔
1295
    pOutput->usum += pInput->usum;
1✔
1296
  } else {
1297
    pOutput->quadraticDSum += pInput->quadraticDSum;
2,211✔
1298
    pOutput->dsum += pInput->dsum;
2,211✔
1299
  }
1300

1301
  pOutput->count += pInput->count;
498,674✔
1302
}
1303

1304
int32_t stdFunctionMerge(SqlFunctionCtx* pCtx) {
498,601✔
1305
  SInputColumnInfoData* pInput = &pCtx->input;
498,601✔
1306
  SColumnInfoData*      pCol = pInput->pData[0];
498,601✔
1307

1308
  if (IS_NULL_TYPE(pCol->info.type)) {
498,601!
1309
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
1310
    return TSDB_CODE_SUCCESS;
×
1311
  }
1312

1313
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
498,601!
1314
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
1315
  }
1316

1317
  SStdRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
498,601✔
1318

1319
  for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
997,272✔
1320
    if (colDataIsNull_s(pCol, i)) continue;
997,342!
1321
    char*       data = colDataGetData(pCol, i);
498,671!
1322
    SStdRes*    pInputInfo = (SStdRes*)varDataVal(data);
498,671✔
1323
    stdTransferInfo(pInputInfo, pInfo);
498,671✔
1324
  }
1325

1326
  SET_VAL(GET_RES_INFO(pCtx), 1, 1);
498,601✔
1327
  return TSDB_CODE_SUCCESS;
498,601✔
1328
}
1329

1330
#ifdef BUILD_NO_CALL
1331
int32_t stdInvertFunction(SqlFunctionCtx* pCtx) {
1332
  int32_t numOfElem = 0;
1333

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

1338
  SStdRes* pStdRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1339

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

1343
  int32_t start = pInput->startRowIndex;
1344
  int32_t numOfRows = pInput->numOfRows;
1345

1346
  switch (type) {
1347
    case TSDB_DATA_TYPE_TINYINT: {
1348
      LIST_STDDEV_SUB_N(pStdRes->isum, int8_t);
1349
      break;
1350
    }
1351
    case TSDB_DATA_TYPE_SMALLINT: {
1352
      LIST_STDDEV_SUB_N(pStdRes->isum, int16_t);
1353
      break;
1354
    }
1355
    case TSDB_DATA_TYPE_INT: {
1356
      LIST_STDDEV_SUB_N(pStdRes->isum, int32_t);
1357
      break;
1358
    }
1359
    case TSDB_DATA_TYPE_BIGINT: {
1360
      LIST_STDDEV_SUB_N(pStdRes->isum, int64_t);
1361
      break;
1362
    }
1363
    case TSDB_DATA_TYPE_UTINYINT: {
1364
      LIST_STDDEV_SUB_N(pStdRes->isum, uint8_t);
1365
      break;
1366
    }
1367
    case TSDB_DATA_TYPE_USMALLINT: {
1368
      LIST_STDDEV_SUB_N(pStdRes->isum, uint16_t);
1369
      break;
1370
    }
1371
    case TSDB_DATA_TYPE_UINT: {
1372
      LIST_STDDEV_SUB_N(pStdRes->isum, uint32_t);
1373
      break;
1374
    }
1375
    case TSDB_DATA_TYPE_UBIGINT: {
1376
      LIST_STDDEV_SUB_N(pStdRes->isum, uint64_t);
1377
      break;
1378
    }
1379
    case TSDB_DATA_TYPE_FLOAT: {
1380
      LIST_STDDEV_SUB_N(pStdRes->dsum, float);
1381
      break;
1382
    }
1383
    case TSDB_DATA_TYPE_DOUBLE: {
1384
      LIST_STDDEV_SUB_N(pStdRes->dsum, double);
1385
      break;
1386
    }
1387
    default:
1388
      break;
1389
  }
1390

1391
  // data in the check operation are all null, not output
1392
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
1393
  return TSDB_CODE_SUCCESS;
1394
}
1395
#endif
1396

1397
int32_t stddevFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
2,143,308✔
1398
  SInputColumnInfoData* pInput = &pCtx->input;
2,143,308✔
1399
  SStdRes*              pStddevRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,143,308✔
1400
  int32_t               type = pStddevRes->type;
2,143,308✔
1401
  double                avg;
1402

1403
  if (pStddevRes->count == 0) {
2,143,308✔
1404
    GET_RES_INFO(pCtx)->numOfRes = 0;
48,113✔
1405
    return functionFinalize(pCtx, pBlock);
48,113✔
1406
  }
1407

1408
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
2,095,195!
1409
    avg = pStddevRes->isum / ((double)pStddevRes->count);
2,055,766✔
1410
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticISum / ((double)pStddevRes->count) - avg * avg));
2,055,766✔
1411
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
39,429!
1412
    avg = pStddevRes->usum / ((double)pStddevRes->count);
10✔
1413
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticUSum / ((double)pStddevRes->count) - avg * avg));
10✔
1414
  } else {
1415
    avg = pStddevRes->dsum / ((double)pStddevRes->count);
39,419✔
1416
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticDSum / ((double)pStddevRes->count) - avg * avg));
39,419✔
1417
  }
1418

1419
  // check for overflow
1420
  if (isinf(pStddevRes->result) || isnan(pStddevRes->result)) {
2,095,195!
1421
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1422
  }
1423

1424
  return functionFinalize(pCtx, pBlock);
2,095,195✔
1425
}
1426

1427
int32_t stdvarFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
×
1428
  SInputColumnInfoData* pInput = &pCtx->input;
×
1429
  SStdRes*              pStdvarRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
×
1430
  int32_t               type = pStdvarRes->type;
×
1431
  double                avg;
1432

1433
  if (pStdvarRes->count == 0) {
×
1434
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1435
    return functionFinalize(pCtx, pBlock);
×
1436
  }
1437

1438
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
×
1439
    avg = pStdvarRes->isum / ((double)pStdvarRes->count);
×
1440
    pStdvarRes->result = fabs(pStdvarRes->quadraticISum / ((double)pStdvarRes->count) - avg * avg);
×
1441
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
1442
    avg = pStdvarRes->usum / ((double)pStdvarRes->count);
×
1443
    pStdvarRes->result = fabs(pStdvarRes->quadraticUSum / ((double)pStdvarRes->count) - avg * avg);
×
1444
  } else {
1445
    avg = pStdvarRes->dsum / ((double)pStdvarRes->count);
×
1446
    pStdvarRes->result = fabs(pStdvarRes->quadraticDSum / ((double)pStdvarRes->count) - avg * avg);
×
1447
  }
1448

1449
  // check for overflow
1450
  if (isinf(pStdvarRes->result) || isnan(pStdvarRes->result)) {
×
1451
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1452
  }
1453

1454
  return functionFinalize(pCtx, pBlock);
×
1455
}
1456

1457
int32_t stdPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
498,581✔
1458
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
498,581✔
1459
  SStdRes*             pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
498,581✔
1460
  int32_t              resultBytes = getStdInfoSize();
498,581✔
1461
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
498,581✔
1462

1463
  if (NULL == res) {
498,581!
1464
    return terrno;
×
1465
  }
1466
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
498,581✔
1467
  varDataSetLen(res, resultBytes);
498,581✔
1468

1469
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
498,581✔
1470
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
498,581✔
1471
  if (NULL == pCol) {
498,582!
1472
    taosMemoryFree(res);
×
1473
    return TSDB_CODE_OUT_OF_RANGE;
×
1474
  }
1475

1476
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
498,582✔
1477

1478
  taosMemoryFree(res);
498,579✔
1479
  return code;
498,582✔
1480
}
1481

1482
int32_t stdCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
3✔
1483
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
3✔
1484
  SStdRes*             pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
3✔
1485

1486
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
3✔
1487
  SStdRes*             pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
3✔
1488
  int16_t              type = pDBuf->type == TSDB_DATA_TYPE_NULL ? pSBuf->type : pDBuf->type;
3!
1489

1490
  stdTransferInfo(pSBuf, pDBuf);
3✔
1491

1492
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
3✔
1493
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
3✔
1494
  return TSDB_CODE_SUCCESS;
3✔
1495
}
1496

1497
bool getLeastSQRFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
43,331✔
1498
  pEnv->calcMemSize = sizeof(SLeastSQRInfo);
43,331✔
1499
  return true;
43,331✔
1500
}
1501

1502
int32_t leastSQRFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
5,322,866✔
1503
  if (pResultInfo->initialized) {
5,322,866!
1504
    return TSDB_CODE_SUCCESS;
×
1505
  }
1506
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
5,322,866!
1507
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1508
  }
1509

1510
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
5,322,873✔
1511

1512
  GET_TYPED_DATA(pInfo->startVal, double, pCtx->param[1].param.nType, &pCtx->param[1].param.i);
5,322,873!
1513
  GET_TYPED_DATA(pInfo->stepVal, double, pCtx->param[2].param.nType, &pCtx->param[2].param.i);
5,322,873!
1514
  return TSDB_CODE_SUCCESS;
5,322,873✔
1515
}
1516

1517
int32_t leastSQRFunction(SqlFunctionCtx* pCtx) {
6,286,509✔
1518
  int32_t numOfElem = 0;
6,286,509✔
1519

1520
  SInputColumnInfoData* pInput = &pCtx->input;
6,286,509✔
1521
  int32_t               type = pInput->pData[0]->info.type;
6,286,509✔
1522

1523
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
6,286,509✔
1524

1525
  SColumnInfoData* pCol = pInput->pData[0];
6,286,509✔
1526

1527
  double(*param)[3] = pInfo->matrix;
6,286,509✔
1528
  double x = pInfo->startVal;
6,286,509✔
1529

1530
  int32_t start = pInput->startRowIndex;
6,286,509✔
1531
  int32_t numOfRows = pInput->numOfRows;
6,286,509✔
1532

1533
  switch (type) {
6,286,509!
1534
    case TSDB_DATA_TYPE_TINYINT: {
9,701✔
1535
      int8_t* plist = (int8_t*)pCol->pData;
9,701✔
1536
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
378,678✔
1537
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
368,977✔
1538
          continue;
286,217✔
1539
        }
1540
        numOfElem++;
82,760✔
1541
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
82,760✔
1542
      }
1543
      break;
9,701✔
1544
    }
1545
    case TSDB_DATA_TYPE_SMALLINT: {
3,158✔
1546
      int16_t* plist = (int16_t*)pCol->pData;
3,158✔
1547
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
86,978✔
1548
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
83,820✔
1549
          continue;
1,660✔
1550
        }
1551

1552
        numOfElem++;
82,160✔
1553
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
82,160✔
1554
      }
1555
      break;
3,158✔
1556
    }
1557

1558
    case TSDB_DATA_TYPE_INT: {
17,469✔
1559
      int32_t* plist = (int32_t*)pCol->pData;
17,469✔
1560
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
1,402,545✔
1561
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
1,385,076✔
1562
          continue;
139,109✔
1563
        }
1564

1565
        numOfElem++;
1,245,967✔
1566
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
1,245,967✔
1567
      }
1568
      break;
17,469✔
1569
    }
1570

1571
    case TSDB_DATA_TYPE_BIGINT: {
1,850,812✔
1572
      int64_t* plist = (int64_t*)pCol->pData;
1,850,812✔
1573
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
6,048,045✔
1574
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
4,197,233✔
1575
          continue;
137,943✔
1576
        }
1577

1578
        numOfElem++;
4,059,290✔
1579
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
4,059,290✔
1580
      }
1581
      break;
1,850,812✔
1582
    }
1583

1584
    case TSDB_DATA_TYPE_UTINYINT: {
154✔
1585
      uint8_t* plist = (uint8_t*)pCol->pData;
154✔
1586
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
80,574✔
1587
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
80,420!
1588
          continue;
110✔
1589
        }
1590
        numOfElem++;
80,310✔
1591
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
80,310✔
1592
      }
1593
      break;
154✔
1594
    }
1595
    case TSDB_DATA_TYPE_USMALLINT: {
154✔
1596
      uint16_t* plist = (uint16_t*)pCol->pData;
154✔
1597
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
80,574✔
1598
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
80,420!
1599
          continue;
100✔
1600
        }
1601

1602
        numOfElem++;
80,320✔
1603
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
80,320✔
1604
      }
1605
      break;
154✔
1606
    }
1607

1608
    case TSDB_DATA_TYPE_UINT: {
154✔
1609
      uint32_t* plist = (uint32_t*)pCol->pData;
154✔
1610
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
80,574✔
1611
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
80,420!
1612
          continue;
100✔
1613
        }
1614

1615
        numOfElem++;
80,320✔
1616
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
80,320✔
1617
      }
1618
      break;
154✔
1619
    }
1620

1621
    case TSDB_DATA_TYPE_UBIGINT: {
154✔
1622
      uint64_t* plist = (uint64_t*)pCol->pData;
154✔
1623
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
80,574✔
1624
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
80,420!
1625
          continue;
100✔
1626
        }
1627

1628
        numOfElem++;
80,320✔
1629
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
80,320✔
1630
      }
1631
      break;
154✔
1632
    }
1633

1634
    case TSDB_DATA_TYPE_FLOAT: {
4,366✔
1635
      float* plist = (float*)pCol->pData;
4,366✔
1636
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
90,186✔
1637
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
85,820✔
1638
          continue;
2,460✔
1639
        }
1640

1641
        numOfElem++;
83,360✔
1642
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
83,360✔
1643
      }
1644
      break;
4,366✔
1645
    }
1646

1647
    case TSDB_DATA_TYPE_DOUBLE: {
4,400,386✔
1648
      double* plist = (double*)pCol->pData;
4,400,386✔
1649
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
14,522,039✔
1650
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
10,121,653✔
1651
          continue;
1,860✔
1652
        }
1653

1654
        numOfElem++;
10,119,793✔
1655
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
10,119,793✔
1656
      }
1657
      break;
4,400,386✔
1658
    }
1659
    case TSDB_DATA_TYPE_NULL: {
×
1660
      GET_RES_INFO(pCtx)->isNullRes = 1;
×
1661
      numOfElem = 1;
×
1662
      break;
×
1663
    }
1664

1665
    default:
1✔
1666
      break;
1✔
1667
  }
1668

1669
  pInfo->startVal = x;
6,286,509✔
1670
  pInfo->num += numOfElem;
6,286,509✔
1671

1672
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
6,286,509✔
1673

1674
  return TSDB_CODE_SUCCESS;
6,286,509✔
1675
}
1676

1677
int32_t leastSQRFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
5,321,158✔
1678
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5,321,158✔
1679
  SLeastSQRInfo*       pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
5,321,158✔
1680
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
5,321,158✔
1681
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
5,321,158✔
1682

1683
  if (NULL == pCol) {
5,321,155!
1684
    return TSDB_CODE_OUT_OF_RANGE;
×
1685
  }
1686
  int32_t currentRow = pBlock->info.rows;
5,321,155✔
1687

1688
  if (0 == pInfo->num) {
5,321,155✔
1689
    colDataSetNULL(pCol, currentRow);
17,804!
1690
    return TSDB_CODE_SUCCESS;
17,804✔
1691
  }
1692

1693
  double(*param)[3] = pInfo->matrix;
5,303,351✔
1694

1695
  param[1][1] = (double)pInfo->num;
5,303,351✔
1696
  param[1][0] = param[0][1];
5,303,351✔
1697

1698
  double param00 = param[0][0] - param[1][0] * (param[0][1] / param[1][1]);
5,303,351✔
1699
  double param02 = param[0][2] - param[1][2] * (param[0][1] / param[1][1]);
5,303,351✔
1700

1701
  if (0 == param00) {
5,303,351✔
1702
    colDataSetNULL(pCol, currentRow);
3,731,391!
1703
    return TSDB_CODE_SUCCESS;
3,731,391✔
1704
  }
1705

1706
  // param[0][1] = 0;
1707
  double param12 = param[1][2] - param02 * (param[1][0] / param00);
1,571,960✔
1708
  // param[1][0] = 0;
1709
  param02 /= param00;
1,571,960✔
1710

1711
  param12 /= param[1][1];
1,571,960✔
1712

1713
  char buf[LEASTSQUARES_BUFF_LENGTH] = {0};
1,571,960✔
1714
  char slopBuf[64] = {0};
1,571,960✔
1715
  char interceptBuf[64] = {0};
1,571,960✔
1716
  int  n = tsnprintf(slopBuf, 64, "%.6lf", param02);
1,571,960✔
1717
  if (n > LEASTSQUARES_DOUBLE_ITEM_LENGTH) {
1,571,966✔
1718
    (void)snprintf(slopBuf, 64, "%." DOUBLE_PRECISION_DIGITS, param02);
10✔
1719
  }
1720
  n = tsnprintf(interceptBuf, 64, "%.6lf", param12);
1,571,966✔
1721
  if (n > LEASTSQUARES_DOUBLE_ITEM_LENGTH) {
1,571,967✔
1722
    (void)snprintf(interceptBuf, 64, "%." DOUBLE_PRECISION_DIGITS, param12);
126,316✔
1723
  }
1724
  size_t len =
1,571,967✔
1725
      snprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE, "{slop:%s, intercept:%s}", slopBuf, interceptBuf);
1,571,967✔
1726
  varDataSetLen(buf, len);
1,571,967✔
1727

1728
  int32_t code = colDataSetVal(pCol, currentRow, buf, pResInfo->isNullRes);
1,571,967✔
1729

1730
  return code;
1,571,967✔
1731
}
1732

1733
int32_t leastSQRCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
1734
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
1735
  SLeastSQRInfo*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
1736
  int32_t              type = pDestCtx->input.pData[0]->info.type;
×
1737
  double(*pDparam)[3] = pDBuf->matrix;
×
1738

1739
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
1740
  SLeastSQRInfo*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
1741
  double(*pSparam)[3] = pSBuf->matrix;
×
1742
  for (int32_t i = 0; i < pSBuf->num; i++) {
×
1743
    pDparam[0][0] += pDBuf->startVal * pDBuf->startVal;
×
1744
    pDparam[0][1] += pDBuf->startVal;
×
1745
    pDBuf->startVal += pDBuf->stepVal;
×
1746
  }
1747
  pDparam[0][2] += pSparam[0][2] + pDBuf->num * pDBuf->stepVal * pSparam[1][2];
×
1748
  pDparam[1][2] += pSparam[1][2];
×
1749
  pDBuf->num += pSBuf->num;
×
1750
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
1751
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
1752
  return TSDB_CODE_SUCCESS;
×
1753
}
1754

1755
bool getPercentileFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
954✔
1756
  pEnv->calcMemSize = sizeof(SPercentileInfo);
954✔
1757
  return true;
954✔
1758
}
1759

1760
int32_t percentileFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
5,518✔
1761
  if (pResultInfo->initialized) {
5,518!
1762
    return TSDB_CODE_SUCCESS;
×
1763
  }
1764
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
5,518!
1765
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1766
  }
1767

1768
  // in the first round, get the min-max value of all involved data
1769
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
5,518✔
1770
  SET_DOUBLE_VAL(&pInfo->minval, DBL_MAX);
5,518✔
1771
  SET_DOUBLE_VAL(&pInfo->maxval, -DBL_MAX);
5,518✔
1772
  pInfo->numOfElems = 0;
5,518✔
1773

1774
  return TSDB_CODE_SUCCESS;
5,518✔
1775
}
1776

1777
void percentileFunctionCleanupExt(SqlFunctionCtx* pCtx) {
×
1778
  if (pCtx == NULL || GET_RES_INFO(pCtx) == NULL || GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)) == NULL) {
×
1779
    return;
×
1780
  }
1781
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
×
1782
  if (pInfo->pMemBucket != NULL) {
×
1783
    tMemBucketDestroy(&(pInfo->pMemBucket));
×
1784
    pInfo->pMemBucket = NULL;
×
1785
  }
1786
}
1787

1788
int32_t percentileFunction(SqlFunctionCtx* pCtx) {
13,200✔
1789
  int32_t              code = TSDB_CODE_SUCCESS;
13,200✔
1790
  int32_t              numOfElems = 0;
13,200✔
1791
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
13,200✔
1792

1793
  SInputColumnInfoData* pInput = &pCtx->input;
13,200✔
1794
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
13,200✔
1795

1796
  SColumnInfoData* pCol = pInput->pData[0];
13,200✔
1797
  int32_t          type = pCol->info.type;
13,200✔
1798

1799
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
13,200✔
1800
  if (pCtx->scanFlag == MAIN_SCAN && pInfo->stage == 0) {
13,200✔
1801
    pInfo->stage += 1;
5,518✔
1802

1803
    // all data are null, set it completed
1804
    if (pInfo->numOfElems == 0) {
5,518✔
1805
      pResInfo->complete = true;
2,500✔
1806
      return TSDB_CODE_SUCCESS;
2,500✔
1807
    } else {
1808
      code = tMemBucketCreate(pCol->info.bytes, type, pInfo->minval, pInfo->maxval, pCtx->hasWindowOrGroup, &pInfo->pMemBucket, pInfo->numOfElems);
3,018✔
1809
      if (TSDB_CODE_SUCCESS != code) {
3,018!
1810
        return code;
×
1811
      }
1812
    }
1813
  }
1814

1815
  // the first stage, only acquire the min/max value
1816
  if (pInfo->stage == 0) {
10,700✔
1817
    if (pCtx->input.colDataSMAIsSet) {
6,658!
1818
      double tmin = 0.0, tmax = 0.0;
×
1819
      if (IS_SIGNED_NUMERIC_TYPE(type)) {
×
1820
        tmin = (double)GET_INT64_VAL(&pAgg->min);
×
1821
        tmax = (double)GET_INT64_VAL(&pAgg->max);
×
1822
      } else if (IS_FLOAT_TYPE(type)) {
×
1823
        tmin = GET_DOUBLE_VAL(&pAgg->min);
×
1824
        tmax = GET_DOUBLE_VAL(&pAgg->max);
×
1825
      } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
1826
        tmin = (double)GET_UINT64_VAL(&pAgg->min);
×
1827
        tmax = (double)GET_UINT64_VAL(&pAgg->max);
×
1828
      }
1829

1830
      if (GET_DOUBLE_VAL(&pInfo->minval) > tmin) {
×
1831
        SET_DOUBLE_VAL(&pInfo->minval, tmin);
×
1832
      }
1833

1834
      if (GET_DOUBLE_VAL(&pInfo->maxval) < tmax) {
×
1835
        SET_DOUBLE_VAL(&pInfo->maxval, tmax);
×
1836
      }
1837

1838
      pInfo->numOfElems += (pInput->numOfRows - pAgg->numOfNull);
×
1839
    } else {
1840
      // check the valid data one by one
1841
      int32_t start = pInput->startRowIndex;
6,658✔
1842
      for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
527,064✔
1843
        if (colDataIsNull_f(pCol->nullbitmap, i)) {
520,406✔
1844
          continue;
4,200✔
1845
        }
1846

1847
        char* data = colDataGetData(pCol, i);
516,206!
1848

1849
        double v = 0;
516,206✔
1850
        GET_TYPED_DATA(v, double, type, data);
516,206!
1851
        if (v < GET_DOUBLE_VAL(&pInfo->minval)) {
516,206✔
1852
          SET_DOUBLE_VAL(&pInfo->minval, v);
3,428✔
1853
        }
1854

1855
        if (v > GET_DOUBLE_VAL(&pInfo->maxval)) {
516,206✔
1856
          SET_DOUBLE_VAL(&pInfo->maxval, v);
410,454✔
1857
        }
1858

1859
        pInfo->numOfElems += 1;
516,206✔
1860
      }
1861
    }
1862
  } else {
1863
    // the second stage, calculate the true percentile value
1864
    int32_t start = pInput->startRowIndex;
4,042✔
1865
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
520,248✔
1866
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
516,206!
1867
        continue;
×
1868
      }
1869

1870
      char* data = colDataGetData(pCol, i);
516,206!
1871
      numOfElems += 1;
516,206✔
1872
      code = tMemBucketPut(pInfo->pMemBucket, data, 1);
516,206✔
1873
      if (code != TSDB_CODE_SUCCESS) {
516,206!
1874
        tMemBucketDestroy(&(pInfo->pMemBucket));
×
1875
        return code;
×
1876
      }
1877
    }
1878

1879
    SET_VAL(pResInfo, numOfElems, 1);
4,042!
1880
  }
1881

1882
  pCtx->needCleanup = true;
10,700✔
1883
  return TSDB_CODE_SUCCESS;
10,700✔
1884
}
1885

1886
int32_t percentileFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
5,518✔
1887
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5,518✔
1888
  SPercentileInfo*     ppInfo = (SPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
5,518✔
1889

1890
  int32_t code = 0;
5,518✔
1891
  double  v = 0;
5,518✔
1892

1893
  tMemBucket** pMemBucket = &ppInfo->pMemBucket;
5,518✔
1894
  if ((*pMemBucket) != NULL && (*pMemBucket)->total > 0) {  // check for null
5,518!
1895
    if (pCtx->numOfParams > 2) {
3,018✔
1896
      char   buf[3200] = {0};
30✔
1897
      // max length of double num is 317, e.g. use %.6lf to print -1.0e+308, consider the comma and bracket, 3200 is enough.
1898
      size_t len = 1;
30✔
1899

1900
      varDataVal(buf)[0] = '[';
30✔
1901
      for (int32_t i = 1; i < pCtx->numOfParams; ++i) {
330✔
1902
        SVariant* pVal = &pCtx->param[i].param;
300✔
1903

1904
        GET_TYPED_DATA(v, double, pVal->nType, &pVal->i);
300!
1905

1906
        code = getPercentile((*pMemBucket), v, &ppInfo->result);
300✔
1907
        if (code != TSDB_CODE_SUCCESS) {
300!
1908
          goto _fin_error;
×
1909
        }
1910

1911
        if (i == pCtx->numOfParams - 1) {
300✔
1912
          len += tsnprintf(varDataVal(buf) + len, sizeof(buf) - VARSTR_HEADER_SIZE - len, "%.6lf]", ppInfo->result);
30✔
1913
        } else {
1914
          len += tsnprintf(varDataVal(buf) + len, sizeof(buf) - VARSTR_HEADER_SIZE - len, "%.6lf, ", ppInfo->result);
270✔
1915
        }
1916
      }
1917

1918
      int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
30✔
1919
      SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
30✔
1920
      if (NULL == pCol) {
30!
1921
        code = terrno;
×
1922
        goto _fin_error;
×
1923
      }
1924

1925
      varDataSetLen(buf, len);
30✔
1926
      code = colDataSetVal(pCol, pBlock->info.rows, buf, false);
30✔
1927
      if (code != TSDB_CODE_SUCCESS) {
30!
1928
        goto _fin_error;
×
1929
      }
1930

1931
      tMemBucketDestroy(pMemBucket);
30✔
1932
      return TSDB_CODE_SUCCESS;
30✔
1933
    } else {
1934
      SVariant* pVal = &pCtx->param[1].param;
2,988✔
1935

1936
      GET_TYPED_DATA(v, double, pVal->nType, &pVal->i);
2,988!
1937

1938
      code = getPercentile((*pMemBucket), v, &ppInfo->result);
2,988✔
1939
      if (code != TSDB_CODE_SUCCESS) {
2,988!
1940
        goto _fin_error;
×
1941
      }
1942

1943
      tMemBucketDestroy(pMemBucket);
2,988✔
1944
      return functionFinalize(pCtx, pBlock);
2,988✔
1945
    }
1946
  } else {
1947
    return functionFinalize(pCtx, pBlock);
2,500✔
1948
  }
1949

1950
_fin_error:
×
1951

1952
  tMemBucketDestroy(pMemBucket);
×
1953
  return code;
×
1954
}
1955

1956
bool getApercentileFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
71,946✔
1957
  int32_t bytesHist =
71,946✔
1958
      (int32_t)(sizeof(SAPercentileInfo) + sizeof(SHistogramInfo) + sizeof(SHistBin) * (MAX_HISTOGRAM_BIN + 1));
1959
  int32_t bytesDigest = (int32_t)(sizeof(SAPercentileInfo) + TDIGEST_SIZE(COMPRESSION));
71,946✔
1960
  pEnv->calcMemSize = TMAX(bytesHist, bytesDigest);
71,946✔
1961
  return true;
71,946✔
1962
}
1963

1964
int32_t getApercentileMaxSize() {
9,497✔
1965
  int32_t bytesHist =
9,497✔
1966
      (int32_t)(sizeof(SAPercentileInfo) + sizeof(SHistogramInfo) + sizeof(SHistBin) * (MAX_HISTOGRAM_BIN + 1));
1967
  int32_t bytesDigest = (int32_t)(sizeof(SAPercentileInfo) + TDIGEST_SIZE(COMPRESSION));
9,497✔
1968
  return TMAX(bytesHist, bytesDigest);
9,497✔
1969
}
1970

1971
static int8_t getApercentileAlgo(char* algoStr) {
24,023✔
1972
  int8_t algoType;
1973
  if (strcasecmp(algoStr, "default") == 0) {
24,023✔
1974
    algoType = APERCT_ALGO_DEFAULT;
11,451✔
1975
  } else if (strcasecmp(algoStr, "t-digest") == 0) {
12,572!
1976
    algoType = APERCT_ALGO_TDIGEST;
12,572✔
1977
  } else {
1978
    algoType = APERCT_ALGO_UNKNOWN;
×
1979
  }
1980

1981
  return algoType;
24,023✔
1982
}
1983

1984
static void buildHistogramInfo(SAPercentileInfo* pInfo) {
889,949✔
1985
  pInfo->pHisto = (SHistogramInfo*)((char*)pInfo + sizeof(SAPercentileInfo));
889,949✔
1986
  pInfo->pHisto->elems = (SHistBin*)((char*)pInfo->pHisto + sizeof(SHistogramInfo));
889,949✔
1987
}
889,949✔
1988

1989
static void buildTDigestInfo(SAPercentileInfo* pInfo) {
27,556✔
1990
  pInfo->pTDigest = (TDigest*)((char*)pInfo + sizeof(SAPercentileInfo));
27,556✔
1991
}
27,556✔
1992

1993
int32_t apercentileFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
309,112✔
1994
  if (pResultInfo->initialized) {
309,112!
1995
    return TSDB_CODE_SUCCESS;
×
1996
  }
1997
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
309,112!
1998
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1999
  }
2000

2001
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
309,144✔
2002

2003
  SVariant* pVal = &pCtx->param[1].param;
309,144✔
2004
  pInfo->percent = 0;
309,144✔
2005
  GET_TYPED_DATA(pInfo->percent, double, pVal->nType, &pVal->i);
309,144!
2006

2007
  if (pCtx->numOfParams == 2) {
309,144✔
2008
    pInfo->algo = APERCT_ALGO_DEFAULT;
285,124✔
2009
  } else if (pCtx->numOfParams == 3) {
24,020!
2010
    pInfo->algo = getApercentileAlgo(varDataVal(pCtx->param[2].param.pz));
24,024✔
2011
    if (pInfo->algo == APERCT_ALGO_UNKNOWN) {
24,018!
2012
      return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
2013
    }
2014
  }
2015

2016
  char* tmp = (char*)pInfo + sizeof(SAPercentileInfo);
309,138✔
2017
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
309,138✔
2018
    pInfo->pTDigest = tdigestNewFrom(tmp, COMPRESSION);
12,569✔
2019
  } else {
2020
    buildHistogramInfo(pInfo);
296,569✔
2021
    pInfo->pHisto = tHistogramCreateFrom(tmp, MAX_HISTOGRAM_BIN);
296,570✔
2022
    qDebug("%s set up histogram, numOfElems:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
296,558✔
2023
           pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2024
  }
2025

2026
  return TSDB_CODE_SUCCESS;
309,131✔
2027
}
2028

2029
int32_t apercentileFunction(SqlFunctionCtx* pCtx) {
324,442✔
2030
  int32_t               numOfElems = 0;
324,442✔
2031
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
324,442✔
2032
  SInputColumnInfoData* pInput = &pCtx->input;
324,442✔
2033

2034
  SColumnInfoData* pCol = pInput->pData[0];
324,442✔
2035
  int32_t          type = pCol->info.type;
324,442✔
2036

2037
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
324,442✔
2038

2039
  int32_t start = pInput->startRowIndex;
324,442✔
2040
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
324,442✔
2041
    buildTDigestInfo(pInfo);
14,786✔
2042
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
14,785✔
2043
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
903,363✔
2044
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
888,589✔
2045
        continue;
278,516✔
2046
      }
2047
      numOfElems += 1;
610,073✔
2048
      char* data = colDataGetData(pCol, i);
610,073!
2049

2050
      double  v = 0;  // value
610,073✔
2051
      int64_t w = 1;  // weigth
610,073✔
2052
      GET_TYPED_DATA(v, double, type, data);
610,073✔
2053
      int32_t code = tdigestAdd(pInfo->pTDigest, v, w);
610,073✔
2054
      if (code != TSDB_CODE_SUCCESS) {
610,060!
2055
        return code;
×
2056
      }
2057
    }
2058
  } else {
2059
    // might be a race condition here that pHisto can be overwritten or setup function
2060
    // has not been called, need to relink the buffer pHisto points to.
2061
    buildHistogramInfo(pInfo);
309,656✔
2062
    qDebug("%s before add %d elements into histogram, total:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems: %p",
309,652✔
2063
           __FUNCTION__, numOfElems, pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto,
2064
           pInfo->pHisto->elems);
2065
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
3,249,554✔
2066
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
2,939,932✔
2067
        continue;
807,206✔
2068
      }
2069
      numOfElems += 1;
2,132,726✔
2070
      char* data = colDataGetData(pCol, i);
2,132,726!
2071

2072
      double v = 0;
2,132,726✔
2073
      GET_TYPED_DATA(v, double, type, data);
2,132,726!
2074
      int32_t code = tHistogramAdd(&pInfo->pHisto, v);
2,132,726✔
2075
      if (code != TSDB_CODE_SUCCESS) {
2,132,695!
2076
        return code;
×
2077
      }
2078
    }
2079

2080
    qDebug("%s after add %d elements into histogram, total:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems: %p",
309,622✔
2081
           __FUNCTION__, numOfElems, pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto,
2082
           pInfo->pHisto->elems);
2083
  }
2084

2085
  SET_VAL(pResInfo, numOfElems, 1);
324,440✔
2086
  return TSDB_CODE_SUCCESS;
324,440✔
2087
}
2088

2089
static int32_t apercentileTransferInfo(SAPercentileInfo* pInput, SAPercentileInfo* pOutput, bool* hasRes) {
8,290✔
2090
  pOutput->percent = pInput->percent;
8,290✔
2091
  pOutput->algo = pInput->algo;
8,290✔
2092
  if (pOutput->algo == APERCT_ALGO_TDIGEST) {
8,290✔
2093
    buildTDigestInfo(pInput);
210✔
2094
    tdigestAutoFill(pInput->pTDigest, COMPRESSION);
210✔
2095

2096
    if (pInput->pTDigest->num_centroids == 0 && pInput->pTDigest->num_buffered_pts == 0) {
210✔
2097
      return TSDB_CODE_SUCCESS;
1✔
2098
    }
2099

2100
    if (hasRes) {
209✔
2101
      *hasRes = true;
207✔
2102
    }
2103

2104
    buildTDigestInfo(pOutput);
209✔
2105
    TDigest* pTDigest = pOutput->pTDigest;
209✔
2106
    tdigestAutoFill(pTDigest, COMPRESSION);
209✔
2107

2108
    if (pTDigest->num_centroids <= 0 && pTDigest->num_buffered_pts == 0) {
209!
2109
      (void)memcpy(pTDigest, pInput->pTDigest, (size_t)TDIGEST_SIZE(COMPRESSION));
207✔
2110
      tdigestAutoFill(pTDigest, COMPRESSION);
207✔
2111
    } else {
2112
      int32_t code = tdigestMerge(pTDigest, pInput->pTDigest);
2✔
2113
      if (TSDB_CODE_SUCCESS != code) {
2!
2114
        return code;
×
2115
      }
2116
    }
2117
  } else {
2118
    buildHistogramInfo(pInput);
8,080✔
2119
    if (pInput->pHisto->numOfElems <= 0) {
8,080✔
2120
      return TSDB_CODE_SUCCESS;
203✔
2121
    }
2122

2123
    if (hasRes) {
7,877✔
2124
      *hasRes = true;
7,875✔
2125
    }
2126

2127
    buildHistogramInfo(pOutput);
7,877✔
2128
    SHistogramInfo* pHisto = pOutput->pHisto;
7,877✔
2129

2130
    if (pHisto->numOfElems <= 0) {
7,877✔
2131
      (void)memcpy(pHisto, pInput->pHisto, sizeof(SHistogramInfo) + sizeof(SHistBin) * (MAX_HISTOGRAM_BIN + 1));
7,274✔
2132
      pHisto->elems = (SHistBin*)((char*)pHisto + sizeof(SHistogramInfo));
7,274✔
2133

2134
      qDebug("%s merge histo, total:%" PRId64 ", entry:%d, %p", __FUNCTION__, pHisto->numOfElems, pHisto->numOfEntries,
7,274✔
2135
             pHisto);
2136
    } else {
2137
      pHisto->elems = (SHistBin*)((char*)pHisto + sizeof(SHistogramInfo));
603✔
2138
      qDebug("%s input histogram, elem:%" PRId64 ", entry:%d, %p", __FUNCTION__, pHisto->numOfElems,
603✔
2139
             pHisto->numOfEntries, pInput->pHisto);
2140

2141
      SHistogramInfo* pRes = NULL;
603✔
2142
      int32_t code = tHistogramMerge(pHisto, pInput->pHisto, MAX_HISTOGRAM_BIN, &pRes);
603✔
2143
      if (TSDB_CODE_SUCCESS != code) {
603!
2144
        tHistogramDestroy(&pRes);
×
2145
        return code;
×
2146
      }
2147
      (void)memcpy(pHisto, pRes, sizeof(SHistogramInfo) + sizeof(SHistBin) * MAX_HISTOGRAM_BIN);
603✔
2148
      pHisto->elems = (SHistBin*)((char*)pHisto + sizeof(SHistogramInfo));
603✔
2149

2150
      qDebug("%s merge histo, total:%" PRId64 ", entry:%d, %p", __FUNCTION__, pHisto->numOfElems, pHisto->numOfEntries,
603✔
2151
             pHisto);
2152
      tHistogramDestroy(&pRes);
603✔
2153
    }
2154
  }
2155
  return TSDB_CODE_SUCCESS;
8,086✔
2156
}
2157

2158
int32_t apercentileFunctionMerge(SqlFunctionCtx* pCtx) {
8,212✔
2159
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
8,212✔
2160

2161
  SInputColumnInfoData* pInput = &pCtx->input;
8,212✔
2162

2163
  SColumnInfoData* pCol = pInput->pData[0];
8,212✔
2164
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
8,212!
2165
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
2166
  }
2167

2168
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
8,212✔
2169

2170
  qDebug("%s total %" PRId64 " rows will merge, %p", __FUNCTION__, pInput->numOfRows, pInfo->pHisto);
8,212✔
2171

2172
  bool hasRes = false;
8,212✔
2173
  int32_t start = pInput->startRowIndex;
8,212✔
2174
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
16,498✔
2175
    char* data = colDataGetData(pCol, i);
8,286!
2176

2177
    SAPercentileInfo* pInputInfo = (SAPercentileInfo*)varDataVal(data);
8,286✔
2178
    int32_t code = apercentileTransferInfo(pInputInfo, pInfo, &hasRes);
8,286✔
2179
    if (TSDB_CODE_SUCCESS != code) {
8,286!
2180
      return code;
×
2181
    }
2182
  }
2183

2184
  if (pInfo->algo != APERCT_ALGO_TDIGEST) {
8,212✔
2185
    buildHistogramInfo(pInfo);
8,004✔
2186
    qDebug("%s after merge, total:%" PRId64 ", numOfEntry:%d, %p", __FUNCTION__, pInfo->pHisto->numOfElems,
8,004✔
2187
           pInfo->pHisto->numOfEntries, pInfo->pHisto);
2188
  }
2189

2190
  SET_VAL(pResInfo, hasRes ? 1 : 0, 1);
8,212✔
2191
  return TSDB_CODE_SUCCESS;
8,212✔
2192
}
2193

2194
int32_t apercentileFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
272,194✔
2195
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
272,194✔
2196
  SAPercentileInfo*    pInfo = (SAPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
272,194✔
2197

2198
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
272,194✔
2199
    buildTDigestInfo(pInfo);
12,359✔
2200
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
12,359✔
2201
    if (pInfo->pTDigest->size > 0) {
12,360!
2202
      pInfo->result = tdigestQuantile(pInfo->pTDigest, pInfo->percent / 100);
12,360✔
2203
    } else {  // no need to free
2204
      // setNull(pCtx->pOutput, pCtx->outputType, pCtx->outputBytes);
2205
      return TSDB_CODE_SUCCESS;
×
2206
    }
2207
  } else {
2208
    buildHistogramInfo(pInfo);
259,835✔
2209
    if (pInfo->pHisto->numOfElems > 0) {
259,836✔
2210
      qDebug("%s get the final res, elements:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
206,610✔
2211
             pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2212

2213
      double  ratio[] = {pInfo->percent};
206,610✔
2214
      double* res = NULL;
206,610✔
2215
      int32_t code = tHistogramUniform(pInfo->pHisto, ratio, 1, &res);
206,610✔
2216
      if (TSDB_CODE_SUCCESS != code) {
206,615!
2217
        taosMemoryFree(res);
×
2218
        return code;
×
2219
      }
2220
      pInfo->result = *res;
206,615✔
2221
      // memcpy(pCtx->pOutput, res, sizeof(double));
2222
      taosMemoryFree(res);
206,615✔
2223
    } else {  // no need to free
2224
      // setNull(pCtx->pOutput, pCtx->outputType, pCtx->outputBytes);
2225
      // return TSDB_CODE_SUCCESS;
2226
      qDebug("%s get the final res, elements:%" PRId64 ", numOfEntry:%d. result is null", __FUNCTION__,
53,226✔
2227
             pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries);
2228
    }
2229
  }
2230

2231
  return functionFinalize(pCtx, pBlock);
272,205✔
2232
}
2233

2234
int32_t apercentilePartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
7,957✔
2235
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
7,957✔
2236
  SAPercentileInfo*    pInfo = (SAPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
7,957✔
2237

2238
  int32_t resultBytes = getApercentileMaxSize();
7,957✔
2239
  char*   res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
7,957✔
2240
  if (NULL == res) {
7,957!
2241
    return terrno;
×
2242
  }
2243

2244
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
7,957✔
2245
    (void)memcpy(varDataVal(res), pInfo, resultBytes);
208✔
2246
    varDataSetLen(res, resultBytes);
208✔
2247
  } else {
2248
    (void)memcpy(varDataVal(res), pInfo, resultBytes);
7,749✔
2249
    varDataSetLen(res, resultBytes);
7,749✔
2250
  }
2251

2252
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
7,957✔
2253
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
7,957✔
2254
  if (NULL == pCol) {
7,957!
2255
    taosMemoryFree(res);
×
2256
    return TSDB_CODE_OUT_OF_RANGE;
×
2257
  }
2258

2259
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
7,957✔
2260

2261
  taosMemoryFree(res);
7,956✔
2262
  return code;
7,957✔
2263
}
2264

2265
int32_t apercentileCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
4✔
2266
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
4✔
2267
  SAPercentileInfo*    pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
4✔
2268

2269
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
4✔
2270
  SAPercentileInfo*    pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
4✔
2271

2272
  qDebug("%s start to combine apercentile, %p", __FUNCTION__, pDBuf->pHisto);
4!
2273

2274
  int32_t code = apercentileTransferInfo(pSBuf, pDBuf, NULL);
4✔
2275
  if (TSDB_CODE_SUCCESS != code) {
4!
2276
    return code;
×
2277
  }
2278
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
4✔
2279
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
4✔
2280
  return TSDB_CODE_SUCCESS;
4✔
2281
}
2282

2283
// TODO: change this function when block data info pks changed
2284
static int32_t comparePkDataWithSValue(int8_t pkType, char* pkData, SValue* pVal, int32_t order) {
4,012✔
2285
  char numVal[8] = {0};
4,012✔
2286
  switch (pkType) {
4,012✔
2287
    case TSDB_DATA_TYPE_INT:
674✔
2288
      *(int32_t*)numVal = (int32_t)pVal->val;
674✔
2289
      break;
674✔
2290
    case TSDB_DATA_TYPE_UINT:
592✔
2291
      *(uint32_t*)numVal = (uint32_t)pVal->val;
592✔
2292
      break;
592✔
2293
    case TSDB_DATA_TYPE_BIGINT:
724✔
2294
      *(int64_t*)numVal = (int64_t)pVal->val;
724✔
2295
      break;
724✔
2296
    case TSDB_DATA_TYPE_UBIGINT:
772✔
2297
      *(uint64_t*)numVal = (uint64_t)pVal->val;
772✔
2298
      break;
772✔
2299
    default:
1,250✔
2300
      break;
1,250✔
2301
  }
2302
  char*         blockData = (IS_NUMERIC_TYPE(pkType)) ? (char*) numVal : (char*)pVal->pData;
4,012!
2303
  __compar_fn_t fn = getKeyComparFunc(pkType, order);
4,012✔
2304
  return fn(pkData, blockData);
4,015✔
2305
}
2306

2307
EFuncDataRequired firstDynDataReq(void* pRes, SDataBlockInfo* pBlockInfo) {
9,257✔
2308
  SResultRowEntryInfo* pEntry = (SResultRowEntryInfo*)pRes;
9,257✔
2309

2310
  // not initialized yet, data is required
2311
  if (pEntry == NULL) {
9,257!
2312
    return FUNC_DATA_REQUIRED_DATA_LOAD;
×
2313
  }
2314

2315
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
9,257✔
2316
  if (pResult->hasResult) {
9,257✔
2317
    if (pResult->pkBytes > 0) {
9,173✔
2318
      pResult->pkData = pResult->buf + pResult->bytes;
3,190✔
2319
    } else {
2320
      pResult->pkData = NULL;
5,983✔
2321
    }    
2322
    if (pResult->ts < pBlockInfo->window.skey) {
9,173✔
2323
      return FUNC_DATA_REQUIRED_NOT_LOAD;
5,924✔
2324
    } else if (pResult->ts == pBlockInfo->window.skey) {
3,249✔
2325
      if (NULL == pResult->pkData) {
1,606✔
2326
        return FUNC_DATA_REQUIRED_NOT_LOAD;
197✔
2327
      }
2328
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 0, TSDB_ORDER_ASC) < 0) {
1,409✔
2329
        return FUNC_DATA_REQUIRED_NOT_LOAD;
186✔
2330
      }
2331
    }
2332
    return FUNC_DATA_REQUIRED_DATA_LOAD;
2,866✔
2333
  } else {
2334
    return FUNC_DATA_REQUIRED_DATA_LOAD;
84✔
2335
  }
2336
}
2337

2338
EFuncDataRequired lastDynDataReq(void* pRes, SDataBlockInfo* pBlockInfo) {
27,906✔
2339
  SResultRowEntryInfo* pEntry = (SResultRowEntryInfo*)pRes;
27,906✔
2340

2341
  // not initialized yet, data is required
2342
  if (pEntry == NULL) {
27,906!
2343
    return FUNC_DATA_REQUIRED_DATA_LOAD;
×
2344
  }
2345

2346
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
27,906✔
2347
  if (pResult->hasResult) {
27,906✔
2348
    if (pResult->pkBytes > 0) {
27,828✔
2349
      pResult->pkData = pResult->buf + pResult->bytes;
7,211✔
2350
    } else {
2351
      pResult->pkData = NULL;
20,617✔
2352
    }
2353
    if (pResult->ts > pBlockInfo->window.ekey) {
27,828✔
2354
      return FUNC_DATA_REQUIRED_NOT_LOAD;
22,144✔
2355
    } else if (pResult->ts == pBlockInfo->window.ekey && pResult->pkData) {
5,684✔
2356
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 1, TSDB_ORDER_DESC) < 0) {
2,606✔
2357
        return FUNC_DATA_REQUIRED_NOT_LOAD;
839✔
2358
      }
2359
    }
2360
    return FUNC_DATA_REQUIRED_DATA_LOAD;
4,845✔
2361
  } else {
2362
    return FUNC_DATA_REQUIRED_DATA_LOAD;
78✔
2363
  }
2364
}
2365

2366
//TODO modify it to include primary key bytes
2367
int32_t getFirstLastInfoSize(int32_t resBytes, int32_t pkBytes) { return sizeof(SFirstLastRes) + resBytes + pkBytes; }
82,736,158✔
2368

2369
bool getFirstLastFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
1,980,269✔
2370
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
1,980,269✔
2371
  //TODO: change SFunctionNode to add pk info
2372
  int32_t pkBytes = (pFunc->hasPk) ? pFunc->pkBytes : 0;
1,981,835✔
2373
  pEnv->calcMemSize = getFirstLastInfoSize(pNode->node.resType.bytes, pkBytes);
1,981,835✔
2374
  return true;
1,980,507✔
2375
}
2376

2377
bool getSelectivityFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
1,339,806✔
2378
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
1,339,806✔
2379
  pEnv->calcMemSize = pNode->node.resType.bytes;
1,340,533✔
2380
  return true;
1,340,533✔
2381
}
2382

2383
bool getGroupKeyFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
296,840✔
2384
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
296,840✔
2385
  pEnv->calcMemSize = sizeof(SGroupKeyInfo) + pNode->node.resType.bytes;
297,129✔
2386
  return true;
297,129✔
2387
}
2388

2389
static FORCE_INLINE TSKEY getRowPTs(SColumnInfoData* pTsColInfo, int32_t rowIndex) {
2390
  if (pTsColInfo == NULL || pTsColInfo->pData == NULL) {
372,252,208!
2391
    return 0;
×
2392
  }
2393

2394
  return *(TSKEY*)colDataGetData(pTsColInfo, rowIndex);
372,292,598!
2395
}
2396

2397
int32_t firstLastFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
9,948,298✔
2398
  if (pResInfo->initialized) {
9,948,298!
2399
    return TSDB_CODE_SUCCESS;
×
2400
  }
2401
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
9,948,298!
2402
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
2403
  }
2404

2405
  SFirstLastRes *       pRes = GET_ROWCELL_INTERBUF(pResInfo);
9,948,388✔
2406
  SInputColumnInfoData* pInput = &pCtx->input;
9,948,388✔
2407

2408
  pRes->nullTupleSaved = false;
9,948,388✔
2409
  pRes->nullTuplePos.pageId = -1;
9,948,388✔
2410
  return TSDB_CODE_SUCCESS;
9,948,388✔
2411
}
2412

2413
static int32_t prepareBuf(SqlFunctionCtx* pCtx) {
230,396,954✔
2414
  if (pCtx->subsidiaries.rowLen == 0) {
230,396,954✔
2415
    int32_t rowLen = 0;
650,395✔
2416
    for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
1,309,621✔
2417
      SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
659,226✔
2418
      rowLen += pc->pExpr->base.resSchema.bytes;
659,226✔
2419
    }
2420

2421
    pCtx->subsidiaries.rowLen = rowLen + pCtx->subsidiaries.num * sizeof(bool);
650,395✔
2422
    pCtx->subsidiaries.buf = taosMemoryMalloc(pCtx->subsidiaries.rowLen);
650,395✔
2423
    if (NULL == pCtx->subsidiaries.buf) {
650,429✔
2424
      return terrno;
1,783✔
2425
    }
2426
  }
2427
  return TSDB_CODE_SUCCESS;
230,395,205✔
2428
}
2429

2430
static int32_t firstlastSaveTupleData(const SSDataBlock* pSrcBlock, int32_t rowIndex, SqlFunctionCtx* pCtx,
275,187,202✔
2431
                                      SFirstLastRes* pInfo, bool noElements) {
2432
  int32_t code = TSDB_CODE_SUCCESS;
275,187,202✔
2433

2434
  if (pCtx->subsidiaries.num <= 0) {
275,187,202✔
2435
    return TSDB_CODE_SUCCESS;
138,566,756✔
2436
  }
2437

2438
  if (!pInfo->hasResult) {
136,620,446✔
2439
    code = saveTupleData(pCtx, rowIndex, pSrcBlock, noElements ? &pInfo->nullTuplePos : &pInfo->pos);
98,234,507✔
2440
  } else {
2441
    code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pInfo->pos);
38,385,939✔
2442
  }
2443

2444
  return code;
136,329,248✔
2445
}
2446

2447
static int32_t doSaveCurrentVal(SqlFunctionCtx* pCtx, int32_t rowIndex, int64_t currentTs, char* pkData, int32_t type, char* pData) {
93,821,787✔
2448
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
93,821,787✔
2449
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
93,821,787✔
2450

2451
  if (IS_VAR_DATA_TYPE(type)) {
93,821,787!
2452
    pInfo->bytes = varDataTLen(pData);
3,677,231✔
2453
  }
2454

2455
  (void)memcpy(pInfo->buf, pData, pInfo->bytes);
93,821,787✔
2456
  if (pkData != NULL) {
93,821,787✔
2457
    if (IS_VAR_DATA_TYPE(pInfo->pkType)) {
1,403,581!
2458
      pInfo->pkBytes = varDataTLen(pkData);
457,490✔
2459
    }
2460
    (void)memcpy(pInfo->buf + pInfo->bytes, pkData, pInfo->pkBytes);
1,403,581✔
2461
    pInfo->pkData = pInfo->buf + pInfo->bytes;
1,403,581✔
2462
  }
2463

2464
  pInfo->ts = currentTs;
93,821,787✔
2465
  int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pInfo, false);
93,821,787✔
2466
  if (code != TSDB_CODE_SUCCESS) {
93,811,916!
2467
    return code;
×
2468
  }
2469

2470
  pInfo->hasResult = true;
93,811,916✔
2471
  return TSDB_CODE_SUCCESS;
93,811,916✔
2472
}
2473

2474
// This ordinary first function does not care if current scan is ascending order or descending order scan
2475
// the OPTIMIZED version of first function will only handle the ascending order scan
2476
int32_t firstFunction(SqlFunctionCtx* pCtx) {
57,484,284✔
2477
  int32_t numOfElems = 0;
57,484,284✔
2478

2479
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
57,484,284✔
2480
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
57,484,284✔
2481

2482
  SInputColumnInfoData* pInput = &pCtx->input;
57,484,284✔
2483
  SColumnInfoData*      pInputCol = pInput->pData[0];
57,484,284✔
2484

2485
  pInfo->bytes = pInputCol->info.bytes;
57,484,284✔
2486

2487
  if (IS_NULL_TYPE(pInputCol->info.type)) {
57,484,284✔
2488
    return TSDB_CODE_SUCCESS;
4,479✔
2489
  }
2490

2491
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
57,479,805✔
2492
  pInfo->pkType = -1;
57,479,805✔
2493
  __compar_fn_t  pkCompareFn = NULL;
57,479,805✔
2494
  if (pCtx->hasPrimaryKey) {
57,479,805✔
2495
    pInfo->pkType = pkCol->info.type;
370,328✔
2496
    pInfo->pkBytes = pkCol->info.bytes;
370,328✔
2497
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_ASC);
370,328✔
2498
  }
2499

2500
  // All null data column, return directly.
2501
  if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) &&
57,542,721!
2502
      pInputCol->hasNull == true) {
×
2503
    // save selectivity value for column consisted of all null values
2504
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, !pInfo->nullTupleSaved);
×
2505
    if (code != TSDB_CODE_SUCCESS) {
×
2506
      return code;
×
2507
    }
2508
    pInfo->nullTupleSaved = true;
×
2509
    return TSDB_CODE_SUCCESS;
×
2510
  }
2511

2512
  SColumnDataAgg* pColAgg = (pInput->colDataSMAIsSet) ? pInput->pColumnDataAgg[0] : NULL;
57,542,721!
2513

2514
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
57,542,721!
2515
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
57,542,721!
2516

2517
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
57,542,721✔
2518

2519
  //  please ref. to the comment in lastRowFunction for the reason why disabling the opt version of last/first
2520
  //  function. we will use this opt implementation in an new version that is only available in scan subplan
2521
#if 0
2522
  if (blockDataOrder == TSDB_ORDER_ASC) {
2523
    // filter according to current result firstly
2524
    if (pResInfo->numOfRes > 0) {
2525
      if (pInfo->ts < startKey) {
2526
        return TSDB_CODE_SUCCESS;
2527
      }
2528
    }
2529

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

2535
      numOfElems++;
2536

2537
      char* data = colDataGetData(pInputCol, i);
2538
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2539
      if (pResInfo->numOfRes == 0 || pInfo->ts > cts) {
2540
        doSaveCurrentVal(pCtx, i, cts, pInputCol->info.type, data);
2541
        break;
2542
      }
2543
    }
2544
  } else {
2545
    // in case of descending order time stamp serial, which usually happens as the results of the nest query,
2546
    // all data needs to be check.
2547
    if (pResInfo->numOfRes > 0) {
2548
      if (pInfo->ts < endKey) {
2549
        return TSDB_CODE_SUCCESS;
2550
      }
2551
    }
2552

2553
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
2554
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2555
        continue;
2556
      }
2557

2558
      numOfElems++;
2559

2560
      char* data = colDataGetData(pInputCol, i);
2561
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2562

2563
      if (pResInfo->numOfRes == 0 || pInfo->ts > cts) {
2564
        doSaveCurrentVal(pCtx, i, cts, pInputCol->info.type, data);
2565
        break;
2566
      }
2567
    }
2568
  }
2569
#else
2570
  int64_t* pts = (int64_t*)pInput->pPTS->pData;
57,542,721✔
2571

2572
  int from = -1;
57,542,721✔
2573
  int32_t i = -1;
57,542,721✔
2574
  while (funcInputGetNextRowIndex(pInput, from, true, &i, &from)) {
200,502,156✔
2575
    if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
194,874,549!
2576
      continue;
7,090,755✔
2577
    }
2578

2579
    numOfElems++;
135,965,745✔
2580
    char* data = colDataGetData(pInputCol, i);
135,965,745!
2581
    char* pkData = NULL;
135,965,745✔
2582
    if (pCtx->hasPrimaryKey) {
135,965,745✔
2583
      pkData = colDataGetData(pkCol, i);
1,365,575!
2584
    }
2585
    TSKEY cts = pts[i];
135,965,745✔
2586
    if (pResInfo->numOfRes == 0 || pInfo->ts > cts || 
135,965,745✔
2587
         (pInfo->ts == cts && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
86,338,431!
2588
      int32_t code = doSaveCurrentVal(pCtx, i, cts, pkData, pInputCol->info.type, data);
49,627,314✔
2589
      if (code != TSDB_CODE_SUCCESS) {
49,530,250!
2590
        return code;
×
2591
      }
2592
      pResInfo->numOfRes = 1;
49,530,250✔
2593
    }
2594
  }
2595
#endif
2596

2597
  if (numOfElems == 0) {
57,151,270✔
2598
    // save selectivity value for column consisted of all null values
2599
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, !pInfo->nullTupleSaved);
38,687✔
2600
    if (code != TSDB_CODE_SUCCESS) {
38,687!
2601
      return code;
×
2602
    }
2603
    pInfo->nullTupleSaved = true;
38,687✔
2604
  }
2605
  SET_VAL(pResInfo, numOfElems, 1);
57,151,270✔
2606
  return TSDB_CODE_SUCCESS;
57,151,270✔
2607
}
2608

2609
int32_t lastFunction(SqlFunctionCtx* pCtx) {
44,382,659✔
2610
  int32_t numOfElems = 0;
44,382,659✔
2611

2612
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
44,382,659✔
2613
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
44,382,659✔
2614

2615
  SInputColumnInfoData* pInput = &pCtx->input;
44,382,659✔
2616
  SColumnInfoData*      pInputCol = pInput->pData[0];
44,382,659✔
2617

2618
  int32_t type = pInputCol->info.type;
44,382,659✔
2619
  int32_t bytes = pInputCol->info.bytes;
44,382,659✔
2620
  pInfo->bytes = bytes;
44,382,659✔
2621

2622
  if (IS_NULL_TYPE(type)) {
44,382,659✔
2623
    return TSDB_CODE_SUCCESS;
4,478✔
2624
  }
2625

2626
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
44,378,181✔
2627
  pInfo->pkType = -1;
44,378,181✔
2628
  __compar_fn_t  pkCompareFn = NULL;
44,378,181✔
2629
  if (pCtx->hasPrimaryKey) {
44,378,181✔
2630
    pInfo->pkType = pkCol->info.type;
433,370✔
2631
    pInfo->pkBytes = pkCol->info.bytes;
433,370✔
2632
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
433,370✔
2633
  }
2634

2635
  // All null data column, return directly.
2636
  if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) &&
44,434,339!
2637
      pInputCol->hasNull == true) {
×
2638
    // save selectivity value for column consisted of all null values
2639
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, !pInfo->nullTupleSaved);
×
2640
    if (code != TSDB_CODE_SUCCESS) {
×
2641
      return code;
×
2642
    }
2643
    pInfo->nullTupleSaved = true;
×
2644
    return TSDB_CODE_SUCCESS;
×
2645
  }
2646

2647
  SColumnDataAgg* pColAgg = (pInput->colDataSMAIsSet) ? pInput->pColumnDataAgg[0] : NULL;
44,434,339!
2648

2649
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
44,434,339!
2650
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
44,434,339!
2651

2652
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
44,434,339✔
2653

2654
  //  please ref. to the comment in lastRowFunction for the reason why disabling the opt version of last/first function.
2655
#if 0
2656
  if (blockDataOrder == TSDB_ORDER_ASC) {
2657
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
2658
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2659
        continue;
2660
      }
2661

2662
      numOfElems++;
2663

2664
      char* data = colDataGetData(pInputCol, i);
2665
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2666
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
2667
        doSaveCurrentVal(pCtx, i, cts, type, data);
2668
      }
2669

2670
      break;
2671
    }
2672
  } else {  // descending order
2673
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
2674
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2675
        continue;
2676
      }
2677

2678
      numOfElems++;
2679

2680
      char* data = colDataGetData(pInputCol, i);
2681
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2682
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
2683
        doSaveCurrentVal(pCtx, i, cts, type, data);
2684
      }
2685
      break;
2686
    }
2687
  }
2688
#else
2689
  int64_t* pts = (int64_t*)pInput->pPTS->pData;
44,434,339✔
2690

2691
#if 0
2692
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
2693
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2694
        continue;
2695
      }
2696

2697
      numOfElems++;
2698
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i]) {
2699
        char* data = colDataGetData(pInputCol, i);
2700
        doSaveCurrentVal(pCtx, i, pts[i], type, data);
2701
        pResInfo->numOfRes = 1;
2702
      }
2703
    }
2704
#else
2705

2706
// todo refactor
2707
  if (!pInputCol->hasNull && !pCtx->hasPrimaryKey) {
68,672,839✔
2708
    numOfElems = 1;
24,268,298✔
2709

2710
    int32_t round = pInput->numOfRows >> 2;
24,268,298✔
2711
    int32_t reminder = pInput->numOfRows & 0x03;
24,268,298✔
2712

2713
    for (int32_t i = pInput->startRowIndex, tick = 0; tick < round; i += 4, tick += 1) {
37,887,540✔
2714
      int64_t cts = pts[i];
13,614,771✔
2715
      int32_t chosen = i;
13,614,771✔
2716

2717
      if (cts < pts[i + 1]) {
13,614,771✔
2718
        cts = pts[i + 1];
4,393,116✔
2719
        chosen = i + 1;
4,393,116✔
2720
      }
2721

2722
      if (cts < pts[i + 2]) {
13,614,771✔
2723
        cts = pts[i + 2];
4,391,999✔
2724
        chosen = i + 2;
4,391,999✔
2725
      }
2726

2727
      if (cts < pts[i + 3]) {
13,614,771✔
2728
        cts = pts[i + 3];
4,392,039✔
2729
        chosen = i + 3;
4,392,039✔
2730
      }
2731

2732
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
13,614,771✔
2733
        char*   data = colDataGetData(pInputCol, chosen);
3,715,060!
2734
        int32_t code = doSaveCurrentVal(pCtx, i, cts, NULL, type, data);
3,715,060✔
2735
        if (code != TSDB_CODE_SUCCESS) {
3,719,531!
2736
          return code;
×
2737
        }
2738
        pResInfo->numOfRes = 1;
3,719,531✔
2739
      }
2740
    }
2741

2742
    for (int32_t i = pInput->startRowIndex + round * 4; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
53,405,614✔
2743
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i]) {
29,167,114✔
2744
        char*   data = colDataGetData(pInputCol, i);
16,417,171!
2745
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], NULL, type, data);
16,417,171✔
2746
        if (code != TSDB_CODE_SUCCESS) {
16,382,902!
2747
          return code;
×
2748
        }
2749
        pResInfo->numOfRes = 1;
16,382,902✔
2750
      }
2751
    }
2752
  } else {
2753
    int from = -1;
20,166,041✔
2754
    int32_t i = -1;
20,166,041✔
2755
    while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
235,020,398✔
2756
      if (colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
429,756,276✔
2757
        continue;
9,332,851✔
2758
      }
2759

2760
      numOfElems++;
205,545,287✔
2761
      char* pkData = NULL;
205,545,287✔
2762
      if (pCtx->hasPrimaryKey) {
205,545,287✔
2763
        pkData = colDataGetData(pkCol, i);
101,417,480!
2764
      }
2765
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i] ||
205,545,287✔
2766
          (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
181,678,565!
2767
        char*   data = colDataGetData(pInputCol, i);
24,111,747!
2768
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], pkData, type, data);
24,111,747✔
2769
        if (code != TSDB_CODE_SUCCESS) {
24,087,969!
2770
          return code;
×
2771
        }
2772
        pResInfo->numOfRes = 1;
24,087,969✔
2773
      }
2774
    }
2775
  }
2776
#endif
2777

2778
#endif
2779

2780
  // save selectivity value for column consisted of all null values
2781
  if (numOfElems == 0) {
44,481,618✔
2782
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, !pInfo->nullTupleSaved);
4,082,508✔
2783
    if (code != TSDB_CODE_SUCCESS) {
4,079,204!
2784
      return code;
×
2785
    }
2786
    pInfo->nullTupleSaved = true;
4,079,204✔
2787
  }
2788

2789
  return TSDB_CODE_SUCCESS;
44,478,314✔
2790
}
2791

2792
static bool firstLastTransferInfoImpl(SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst) {
77,485,953✔
2793
  if (!pInput->hasResult) {
77,485,953✔
2794
    return false;
2✔
2795
  }
2796
  __compar_fn_t pkCompareFn = NULL;
77,485,951✔
2797
  if (pInput->pkData) {
77,485,951✔
2798
    pkCompareFn = getKeyComparFunc(pInput->pkType, (isFirst) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC);
43,454✔
2799
  }
2800
  if (pOutput->hasResult) {
77,495,250✔
2801
    if (isFirst) {
32,969,261✔
2802
      if (pInput->ts > pOutput->ts ||
8,727,653✔
2803
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
8,673,834✔
2804
        return false;
54,331✔
2805
      }
2806
    } else {
2807
      if (pInput->ts < pOutput->ts ||
24,241,608✔
2808
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
14,137,737✔
2809
        return false;
10,109,020✔
2810
      }
2811
    }
2812
  }
2813

2814
  pOutput->isNull = pInput->isNull;
67,331,899✔
2815
  pOutput->ts = pInput->ts;
67,331,899✔
2816
  pOutput->bytes = pInput->bytes;
67,331,899✔
2817
  pOutput->pkType = pInput->pkType;
67,331,899✔
2818

2819
  (void)memcpy(pOutput->buf, pInput->buf, pOutput->bytes);
67,331,899✔
2820
  if (pInput->pkData) {
67,331,899✔
2821
    pOutput->pkBytes = pInput->pkBytes;
40,259✔
2822
    (void)memcpy(pOutput->buf + pOutput->bytes, pInput->pkData, pOutput->pkBytes);
40,259✔
2823
    pOutput->pkData = pOutput->buf + pOutput->bytes;
40,259✔
2824
  }
2825
  return true;
67,331,899✔
2826
}
2827

2828
static int32_t firstLastTransferInfo(SqlFunctionCtx* pCtx, SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst,
77,485,717✔
2829
                                     int32_t rowIndex) {
2830
  if (firstLastTransferInfoImpl(pInput, pOutput, isFirst)) {
77,485,717✔
2831
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pOutput, pOutput->nullTupleSaved);
67,330,776✔
2832
    if (TSDB_CODE_SUCCESS != code) {
67,321,206!
2833
      return code;
×
2834
    }
2835
    pOutput->hasResult = true;
67,321,206✔
2836
  }
2837
  return TSDB_CODE_SUCCESS;
77,477,488✔
2838
}
2839

2840
static int32_t firstLastFunctionMergeImpl(SqlFunctionCtx* pCtx, bool isFirstQuery) {
44,711,223✔
2841
  SInputColumnInfoData* pInput = &pCtx->input;
44,711,223✔
2842
  SColumnInfoData*      pCol = pInput->pData[0];
44,711,223✔
2843

2844
  if (IS_NULL_TYPE(pCol->info.type)) {
44,711,223!
2845
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
2846
    return TSDB_CODE_SUCCESS;
×
2847
  }
2848

2849
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
44,711,223!
2850
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
2851
  }
2852

2853
  SFirstLastRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
44,711,223✔
2854

2855
  int32_t start = pInput->startRowIndex;
44,711,223✔
2856
  int32_t numOfElems = 0;
44,711,223✔
2857

2858
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
124,479,396✔
2859
    if (colDataIsNull_s(pCol, i)) {
159,577,810✔
2860
      continue;
2,291,685✔
2861
    }
2862
    char*          data = colDataGetData(pCol, i);
77,497,220!
2863
    SFirstLastRes* pInputInfo = (SFirstLastRes*)varDataVal(data);
77,497,220✔
2864
    if (pCtx->hasPrimaryKey) {
77,497,220✔
2865
      pInputInfo->pkData = pInputInfo->buf + pInputInfo->bytes;
43,453✔
2866
    } else {
2867
      pInputInfo->pkData = NULL;
77,453,767✔
2868
    }
2869

2870
    int32_t code = firstLastTransferInfo(pCtx, pInputInfo, pInfo, isFirstQuery, i);
77,497,220✔
2871
    if (code != TSDB_CODE_SUCCESS) {
77,476,488!
2872
      return code;
×
2873
    }
2874
    if (!numOfElems) {
77,476,488✔
2875
      numOfElems = pInputInfo->hasResult ? 1 : 0;
44,693,767✔
2876
    }
2877
  }
2878

2879
  if (numOfElems == 0) {
44,690,491✔
2880
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, !pInfo->nullTupleSaved);
14,347✔
2881
    if (code != TSDB_CODE_SUCCESS) {
14,347!
2882
      return code;
×
2883
    }
2884
    pInfo->nullTupleSaved = true;
14,347✔
2885
  }
2886

2887
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
44,690,491✔
2888
  return TSDB_CODE_SUCCESS;
44,690,491✔
2889
}
2890

2891
int32_t firstFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, true); }
15,497,045✔
2892

2893
int32_t lastFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, false); }
29,220,298✔
2894

2895
int32_t firstLastFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
109,030,457✔
2896
  int32_t          code = TSDB_CODE_SUCCESS;
109,030,457✔
2897
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
109,030,457✔
2898
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
109,030,457✔
2899
  if (NULL == pCol) {
109,003,974!
2900
    return TSDB_CODE_OUT_OF_RANGE;
×
2901
  }
2902

2903
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
109,003,974✔
2904
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
109,003,974✔
2905

2906
  SFirstLastRes* pRes = GET_ROWCELL_INTERBUF(pResInfo);
109,003,974✔
2907

2908
  if (pResInfo->isNullRes) {
109,003,974✔
2909
    colDataSetNULL(pCol, pBlock->info.rows);
47,744✔
2910
    return setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, pBlock->info.rows);
47,744✔
2911
  }
2912
  code = colDataSetVal(pCol, pBlock->info.rows, pRes->buf, pRes->isNull || pResInfo->isNullRes);
108,956,230!
2913
  if (TSDB_CODE_SUCCESS != code) {
108,906,002!
2914
    return code;
×
2915
  }
2916

2917
  // handle selectivity
2918
  code = setSelectivityValue(pCtx, pBlock, &pRes->pos, pBlock->info.rows);
108,906,002✔
2919

2920
  return code;
108,887,993✔
2921
}
2922

2923
int32_t firstLastPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
80,691,610✔
2924
  int32_t code = TSDB_CODE_SUCCESS;
80,691,610✔
2925

2926
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
80,691,610✔
2927
  SFirstLastRes*       pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
80,691,610✔
2928

2929
  int32_t resultBytes = getFirstLastInfoSize(pRes->bytes, pRes->pkBytes);
80,691,610✔
2930

2931
  // todo check for failure
2932
  char* res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
80,600,666✔
2933
  if (NULL == res) {
81,871,208!
2934
    return terrno;
×
2935
  }
2936
  (void)memcpy(varDataVal(res), pRes, resultBytes);
81,871,208✔
2937

2938
  varDataSetLen(res, resultBytes);
81,871,208✔
2939

2940
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
81,871,208✔
2941
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
81,871,208✔
2942
  if (NULL == pCol) {
81,604,089!
2943
    taosMemoryFree(res);
×
2944
    return TSDB_CODE_OUT_OF_RANGE;
×
2945
  }
2946

2947
  if (pEntryInfo->numOfRes == 0) {
81,624,917✔
2948
    colDataSetNULL(pCol, pBlock->info.rows);
2,386,748!
2949
    code = setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, pBlock->info.rows);
2,386,748✔
2950
  } else {
2951
    code = colDataSetVal(pCol, pBlock->info.rows, res, false);
79,238,169✔
2952
    if (TSDB_CODE_SUCCESS != code) {
78,296,585!
2953
      taosMemoryFree(res);
×
2954
      return code;
×
2955
    }
2956
    code = setSelectivityValue(pCtx, pBlock, &pRes->pos, pBlock->info.rows);
78,296,585✔
2957
  }
2958
  taosMemoryFree(res);
80,610,297✔
2959
  return code;
81,789,373✔
2960
}
2961

2962
int32_t lastCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
3✔
2963
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
3✔
2964
  SFirstLastRes*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
3✔
2965
  int32_t              bytes = pDBuf->bytes;
3✔
2966

2967
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
3✔
2968
  SFirstLastRes*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
3✔
2969

2970
  pDBuf->hasResult = firstLastTransferInfoImpl(pSBuf, pDBuf, false);
3✔
2971
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
3✔
2972
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
3✔
2973
  return TSDB_CODE_SUCCESS;
3✔
2974
}
2975

2976
static int32_t doSaveLastrow(SqlFunctionCtx* pCtx, char* pData, int32_t rowIndex, int64_t cts, SFirstLastRes* pInfo) {
110,139,340✔
2977
  SInputColumnInfoData* pInput = &pCtx->input;
110,139,340✔
2978
  SColumnInfoData*      pInputCol = pInput->pData[0];
110,139,340✔
2979
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
110,139,340✔
2980

2981

2982
  if (colDataIsNull_s(pInputCol, rowIndex)) {
220,278,680✔
2983
    pInfo->isNull = true;
11,169✔
2984
  } else {
2985
    pInfo->isNull = false;
110,128,171✔
2986

2987
    if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
110,128,171!
2988
      pInfo->bytes = varDataTLen(pData);
83,426✔
2989
    }
2990

2991
    (void)memcpy(pInfo->buf, pData, pInfo->bytes);
110,128,171✔
2992
  }
2993

2994
  if (pCtx->hasPrimaryKey && !colDataIsNull_s(pkCol, rowIndex)) {
110,211,858✔
2995
    char* pkData = colDataGetData(pkCol, rowIndex);
72,508!
2996
    if (IS_VAR_DATA_TYPE(pInfo->pkType)) {
72,508!
2997
      pInfo->pkBytes = varDataTLen(pkData);
23,974✔
2998
    }
2999
    (void)memcpy(pInfo->buf + pInfo->bytes, pkData, pInfo->pkBytes);
72,508✔
3000
    pInfo->pkData = pInfo->buf + pInfo->bytes;
72,508✔
3001
  }
3002
  pInfo->ts = cts;
110,139,340✔
3003
  int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pInfo, false);
110,139,340✔
3004
  if (code != TSDB_CODE_SUCCESS) {
109,967,372!
3005
    return code;
×
3006
  }
3007

3008
  pInfo->hasResult = true;
109,967,372✔
3009

3010
  return TSDB_CODE_SUCCESS;
109,967,372✔
3011
}
3012

3013
int32_t lastRowFunction(SqlFunctionCtx* pCtx) {
83,846,963✔
3014
  int32_t numOfElems = 0;
83,846,963✔
3015

3016
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
83,846,963✔
3017
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
83,846,963✔
3018

3019
  SInputColumnInfoData* pInput = &pCtx->input;
83,846,963✔
3020
  SColumnInfoData*      pInputCol = pInput->pData[0];
83,846,963✔
3021

3022
  int32_t type = pInputCol->info.type;
83,846,963✔
3023
  int32_t bytes = pInputCol->info.bytes;
83,846,963✔
3024
  pInfo->bytes = bytes;
83,846,963✔
3025

3026
  if (IS_NULL_TYPE(type)) {
83,846,963✔
3027
    return TSDB_CODE_SUCCESS;
40✔
3028
  }
3029
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
83,846,923✔
3030
  pInfo->pkType = -1;
83,846,923✔
3031
  __compar_fn_t  pkCompareFn = NULL;
83,846,923✔
3032
  if (pCtx->hasPrimaryKey) {
83,846,923✔
3033
    pInfo->pkType = pkCol->info.type;
387,765✔
3034
    pInfo->pkBytes = pkCol->info.bytes;
387,765✔
3035
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
387,765✔
3036
  }
3037
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
83,926,624✔
3038
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
83,926,624!
3039

3040
#if 0
3041
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
3042

3043
  // the optimized version only valid if all tuples in one block are monotonious increasing or descreasing.
3044
  // this assumption is NOT always works if project operator exists in downstream.
3045
  if (blockDataOrder == TSDB_ORDER_ASC) {
3046
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
3047
      char* data = colDataGetData(pInputCol, i);
3048
      TSKEY cts = getRowPTs(pInput->pPTS, i);
3049
      numOfElems++;
3050

3051
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
3052
        doSaveLastrow(pCtx, data, i, cts, pInfo);
3053
      }
3054

3055
      break;
3056
    }
3057
  } else {  // descending order
3058
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
3059
      char* data = colDataGetData(pInputCol, i);
3060
      TSKEY cts = getRowPTs(pInput->pPTS, i);
3061
      numOfElems++;
3062

3063
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
3064
        doSaveLastrow(pCtx, data, i, cts, pInfo);
3065
      }
3066
      break;
3067
    }
3068
  }
3069
#else
3070

3071
  int64_t* pts = (int64_t*)pInput->pPTS->pData;
83,926,624✔
3072
  int from = -1;
83,926,624✔
3073
  int32_t i = -1;
83,926,624✔
3074
  while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
309,357,174✔
3075
    bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
225,521,342✔
3076
    char* data = isNull ? NULL : colDataGetData(pInputCol, i);
225,521,342!
3077
    TSKEY cts = pts[i];
225,521,342✔
3078

3079
    numOfElems++;
225,521,342✔
3080
    char* pkData = NULL;
225,521,342✔
3081
    if (pCtx->hasPrimaryKey) {
225,521,342✔
3082
      pkData = colDataGetData(pkCol, i);
1,379,153!
3083
    }
3084
    if (pResInfo->numOfRes == 0 || pInfo->ts < cts ||
225,521,342✔
3085
        (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
115,519,972✔
3086
      int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
110,001,376✔
3087
      if (code != TSDB_CODE_SUCCESS) {
109,910,584!
3088
        return code;
×
3089
      }
3090
      pResInfo->numOfRes = 1;
109,910,584✔
3091
    }
3092
  }
3093

3094
#endif
3095

3096
  SET_VAL(pResInfo, numOfElems, 1);
83,071,373!
3097
  return TSDB_CODE_SUCCESS;
83,071,373✔
3098
}
3099

3100
bool getDiffFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
39,596✔
3101
  pEnv->calcMemSize = sizeof(SDiffInfo);
39,596✔
3102
  return true;
39,596✔
3103
}
3104

3105
int32_t diffFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
463,527✔
3106
  if (pResInfo->initialized) {
463,527✔
3107
    return TSDB_CODE_SUCCESS;
371,777✔
3108
  }
3109
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
91,750!
3110
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
3111
  }
3112
  SDiffInfo* pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
91,750✔
3113
  pDiffInfo->hasPrev = false;
91,750✔
3114
  pDiffInfo->isFirstRow = true;
91,750✔
3115
  pDiffInfo->prev.i64 = 0;
91,750✔
3116
  pDiffInfo->prevTs = -1;
91,750✔
3117
  if (pCtx->numOfParams > 1) {
91,750!
3118
    pDiffInfo->ignoreOption = pCtx->param[1].param.i;  // TODO set correct param
91,750✔
3119
  } else {
3120
    pDiffInfo->ignoreOption = 0;
×
3121
  }
3122
  return TSDB_CODE_SUCCESS;
91,750✔
3123
}
3124

3125
static int32_t doSetPrevVal(SDiffInfo* pDiffInfo, int32_t type, const char* pv, int64_t ts) {
1,550,277✔
3126
  switch (type) {
1,550,277!
3127
    case TSDB_DATA_TYPE_BOOL:
38✔
3128
      pDiffInfo->prev.i64 = *(bool*)pv ? 1 : 0;
38✔
3129
      break;
38✔
3130
    case TSDB_DATA_TYPE_UTINYINT:
69,028✔
3131
    case TSDB_DATA_TYPE_TINYINT:
3132
      pDiffInfo->prev.i64 = *(int8_t*)pv;
69,028✔
3133
      break;
69,028✔
3134
    case TSDB_DATA_TYPE_UINT:
1,190,225✔
3135
    case TSDB_DATA_TYPE_INT:
3136
      pDiffInfo->prev.i64 = *(int32_t*)pv;
1,190,225✔
3137
      break;
1,190,225✔
3138
    case TSDB_DATA_TYPE_USMALLINT:
393✔
3139
    case TSDB_DATA_TYPE_SMALLINT:
3140
      pDiffInfo->prev.i64 = *(int16_t*)pv;
393✔
3141
      break;
393✔
3142
    case TSDB_DATA_TYPE_TIMESTAMP:
669✔
3143
    case TSDB_DATA_TYPE_UBIGINT:
3144
    case TSDB_DATA_TYPE_BIGINT:
3145
      pDiffInfo->prev.i64 = *(int64_t*)pv;
669✔
3146
      break;
669✔
3147
    case TSDB_DATA_TYPE_FLOAT:
213,059✔
3148
      pDiffInfo->prev.d64 = *(float*)pv;
213,059✔
3149
      break;
213,059✔
3150
    case TSDB_DATA_TYPE_DOUBLE:
76,865✔
3151
      pDiffInfo->prev.d64 = *(double*)pv;
76,865✔
3152
      break;
76,865✔
3153
    default:
×
3154
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3155
  }
3156
  pDiffInfo->prevTs = ts;
1,550,277✔
3157
  pDiffInfo->hasPrev = true;
1,550,277✔
3158
  return TSDB_CODE_SUCCESS;
1,550,277✔
3159
}
3160

3161
static bool diffIsNegtive(SDiffInfo* pDiffInfo, int32_t type, const char* pv) {
6,957,150✔
3162
  switch (type) {
6,957,150!
3163
    case TSDB_DATA_TYPE_UINT: {
×
3164
      int64_t v = *(uint32_t*)pv;
×
3165
      return v < pDiffInfo->prev.i64;
×
3166
    }
3167
    case TSDB_DATA_TYPE_INT: {
5,417,221✔
3168
      int64_t v = *(int32_t*)pv;
5,417,221✔
3169
      return v < pDiffInfo->prev.i64;
5,417,221✔
3170
    }
3171
    case TSDB_DATA_TYPE_BOOL: {
×
3172
      int64_t v = *(bool*)pv;
×
3173
      return v < pDiffInfo->prev.i64;
×
3174
    }
3175
    case TSDB_DATA_TYPE_UTINYINT: {
×
3176
      int64_t v = *(uint8_t*)pv;
×
3177
      return v < pDiffInfo->prev.i64;
×
3178
    }
3179
    case TSDB_DATA_TYPE_TINYINT: {
279,731✔
3180
      int64_t v = *(int8_t*)pv;
279,731✔
3181
      return v < pDiffInfo->prev.i64;
279,731✔
3182
    }
3183
    case TSDB_DATA_TYPE_USMALLINT: {
×
3184
      int64_t v = *(uint16_t*)pv;
×
3185
      return v < pDiffInfo->prev.i64;
×
3186
    }
3187
    case TSDB_DATA_TYPE_SMALLINT: {
5,866✔
3188
      int64_t v = *(int16_t*)pv;
5,866✔
3189
      return v < pDiffInfo->prev.i64;
5,866✔
3190
    }
3191
    case TSDB_DATA_TYPE_UBIGINT:{
40✔
3192
      uint64_t v = *(uint64_t*)pv;
40✔
3193
      return v < (uint64_t)pDiffInfo->prev.i64;
40✔
3194
    }
3195
    case TSDB_DATA_TYPE_TIMESTAMP:
4,002✔
3196
    case TSDB_DATA_TYPE_BIGINT: {
3197
      int64_t v = *(int64_t*)pv;
4,002✔
3198
      return v < pDiffInfo->prev.i64;
4,002✔
3199
    }
3200
    case TSDB_DATA_TYPE_FLOAT: {
830,528✔
3201
      float v = *(float*)pv;
830,528✔
3202
      return v < pDiffInfo->prev.d64;
830,528✔
3203
    }
3204
    case TSDB_DATA_TYPE_DOUBLE: {
419,762✔
3205
      double v = *(double*)pv;
419,762✔
3206
      return v < pDiffInfo->prev.d64;
419,762✔
3207
    }
3208
    default:
×
3209
      return false;
×
3210
  }
3211

3212
  return false;
3213
}
3214

3215
static void tryToSetInt64(SDiffInfo* pDiffInfo, int32_t type, SColumnInfoData* pOutput, int64_t v, int32_t pos) {
37,485,745✔
3216
  bool isNegative = v < pDiffInfo->prev.i64;
37,485,745✔
3217
  if(type == TSDB_DATA_TYPE_UBIGINT){
37,485,745✔
3218
    isNegative = (uint64_t)v < (uint64_t)pDiffInfo->prev.i64;
3,745✔
3219
  }
3220
  int64_t delta = v - pDiffInfo->prev.i64;
37,485,745✔
3221
  if (isNegative && ignoreNegative(pDiffInfo->ignoreOption)) {
37,485,745✔
3222
    colDataSetNull_f_s(pOutput, pos);
1,660,380✔
3223
    pOutput->hasNull = true;
1,660,380✔
3224
  } else {
3225
    colDataSetInt64(pOutput, pos, &delta);
35,825,365✔
3226
  }
3227
  pDiffInfo->prev.i64 = v;
37,485,745✔
3228
}
37,485,745✔
3229

3230
static void tryToSetDouble(SDiffInfo* pDiffInfo, SColumnInfoData* pOutput, double v, int32_t pos) {
1,471,666✔
3231
  double delta = v - pDiffInfo->prev.d64;
1,471,666✔
3232
  if (delta < 0 && ignoreNegative(pDiffInfo->ignoreOption)) {
1,471,666✔
3233
    colDataSetNull_f_s(pOutput, pos);
356,180✔
3234
  } else {
3235
    colDataSetDouble(pOutput, pos, &delta);
1,115,486✔
3236
  }
3237
  pDiffInfo->prev.d64 = v;
1,471,666✔
3238
}
1,471,666✔
3239

3240
static int32_t doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, SColumnInfoData* pOutput, int32_t pos,
38,958,026✔
3241
                            int64_t ts) {
3242
  if (!pDiffInfo->hasPrev) {
38,958,026✔
3243
    colDataSetNull_f_s(pOutput, pos);
615✔
3244
    return doSetPrevVal(pDiffInfo, type, pv, ts);
615✔
3245
  }
3246
  pDiffInfo->prevTs = ts;
38,957,411✔
3247
  switch (type) {
38,957,411!
3248
    case TSDB_DATA_TYPE_UINT: {
3,675✔
3249
      int64_t v = *(uint32_t*)pv;
3,675✔
3250
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
3,675✔
3251
      break;
3,675✔
3252
    }
3253
    case TSDB_DATA_TYPE_INT: {
31,801,698✔
3254
      int64_t v = *(int32_t*)pv;
31,801,698✔
3255
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
31,801,698✔
3256
      break;
31,801,698✔
3257
    }
3258
    case TSDB_DATA_TYPE_BOOL: {
10,877✔
3259
      int64_t v = *(bool*)pv;
10,877✔
3260
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
10,877✔
3261
      break;
10,877✔
3262
    }
3263
    case TSDB_DATA_TYPE_UTINYINT: {
675✔
3264
      int64_t v = *(uint8_t*)pv;
675✔
3265
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
675✔
3266
      break;
675✔
3267
    }
3268
    case TSDB_DATA_TYPE_TINYINT: {
380,566✔
3269
      int64_t v = *(int8_t*)pv;
380,566✔
3270
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
380,566✔
3271
      break;
380,566✔
3272
    }
3273
    case TSDB_DATA_TYPE_USMALLINT:{
675✔
3274
      int64_t v = *(uint16_t*)pv;
675✔
3275
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
675✔
3276
      break;
675✔
3277
    }
3278
    case TSDB_DATA_TYPE_SMALLINT: {
36,467✔
3279
      int64_t v = *(int16_t*)pv;
36,467✔
3280
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
36,467✔
3281
      break;
36,467✔
3282
    }
3283
    case TSDB_DATA_TYPE_TIMESTAMP:
5,251,112✔
3284
    case TSDB_DATA_TYPE_UBIGINT:
3285
    case TSDB_DATA_TYPE_BIGINT: {
3286
      int64_t v = *(int64_t*)pv;
5,251,112✔
3287
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
5,251,112✔
3288
      break;
5,251,112✔
3289
    }
3290
    case TSDB_DATA_TYPE_FLOAT: {
1,080,677✔
3291
      double v = *(float*)pv;
1,080,677✔
3292
      tryToSetDouble(pDiffInfo, pOutput, v, pos);
1,080,677✔
3293
      break;
1,080,677✔
3294
    }
3295
    case TSDB_DATA_TYPE_DOUBLE: {
390,989✔
3296
      double v = *(double*)pv;
390,989✔
3297
      tryToSetDouble(pDiffInfo, pOutput, v, pos);
390,989✔
3298
      break;
390,989✔
3299
    }
3300
    default:
×
3301
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3302
  }
3303
  pDiffInfo->hasPrev = true;
38,957,411✔
3304
  return TSDB_CODE_SUCCESS;
38,957,411✔
3305
}
3306

3307
//TODO: the primary key compare can be skipped for ordered pk if knonwn before
3308
//TODO: for desc ordered, pk shall select the smallest one for one ts. if across block boundaries.
3309
bool funcInputGetNextRowIndex(SInputColumnInfoData* pInput, int32_t from, bool firstOccur, int32_t* pRowIndex, int32_t* nextFrom) {
743,049,398✔
3310
  if (pInput->pPrimaryKey == NULL) {
743,049,398✔
3311
    if (from == -1) {
637,914,634✔
3312
      from = pInput->startRowIndex;
162,100,962✔
3313
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
475,813,672✔
3314
      return false;
161,257,310✔
3315
    }
3316
    *pRowIndex = from;
476,657,324✔
3317
    *nextFrom = from + 1;
476,657,324✔
3318
    return true;
476,657,324✔
3319
  } else {
3320
    if (from == -1) {
105,134,764✔
3321
      from = pInput->startRowIndex;
1,190,669✔
3322
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
103,944,095✔
3323
      return false;
1,190,739✔
3324
    }
3325
    TSKEY* tsList = (int64_t*)pInput->pPTS->pData;
103,944,025✔
3326
    SColumnInfoData* pkCol = pInput->pPrimaryKey;
103,944,025✔
3327
    int8_t pkType = pkCol->info.type;
103,944,025✔
3328
    int32_t order = (firstOccur) ? TSDB_ORDER_ASC: TSDB_ORDER_DESC;
103,944,025✔
3329
    __compar_fn_t compareFunc = getKeyComparFunc(pkType, order);
103,944,025✔
3330
    int32_t select = from;
104,146,843✔
3331
    char* val = colDataGetData(pkCol, select);
104,146,843!
3332
    while (from < pInput->numOfRows + pInput->startRowIndex - 1  &&  tsList[from + 1] == tsList[from]) {
110,392,892✔
3333
      char* val1 = colDataGetData(pkCol, from + 1);
6,247,974!
3334
      if (compareFunc(val1, val) < 0)  {
6,247,974✔
3335
        select = from + 1;
1,925,365✔
3336
        val = val1;
1,925,365✔
3337
      }
3338
      from = from + 1;
6,246,049✔
3339
    }
3340
    *pRowIndex = select;
104,144,918✔
3341
    *nextFrom = from + 1;
104,144,918✔
3342
    return true;
104,144,918✔
3343
  }
3344
}
3345

3346
bool getForecastConfEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
×
3347
  pEnv->calcMemSize = sizeof(float);
×
3348
  return true;
×
3349
}
3350

3351
int32_t diffResultIsNull(SqlFunctionCtx* pCtx, SFuncInputRow* pRow){
40,606,199✔
3352
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
40,606,199✔
3353
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
40,606,199✔
3354

3355
  if (pRow->isDataNull || !pDiffInfo->hasPrev ) {
40,606,199✔
3356
    return true;
188,999✔
3357
  }  else if (ignoreNegative(pDiffInfo->ignoreOption)){
40,417,200✔
3358
    return diffIsNegtive(pDiffInfo, pCtx->input.pData[0]->info.type, pRow->pData);
6,957,150✔
3359
  }
3360
  return false;
33,460,050✔
3361
}
3362

3363
bool isFirstRow(SqlFunctionCtx* pCtx, SFuncInputRow* pRow) {
39,133,055✔
3364
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
39,133,055✔
3365
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
39,133,055✔
3366
  return pDiffInfo->isFirstRow;
39,133,055✔
3367
}
3368

3369
int32_t trySetPreVal(SqlFunctionCtx* pCtx, SFuncInputRow* pRow) {
1,551,654✔
3370
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,551,654✔
3371
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
1,551,654✔
3372
  pDiffInfo->isFirstRow = false;
1,551,654✔
3373
  if (pRow->isDataNull) {
1,551,654✔
3374
    return TSDB_CODE_SUCCESS;
1,992✔
3375
  }
3376

3377
  SInputColumnInfoData* pInput = &pCtx->input;
1,549,662✔
3378
  SColumnInfoData*      pInputCol = pInput->pData[0];
1,549,662✔
3379
  int8_t                inputType = pInputCol->info.type;
1,549,662✔
3380

3381
  char*   pv = pRow->pData;
1,549,662✔
3382
  return doSetPrevVal(pDiffInfo, inputType, pv, pRow->ts);
1,549,662✔
3383
}
3384

3385
int32_t setDoDiffResult(SqlFunctionCtx* pCtx, SFuncInputRow* pRow, int32_t pos) {
39,054,545✔
3386
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
39,054,545✔
3387
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
39,054,545✔
3388

3389
  SInputColumnInfoData* pInput = &pCtx->input;
39,054,545✔
3390
  SColumnInfoData*      pInputCol = pInput->pData[0];
39,054,545✔
3391
  int8_t                inputType = pInputCol->info.type;
39,054,545✔
3392
  SColumnInfoData*      pOutput = (SColumnInfoData*)pCtx->pOutput;
39,054,545✔
3393
  int32_t               code = TSDB_CODE_SUCCESS;
39,054,545✔
3394
  if (pRow->isDataNull) {
39,054,545✔
3395
    colDataSetNull_f_s(pOutput, pos);
96,496✔
3396
    pOutput->hasNull = true;
96,496✔
3397

3398
    // handle selectivity
3399
    if (pCtx->subsidiaries.num > 0) {
96,496✔
3400
      code = appendSelectivityCols(pCtx, pRow->block, pRow->rowIndex, pos);
860✔
3401
      if (code != TSDB_CODE_SUCCESS) {
860!
3402
        return code;
×
3403
      }
3404
    }
3405
    return TSDB_CODE_SUCCESS;
96,496✔
3406
  }
3407

3408
  char* pv = pRow->pData;
38,958,049✔
3409

3410
  if (pRow->ts == pDiffInfo->prevTs) {
38,958,049✔
3411
    return TSDB_CODE_FUNC_DUP_TIMESTAMP;
23✔
3412
  }
3413
  code = doHandleDiff(pDiffInfo, inputType, pv, pOutput, pos, pRow->ts);
38,958,026✔
3414
  if (code != TSDB_CODE_SUCCESS) {
38,958,026!
3415
    return code;
×
3416
  }
3417
  // handle selectivity
3418
  if (pCtx->subsidiaries.num > 0) {
38,958,026✔
3419
    code = appendSelectivityCols(pCtx, pRow->block, pRow->rowIndex, pos);
35,533,776✔
3420
    if (code != TSDB_CODE_SUCCESS) {
35,533,776!
3421
      return code;
×
3422
    }
3423
  }
3424

3425
  return TSDB_CODE_SUCCESS;
38,958,026✔
3426
}
3427

3428
int32_t diffFunction(SqlFunctionCtx* pCtx) {
423,931✔
3429
  return TSDB_CODE_SUCCESS;
423,931✔
3430
}
3431

3432
int32_t diffFunctionByRow(SArray* pCtxArray) {
423,673✔
3433
  int32_t code = TSDB_CODE_SUCCESS;
423,673✔
3434
  int diffColNum = pCtxArray->size;
423,673✔
3435
  if(diffColNum == 0) {
423,673!
3436
    return TSDB_CODE_SUCCESS;
×
3437
  }
3438
  int32_t numOfElems = 0;
423,673✔
3439

3440
  SArray*  pRows = taosArrayInit_s(sizeof(SFuncInputRow), diffColNum);
423,673✔
3441
  if (NULL == pRows) {
423,673!
3442
    return terrno;
×
3443
  }
3444

3445
  bool keepNull = false;
423,673✔
3446
  for (int i = 0; i < diffColNum; ++i) {
847,604✔
3447
    SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
423,931✔
3448
    if (NULL == pCtx) {
423,931!
3449
      code = terrno;
×
3450
      goto _exit;
×
3451
    }
3452
    funcInputUpdate(pCtx);
423,931✔
3453
    SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
423,931✔
3454
    SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
423,931✔
3455
    if (!ignoreNull(pDiffInfo->ignoreOption)) {
423,931✔
3456
      keepNull = true;
405,030✔
3457
    }
3458
  }
3459

3460
  SqlFunctionCtx* pCtx0 = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, 0);
423,673✔
3461
  SFuncInputRow* pRow0 = (SFuncInputRow*)taosArrayGet(pRows, 0);
423,673✔
3462
  if (NULL == pCtx0 || NULL == pRow0) {
423,673!
3463
    code = terrno;
×
3464
    goto _exit;
×
3465
  }
3466
  int32_t startOffset = pCtx0->offset;
423,673✔
3467
  bool    result = false;
423,673✔
3468
  while (1) {
40,588,686✔
3469
    code = funcInputGetNextRow(pCtx0, pRow0, &result);
41,012,359✔
3470
    if (TSDB_CODE_SUCCESS != code) {
41,012,359!
3471
      goto _exit;
×
3472
    }
3473
    if (!result) {
41,012,359✔
3474
      break;
423,650✔
3475
    }
3476
    bool hasNotNullValue = !diffResultIsNull(pCtx0, pRow0);
40,588,709✔
3477
    for (int i = 1; i < diffColNum; ++i) {
40,606,199✔
3478
      SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
17,490✔
3479
      SFuncInputRow* pRow = (SFuncInputRow*)taosArrayGet(pRows, i);
17,490✔
3480
      if (NULL == pCtx || NULL == pRow) {
17,490!
3481
        code = terrno;
×
3482
        goto _exit;
×
3483
      }
3484
      code = funcInputGetNextRow(pCtx, pRow, &result);
17,490✔
3485
      if (TSDB_CODE_SUCCESS != code) {
17,490!
3486
        goto _exit;
×
3487
      }
3488
      if (!result) {
17,490!
3489
        // rows are not equal
3490
        code = TSDB_CODE_QRY_EXECUTOR_INTERNAL_ERROR;
×
3491
        goto _exit;
×
3492
      }
3493
      if (!diffResultIsNull(pCtx, pRow)) {
17,490✔
3494
        hasNotNullValue = true;
16,754✔
3495
      }
3496
    }
3497
    int32_t pos = startOffset + numOfElems;
40,588,709✔
3498

3499
    bool newRow = false;
40,588,709✔
3500
    for (int i = 0; i < diffColNum; ++i) {
81,194,885✔
3501
      SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
40,606,199✔
3502
      SFuncInputRow*  pRow = (SFuncInputRow*)taosArrayGet(pRows, i);
40,606,199✔
3503
      if (NULL == pCtx || NULL == pRow) {
40,606,199!
3504
        code = terrno;
×
3505
        goto _exit;
×
3506
      }
3507
      if ((keepNull || hasNotNullValue) && !isFirstRow(pCtx, pRow)){
40,606,199✔
3508
        code = setDoDiffResult(pCtx, pRow, pos);
39,054,545✔
3509
        if (code != TSDB_CODE_SUCCESS) {
39,054,545✔
3510
          goto _exit;
23✔
3511
        }
3512
        newRow = true;
39,054,522✔
3513
      } else {
3514
        code = trySetPreVal(pCtx, pRow);
1,551,654✔
3515
        if (code != TSDB_CODE_SUCCESS) {
1,551,654!
3516
          goto _exit;
×
3517
        } 
3518
      }
3519
    }
3520
    if (newRow) ++numOfElems;
40,588,686✔
3521
  }
3522

3523
  for (int i = 0; i < diffColNum; ++i) {
847,553✔
3524
    SqlFunctionCtx*      pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
423,903✔
3525
    if (NULL == pCtx) {
423,903!
3526
      code = terrno;
×
3527
      goto _exit;
×
3528
    }
3529
    SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
423,903✔
3530
    pResInfo->numOfRes = numOfElems;
423,903✔
3531
  }
3532

3533
_exit:
423,650✔
3534
  if (pRows) {
423,673!
3535
    taosArrayDestroy(pRows);
423,673✔
3536
    pRows = NULL;
423,673✔
3537
  }
3538
  return code;
423,673✔
3539
}
3540

3541
int32_t getTopBotInfoSize(int64_t numOfItems) { return sizeof(STopBotRes) + numOfItems * sizeof(STopBotResItem); }
×
3542

3543
bool getTopBotFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
55,113✔
3544
  SValueNode* pkNode = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
55,113✔
3545
  pEnv->calcMemSize = sizeof(STopBotRes) + pkNode->datum.i * sizeof(STopBotResItem);
55,150✔
3546
  return true;
55,150✔
3547
}
3548

3549
int32_t topBotFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
17,322,074✔
3550
  if (pResInfo->initialized) {
17,322,074!
3551
    return TSDB_CODE_SUCCESS;
×
3552
  }
3553
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
17,322,074!
3554
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
3555
  }
3556

3557
  STopBotRes*           pRes = GET_ROWCELL_INTERBUF(pResInfo);
17,344,924✔
3558
  SInputColumnInfoData* pInput = &pCtx->input;
17,344,924✔
3559

3560
  pRes->maxSize = pCtx->param[1].param.i;
17,344,924✔
3561

3562
  pRes->nullTupleSaved = false;
17,344,924✔
3563
  pRes->nullTuplePos.pageId = -1;
17,344,924✔
3564
  return TSDB_CODE_SUCCESS;
17,344,924✔
3565
}
3566

3567
static STopBotRes* getTopBotOutputInfo(SqlFunctionCtx* pCtx) {
97,403,394✔
3568
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
97,403,394✔
3569
  STopBotRes*          pRes = GET_ROWCELL_INTERBUF(pResInfo);
97,403,394✔
3570
  pRes->pItems = (STopBotResItem*)((char*)pRes + sizeof(STopBotRes));
97,403,394✔
3571

3572
  return pRes;
97,403,394✔
3573
}
3574

3575
static int32_t doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock,
3576
                               uint16_t type, uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery);
3577

3578
static int32_t addResult(SqlFunctionCtx* pCtx, STopBotResItem* pSourceItem, int16_t type, bool isTopQuery);
3579

3580
int32_t topFunction(SqlFunctionCtx* pCtx) {
14,194,624✔
3581
  int32_t              numOfElems = 0;
14,194,624✔
3582
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
14,194,624✔
3583

3584
  SInputColumnInfoData* pInput = &pCtx->input;
14,194,624✔
3585
  SColumnInfoData*      pCol = pInput->pData[0];
14,194,624✔
3586

3587
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
14,194,624✔
3588
  pRes->type = pInput->pData[0]->info.type;
14,192,507✔
3589

3590
  int32_t start = pInput->startRowIndex;
14,192,507✔
3591
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
56,420,938✔
3592
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
42,216,814✔
3593
      continue;
23,717✔
3594
    }
3595

3596
    numOfElems++;
42,193,097✔
3597
    char*   data = colDataGetData(pCol, i);
42,193,097!
3598
    int32_t code = doAddIntoResult(pCtx, data, i, pCtx->pSrcBlock, pRes->type, pInput->uid, pResInfo, true);
42,193,097✔
3599
    if (code != TSDB_CODE_SUCCESS) {
42,204,714!
3600
      return code;
×
3601
    }
3602
  }
3603

3604
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pRes->nullTupleSaved) {
14,204,124✔
3605
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pRes->nullTuplePos);
113✔
3606
    if (code != TSDB_CODE_SUCCESS) {
113!
3607
      return code;
×
3608
    }
3609
    pRes->nullTupleSaved = true;
113✔
3610
  }
3611
  return TSDB_CODE_SUCCESS;
14,204,124✔
3612
}
3613

3614
int32_t bottomFunction(SqlFunctionCtx* pCtx) {
3,693,786✔
3615
  int32_t              numOfElems = 0;
3,693,786✔
3616
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
3,693,786✔
3617

3618
  SInputColumnInfoData* pInput = &pCtx->input;
3,693,786✔
3619
  SColumnInfoData*      pCol = pInput->pData[0];
3,693,786✔
3620

3621
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
3,693,786✔
3622
  pRes->type = pInput->pData[0]->info.type;
3,693,724✔
3623

3624
  int32_t start = pInput->startRowIndex;
3,693,724✔
3625
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
24,016,291✔
3626
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
20,319,880✔
3627
      continue;
30,096✔
3628
    }
3629

3630
    numOfElems++;
20,289,784✔
3631
    char*   data = colDataGetData(pCol, i);
20,289,784!
3632
    int32_t code = doAddIntoResult(pCtx, data, i, pCtx->pSrcBlock, pRes->type, pInput->uid, pResInfo, false);
20,289,784✔
3633
    if (code != TSDB_CODE_SUCCESS) {
20,292,471!
3634
      return code;
×
3635
    }
3636
  }
3637

3638
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pRes->nullTupleSaved) {
3,696,411✔
3639
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pRes->nullTuplePos);
200✔
3640
    if (code != TSDB_CODE_SUCCESS) {
200!
3641
      return code;
×
3642
    }
3643
    pRes->nullTupleSaved = true;
200✔
3644
  }
3645

3646
  return TSDB_CODE_SUCCESS;
3,696,411✔
3647
}
3648

3649
static int32_t topBotResComparFn(const void* p1, const void* p2, const void* param) {
278,734,612✔
3650
  uint16_t type = *(uint16_t*)param;
278,734,612✔
3651

3652
  STopBotResItem* val1 = (STopBotResItem*)p1;
278,734,612✔
3653
  STopBotResItem* val2 = (STopBotResItem*)p2;
278,734,612✔
3654

3655
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
278,734,612!
3656
    if (val1->v.i == val2->v.i) {
207,414,792✔
3657
      return 0;
260,110✔
3658
    }
3659

3660
    return (val1->v.i > val2->v.i) ? 1 : -1;
207,154,682✔
3661
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
71,319,820✔
3662
    if (val1->v.u == val2->v.u) {
831,803✔
3663
      return 0;
177,108✔
3664
    }
3665

3666
    return (val1->v.u > val2->v.u) ? 1 : -1;
654,695✔
3667
  } else if (TSDB_DATA_TYPE_FLOAT == type) {
70,488,017✔
3668
    if (val1->v.f == val2->v.f) {
13,917,189✔
3669
      return 0;
63✔
3670
    }
3671

3672
    return (val1->v.f > val2->v.f) ? 1 : -1;
13,917,126✔
3673
  }
3674

3675
  if (val1->v.d == val2->v.d) {
56,570,828✔
3676
    return 0;
11✔
3677
  }
3678

3679
  return (val1->v.d > val2->v.d) ? 1 : -1;
56,570,817✔
3680
}
3681

3682
int32_t doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, uint16_t type,
62,462,007✔
3683
                        uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery) {
3684
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
62,462,007✔
3685
  int32_t     code = TSDB_CODE_SUCCESS;
62,444,454✔
3686

3687
  SVariant val = {0};
62,444,454✔
3688
  TAOS_CHECK_RETURN(taosVariantCreateFromBinary(&val, pData, tDataTypes[type].bytes, type));
62,444,454!
3689

3690
  STopBotResItem* pItems = pRes->pItems;
62,491,652✔
3691

3692
  // not full yet
3693
  if (pEntryInfo->numOfRes < pRes->maxSize) {
62,491,652✔
3694
    STopBotResItem* pItem = &pItems[pEntryInfo->numOfRes];
33,805,791✔
3695
    pItem->v = val;
33,805,791✔
3696
    pItem->uid = uid;
33,805,791✔
3697

3698
    // save the data of this tuple
3699
    if (pCtx->subsidiaries.num > 0) {
33,805,791✔
3700
      code = saveTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
5,043,603✔
3701
      if (code != TSDB_CODE_SUCCESS) {
5,038,846!
3702
        return code;
×
3703
      }
3704
    }
3705
#ifdef BUF_PAGE_DEBUG
3706
    qDebug("page_saveTuple i:%d, item:%p,pageId:%d, offset:%d\n", pEntryInfo->numOfRes, pItem, pItem->tuplePos.pageId,
3707
           pItem->tuplePos.offset);
3708
#endif
3709
    // allocate the buffer and keep the data of this row into the new allocated buffer
3710
    pEntryInfo->numOfRes++;
33,801,034✔
3711
    code = taosheapsort((void*)pItems, sizeof(STopBotResItem), pEntryInfo->numOfRes, (const void*)&type,
33,801,034✔
3712
                        topBotResComparFn, !isTopQuery);
33,801,034✔
3713
    if (code != TSDB_CODE_SUCCESS) {
33,834,769!
3714
      return code;
×
3715
    }
3716
  } else {  // replace the minimum value in the result
3717
    if ((isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i > pItems[0].v.i) ||
28,685,861!
3718
                        (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u > pItems[0].v.u) ||
12,670,663!
3719
                        (TSDB_DATA_TYPE_FLOAT == type && val.f > pItems[0].v.f) ||
12,575,948✔
3720
                        (TSDB_DATA_TYPE_DOUBLE == type && val.d > pItems[0].v.d))) ||
12,210,441✔
3721
        (!isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i < pItems[0].v.i) ||
24,994,793!
3722
                         (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u < pItems[0].v.u) ||
12,730,268!
3723
                         (TSDB_DATA_TYPE_FLOAT == type && val.f < pItems[0].v.f) ||
12,726,060✔
3724
                         (TSDB_DATA_TYPE_DOUBLE == type && val.d < pItems[0].v.d)))) {
12,528,295✔
3725
      // replace the old data and the coresponding tuple data
3726
      STopBotResItem* pItem = &pItems[0];
6,060,077✔
3727
      pItem->v = val;
6,060,077✔
3728
      pItem->uid = uid;
6,060,077✔
3729

3730
      // save the data of this tuple by over writing the old data
3731
      if (pCtx->subsidiaries.num > 0) {
6,060,077✔
3732
        code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
3,288,558✔
3733
        if (code != TSDB_CODE_SUCCESS) {
3,285,675!
3734
          return code;
×
3735
        }
3736
      }
3737
#ifdef BUF_PAGE_DEBUG
3738
      qDebug("page_copyTuple pageId:%d, offset:%d", pItem->tuplePos.pageId, pItem->tuplePos.offset);
3739
#endif
3740
      code = taosheapadjust((void*)pItems, sizeof(STopBotResItem), 0, pEntryInfo->numOfRes - 1, (const void*)&type,
6,057,194✔
3741
                     topBotResComparFn, NULL, !isTopQuery);
6,057,194✔
3742
      if (code != TSDB_CODE_SUCCESS) {
6,026,280!
3743
        return code;
×
3744
      }
3745
    }
3746
  }
3747

3748
  return TSDB_CODE_SUCCESS;
62,486,833✔
3749
}
3750

3751
/*
3752
 * +------------------------------------+--------------+--------------+
3753
 * |            null bitmap             |              |              |
3754
 * |(n columns, one bit for each column)| src column #1| src column #2|
3755
 * +------------------------------------+--------------+--------------+
3756
 */
3757
int32_t serializeTupleData(const SSDataBlock* pSrcBlock, int32_t rowIndex, SSubsidiaryResInfo* pSubsidiaryies,
230,369,134✔
3758
                         char* buf, char** res) {
3759
  char* nullList = buf;
230,369,134✔
3760
  char* pStart = (char*)(nullList + sizeof(bool) * pSubsidiaryies->num);
230,369,134✔
3761

3762
  int32_t offset = 0;
230,369,134✔
3763
  for (int32_t i = 0; i < pSubsidiaryies->num; ++i) {
460,620,479✔
3764
    SqlFunctionCtx* pc = pSubsidiaryies->pCtx[i];
230,467,460✔
3765

3766
    // group_key function has its own process function
3767
    // do not process there
3768
    if (fmIsGroupKeyFunc(pc->functionId)) {
230,467,460✔
3769
      continue;
8,185,887✔
3770
    }
3771

3772
    SFunctParam* pFuncParam = &pc->pExpr->base.pParam[0];
222,253,759✔
3773
    int32_t      srcSlotId = pFuncParam->pCol->slotId;
222,253,759✔
3774

3775
    SColumnInfoData* pCol = taosArrayGet(pSrcBlock->pDataBlock, srcSlotId);
222,253,759✔
3776
    if (NULL == pCol) {
222,065,458!
3777
      return TSDB_CODE_OUT_OF_RANGE;
×
3778
    }
3779
    if ((nullList[i] = colDataIsNull_s(pCol, rowIndex)) == true) {
444,130,916✔
3780
      offset += pCol->info.bytes;
437✔
3781
      continue;
437✔
3782
    }
3783

3784
    char* p = colDataGetData(pCol, rowIndex);
222,065,021!
3785
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
222,065,021!
3786
      (void)memcpy(pStart + offset, p, (pCol->info.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(p) : varDataTLen(p));
65,416!
3787
    } else {
3788
      (void)memcpy(pStart + offset, p, pCol->info.bytes);
221,999,605✔
3789
    }
3790

3791
    offset += pCol->info.bytes;
222,065,021✔
3792
  }
3793

3794
  *res = buf;
230,153,019✔
3795
  return TSDB_CODE_SUCCESS;
230,153,019✔
3796
}
3797

3798
static int32_t doSaveTupleData(SSerializeDataHandle* pHandle, const void* pBuf, size_t length, SWinKey* key,
245,236,197✔
3799
                               STuplePos* pPos, SFunctionStateStore* pStore) {
3800
  STuplePos p = {0};
245,236,197✔
3801
  if (pHandle->pBuf != NULL) {
245,236,197✔
3802
    SFilePage* pPage = NULL;
245,109,885✔
3803

3804
    if (pHandle->currentPage == -1) {
245,109,885✔
3805
      pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
658,621✔
3806
      if (pPage == NULL) {
658,649!
3807
        return terrno;
×
3808
      }
3809
      pPage->num = sizeof(SFilePage);
658,649✔
3810
    } else {
3811
      pPage = getBufPage(pHandle->pBuf, pHandle->currentPage);
244,451,264✔
3812
      if (pPage == NULL) {
244,433,258!
3813
        return terrno;
×
3814
      }
3815
      if (pPage->num + length > getBufPageSize(pHandle->pBuf)) {
244,433,258✔
3816
        // current page is all used, let's prepare a new buffer page
3817
        releaseBufPage(pHandle->pBuf, pPage);
1,241,601✔
3818
        pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
1,241,601✔
3819
        if (pPage == NULL) {
1,241,601!
3820
          return terrno;
×
3821
        }
3822
        pPage->num = sizeof(SFilePage);
1,241,601✔
3823
      }
3824
    }
3825

3826
    p = (STuplePos){.pageId = pHandle->currentPage, .offset = pPage->num};
245,074,831✔
3827
    (void)memcpy(pPage->data + pPage->num, pBuf, length);
245,074,831✔
3828

3829
    pPage->num += length;
245,074,831✔
3830
    setBufPageDirty(pPage, true);
245,074,831✔
3831
    releaseBufPage(pHandle->pBuf, pPage);
244,968,451✔
3832
  } else { // other tuple save policy
3833
    if (pStore->streamStateFuncPut(pHandle->pState, key, pBuf, length) >= 0) {
126,312✔
3834
      p.streamTupleKey = *key;
141,756✔
3835
    }
3836
  }
3837

3838
  *pPos = p;
245,043,108✔
3839
  return TSDB_CODE_SUCCESS;
245,043,108✔
3840
}
3841

3842
int32_t saveTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
162,522,880✔
3843
  int32_t code = prepareBuf(pCtx);
162,522,880✔
3844
  if (TSDB_CODE_SUCCESS != code) {
162,478,555!
3845
    return code;
×
3846
  }
3847

3848
  SWinKey key = {0};
162,478,555✔
3849
  if (pCtx->saveHandle.pBuf == NULL) {
162,478,555✔
3850
    SColumnInfoData* pColInfo = taosArrayGet(pSrcBlock->pDataBlock, pCtx->saveHandle.pState->tsIndex);
141,754✔
3851
    if (NULL == pColInfo) {
141,753!
3852
      return TSDB_CODE_OUT_OF_RANGE;
×
3853
    }
3854
    if (pColInfo->info.type != TSDB_DATA_TYPE_TIMESTAMP) {
141,753!
3855
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3856
    }
3857
    key.groupId = pSrcBlock->info.id.groupId;
141,753✔
3858
    key.ts = *(int64_t*)colDataGetData(pColInfo, rowIndex);
141,753!
3859
  }
3860

3861
  char* buf = NULL;
162,478,554✔
3862
  code = serializeTupleData(pSrcBlock, rowIndex, &pCtx->subsidiaries, pCtx->subsidiaries.buf, &buf);
162,478,554✔
3863
  if (TSDB_CODE_SUCCESS != code) {
162,357,232!
3864
    return code;
×
3865
  }
3866
  return doSaveTupleData(&pCtx->saveHandle, buf, pCtx->subsidiaries.rowLen, &key, pPos, pCtx->pStore);
162,357,232✔
3867
}
3868

3869
static int32_t doUpdateTupleData(SSerializeDataHandle* pHandle, const void* pBuf, size_t length, STuplePos* pPos, SFunctionStateStore* pStore) {
67,952,413✔
3870
  if (pHandle->pBuf != NULL) {
67,952,413✔
3871
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
67,626,867✔
3872
    if (pPage == NULL) {
67,627,412!
3873
      return terrno;
×
3874
    }
3875
    (void)memcpy(pPage->data + pPos->offset, pBuf, length);
67,627,412✔
3876
    setBufPageDirty(pPage, true);
67,627,412✔
3877
    releaseBufPage(pHandle->pBuf, pPage);
67,622,728✔
3878
  } else {
3879
    int32_t code = pStore->streamStateFuncPut(pHandle->pState, &pPos->streamTupleKey, pBuf, length);
325,546✔
3880
    if (TSDB_CODE_SUCCESS != code) {
326,150!
3881
      return code;
×
3882
    }
3883
  }
3884

3885
  return TSDB_CODE_SUCCESS;
67,940,203✔
3886
}
3887

3888
int32_t updateTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
67,961,068✔
3889
  int32_t code = prepareBuf(pCtx);
67,961,068✔
3890
  if (TSDB_CODE_SUCCESS != code) {
67,958,564!
3891
    return code;
×
3892
  }
3893

3894
  char* buf = NULL;
67,958,564✔
3895
  code = serializeTupleData(pSrcBlock, rowIndex, &pCtx->subsidiaries, pCtx->subsidiaries.buf, &buf);
67,958,564✔
3896
  if (TSDB_CODE_SUCCESS != code) {
67,952,031!
3897
    return code;
×
3898
  }
3899
  return doUpdateTupleData(&pCtx->saveHandle, buf, pCtx->subsidiaries.rowLen, pPos, pCtx->pStore);
67,952,031✔
3900
}
3901

3902
static int32_t doLoadTupleData(SSerializeDataHandle* pHandle, const STuplePos* pPos, SFunctionStateStore* pStore, char** value) {
115,278,102✔
3903
  if (pHandle->pBuf != NULL) {
115,278,102✔
3904
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
115,123,383✔
3905
    if (pPage == NULL) {
115,214,737!
3906
      *value = NULL;
×
3907
      return terrno;
×
3908
    }
3909
    *value = pPage->data + pPos->offset;
115,214,737✔
3910
    releaseBufPage(pHandle->pBuf, pPage);
115,214,737✔
3911
    return TSDB_CODE_SUCCESS;
115,077,959✔
3912
  } else {
3913
    *value = NULL;
154,719✔
3914
    int32_t vLen;
3915
    int32_t code = pStore->streamStateFuncGet(pHandle->pState, &pPos->streamTupleKey, (void **)(value), &vLen);
154,719✔
3916
    if (TSDB_CODE_SUCCESS != code) {
167,528!
3917
      return code;
×
3918
    }
3919
    return TSDB_CODE_SUCCESS;
167,528✔
3920
  }
3921
}
3922

3923
int32_t loadTupleData(SqlFunctionCtx* pCtx, const STuplePos* pPos, char** value) {
115,106,791✔
3924
  return doLoadTupleData(&pCtx->saveHandle, pPos, pCtx->pStore, value);
115,106,791✔
3925
}
3926

3927
int32_t topBotFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
17,183,411✔
3928
  int32_t code = TSDB_CODE_SUCCESS;
17,183,411✔
3929

3930
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
17,183,411✔
3931
  STopBotRes*          pRes = getTopBotOutputInfo(pCtx);
17,183,411✔
3932

3933
  int16_t type = pCtx->pExpr->base.resSchema.type;
17,179,990✔
3934
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
17,179,990✔
3935

3936
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
17,179,990✔
3937
  if (NULL == pCol) {
17,175,736!
3938
    return TSDB_CODE_OUT_OF_RANGE;
×
3939
  }
3940

3941
  // todo assign the tag value and the corresponding row data
3942
  int32_t currentRow = pBlock->info.rows;
17,175,736✔
3943
  if (pEntryInfo->numOfRes <= 0) {
17,175,736✔
3944
    colDataSetNULL(pCol, currentRow);
539!
3945
    code = setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, currentRow);
539✔
3946
    return code;
539✔
3947
  }
3948
  for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
50,531,741✔
3949
    STopBotResItem* pItem = &pRes->pItems[i];
33,364,135✔
3950
    code = colDataSetVal(pCol, currentRow, (const char*)&pItem->v.i, false);
33,364,135✔
3951
    if (TSDB_CODE_SUCCESS != code) {
33,359,011!
3952
      return code;
×
3953
    }
3954
#ifdef BUF_PAGE_DEBUG
3955
    qDebug("page_finalize i:%d,item:%p,pageId:%d, offset:%d\n", i, pItem, pItem->tuplePos.pageId,
3956
           pItem->tuplePos.offset);
3957
#endif
3958
    code = setSelectivityValue(pCtx, pBlock, &pRes->pItems[i].tuplePos, currentRow);
33,359,011✔
3959
    if (TSDB_CODE_SUCCESS != code) {
33,356,544!
3960
      return code;
×
3961
    }
3962
    currentRow += 1;
33,356,544✔
3963
  }
3964

3965
  return code;
17,167,606✔
3966
}
3967

3968
int32_t addResult(SqlFunctionCtx* pCtx, STopBotResItem* pSourceItem, int16_t type, bool isTopQuery) {
×
3969
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
×
3970
  STopBotRes*          pRes = getTopBotOutputInfo(pCtx);
×
3971
  STopBotResItem*      pItems = pRes->pItems;
×
3972
  int32_t              code = TSDB_CODE_SUCCESS;
×
3973

3974
  // not full yet
3975
  if (pEntryInfo->numOfRes < pRes->maxSize) {
×
3976
    STopBotResItem* pItem = &pItems[pEntryInfo->numOfRes];
×
3977
    pItem->v = pSourceItem->v;
×
3978
    pItem->uid = pSourceItem->uid;
×
3979
    pItem->tuplePos.pageId = -1;
×
3980
    replaceTupleData(&pItem->tuplePos, &pSourceItem->tuplePos);
×
3981
    pEntryInfo->numOfRes++;
×
3982
   code = taosheapsort((void*)pItems, sizeof(STopBotResItem), pEntryInfo->numOfRes, (const void*)&type,
×
3983
                        topBotResComparFn, !isTopQuery);
×
3984
   if (TSDB_CODE_SUCCESS != code) {
×
3985
     return code;
×
3986
   }
3987
  } else {  // replace the minimum value in the result
3988
    if ((isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && pSourceItem->v.i > pItems[0].v.i) ||
×
3989
                        (IS_UNSIGNED_NUMERIC_TYPE(type) && pSourceItem->v.u > pItems[0].v.u) ||
×
3990
                        (TSDB_DATA_TYPE_FLOAT == type && pSourceItem->v.f > pItems[0].v.f) ||
×
3991
                        (TSDB_DATA_TYPE_DOUBLE == type && pSourceItem->v.d > pItems[0].v.d))) ||
×
3992
        (!isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && pSourceItem->v.i < pItems[0].v.i) ||
×
3993
                         (IS_UNSIGNED_NUMERIC_TYPE(type) && pSourceItem->v.u < pItems[0].v.u) ||
×
3994
                         (TSDB_DATA_TYPE_FLOAT == type && pSourceItem->v.f < pItems[0].v.f) ||
×
3995
                         (TSDB_DATA_TYPE_DOUBLE == type && pSourceItem->v.d < pItems[0].v.d)))) {
×
3996
      // replace the old data and the coresponding tuple data
3997
      STopBotResItem* pItem = &pItems[0];
×
3998
      pItem->v = pSourceItem->v;
×
3999
      pItem->uid = pSourceItem->uid;
×
4000

4001
      // save the data of this tuple by over writing the old data
4002
      replaceTupleData(&pItem->tuplePos, &pSourceItem->tuplePos);
×
4003
      code = taosheapadjust((void*)pItems, sizeof(STopBotResItem), 0, pEntryInfo->numOfRes - 1, (const void*)&type,
×
4004
                            topBotResComparFn, NULL, !isTopQuery);
×
4005
      if (TSDB_CODE_SUCCESS != code) {
×
4006
        return code;
×
4007
      }
4008
    }
4009
  }
4010
  return code;
×
4011
}
4012

4013
int32_t topCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4014
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4015
  STopBotRes*          pSBuf = getTopBotOutputInfo(pSourceCtx);
×
4016
  int16_t              type = pSBuf->type;
×
4017
  int32_t              code = TSDB_CODE_SUCCESS;
×
4018
  for (int32_t i = 0; i < pSResInfo->numOfRes; i++) {
×
4019
    code = addResult(pDestCtx, pSBuf->pItems + i, type, true);
×
4020
    if (TSDB_CODE_SUCCESS != code) {
×
4021
      return code;
×
4022
    }
4023
  }
4024
  return TSDB_CODE_SUCCESS;
×
4025
}
4026

4027
int32_t bottomCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4028
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4029
  STopBotRes*          pSBuf = getTopBotOutputInfo(pSourceCtx);
×
4030
  int16_t              type = pSBuf->type;
×
4031
  int32_t              code = TSDB_CODE_SUCCESS;
×
4032
  for (int32_t i = 0; i < pSResInfo->numOfRes; i++) {
×
4033
    code = addResult(pDestCtx, pSBuf->pItems + i, type, false);
×
4034
    if (TSDB_CODE_SUCCESS != code) {
×
4035
      return code;
×
4036
    }
4037
  }
4038
  return TSDB_CODE_SUCCESS;
×
4039
}
4040

4041
int32_t getSpreadInfoSize() { return (int32_t)sizeof(SSpreadInfo); }
948,396✔
4042

4043
bool getSpreadFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
104,972✔
4044
  pEnv->calcMemSize = sizeof(SSpreadInfo);
104,972✔
4045
  return true;
104,972✔
4046
}
4047

4048
int32_t spreadFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
4,695,330✔
4049
  if (pResultInfo->initialized) {
4,695,330!
4050
    return TSDB_CODE_SUCCESS;
×
4051
  }
4052
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
4,695,330!
4053
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
4054
  }
4055

4056
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
4,695,348✔
4057
  SET_DOUBLE_VAL(&pInfo->min, DBL_MAX);
4,695,348✔
4058
  SET_DOUBLE_VAL(&pInfo->max, -DBL_MAX);
4,695,348✔
4059
  pInfo->hasResult = false;
4,695,348✔
4060
  return TSDB_CODE_SUCCESS;
4,695,348✔
4061
}
4062

4063
int32_t spreadFunction(SqlFunctionCtx* pCtx) {
4,666,410✔
4064
  int32_t numOfElems = 0;
4,666,410✔
4065

4066
  // Only the pre-computing information loaded and actual data does not loaded
4067
  SInputColumnInfoData* pInput = &pCtx->input;
4,666,410✔
4068
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
4,666,410✔
4069
  int32_t               type = pInput->pData[0]->info.type;
4,666,410✔
4070

4071
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
4,666,410✔
4072

4073
  if (pInput->colDataSMAIsSet) {
4,666,410!
4074
    numOfElems = pInput->numOfRows - pAgg->numOfNull;
×
4075
    if (numOfElems == 0) {
×
4076
      goto _spread_over;
×
4077
    }
4078
    double tmin = 0.0, tmax = 0.0;
×
4079
    if (IS_SIGNED_NUMERIC_TYPE(type) || IS_TIMESTAMP_TYPE(type)) {
×
4080
      tmin = (double)GET_INT64_VAL(&pAgg->min);
×
4081
      tmax = (double)GET_INT64_VAL(&pAgg->max);
×
4082
    } else if (IS_FLOAT_TYPE(type)) {
×
4083
      tmin = GET_DOUBLE_VAL(&pAgg->min);
×
4084
      tmax = GET_DOUBLE_VAL(&pAgg->max);
×
4085
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
4086
      tmin = (double)GET_UINT64_VAL(&pAgg->min);
×
4087
      tmax = (double)GET_UINT64_VAL(&pAgg->max);
×
4088
    }
4089

4090
    if (GET_DOUBLE_VAL(&pInfo->min) > tmin) {
×
4091
      SET_DOUBLE_VAL(&pInfo->min, tmin);
×
4092
    }
4093

4094
    if (GET_DOUBLE_VAL(&pInfo->max) < tmax) {
×
4095
      SET_DOUBLE_VAL(&pInfo->max, tmax);
×
4096
    }
4097

4098
  } else {  // computing based on the true data block
4099
    SColumnInfoData* pCol = pInput->pData[0];
4,666,410✔
4100

4101
    int32_t start = pInput->startRowIndex;
4,666,410✔
4102
    // check the valid data one by one
4103
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
24,056,118✔
4104
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
19,389,708✔
4105
        continue;
1,575,670✔
4106
      }
4107

4108
      char* data = colDataGetData(pCol, i);
17,814,038!
4109

4110
      double v = 0;
17,814,038✔
4111
      GET_TYPED_DATA(v, double, type, data);
17,814,038!
4112
      if (v < GET_DOUBLE_VAL(&pInfo->min)) {
17,814,038✔
4113
        SET_DOUBLE_VAL(&pInfo->min, v);
5,608,420✔
4114
      }
4115

4116
      if (v > GET_DOUBLE_VAL(&pInfo->max)) {
17,814,038✔
4117
        SET_DOUBLE_VAL(&pInfo->max, v);
5,732,414✔
4118
      }
4119

4120
      numOfElems += 1;
17,814,038✔
4121
    }
4122
  }
4123

4124
_spread_over:
4,666,410✔
4125
  // data in the check operation are all null, not output
4126
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
4,666,410✔
4127
  if (numOfElems > 0) {
4,666,410✔
4128
    pInfo->hasResult = true;
4,641,493✔
4129
  }
4130

4131
  return TSDB_CODE_SUCCESS;
4,666,410✔
4132
}
4133

4134
static void spreadTransferInfo(SSpreadInfo* pInput, SSpreadInfo* pOutput) {
947,039✔
4135
  pOutput->hasResult = pInput->hasResult;
947,039✔
4136
  if (pInput->max > pOutput->max) {
947,039✔
4137
    pOutput->max = pInput->max;
942,314✔
4138
  }
4139

4140
  if (pInput->min < pOutput->min) {
947,039✔
4141
    pOutput->min = pInput->min;
942,306✔
4142
  }
4143
}
947,039✔
4144

4145
int32_t spreadFunctionMerge(SqlFunctionCtx* pCtx) {
943,059✔
4146
  SInputColumnInfoData* pInput = &pCtx->input;
943,059✔
4147
  SColumnInfoData*      pCol = pInput->pData[0];
943,059✔
4148

4149
  if (IS_NULL_TYPE(pCol->info.type)) {
943,059!
4150
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
4151
    return TSDB_CODE_SUCCESS;
×
4152
  }
4153

4154
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
943,059!
4155
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
4156
  }
4157

4158
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
943,059✔
4159

4160
  int32_t start = pInput->startRowIndex;
943,059✔
4161
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
1,890,313✔
4162
    if(colDataIsNull_s(pCol, i)) continue;
1,894,508!
4163
    char*        data = colDataGetData(pCol, i);
947,254!
4164
    SSpreadInfo* pInputInfo = (SSpreadInfo*)varDataVal(data);
947,254✔
4165
    if (pInputInfo->hasResult) {
947,254✔
4166
      spreadTransferInfo(pInputInfo, pInfo);
947,038✔
4167
    }
4168
  }
4169

4170
  if (pInfo->hasResult) {
943,059✔
4171
    GET_RES_INFO(pCtx)->numOfRes = 1;
942,912✔
4172
  }
4173

4174
  return TSDB_CODE_SUCCESS;
943,059✔
4175
}
4176

4177
int32_t spreadFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
3,732,802✔
4178
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
3,732,802✔
4179
  if (pInfo->hasResult == true) {
3,732,802✔
4180
    SET_DOUBLE_VAL(&pInfo->result, pInfo->max - pInfo->min);
3,708,521✔
4181
  } else {
4182
    GET_RES_INFO(pCtx)->isNullRes = 1;
24,281✔
4183
  }
4184
  return functionFinalize(pCtx, pBlock);
3,732,802✔
4185
}
4186

4187
int32_t spreadPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
947,036✔
4188
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
947,036✔
4189
  SSpreadInfo*         pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
947,036✔
4190
  int32_t              resultBytes = getSpreadInfoSize();
947,036✔
4191
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
947,036✔
4192

4193
  if (NULL == res) {
947,039!
4194
    return terrno;
×
4195
  }
4196
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
947,039✔
4197
  varDataSetLen(res, resultBytes);
947,039✔
4198

4199
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
947,039✔
4200
  int32_t          code = TSDB_CODE_SUCCESS;
947,039✔
4201
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
947,039✔
4202
  if (NULL == pCol) {
947,039!
4203
    code = terrno;
×
4204
    goto _exit;
×
4205
  }
4206

4207
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
947,039✔
4208
  if (TSDB_CODE_SUCCESS != code) {
947,038!
4209
    goto _exit;
×
4210
  }
4211

4212
_exit:
947,038✔
4213
  taosMemoryFree(res);
947,038✔
4214
  return code;
947,039✔
4215
}
4216

4217
int32_t spreadCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
1✔
4218
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
1✔
4219
  SSpreadInfo*         pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
1✔
4220

4221
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
1✔
4222
  SSpreadInfo*         pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
1✔
4223
  spreadTransferInfo(pSBuf, pDBuf);
1✔
4224
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
1✔
4225
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
1✔
4226
  return TSDB_CODE_SUCCESS;
1✔
4227
}
4228

4229
int32_t getElapsedInfoSize() { return (int32_t)sizeof(SElapsedInfo); }
×
4230

4231
bool getElapsedFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
60,639✔
4232
  pEnv->calcMemSize = sizeof(SElapsedInfo);
60,639✔
4233
  return true;
60,639✔
4234
}
4235

4236
int32_t elapsedFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
3,940,326✔
4237
  if (pResultInfo->initialized) {
3,940,326!
4238
    return TSDB_CODE_SUCCESS;
×
4239
  }
4240
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
3,940,326!
4241
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
4242
  }
4243

4244
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
3,940,337✔
4245
  pInfo->result = 0;
3,940,337✔
4246
  pInfo->min = TSKEY_MAX;
3,940,337✔
4247
  pInfo->max = 0;
3,940,337✔
4248

4249
  if (pCtx->numOfParams > 1) {
3,940,337✔
4250
    pInfo->timeUnit = pCtx->param[1].param.i;
23,643✔
4251
  } else {
4252
    pInfo->timeUnit = 1;
3,916,694✔
4253
  }
4254

4255
  return TSDB_CODE_SUCCESS;
3,940,337✔
4256
}
4257

4258
int32_t elapsedFunction(SqlFunctionCtx* pCtx) {
3,940,384✔
4259
  int32_t numOfElems = 0;
3,940,384✔
4260

4261
  // Only the pre-computing information loaded and actual data does not loaded
4262
  SInputColumnInfoData* pInput = &pCtx->input;
3,940,384✔
4263
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
3,940,384✔
4264

4265
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
3,940,384✔
4266

4267
  numOfElems = pInput->numOfRows;  // since this is the primary timestamp, no need to exclude NULL values
3,940,384✔
4268
  if (numOfElems == 0) {
3,940,384✔
4269
    // for stream
4270
    if (pCtx->end.key != INT64_MIN) {
56!
4271
      pInfo->max = pCtx->end.key + 1;
56✔
4272
    }
4273
    goto _elapsed_over;
56✔
4274
  }
4275

4276
  if (pInput->colDataSMAIsSet) {
3,940,328!
4277
    if (pInfo->min == TSKEY_MAX) {
×
4278
      pInfo->min = GET_INT64_VAL(&pAgg->min);
×
4279
      pInfo->max = GET_INT64_VAL(&pAgg->max);
×
4280
    } else {
4281
      if (pCtx->order == TSDB_ORDER_ASC) {
×
4282
        pInfo->max = GET_INT64_VAL(&pAgg->max);
×
4283
      } else {
4284
        pInfo->min = GET_INT64_VAL(&pAgg->min);
×
4285
      }
4286
    }
4287
  } else {  // computing based on the true data block
4288
    if (0 == pInput->numOfRows) {
3,940,328!
4289
      if (pCtx->order == TSDB_ORDER_DESC) {
×
4290
        if (pCtx->end.key != INT64_MIN) {
×
4291
          pInfo->min = pCtx->end.key;
×
4292
        }
4293
      } else {
4294
        if (pCtx->end.key != INT64_MIN) {
×
4295
          pInfo->max = pCtx->end.key + 1;
×
4296
        }
4297
      }
4298
      goto _elapsed_over;
×
4299
    }
4300

4301
    SColumnInfoData* pCol = pInput->pData[0];
3,940,328✔
4302

4303
    int32_t start = pInput->startRowIndex;
3,940,328✔
4304
    TSKEY*  ptsList = (int64_t*)colDataGetData(pCol, 0);
3,940,328!
4305
    if (pCtx->order == TSDB_ORDER_DESC) {
3,940,328✔
4306
      if (pCtx->start.key == INT64_MIN) {
314!
4307
        pInfo->max = (pInfo->max < ptsList[start]) ? ptsList[start] : pInfo->max;
314✔
4308
      } else {
4309
        pInfo->max = pCtx->start.key + 1;
×
4310
      }
4311

4312
      if (pCtx->end.key == INT64_MIN) {
314!
4313
        pInfo->min =
315✔
4314
            (pInfo->min > ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->min;
315✔
4315
      } else {
4316
        pInfo->min = pCtx->end.key;
×
4317
      }
4318
    } else {
4319
      if (pCtx->start.key == INT64_MIN) {
3,940,014✔
4320
        pInfo->min = (pInfo->min > ptsList[start]) ? ptsList[start] : pInfo->min;
1,945,068✔
4321
      } else {
4322
        pInfo->min = pCtx->start.key;
1,994,946✔
4323
      }
4324

4325
      if (pCtx->end.key == INT64_MIN) {
3,940,014✔
4326
        pInfo->max =
1,818,408✔
4327
            (pInfo->max < ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->max;
1,818,408✔
4328
      } else {
4329
        pInfo->max = pCtx->end.key + 1;
2,121,606✔
4330
      }
4331
    }
4332
  }
4333

4334
_elapsed_over:
3,940,384✔
4335
  // data in the check operation are all null, not output
4336
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
3,940,384✔
4337

4338
  return TSDB_CODE_SUCCESS;
3,940,384✔
4339
}
4340

4341
static void elapsedTransferInfo(SElapsedInfo* pInput, SElapsedInfo* pOutput) {
×
4342
  pOutput->timeUnit = pInput->timeUnit;
×
4343
  if (pOutput->min > pInput->min) {
×
4344
    pOutput->min = pInput->min;
×
4345
  }
4346

4347
  if (pOutput->max < pInput->max) {
×
4348
    pOutput->max = pInput->max;
×
4349
  }
4350
}
×
4351

4352
int32_t elapsedFunctionMerge(SqlFunctionCtx* pCtx) {
×
4353
  SInputColumnInfoData* pInput = &pCtx->input;
×
4354
  SColumnInfoData*      pCol = pInput->pData[0];
×
4355
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
×
4356
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
4357
  }
4358

4359
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
×
4360

4361
  int32_t start = pInput->startRowIndex;
×
4362

4363
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
×
4364
    char*         data = colDataGetData(pCol, i);
×
4365
    SElapsedInfo* pInputInfo = (SElapsedInfo*)varDataVal(data);
×
4366
    elapsedTransferInfo(pInputInfo, pInfo);
×
4367
  }
4368

4369
  SET_VAL(GET_RES_INFO(pCtx), 1, 1);
×
4370
  return TSDB_CODE_SUCCESS;
×
4371
}
4372

4373
int32_t elapsedFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
3,938,837✔
4374
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
3,938,837✔
4375
  double        result = (double)pInfo->max - (double)pInfo->min;
3,938,837✔
4376
  result = (result >= 0) ? result : -result;
3,938,837✔
4377
  pInfo->result = result / pInfo->timeUnit;
3,938,837✔
4378
  return functionFinalize(pCtx, pBlock);
3,938,837✔
4379
}
4380

4381
int32_t elapsedPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
×
4382
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
×
4383
  SElapsedInfo*        pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
×
4384
  int32_t              resultBytes = getElapsedInfoSize();
×
4385
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
×
4386

4387
  if (NULL == res) {
×
4388
    return terrno;
×
4389
  }
4390
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
×
4391
  varDataSetLen(res, resultBytes);
×
4392

4393
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
×
4394
  int32_t          code = TSDB_CODE_SUCCESS;
×
4395
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
×
4396
  if (NULL == pCol) {
×
4397
    code = terrno;
×
4398
    goto _exit;
×
4399
  }
4400

4401
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
×
4402
  if (TSDB_CODE_SUCCESS != code) {
×
4403
    goto _exit;
×
4404
  }
4405
_exit:
×
4406
  taosMemoryFree(res);
×
4407
  return code;
×
4408
}
4409

4410
int32_t elapsedCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4411
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
4412
  SElapsedInfo*        pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
4413

4414
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4415
  SElapsedInfo*        pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
4416

4417
  elapsedTransferInfo(pSBuf, pDBuf);
×
4418
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
4419
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
4420
  return TSDB_CODE_SUCCESS;
×
4421
}
4422

4423
int32_t getHistogramInfoSize() {
2,082,878✔
4424
  return (int32_t)sizeof(SHistoFuncInfo) + HISTOGRAM_MAX_BINS_NUM * sizeof(SHistoFuncBin);
2,082,878✔
4425
}
4426

4427
bool getHistogramFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
113,130✔
4428
  pEnv->calcMemSize = sizeof(SHistoFuncInfo) + HISTOGRAM_MAX_BINS_NUM * sizeof(SHistoFuncBin);
113,130✔
4429
  return true;
113,130✔
4430
}
4431

4432
static int8_t getHistogramBinType(char* binTypeStr) {
8,813,019✔
4433
  int8_t binType;
4434
  if (strcasecmp(binTypeStr, "user_input") == 0) {
8,813,019✔
4435
    binType = USER_INPUT_BIN;
1,605✔
4436
  } else if (strcasecmp(binTypeStr, "linear_bin") == 0) {
8,811,414✔
4437
    binType = LINEAR_BIN;
2,526✔
4438
  } else if (strcasecmp(binTypeStr, "log_bin") == 0) {
8,808,888!
4439
    binType = LOG_BIN;
8,809,166✔
4440
  } else {
4441
    binType = UNKNOWN_BIN;
×
4442
  }
4443

4444
  return binType;
8,813,019✔
4445
}
4446

4447
static int32_t getHistogramBinDesc(SHistoFuncInfo* pInfo, char* binDescStr, int8_t binType, bool normalized) {
8,812,828✔
4448
  cJSON*  binDesc = cJSON_Parse(binDescStr);
8,812,828✔
4449
  int32_t numOfBins;
4450
  double* intervals;
4451
  if (cJSON_IsObject(binDesc)) { /* linaer/log bins */
8,812,923✔
4452
    int32_t numOfParams = cJSON_GetArraySize(binDesc);
8,811,297✔
4453
    int32_t startIndex;
4454
    if (numOfParams != 4) {
8,811,224!
4455
      cJSON_Delete(binDesc);
×
4456
      return TSDB_CODE_FAILED;
×
4457
    }
4458

4459
    cJSON* start = cJSON_GetObjectItem(binDesc, "start");
8,811,224✔
4460
    cJSON* factor = cJSON_GetObjectItem(binDesc, "factor");
8,811,456✔
4461
    cJSON* width = cJSON_GetObjectItem(binDesc, "width");
8,811,382✔
4462
    cJSON* count = cJSON_GetObjectItem(binDesc, "count");
8,809,895✔
4463
    cJSON* infinity = cJSON_GetObjectItem(binDesc, "infinity");
8,811,102✔
4464

4465
    if (!cJSON_IsNumber(start) || !cJSON_IsNumber(count) || !cJSON_IsBool(infinity)) {
8,811,431!
4466
      cJSON_Delete(binDesc);
×
4467
      return TSDB_CODE_FAILED;
×
4468
    }
4469

4470
    if (count->valueint <= 0 || count->valueint > 1000) {  // limit count to 1000
8,811,319!
4471
      cJSON_Delete(binDesc);
×
4472
      return TSDB_CODE_FAILED;
×
4473
    }
4474

4475
    if (isinf(start->valuedouble) || (width != NULL && isinf(width->valuedouble)) ||
8,811,325!
4476
        (factor != NULL && isinf(factor->valuedouble)) || (count != NULL && isinf(count->valuedouble))) {
8,811,325!
4477
      cJSON_Delete(binDesc);
×
4478
      return TSDB_CODE_FAILED;
×
4479
    }
4480

4481
    int32_t counter = (int32_t)count->valueint;
8,811,325✔
4482
    if (infinity->valueint == false) {
8,811,325✔
4483
      startIndex = 0;
5,119,262✔
4484
      numOfBins = counter + 1;
5,119,262✔
4485
    } else {
4486
      startIndex = 1;
3,692,063✔
4487
      numOfBins = counter + 3;
3,692,063✔
4488
    }
4489

4490
    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
8,811,325✔
4491
    if (NULL == intervals) {
8,811,565!
4492
      cJSON_Delete(binDesc);
×
4493
      qError("histogram function out of memory");
×
4494
      return terrno;
×
4495
    }
4496
    if (cJSON_IsNumber(width) && factor == NULL && binType == LINEAR_BIN) {
8,811,565!
4497
      // linear bin process
4498
      if (width->valuedouble == 0) {
2,526!
4499
        taosMemoryFree(intervals);
×
4500
        cJSON_Delete(binDesc);
×
4501
        return TSDB_CODE_FAILED;
×
4502
      }
4503
      for (int i = 0; i < counter + 1; ++i) {
26,345✔
4504
        intervals[startIndex] = start->valuedouble + i * width->valuedouble;
23,819✔
4505
        if (isinf(intervals[startIndex])) {
23,819!
4506
          taosMemoryFree(intervals);
×
4507
          cJSON_Delete(binDesc);
×
4508
          return TSDB_CODE_FAILED;
×
4509
        }
4510
        startIndex++;
23,819✔
4511
      }
4512
    } else if (cJSON_IsNumber(factor) && width == NULL && binType == LOG_BIN) {
8,808,976!
4513
      // log bin process
4514
      if (start->valuedouble == 0) {
8,808,930!
4515
        taosMemoryFree(intervals);
×
4516
        cJSON_Delete(binDesc);
×
4517
        return TSDB_CODE_FAILED;
×
4518
      }
4519
      if (factor->valuedouble < 0 || factor->valuedouble == 0 || factor->valuedouble == 1) {
8,808,930!
4520
        taosMemoryFree(intervals);
9✔
4521
        cJSON_Delete(binDesc);
×
4522
        return TSDB_CODE_FAILED;
×
4523
      }
4524
      for (int i = 0; i < counter + 1; ++i) {
61,655,089✔
4525
        intervals[startIndex] = start->valuedouble * pow(factor->valuedouble, i * 1.0);
52,846,168✔
4526
        if (isinf(intervals[startIndex])) {
52,846,168!
4527
          taosMemoryFree(intervals);
×
4528
          cJSON_Delete(binDesc);
×
4529
          return TSDB_CODE_FAILED;
×
4530
        }
4531
        startIndex++;
52,846,168✔
4532
      }
4533
    } else {
4534
      taosMemoryFree(intervals);
×
4535
      cJSON_Delete(binDesc);
×
4536
      return TSDB_CODE_FAILED;
×
4537
    }
4538

4539
    if (infinity->valueint == true) {
8,811,447✔
4540
      intervals[0] = -INFINITY;
3,692,567✔
4541
      intervals[numOfBins - 1] = INFINITY;
3,692,567✔
4542
      // in case of desc bin orders, -inf/inf should be swapped
4543
      if (numOfBins < 4) {
3,692,567!
4544
        return TSDB_CODE_FAILED;
×
4545
      }
4546
      if (intervals[1] > intervals[numOfBins - 2]) {
3,692,567✔
4547
        TSWAP(intervals[0], intervals[numOfBins - 1]);
3,690,884✔
4548
      }
4549
    }
4550
  } else if (cJSON_IsArray(binDesc)) { /* user input bins */
1,605!
4551
    if (binType != USER_INPUT_BIN) {
1,604!
4552
      cJSON_Delete(binDesc);
×
4553
      return TSDB_CODE_FAILED;
×
4554
    }
4555
    numOfBins = cJSON_GetArraySize(binDesc);
1,604✔
4556
    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
1,604✔
4557
    if (NULL == intervals) {
1,605!
4558
      cJSON_Delete(binDesc);
×
4559
      qError("histogram function out of memory");
×
4560
      return terrno;
×
4561
    }
4562
    cJSON* bin = binDesc->child;
1,605✔
4563
    if (bin == NULL) {
1,605!
4564
      taosMemoryFree(intervals);
×
4565
      cJSON_Delete(binDesc);
×
4566
      return TSDB_CODE_FAILED;
×
4567
    }
4568
    int i = 0;
1,605✔
4569
    while (bin) {
6,066✔
4570
      intervals[i] = bin->valuedouble;
4,462✔
4571
      if (!cJSON_IsNumber(bin)) {
4,462!
4572
        taosMemoryFree(intervals);
×
4573
        cJSON_Delete(binDesc);
×
4574
        return TSDB_CODE_FAILED;
×
4575
      }
4576
      if (i != 0 && intervals[i] <= intervals[i - 1]) {
4,461!
4577
        taosMemoryFree(intervals);
×
4578
        cJSON_Delete(binDesc);
×
4579
        return TSDB_CODE_FAILED;
×
4580
      }
4581
      bin = bin->next;
4,461✔
4582
      i++;
4,461✔
4583
    }
4584
  } else {
4585
    cJSON_Delete(binDesc);
×
4586
    return TSDB_CODE_FAILED;
×
4587
  }
4588

4589
  pInfo->numOfBins = numOfBins - 1;
8,813,051✔
4590
  pInfo->normalized = normalized;
8,813,051✔
4591
  for (int32_t i = 0; i < pInfo->numOfBins; ++i) {
60,262,538✔
4592
    pInfo->bins[i].lower = intervals[i] < intervals[i + 1] ? intervals[i] : intervals[i + 1];
51,449,487✔
4593
    pInfo->bins[i].upper = intervals[i + 1] > intervals[i] ? intervals[i + 1] : intervals[i];
51,449,487✔
4594
    pInfo->bins[i].count = 0;
51,449,487✔
4595
  }
4596

4597
  taosMemoryFree(intervals);
8,813,051✔
4598
  cJSON_Delete(binDesc);
8,812,993✔
4599

4600
  return TSDB_CODE_SUCCESS;
8,813,051✔
4601
}
4602

4603
int32_t histogramFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
8,812,966✔
4604
  if (pResultInfo->initialized) {
8,812,966!
4605
    return TSDB_CODE_SUCCESS;
×
4606
  }
4607
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
8,812,966!
4608
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
4609
  }
4610

4611
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
8,813,039✔
4612
  pInfo->numOfBins = 0;
8,813,039✔
4613
  pInfo->totalCount = 0;
8,813,039✔
4614
  pInfo->normalized = 0;
8,813,039✔
4615

4616
  char*  binTypeStr = taosStrndup(varDataVal(pCtx->param[1].param.pz), varDataLen(pCtx->param[1].param.pz));
8,813,039✔
4617
  if (binTypeStr == NULL) {
8,813,038!
4618
    return terrno;
×
4619
  }
4620
  int8_t binType = getHistogramBinType(binTypeStr);
8,813,038✔
4621
  taosMemoryFree(binTypeStr);
8,813,132✔
4622

4623
  if (binType == UNKNOWN_BIN) {
8,812,918!
4624
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
4625
  }
4626
  char*   binDesc = taosStrndup(varDataVal(pCtx->param[2].param.pz), varDataLen(pCtx->param[2].param.pz));
8,812,918✔
4627
  if (binDesc == NULL) {
8,812,873!
4628
    return terrno;
×
4629
  }
4630
  int64_t normalized = pCtx->param[3].param.i;
8,812,873✔
4631
  if (normalized != 0 && normalized != 1) {
8,812,873!
4632
    taosMemoryFree(binDesc);
×
4633
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
4634
  }
4635
  int32_t code = getHistogramBinDesc(pInfo, binDesc, binType, (bool)normalized);
8,812,873✔
4636
  if (TSDB_CODE_SUCCESS != code) {
8,813,051!
4637
    taosMemoryFree(binDesc);
×
4638
    return code;
×
4639
  }
4640
  taosMemoryFree(binDesc);
8,813,051✔
4641

4642
  return TSDB_CODE_SUCCESS;
8,813,168✔
4643
}
4644

4645
static int32_t histogramFunctionImpl(SqlFunctionCtx* pCtx, bool isPartial) {
8,896,990✔
4646
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
8,896,990✔
4647

4648
  SInputColumnInfoData* pInput = &pCtx->input;
8,896,990✔
4649
  SColumnInfoData*      pCol = pInput->pData[0];
8,896,990✔
4650

4651
  int32_t type = pInput->pData[0]->info.type;
8,896,990✔
4652

4653
  int32_t start = pInput->startRowIndex;
8,896,990✔
4654
  int32_t numOfRows = pInput->numOfRows;
8,896,990✔
4655

4656
  int32_t numOfElems = 0;
8,896,990✔
4657
  for (int32_t i = start; i < numOfRows + start; ++i) {
28,714,434✔
4658
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
19,817,444✔
4659
      continue;
705,576✔
4660
    }
4661

4662
    numOfElems++;
19,111,868✔
4663

4664
    char*  data = colDataGetData(pCol, i);
19,111,868!
4665
    double v;
4666
    GET_TYPED_DATA(v, double, type, data);
19,111,868!
4667

4668
    for (int32_t k = 0; k < pInfo->numOfBins; ++k) {
76,440,374✔
4669
      if (v > pInfo->bins[k].lower && v <= pInfo->bins[k].upper) {
67,718,785✔
4670
        pInfo->bins[k].count++;
10,390,279✔
4671
        pInfo->totalCount++;
10,390,279✔
4672
        break;
10,390,279✔
4673
      }
4674
    }
4675
  }
4676

4677
  if (!isPartial) {
8,896,990✔
4678
    GET_RES_INFO(pCtx)->numOfRes = pInfo->numOfBins;
6,772,597✔
4679
  } else {
4680
    GET_RES_INFO(pCtx)->numOfRes = 1;
2,124,393✔
4681
  }
4682
  return TSDB_CODE_SUCCESS;
8,896,990✔
4683
}
4684

4685
int32_t histogramFunction(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, false); }
6,772,802✔
4686

4687
int32_t histogramFunctionPartial(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, true); }
2,124,271✔
4688

4689
static void histogramTransferInfo(SHistoFuncInfo* pInput, SHistoFuncInfo* pOutput) {
2,052,634✔
4690
  pOutput->normalized = pInput->normalized;
2,052,634✔
4691
  pOutput->numOfBins = pInput->numOfBins;
2,052,634✔
4692
  pOutput->totalCount += pInput->totalCount;
2,052,634✔
4693
  for (int32_t k = 0; k < pOutput->numOfBins; ++k) {
12,329,891✔
4694
    pOutput->bins[k].lower = pInput->bins[k].lower;
10,277,257✔
4695
    pOutput->bins[k].upper = pInput->bins[k].upper;
10,277,257✔
4696
    pOutput->bins[k].count += pInput->bins[k].count;
10,277,257✔
4697
  }
4698
}
2,052,634✔
4699

4700
int32_t histogramFunctionMerge(SqlFunctionCtx* pCtx) {
2,052,634✔
4701
  SInputColumnInfoData* pInput = &pCtx->input;
2,052,634✔
4702
  SColumnInfoData*      pCol = pInput->pData[0];
2,052,634✔
4703
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
2,052,634!
4704
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
4705
  }
4706

4707
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,052,634✔
4708

4709
  int32_t start = pInput->startRowIndex;
2,052,634✔
4710

4711
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
4,105,268✔
4712
    char*           data = colDataGetData(pCol, i);
2,052,634!
4713
    SHistoFuncInfo* pInputInfo = (SHistoFuncInfo*)varDataVal(data);
2,052,634✔
4714
    histogramTransferInfo(pInputInfo, pInfo);
2,052,634✔
4715
  }
4716

4717
  SET_VAL(GET_RES_INFO(pCtx), pInfo->numOfBins, pInfo->numOfBins);
2,052,634!
4718
  return TSDB_CODE_SUCCESS;
2,052,634✔
4719
}
4720

4721
int32_t histogramFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
8,718,771✔
4722
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
8,718,771✔
4723
  SHistoFuncInfo*      pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
8,718,771✔
4724
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
8,718,771✔
4725
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
8,718,771✔
4726
  int32_t              code = TSDB_CODE_SUCCESS;
8,718,655✔
4727

4728
  int32_t currentRow = pBlock->info.rows;
8,718,655✔
4729
  if (NULL == pCol) {
8,718,655!
4730
    return TSDB_CODE_OUT_OF_RANGE;
×
4731
  }
4732

4733
  if (pInfo->normalized) {
8,718,655✔
4734
    for (int32_t k = 0; k < pResInfo->numOfRes; ++k) {
29,124,878✔
4735
      if (pInfo->totalCount != 0) {
25,482,918✔
4736
        pInfo->bins[k].percentage = pInfo->bins[k].count / (double)pInfo->totalCount;
25,473,863✔
4737
      } else {
4738
        pInfo->bins[k].percentage = 0;
9,055✔
4739
      }
4740
    }
4741
  }
4742

4743
  for (int32_t i = 0; i < pResInfo->numOfRes; ++i) {
59,566,794✔
4744
    int32_t len;
4745
    char    buf[512] = {0};
50,874,445✔
4746
    if (!pInfo->normalized) {
50,874,445✔
4747
      len = tsnprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE, "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%" PRId64 "}",
25,391,527✔
4748
                    pInfo->bins[i].lower, pInfo->bins[i].upper, pInfo->bins[i].count);
4749
    } else {
4750
      len = tsnprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE, "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%lf}", pInfo->bins[i].lower,
25,482,918✔
4751
                    pInfo->bins[i].upper, pInfo->bins[i].percentage);
4752
    }
4753
    varDataSetLen(buf, len);
50,874,450✔
4754
    code = colDataSetVal(pCol, currentRow, buf, false);
50,874,450✔
4755
    if (TSDB_CODE_SUCCESS != code) {
50,848,139!
4756
      return code;
×
4757
    }
4758
    currentRow++;
50,848,139✔
4759
  }
4760

4761
  return code;
8,692,349✔
4762
}
4763

4764
int32_t histogramPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
2,076,392✔
4765
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,076,392✔
4766
  SHistoFuncInfo*      pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,076,392✔
4767
  int32_t              resultBytes = getHistogramInfoSize();
2,076,392✔
4768
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
2,076,391✔
4769

4770
  if (NULL == res) {
2,076,392!
4771
    return terrno;
×
4772
  }
4773
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
2,076,392✔
4774
  varDataSetLen(res, resultBytes);
2,076,392✔
4775

4776
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
2,076,392✔
4777
  int32_t          code = TSDB_CODE_SUCCESS;
2,076,392✔
4778
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
2,076,392✔
4779
  if (NULL == pCol) {
2,076,394!
4780
    code = terrno;
×
4781
    goto _exit;
×
4782
  }
4783
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
2,076,394✔
4784

4785
_exit:
2,076,392✔
4786
  taosMemoryFree(res);
2,076,392✔
4787
  return code;
2,076,394✔
4788
}
4789

4790
int32_t histogramCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4791
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
4792
  SHistoFuncInfo*      pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
4793

4794
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4795
  SHistoFuncInfo*      pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
4796

4797
  histogramTransferInfo(pSBuf, pDBuf);
×
4798
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
4799
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
4800
  return TSDB_CODE_SUCCESS;
×
4801
}
4802

4803
int32_t getHLLInfoSize() { return (int32_t)sizeof(SHLLInfo); }
10,556✔
4804

4805
bool getHLLFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
65,584✔
4806
  pEnv->calcMemSize = sizeof(SHLLInfo);
65,584✔
4807
  return true;
65,584✔
4808
}
4809

4810
static uint8_t hllCountNum(void* data, int32_t bytes, int32_t* buk) {
3,606,803✔
4811
  uint64_t hash = MurmurHash3_64(data, bytes);
3,606,803✔
4812
  int32_t  index = hash & HLL_BUCKET_MASK;
3,605,976✔
4813
  hash >>= HLL_BUCKET_BITS;
3,605,976✔
4814
  hash |= ((uint64_t)1 << HLL_DATA_BITS);
3,605,976✔
4815
  uint64_t bit = 1;
3,605,976✔
4816
  uint8_t  count = 1;
3,605,976✔
4817
  while ((hash & bit) == 0) {
6,698,036✔
4818
    count++;
3,092,060✔
4819
    bit <<= 1;
3,092,060✔
4820
  }
4821
  *buk = index;
3,605,976✔
4822
  return count;
3,605,976✔
4823
}
4824

4825
static void hllBucketHisto(uint8_t* buckets, int32_t* bucketHisto) {
234,364✔
4826
  uint64_t* word = (uint64_t*)buckets;
234,364✔
4827
  uint8_t*  bytes;
4828

4829
  for (int32_t j = 0; j < HLL_BUCKETS >> 3; j++) {
472,225,515✔
4830
    if (*word == 0) {
471,991,151✔
4831
      bucketHisto[0] += 8;
471,089,510✔
4832
    } else {
4833
      bytes = (uint8_t*)word;
901,641✔
4834
      bucketHisto[bytes[0]]++;
901,641✔
4835
      bucketHisto[bytes[1]]++;
901,641✔
4836
      bucketHisto[bytes[2]]++;
901,641✔
4837
      bucketHisto[bytes[3]]++;
901,641✔
4838
      bucketHisto[bytes[4]]++;
901,641✔
4839
      bucketHisto[bytes[5]]++;
901,641✔
4840
      bucketHisto[bytes[6]]++;
901,641✔
4841
      bucketHisto[bytes[7]]++;
901,641✔
4842
    }
4843
    word++;
471,991,151✔
4844
  }
4845
}
234,364✔
4846
static double hllTau(double x) {
234,362✔
4847
  if (x == 0. || x == 1.) return 0.;
234,362!
4848
  double zPrime;
4849
  double y = 1.0;
×
4850
  double z = 1 - x;
×
4851
  do {
4852
    x = sqrt(x);
×
4853
    zPrime = z;
×
4854
    y *= 0.5;
×
4855
    z -= pow(1 - x, 2) * y;
×
4856
  } while (zPrime != z);
×
4857
  return z / 3;
×
4858
}
4859

4860
static double hllSigma(double x) {
234,381✔
4861
  if (x == 1.0) return INFINITY;
234,381✔
4862
  double zPrime;
4863
  double y = 1;
208,519✔
4864
  double z = x;
208,519✔
4865
  do {
4866
    x *= x;
4,088,562✔
4867
    zPrime = z;
4,088,562✔
4868
    z += x * y;
4,088,562✔
4869
    y += y;
4,088,562✔
4870
  } while (zPrime != z);
4,088,562✔
4871
  return z;
208,519✔
4872
}
4873

4874
// estimate the cardinality, the algorithm refer this paper: "New cardinality estimation algorithms for HyperLogLog
4875
// sketches"
4876
static uint64_t hllCountCnt(uint8_t* buckets) {
234,333✔
4877
  double  m = HLL_BUCKETS;
234,333✔
4878
  int32_t buckethisto[64] = {0};
234,333✔
4879
  hllBucketHisto(buckets, buckethisto);
234,333✔
4880

4881
  double z = m * hllTau((m - buckethisto[HLL_DATA_BITS + 1]) / (double)m);
234,362✔
4882
  for (int j = HLL_DATA_BITS; j >= 1; --j) {
11,950,036✔
4883
    z += buckethisto[j];
11,715,656✔
4884
    z *= 0.5;
11,715,656✔
4885
  }
4886

4887
  z += m * hllSigma(buckethisto[0] / (double)m);
234,380✔
4888
  double E = (double)llroundl(HLL_ALPHA_INF * m * m / z);
234,381✔
4889

4890
  return (uint64_t)E;
234,381✔
4891
}
4892

4893
int32_t hllFunction(SqlFunctionCtx* pCtx) {
259,508✔
4894
  SHLLInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
259,508✔
4895

4896
  SInputColumnInfoData* pInput = &pCtx->input;
259,508✔
4897
  SColumnInfoData*      pCol = pInput->pData[0];
259,508✔
4898

4899
  int32_t type = pCol->info.type;
259,508✔
4900
  int32_t bytes = pCol->info.bytes;
259,508✔
4901

4902
  int32_t start = pInput->startRowIndex;
259,508✔
4903
  int32_t numOfRows = pInput->numOfRows;
259,508✔
4904

4905
  int32_t numOfElems = 0;
259,508✔
4906
  if (IS_NULL_TYPE(type)) {
259,508✔
4907
    goto _hll_over;
1,708✔
4908
  }
4909

4910
  for (int32_t i = start; i < numOfRows + start; ++i) {
4,817,615✔
4911
    if (pCol->hasNull && colDataIsNull_s(pCol, i)) {
6,362,246!
4912
      continue;
952,280✔
4913
    }
4914

4915
    numOfElems++;
3,608,292✔
4916

4917
    char* data = colDataGetData(pCol, i);
3,608,292!
4918
    if (IS_VAR_DATA_TYPE(type)) {
3,608,292!
4919
      bytes = varDataLen(data);
1,156,828✔
4920
      data = varDataVal(data);
1,156,828✔
4921
    }
4922

4923
    int32_t index = 0;
3,608,292✔
4924
    uint8_t count = hllCountNum(data, bytes, &index);
3,608,292✔
4925
    uint8_t oldcount = pInfo->buckets[index];
3,607,535✔
4926
    if (count > oldcount) {
3,607,535✔
4927
      pInfo->buckets[index] = count;
933,797✔
4928
    }
4929
  }
4930

4931
_hll_over:
257,043✔
4932
  pInfo->totalCount += numOfElems;
258,751✔
4933

4934
  if (pInfo->totalCount == 0 && !tsCountAlwaysReturnValue) {
258,751✔
4935
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
2,781✔
4936
  } else {
4937
    SET_VAL(GET_RES_INFO(pCtx), 1, 1);
255,970✔
4938
  }
4939

4940
  return TSDB_CODE_SUCCESS;
258,751✔
4941
}
4942

4943
static void hllTransferInfo(SHLLInfo* pInput, SHLLInfo* pOutput) {
10,844✔
4944
  for (int32_t k = 0; k < HLL_BUCKETS; ++k) {
173,591,962✔
4945
    if (pOutput->buckets[k] < pInput->buckets[k]) {
173,581,118✔
4946
      pOutput->buckets[k] = pInput->buckets[k];
240,139✔
4947
    }
4948
  }
4949
  pOutput->totalCount += pInput->totalCount;
10,844✔
4950
}
10,844✔
4951

4952
int32_t hllFunctionMerge(SqlFunctionCtx* pCtx) {
10,779✔
4953
  SInputColumnInfoData* pInput = &pCtx->input;
10,779✔
4954
  SColumnInfoData*      pCol = pInput->pData[0];
10,779✔
4955

4956
  if (IS_NULL_TYPE(pCol->info.type)) {
10,779!
4957
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
4958
    return TSDB_CODE_SUCCESS;
×
4959
  }
4960

4961
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
10,779!
4962
    return TSDB_CODE_SUCCESS;
×
4963
  }
4964

4965
  SHLLInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
10,779✔
4966

4967
  int32_t start = pInput->startRowIndex;
10,779✔
4968

4969
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
21,622✔
4970
    if (colDataIsNull_s(pCol, i)) continue;
21,684!
4971
    char*     data = colDataGetData(pCol, i);
10,842!
4972
    SHLLInfo* pInputInfo = (SHLLInfo*)varDataVal(data);
10,842✔
4973
    hllTransferInfo(pInputInfo, pInfo);
10,842✔
4974
  }
4975

4976
  if (pInfo->totalCount == 0 && !tsCountAlwaysReturnValue) {
10,780✔
4977
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
5✔
4978
  } else {
4979
    SET_VAL(GET_RES_INFO(pCtx), 1, 1);
10,775✔
4980
  }
4981

4982
  return TSDB_CODE_SUCCESS;
10,780✔
4983
}
4984

4985
int32_t hllFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
234,334✔
4986
  SResultRowEntryInfo* pInfo = GET_RES_INFO(pCtx);
234,334✔
4987

4988
  SHLLInfo* pHllInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
234,334✔
4989
  pHllInfo->result = hllCountCnt(pHllInfo->buckets);
234,334✔
4990
  if (tsCountAlwaysReturnValue && pHllInfo->result == 0) {
234,382✔
4991
    pInfo->numOfRes = 1;
23,116✔
4992
  }
4993

4994
  return functionFinalize(pCtx, pBlock);
234,382✔
4995
}
4996

4997
int32_t hllPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
10,556✔
4998
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
10,556✔
4999
  SHLLInfo*            pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
10,556✔
5000
  int32_t              resultBytes = getHLLInfoSize();
10,556✔
5001
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
10,556✔
5002

5003
  if (NULL == res) {
10,556!
5004
    return terrno;
×
5005
  }
5006
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
10,556✔
5007
  varDataSetLen(res, resultBytes);
10,556✔
5008

5009
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
10,556✔
5010
  int32_t          code = TSDB_CODE_SUCCESS;
10,556✔
5011
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
10,556✔
5012
  if (NULL == pCol) {
10,559!
5013
    code = terrno;
×
5014
    goto _exit;
×
5015
  }
5016

5017
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
10,559✔
5018

5019
_exit:
10,558✔
5020
  taosMemoryFree(res);
10,558✔
5021
  return code;
10,558✔
5022
}
5023

5024
int32_t hllCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
1✔
5025
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
1✔
5026
  SHLLInfo*            pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
1✔
5027

5028
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
1✔
5029
  SHLLInfo*            pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
1✔
5030

5031
  hllTransferInfo(pSBuf, pDBuf);
1✔
5032
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
1✔
5033
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
1✔
5034
  return TSDB_CODE_SUCCESS;
1✔
5035
}
5036

5037
bool getStateFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
12,770✔
5038
  pEnv->calcMemSize = sizeof(SStateInfo);
12,770✔
5039
  return true;
12,770✔
5040
}
5041

5042
static int8_t getStateOpType(char* opStr) {
16,489✔
5043
  int8_t opType;
5044
  if (strncasecmp(opStr, "LT", 2) == 0) {
16,489✔
5045
    opType = STATE_OPER_LT;
1,932✔
5046
  } else if (strncasecmp(opStr, "GT", 2) == 0) {
14,557✔
5047
    opType = STATE_OPER_GT;
7,835✔
5048
  } else if (strncasecmp(opStr, "LE", 2) == 0) {
6,722✔
5049
    opType = STATE_OPER_LE;
992✔
5050
  } else if (strncasecmp(opStr, "GE", 2) == 0) {
5,730✔
5051
    opType = STATE_OPER_GE;
1,855✔
5052
  } else if (strncasecmp(opStr, "NE", 2) == 0) {
3,875✔
5053
    opType = STATE_OPER_NE;
1,084✔
5054
  } else if (strncasecmp(opStr, "EQ", 2) == 0) {
2,791!
5055
    opType = STATE_OPER_EQ;
2,791✔
5056
  } else {
5057
    opType = STATE_OPER_INVALID;
×
5058
  }
5059

5060
  return opType;
16,489✔
5061
}
5062

5063
static bool checkStateOp(int8_t op, SColumnInfoData* pCol, int32_t index, SVariant param) {
5,722,024✔
5064
  char* data = colDataGetData(pCol, index);
5,722,024!
5065
  switch (pCol->info.type) {
5,722,024!
5066
    case TSDB_DATA_TYPE_TINYINT: {
107,096✔
5067
      int8_t v = *(int8_t*)data;
107,096✔
5068
      STATE_COMP(op, v, param);
107,096!
5069
      break;
×
5070
    }
5071
    case TSDB_DATA_TYPE_UTINYINT: {
5,760✔
5072
      uint8_t v = *(uint8_t*)data;
5,760✔
5073
      STATE_COMP(op, v, param);
5,760!
5074
      break;
×
5075
    }
5076
    case TSDB_DATA_TYPE_SMALLINT: {
38,612✔
5077
      int16_t v = *(int16_t*)data;
38,612✔
5078
      STATE_COMP(op, v, param);
38,612!
5079
      break;
×
5080
    }
5081
    case TSDB_DATA_TYPE_USMALLINT: {
5,760✔
5082
      uint16_t v = *(uint16_t*)data;
5,760✔
5083
      STATE_COMP(op, v, param);
5,760!
5084
      break;
×
5085
    }
5086
    case TSDB_DATA_TYPE_INT: {
149,024✔
5087
      int32_t v = *(int32_t*)data;
149,024✔
5088
      STATE_COMP(op, v, param);
149,024!
5089
      break;
×
5090
    }
5091
    case TSDB_DATA_TYPE_UINT: {
5,760✔
5092
      uint32_t v = *(uint32_t*)data;
5,760✔
5093
      STATE_COMP(op, v, param);
5,760!
5094
      break;
×
5095
    }
5096
    case TSDB_DATA_TYPE_BIGINT: {
5,265,308✔
5097
      int64_t v = *(int64_t*)data;
5,265,308✔
5098
      STATE_COMP(op, v, param);
5,265,308!
5099
      break;
×
5100
    }
5101
    case TSDB_DATA_TYPE_UBIGINT: {
5,760✔
5102
      uint64_t v = *(uint64_t*)data;
5,760✔
5103
      STATE_COMP(op, v, param);
5,760!
5104
      break;
×
5105
    }
5106
    case TSDB_DATA_TYPE_FLOAT: {
105,112✔
5107
      float v = *(float*)data;
105,112✔
5108
      STATE_COMP(op, v, param);
105,112!
5109
      break;
×
5110
    }
5111
    case TSDB_DATA_TYPE_DOUBLE: {
33,956✔
5112
      double v = *(double*)data;
33,956✔
5113
      STATE_COMP(op, v, param);
33,956!
5114
      break;
×
5115
    }
5116
    default: {
×
5117
      return false;
×
5118
    }
5119
  }
5120
  return false;
×
5121
}
5122

5123
int32_t stateCountFunction(SqlFunctionCtx* pCtx) {
8,420✔
5124
  int32_t              code = TSDB_CODE_SUCCESS;
8,420✔
5125
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
8,420✔
5126
  SStateInfo*          pInfo = GET_ROWCELL_INTERBUF(pResInfo);
8,420✔
5127

5128
  SInputColumnInfoData* pInput = &pCtx->input;
8,420✔
5129
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
8,420✔
5130

5131
  SColumnInfoData* pInputCol = pInput->pData[0];
8,420✔
5132

5133
  int32_t          numOfElems = 0;
8,420✔
5134
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
8,420✔
5135

5136
  int8_t op = getStateOpType(varDataVal(pCtx->param[1].param.pz));
8,420✔
5137
  if (STATE_OPER_INVALID == op) {
8,420!
5138
    return 0;
×
5139
  }
5140

5141
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
5,792,806✔
5142
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
5,784,386!
5143
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5144
    } else {
5145
      pInfo->prevTs = tsList[i];
5,784,386✔
5146
    }
5147

5148
    pInfo->isPrevTsSet = true;
5,784,386✔
5149
    numOfElems++;
5,784,386✔
5150

5151
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
5,784,386✔
5152
      colDataSetNULL(pOutput, i);
265,024!
5153
      // handle selectivity
5154
      if (pCtx->subsidiaries.num > 0) {
265,024✔
5155
        code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
44✔
5156
        if (TSDB_CODE_SUCCESS != code) {
44!
5157
          return code;
×
5158
        }
5159
      }
5160
      continue;
265,024✔
5161
    }
5162

5163
    bool ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
5,519,362✔
5164

5165
    int64_t output = -1;
5,519,362✔
5166
    if (ret) {
5,519,362✔
5167
      output = ++pInfo->count;
2,721,650✔
5168
    } else {
5169
      pInfo->count = 0;
2,797,712✔
5170
    }
5171
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
5,519,362✔
5172
    if (TSDB_CODE_SUCCESS != code) {
5,519,362!
5173
      return code;
×
5174
    }
5175

5176
    // handle selectivity
5177
    if (pCtx->subsidiaries.num > 0) {
5,519,362✔
5178
      code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
528✔
5179
      if (TSDB_CODE_SUCCESS != code) {
528!
5180
        return code;
×
5181
      }
5182
    }
5183
  }
5184

5185
  pResInfo->numOfRes = numOfElems;
8,420✔
5186
  return TSDB_CODE_SUCCESS;
8,420✔
5187
}
5188

5189
int32_t stateDurationFunction(SqlFunctionCtx* pCtx) {
8,069✔
5190
  int32_t              code = TSDB_CODE_SUCCESS;
8,069✔
5191
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
8,069✔
5192
  SStateInfo*          pInfo = GET_ROWCELL_INTERBUF(pResInfo);
8,069✔
5193

5194
  SInputColumnInfoData* pInput = &pCtx->input;
8,069✔
5195
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
8,069✔
5196

5197
  SColumnInfoData* pInputCol = pInput->pData[0];
8,069✔
5198

5199
  int32_t          numOfElems = 0;
8,069✔
5200
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
8,069✔
5201

5202
  // TODO: process timeUnit for different db precisions
5203
  int32_t timeUnit = 1;
8,069✔
5204
  if (pCtx->numOfParams == 5) {  // TODO: param number incorrect
8,069✔
5205
    timeUnit = pCtx->param[3].param.i;
6,109✔
5206
  }
5207

5208
  int8_t op = getStateOpType(varDataVal(pCtx->param[1].param.pz));
8,069✔
5209
  if (STATE_OPER_INVALID == op) {
8,069!
5210
    return TSDB_CODE_INVALID_PARA;
×
5211
  }
5212

5213
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
410,924✔
5214
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
402,855!
5215
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5216
    } else {
5217
      pInfo->prevTs = tsList[i];
402,855✔
5218
    }
5219

5220
    pInfo->isPrevTsSet = true;
402,855✔
5221
    numOfElems++;
402,855✔
5222

5223
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
402,855✔
5224
      colDataSetNULL(pOutput, i);
200,069!
5225
      // handle selectivity
5226
      if (pCtx->subsidiaries.num > 0) {
200,069✔
5227
        code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
60✔
5228
        if (TSDB_CODE_SUCCESS != code) {
60!
5229
          return code;
×
5230
        }
5231
      }
5232
      continue;
200,069✔
5233
    }
5234

5235
    bool    ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
202,786✔
5236
    int64_t output = -1;
202,786✔
5237
    if (ret) {
202,786✔
5238
      if (pInfo->durationStart == 0) {
62,643✔
5239
        output = 0;
20,867✔
5240
        pInfo->durationStart = tsList[i];
20,867✔
5241
      } else {
5242
        output = (tsList[i] - pInfo->durationStart) / timeUnit;
41,776✔
5243
      }
5244
    } else {
5245
      pInfo->durationStart = 0;
140,143✔
5246
    }
5247
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
202,786✔
5248
    if (TSDB_CODE_SUCCESS != code) {
202,786!
5249
      return code;
×
5250
    }
5251

5252
    // handle selectivity
5253
    if (pCtx->subsidiaries.num > 0) {
202,786✔
5254
      code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
720✔
5255
      if (TSDB_CODE_SUCCESS != code) {
720!
5256
        return code;
×
5257
      }
5258
    }
5259
  }
5260

5261
  pResInfo->numOfRes = numOfElems;
8,069✔
5262
  return TSDB_CODE_SUCCESS;
8,069✔
5263
}
5264

5265
bool getCsumFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
15,658✔
5266
  pEnv->calcMemSize = sizeof(SSumRes);
15,658✔
5267
  return true;
15,658✔
5268
}
5269

5270
int32_t csumFunction(SqlFunctionCtx* pCtx) {
28,976✔
5271
  int32_t              code = TSDB_CODE_SUCCESS;
28,976✔
5272
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
28,976✔
5273
  SSumRes*             pSumRes = GET_ROWCELL_INTERBUF(pResInfo);
28,976✔
5274

5275
  SInputColumnInfoData* pInput = &pCtx->input;
28,976✔
5276
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
28,976✔
5277

5278
  SColumnInfoData* pInputCol = pInput->pData[0];
28,976✔
5279
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
28,976✔
5280

5281
  int32_t numOfElems = 0;
28,976✔
5282
  int32_t type = pInputCol->info.type;
28,976✔
5283
  int32_t startOffset = pCtx->offset;
28,976✔
5284
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
4,008,686✔
5285
    if (pSumRes->isPrevTsSet == true && tsList[i] == pSumRes->prevTs) {
3,979,709✔
5286
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
18✔
5287
    } else {
5288
      pSumRes->prevTs = tsList[i];
3,979,691✔
5289
    }
5290
    pSumRes->isPrevTsSet = true;
3,979,691✔
5291

5292
    int32_t pos = startOffset + numOfElems;
3,979,691✔
5293
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
3,979,691✔
5294
      // colDataSetNULL(pOutput, i);
5295
      continue;
453,585✔
5296
    }
5297

5298
    char* data = colDataGetData(pInputCol, i);
3,526,106!
5299
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
3,765,038!
5300
      int64_t v;
5301
      GET_TYPED_DATA(v, int64_t, type, data);
238,913!
5302
      pSumRes->isum += v;
238,913✔
5303
      code = colDataSetVal(pOutput, pos, (char*)&pSumRes->isum, false);
238,913✔
5304
      if (TSDB_CODE_SUCCESS != code) {
238,932!
5305
        return code;
×
5306
      }
5307
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
3,287,873!
5308
      uint64_t v;
5309
      GET_TYPED_DATA(v, uint64_t, type, data);
680!
5310
      pSumRes->usum += v;
680✔
5311
      code = colDataSetVal(pOutput, pos, (char*)&pSumRes->usum, false);
680✔
5312
      if (TSDB_CODE_SUCCESS != code) {
680!
5313
        return code;
×
5314
      }
5315
    } else if (IS_FLOAT_TYPE(type)) {
3,286,513!
5316
      double v;
5317
      GET_TYPED_DATA(v, double, type, data);
3,287,914!
5318
      pSumRes->dsum += v;
3,287,914✔
5319
      // check for overflow
5320
      if (isinf(pSumRes->dsum) || isnan(pSumRes->dsum)) {
3,287,914!
5321
        colDataSetNULL(pOutput, pos);
8!
5322
      } else {
5323
        code = colDataSetVal(pOutput, pos, (char*)&pSumRes->dsum, false);
3,287,906✔
5324
        if (TSDB_CODE_SUCCESS != code) {
3,287,906!
5325
          return code;
×
5326
        }
5327
      }
5328
    }
5329

5330
    // handle selectivity
5331
    if (pCtx->subsidiaries.num > 0) {
3,526,125✔
5332
      code = appendSelectivityValue(pCtx, i, pos);
2,007,814✔
5333
      if (TSDB_CODE_SUCCESS != code) {
2,007,814!
5334
        return code;
×
5335
      }
5336
    }
5337

5338
    numOfElems++;
3,526,125✔
5339
  }
5340

5341
  pResInfo->numOfRes = numOfElems;
28,977✔
5342
  return TSDB_CODE_SUCCESS;
28,977✔
5343
}
5344

5345
bool getMavgFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
13,739✔
5346
  pEnv->calcMemSize = sizeof(SMavgInfo) + MAVG_MAX_POINTS_NUM * sizeof(double);
13,739✔
5347
  return true;
13,739✔
5348
}
5349

5350
int32_t mavgFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
252,122✔
5351
  if (pResultInfo->initialized) {
252,122✔
5352
    return TSDB_CODE_SUCCESS;
237,372✔
5353
  }
5354
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
14,750!
5355
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5356
  }
5357

5358
  SMavgInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
14,750✔
5359
  pInfo->pos = 0;
14,750✔
5360
  pInfo->sum = 0;
14,750✔
5361
  pInfo->prevTs = -1;
14,750✔
5362
  pInfo->isPrevTsSet = false;
14,750✔
5363
  pInfo->numOfPoints = pCtx->param[1].param.i;
14,750✔
5364
  if (pInfo->numOfPoints < 1 || pInfo->numOfPoints > MAVG_MAX_POINTS_NUM) {
14,750!
5365
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
5366
  }
5367
  pInfo->pointsMeet = false;
14,751✔
5368

5369
  return TSDB_CODE_SUCCESS;
14,751✔
5370
}
5371

5372
int32_t mavgFunction(SqlFunctionCtx* pCtx) {
238,383✔
5373
  int32_t              code = TSDB_CODE_SUCCESS;
238,383✔
5374
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
238,383✔
5375
  SMavgInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
238,383✔
5376

5377
  SInputColumnInfoData* pInput = &pCtx->input;
238,383✔
5378
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
238,383✔
5379

5380
  SColumnInfoData* pInputCol = pInput->pData[0];
238,383✔
5381
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
238,383✔
5382
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
238,383✔
5383

5384
  int32_t numOfElems = 0;
238,383✔
5385
  int32_t type = pInputCol->info.type;
238,383✔
5386
  int32_t startOffset = pCtx->offset;
238,383✔
5387
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
59,436,056✔
5388
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
59,197,665!
5389
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5390
    } else {
5391
      pInfo->prevTs = tsList[i];
59,197,665✔
5392
    }
5393
    pInfo->isPrevTsSet = true;
59,197,665✔
5394

5395
    int32_t pos = startOffset + numOfElems;
59,197,665✔
5396
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
59,197,665✔
5397
      // colDataSetNULL(pOutput, i);
5398
      continue;
303,225✔
5399
    }
5400

5401
    char*  data = colDataGetData(pInputCol, i);
58,894,440!
5402
    double v;
5403
    GET_TYPED_DATA(v, double, type, data);
58,894,440!
5404

5405
    if (!pInfo->pointsMeet && (pInfo->pos < pInfo->numOfPoints - 1)) {
58,894,440✔
5406
      pInfo->points[pInfo->pos] = v;
6,622,144✔
5407
      pInfo->sum += v;
6,622,144✔
5408
    } else {
5409
      if (!pInfo->pointsMeet && (pInfo->pos == pInfo->numOfPoints - 1)) {
52,272,296!
5410
        pInfo->sum += v;
11,089✔
5411
        pInfo->pointsMeet = true;
11,089✔
5412
      } else {
5413
        pInfo->sum = pInfo->sum + v - pInfo->points[pInfo->pos];
52,261,207✔
5414
      }
5415

5416
      pInfo->points[pInfo->pos] = v;
52,272,296✔
5417
      double result = pInfo->sum / pInfo->numOfPoints;
52,272,296✔
5418
      // check for overflow
5419
      if (isinf(result) || isnan(result)) {
52,272,296!
5420
        colDataSetNULL(pOutput, pos);
×
5421
      } else {
5422
        code = colDataSetVal(pOutput, pos, (char*)&result, false);
52,272,345✔
5423
        if (TSDB_CODE_SUCCESS != code) {
52,272,353!
5424
          return code;
×
5425
        }
5426
      }
5427

5428
      // handle selectivity
5429
      if (pCtx->subsidiaries.num > 0) {
52,272,304✔
5430
        code = appendSelectivityValue(pCtx, i, pos);
32,798,078✔
5431
        if (TSDB_CODE_SUCCESS != code) {
32,798,078!
5432
          return code;
×
5433
        }
5434
      }
5435

5436
      numOfElems++;
52,272,304✔
5437
    }
5438

5439
    pInfo->pos++;
58,894,448✔
5440
    if (pInfo->pos == pInfo->numOfPoints) {
58,894,448✔
5441
      pInfo->pos = 0;
147,875✔
5442
    }
5443
  }
5444

5445
  pResInfo->numOfRes = numOfElems;
238,391✔
5446
  return TSDB_CODE_SUCCESS;
238,391✔
5447
}
5448

5449
static SSampleInfo* getSampleOutputInfo(SqlFunctionCtx* pCtx) {
17,861,464✔
5450
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
17,861,464✔
5451
  SSampleInfo*         pInfo = GET_ROWCELL_INTERBUF(pResInfo);
17,861,464✔
5452

5453
  pInfo->data = (char*)pInfo + sizeof(SSampleInfo);
17,861,464✔
5454
  pInfo->tuplePos = (STuplePos*)((char*)pInfo + sizeof(SSampleInfo) + pInfo->samples * pInfo->colBytes);
17,861,464✔
5455

5456
  return pInfo;
17,861,464✔
5457
}
5458

5459
bool getSampleFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
21,417✔
5460
  SColumnNode* pCol = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
21,417✔
5461
  SValueNode*  pVal = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
21,429✔
5462
  int32_t      numOfSamples = pVal->datum.i;
21,430✔
5463
  pEnv->calcMemSize = sizeof(SSampleInfo) + numOfSamples * (pCol->node.resType.bytes + sizeof(STuplePos));
21,430✔
5464
  return true;
21,430✔
5465
}
5466

5467
int32_t sampleFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
7,803,094✔
5468
  if (pResultInfo->initialized) {
7,803,094!
5469
    return TSDB_CODE_SUCCESS;
×
5470
  }
5471
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
7,803,094!
5472
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5473
  }
5474

5475
  taosSeedRand(taosSafeRand());
7,803,095✔
5476

5477
  SSampleInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
7,803,095✔
5478
  pInfo->samples = pCtx->param[1].param.i;
7,803,095✔
5479
  pInfo->totalPoints = 0;
7,803,095✔
5480
  pInfo->numSampled = 0;
7,803,095✔
5481
  pInfo->colType = pCtx->resDataInfo.type;
7,803,095✔
5482
  pInfo->colBytes = pCtx->resDataInfo.bytes;
7,803,095✔
5483
  pInfo->nullTuplePos.pageId = -1;
7,803,095✔
5484
  pInfo->nullTupleSaved = false;
7,803,095✔
5485
  pInfo->data = (char*)pInfo + sizeof(SSampleInfo);
7,803,095✔
5486
  pInfo->tuplePos = (STuplePos*)((char*)pInfo + sizeof(SSampleInfo) + pInfo->samples * pInfo->colBytes);
7,803,095✔
5487

5488
  return TSDB_CODE_SUCCESS;
7,803,095✔
5489
}
5490

5491
static void sampleAssignResult(SSampleInfo* pInfo, char* data, int32_t index) {
24,382,180✔
5492
  assignVal(pInfo->data + index * pInfo->colBytes, data, pInfo->colBytes, pInfo->colType);
24,382,180✔
5493
}
24,381,984✔
5494

5495
static int32_t doReservoirSample(SqlFunctionCtx* pCtx, SSampleInfo* pInfo, char* data, int32_t index) {
26,336,650✔
5496
  pInfo->totalPoints++;
26,336,650✔
5497
  if (pInfo->numSampled < pInfo->samples) {
26,336,650✔
5498
    sampleAssignResult(pInfo, data, pInfo->numSampled);
22,271,112✔
5499
    if (pCtx->subsidiaries.num > 0) {
22,271,007✔
5500
      int32_t code = saveTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[pInfo->numSampled]);
1,556,891✔
5501
      if (code != TSDB_CODE_SUCCESS) {
1,557,010!
5502
        return code;
×
5503
      }
5504
    }
5505
    pInfo->numSampled++;
22,271,126✔
5506
  } else {
5507
    int32_t j = taosRand() % (pInfo->totalPoints);
4,065,538✔
5508
    if (j < pInfo->samples) {
4,067,241✔
5509
      sampleAssignResult(pInfo, data, j);
2,111,694✔
5510
      if (pCtx->subsidiaries.num > 0) {
2,111,668✔
5511
        int32_t code = updateTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[j]);
759,051✔
5512
        if (code != TSDB_CODE_SUCCESS) {
757,597!
5513
          return code;
×
5514
        }
5515
      }
5516
    }
5517
  }
5518

5519
  return TSDB_CODE_SUCCESS;
26,336,887✔
5520
}
5521

5522
int32_t sampleFunction(SqlFunctionCtx* pCtx) {
10,410,440✔
5523
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
10,410,440✔
5524
  SSampleInfo*         pInfo = getSampleOutputInfo(pCtx);
10,410,440✔
5525

5526
  SInputColumnInfoData* pInput = &pCtx->input;
10,410,439✔
5527

5528
  SColumnInfoData* pInputCol = pInput->pData[0];
10,410,439✔
5529
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
37,171,471✔
5530
    if (colDataIsNull_s(pInputCol, i)) {
53,516,842✔
5531
      continue;
424,257✔
5532
    }
5533

5534
    char*   data = colDataGetData(pInputCol, i);
26,334,164!
5535
    int32_t code = doReservoirSample(pCtx, pInfo, data, i);
26,334,164✔
5536
    if (code != TSDB_CODE_SUCCESS) {
26,336,775!
5537
      return code;
×
5538
    }
5539
  }
5540

5541
  if (pInfo->numSampled == 0 && pCtx->subsidiaries.num > 0 && !pInfo->nullTupleSaved) {
10,413,050✔
5542
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pInfo->nullTuplePos);
35✔
5543
    if (code != TSDB_CODE_SUCCESS) {
35!
5544
      return code;
×
5545
    }
5546
    pInfo->nullTupleSaved = true;
35✔
5547
  }
5548

5549
  SET_VAL(pResInfo, pInfo->numSampled, pInfo->numSampled);
10,413,050✔
5550
  return TSDB_CODE_SUCCESS;
10,413,050✔
5551
}
5552

5553
int32_t sampleFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
7,451,026✔
5554
  int32_t              code = TSDB_CODE_SUCCESS;
7,451,026✔
5555
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
7,451,026✔
5556

5557
  SSampleInfo* pInfo = getSampleOutputInfo(pCtx);
7,451,026✔
5558
  pEntryInfo->complete = true;
7,451,027✔
5559

5560
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
7,451,027✔
5561
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
7,451,027✔
5562
  if (NULL == pCol) {
7,451,028!
5563
    return TSDB_CODE_OUT_OF_RANGE;
×
5564
  }
5565

5566
  int32_t currentRow = pBlock->info.rows;
7,451,028✔
5567
  if (pInfo->numSampled == 0) {
7,451,028✔
5568
    colDataSetNULL(pCol, currentRow);
2,483✔
5569
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
2,483✔
5570
    return code;
2,484✔
5571
  }
5572
  for (int32_t i = 0; i < pInfo->numSampled; ++i) {
28,119,417✔
5573
    code = colDataSetVal(pCol, currentRow + i, pInfo->data + i * pInfo->colBytes, false);
20,671,167✔
5574
    if (TSDB_CODE_SUCCESS != code) {
20,670,900!
5575
      return code;
×
5576
    }
5577
    code = setSelectivityValue(pCtx, pBlock, &pInfo->tuplePos[i], currentRow + i);
20,670,900✔
5578
    if (TSDB_CODE_SUCCESS != code) {
20,670,872!
5579
      return code;
×
5580
    }
5581
  }
5582

5583
  return code;
7,448,250✔
5584
}
5585

5586
bool getTailFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
×
5587
#if 0
5588
  SColumnNode* pCol = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
5589
  SValueNode*  pVal = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
5590
  int32_t      numOfPoints = pVal->datum.i;
5591
  pEnv->calcMemSize = sizeof(STailInfo) + numOfPoints * (POINTER_BYTES + sizeof(STailItem) + pCol->node.resType.bytes);
5592
#endif
5593
  return true;
×
5594
}
5595

5596
int32_t tailFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
×
5597
#if 0
5598
  if (!functionSetup(pCtx, pResultInfo)) {
5599
    return false;
5600
  }
5601

5602
  STailInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
5603
  pInfo->numAdded = 0;
5604
  pInfo->numOfPoints = pCtx->param[1].param.i;
5605
  if (pCtx->numOfParams == 4) {
5606
    pInfo->offset = pCtx->param[2].param.i;
5607
  } else {
5608
    pInfo->offset = 0;
5609
  }
5610
  pInfo->colType = pCtx->resDataInfo.type;
5611
  pInfo->colBytes = pCtx->resDataInfo.bytes;
5612
  if ((pInfo->numOfPoints < 1 || pInfo->numOfPoints > TAIL_MAX_POINTS_NUM) ||
5613
      (pInfo->numOfPoints < 0 || pInfo->numOfPoints > TAIL_MAX_OFFSET)) {
5614
    return false;
5615
  }
5616

5617
  pInfo->pItems = (STailItem**)((char*)pInfo + sizeof(STailInfo));
5618
  char* pItem = (char*)pInfo->pItems + pInfo->numOfPoints * POINTER_BYTES;
5619

5620
  size_t unitSize = sizeof(STailItem) + pInfo->colBytes;
5621
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
5622
    pInfo->pItems[i] = (STailItem*)(pItem + i * unitSize);
5623
    pInfo->pItems[i]->isNull = false;
5624
  }
5625
#endif
5626

5627
  return TSDB_CODE_SUCCESS;
×
5628
}
5629

5630
static void tailAssignResult(STailItem* pItem, char* data, int32_t colBytes, TSKEY ts, bool isNull) {
×
5631
#if 0
5632
  pItem->timestamp = ts;
5633
  if (isNull) {
5634
    pItem->isNull = true;
5635
  } else {
5636
    pItem->isNull = false;
5637
    memcpy(pItem->data, data, colBytes);
5638
  }
5639
#endif
5640
}
×
5641

5642
#if 0
5643
static int32_t tailCompFn(const void* p1, const void* p2, const void* param) {
5644
  STailItem* d1 = *(STailItem**)p1;
5645
  STailItem* d2 = *(STailItem**)p2;
5646
  return compareInt64Val(&d1->timestamp, &d2->timestamp);
5647
}
5648

5649
static void doTailAdd(STailInfo* pInfo, char* data, TSKEY ts, bool isNull) {
5650
  STailItem** pList = pInfo->pItems;
5651
  if (pInfo->numAdded < pInfo->numOfPoints) {
5652
    tailAssignResult(pList[pInfo->numAdded], data, pInfo->colBytes, ts, isNull);
5653
    taosheapsort((void*)pList, sizeof(STailItem**), pInfo->numAdded + 1, NULL, tailCompFn, 0);
5654
    pInfo->numAdded++;
5655
  } else if (pList[0]->timestamp < ts) {
5656
    tailAssignResult(pList[0], data, pInfo->colBytes, ts, isNull);
5657
    taosheapadjust((void*)pList, sizeof(STailItem**), 0, pInfo->numOfPoints - 1, NULL, tailCompFn, NULL, 0);
5658
  }
5659
}
5660
#endif
5661

5662
int32_t tailFunction(SqlFunctionCtx* pCtx) {
×
5663
#if 0
5664
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5665
  STailInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5666

5667
  SInputColumnInfoData* pInput = &pCtx->input;
5668
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
5669

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

5673
  int32_t startOffset = pCtx->offset;
5674
  if (pInfo->offset >= pInput->numOfRows) {
5675
    return 0;
5676
  } else {
5677
    pInfo->numOfPoints = TMIN(pInfo->numOfPoints, pInput->numOfRows - pInfo->offset);
5678
  }
5679
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex - pInfo->offset; i += 1) {
5680
    char* data = colDataGetData(pInputCol, i);
5681
    doTailAdd(pInfo, data, tsList[i], colDataIsNull_s(pInputCol, i));
5682
  }
5683

5684
  taosqsort(pInfo->pItems, pInfo->numOfPoints, POINTER_BYTES, NULL, tailCompFn);
5685

5686
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
5687
    int32_t    pos = startOffset + i;
5688
    STailItem* pItem = pInfo->pItems[i];
5689
    if (pItem->isNull) {
5690
      colDataSetNULL(pOutput, pos);
5691
    } else {
5692
      colDataSetVal(pOutput, pos, pItem->data, false);
5693
    }
5694
  }
5695

5696
  return pInfo->numOfPoints;
5697
#endif
5698
  return 0;
×
5699
}
5700

5701
int32_t tailFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
×
5702
#if 0
5703
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
5704
  STailInfo*           pInfo = GET_ROWCELL_INTERBUF(pEntryInfo);
5705
  pEntryInfo->complete = true;
5706

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

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

5712
  // todo assign the tag value and the corresponding row data
5713
  int32_t currentRow = pBlock->info.rows;
5714
  for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
5715
    STailItem* pItem = pInfo->pItems[i];
5716
    colDataSetVal(pCol, currentRow, pItem->data, false);
5717
    currentRow += 1;
5718
  }
5719

5720
  return pEntryInfo->numOfRes;
5721
#endif
5722
  return 0;
×
5723
}
5724

5725
bool getUniqueFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
×
5726
#if 0
5727
  pEnv->calcMemSize = sizeof(SUniqueInfo) + UNIQUE_MAX_RESULT_SIZE;
5728
#endif
5729
  return true;
×
5730
}
5731

5732
int32_t uniqueFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
×
5733
#if 0
5734
  if (!functionSetup(pCtx, pResInfo)) {
5735
    return false;
5736
  }
5737

5738
  SUniqueInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5739
  pInfo->numOfPoints = 0;
5740
  pInfo->colType = pCtx->resDataInfo.type;
5741
  pInfo->colBytes = pCtx->resDataInfo.bytes;
5742
  if (pInfo->pHash != NULL) {
5743
    taosHashClear(pInfo->pHash);
5744
  } else {
5745
    pInfo->pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
5746
  }
5747
#endif
5748
  return TSDB_CODE_SUCCESS;
×
5749
}
5750

5751
#if 0
5752
static void doUniqueAdd(SUniqueInfo* pInfo, char* data, TSKEY ts, bool isNull) {
5753
  // handle null elements
5754
  if (isNull == true) {
5755
    int32_t      size = sizeof(SUniqueItem) + pInfo->colBytes;
5756
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + pInfo->numOfPoints * size);
5757
    if (pInfo->hasNull == false && pItem->isNull == false) {
5758
      pItem->timestamp = ts;
5759
      pItem->isNull = true;
5760
      pInfo->numOfPoints++;
5761
      pInfo->hasNull = true;
5762
    } else if (pItem->timestamp > ts && pItem->isNull == true) {
5763
      pItem->timestamp = ts;
5764
    }
5765
    return;
5766
  }
5767

5768
  int32_t      hashKeyBytes = IS_VAR_DATA_TYPE(pInfo->colType) ? varDataTLen(data) : pInfo->colBytes;
5769
  SUniqueItem* pHashItem = taosHashGet(pInfo->pHash, data, hashKeyBytes);
5770
  if (pHashItem == NULL) {
5771
    int32_t      size = sizeof(SUniqueItem) + pInfo->colBytes;
5772
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + pInfo->numOfPoints * size);
5773
    pItem->timestamp = ts;
5774
    memcpy(pItem->data, data, pInfo->colBytes);
5775

5776
    taosHashPut(pInfo->pHash, data, hashKeyBytes, (char*)pItem, sizeof(SUniqueItem*));
5777
    pInfo->numOfPoints++;
5778
  } else if (pHashItem->timestamp > ts) {
5779
    pHashItem->timestamp = ts;
5780
  }
5781
}
5782
#endif
5783

5784
int32_t uniqueFunction(SqlFunctionCtx* pCtx) {
×
5785
#if 0
5786
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5787
  SUniqueInfo*         pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5788

5789
  SInputColumnInfoData* pInput = &pCtx->input;
5790
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
5791

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

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

5801
    if (sizeof(SUniqueInfo) + pInfo->numOfPoints * (sizeof(SUniqueItem) + pInfo->colBytes) >= UNIQUE_MAX_RESULT_SIZE) {
5802
      taosHashCleanup(pInfo->pHash);
5803
      return 0;
5804
    }
5805
  }
5806

5807
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
5808
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + i * (sizeof(SUniqueItem) + pInfo->colBytes));
5809
    if (pItem->isNull == true) {
5810
      colDataSetNULL(pOutput, i);
5811
    } else {
5812
      colDataSetVal(pOutput, i, pItem->data, false);
5813
    }
5814
    if (pTsOutput != NULL) {
5815
      colDataSetInt64(pTsOutput, i, &pItem->timestamp);
5816
    }
5817
  }
5818

5819
  return pInfo->numOfPoints;
5820
#endif
5821
  return 0;
×
5822
}
5823

5824
bool getModeFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
23,576✔
5825
  pEnv->calcMemSize = sizeof(SModeInfo);
23,576✔
5826
  return true;
23,576✔
5827
}
5828

5829
int32_t modeFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
24,534✔
5830
  if (pResInfo->initialized) {
24,534!
5831
    return TSDB_CODE_SUCCESS;
×
5832
  }
5833
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
24,534!
5834
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5835
  }
5836

5837
  SModeInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
24,534✔
5838
  pInfo->colType = pCtx->resDataInfo.type;
24,534✔
5839
  pInfo->colBytes = pCtx->resDataInfo.bytes;
24,534✔
5840
  if (pInfo->pHash != NULL) {
24,534!
5841
    taosHashClear(pInfo->pHash);
×
5842
  } else {
5843
    pInfo->pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
24,534✔
5844
    if (NULL == pInfo->pHash) {
24,535!
5845
      return terrno;
×
5846
    }
5847
  }
5848
  pInfo->nullTupleSaved = false;
24,535✔
5849
  pInfo->nullTuplePos.pageId = -1;
24,535✔
5850

5851
  pInfo->buf = taosMemoryMalloc(pInfo->colBytes);
24,535✔
5852
  if (NULL == pInfo->buf) {
24,535!
5853
    taosHashCleanup(pInfo->pHash);
×
5854
    pInfo->pHash = NULL;
×
5855
    return terrno;
×
5856
  }
5857
  pCtx->needCleanup = true;
24,535✔
5858
  return TSDB_CODE_SUCCESS;
24,535✔
5859
}
5860

5861
static void modeFunctionCleanup(SModeInfo * pInfo) {
24,534✔
5862
  taosHashCleanup(pInfo->pHash);
24,534✔
5863
  pInfo->pHash = NULL;
24,535✔
5864
  taosMemoryFreeClear(pInfo->buf);
24,535!
5865
}
24,534✔
5866

5867
void modeFunctionCleanupExt(SqlFunctionCtx* pCtx) {
×
5868
  if (pCtx == NULL || GET_RES_INFO(pCtx) == NULL || GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)) == NULL) {
×
5869
    return;
×
5870
  }
5871
  modeFunctionCleanup(GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)));
×
5872
}
5873

5874
static int32_t saveModeTupleData(SqlFunctionCtx* pCtx, char* data, SModeInfo *pInfo, STuplePos* pPos) {
82,859,167✔
5875
  if (IS_VAR_DATA_TYPE(pInfo->colType)) {
82,859,167!
5876
    (void)memcpy(pInfo->buf, data, varDataTLen(data));
16,849,293✔
5877
  } else {
5878
    (void)memcpy(pInfo->buf, data, pInfo->colBytes);
66,009,874✔
5879
  }
5880

5881
  return doSaveTupleData(&pCtx->saveHandle, pInfo->buf, pInfo->colBytes, NULL, pPos, pCtx->pStore);
82,859,167✔
5882
}
5883

5884
static int32_t doModeAdd(SModeInfo* pInfo, int32_t rowIndex, SqlFunctionCtx* pCtx, char* data) {
110,828,072✔
5885
  int32_t code = TSDB_CODE_SUCCESS;
110,828,072✔
5886
  int32_t hashKeyBytes = IS_STR_DATA_TYPE(pInfo->colType) ? varDataTLen(data) : pInfo->colBytes;
110,828,072✔
5887

5888
  SModeItem* pHashItem = (SModeItem *)taosHashGet(pInfo->pHash, data, hashKeyBytes);
110,828,072✔
5889
  if (pHashItem == NULL) {
110,827,120✔
5890
    int32_t    size = sizeof(SModeItem);
82,859,285✔
5891
    SModeItem  item = {0};
82,859,285✔
5892

5893
    item.count += 1;
82,859,285✔
5894
    code = saveModeTupleData(pCtx, data, pInfo, &item.dataPos);
82,859,285✔
5895
    if (code != TSDB_CODE_SUCCESS) {
82,858,364!
5896
      return code;
×
5897
    }
5898

5899
    if (pCtx->subsidiaries.num > 0) {
82,858,364✔
5900
      code = saveTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &item.tuplePos);
46,999,388✔
5901
      if (code != TSDB_CODE_SUCCESS) {
46,999,388!
5902
        return code;
×
5903
      }
5904
    }
5905

5906
    code = taosHashPut(pInfo->pHash, data, hashKeyBytes, &item, sizeof(SModeItem));
82,858,364✔
5907
    if (code != TSDB_CODE_SUCCESS) {
82,860,661!
5908
      return code;
×
5909
    }
5910
  } else {
5911
    pHashItem->count += 1;
27,967,835✔
5912
    if (pCtx->subsidiaries.num > 0) {
27,967,835✔
5913
      code = updateTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &pHashItem->tuplePos);
24,041,648✔
5914
      if (code != TSDB_CODE_SUCCESS) {
24,041,648!
5915
        return code;
×
5916
      }
5917
    }
5918
  }
5919

5920
  return code;
110,828,496✔
5921
}
5922

5923
int32_t modeFunction(SqlFunctionCtx* pCtx) {
2,107,761✔
5924
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,107,761✔
5925
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,107,761✔
5926

5927
  SInputColumnInfoData* pInput = &pCtx->input;
2,107,761✔
5928

5929
  SColumnInfoData* pInputCol = pInput->pData[0];
2,107,761✔
5930
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
2,107,761✔
5931

5932
  int32_t numOfElems = 0;
2,107,761✔
5933
  int32_t startOffset = pCtx->offset;
2,107,761✔
5934
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
113,393,721✔
5935
    if (colDataIsNull_s(pInputCol, i)) {
222,571,696✔
5936
      continue;
458,031✔
5937
    }
5938
    numOfElems++;
110,827,817✔
5939

5940
    char*   data = colDataGetData(pInputCol, i);
110,827,817!
5941
    int32_t code = doModeAdd(pInfo, i, pCtx, data);
110,827,817✔
5942
    if (code != TSDB_CODE_SUCCESS) {
110,828,480✔
5943
      modeFunctionCleanup(pInfo);
551✔
5944
      return code;
×
5945
    }
5946
  }
5947

5948
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pInfo->nullTupleSaved) {
2,107,873!
5949
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pInfo->nullTuplePos);
50✔
5950
    if (code != TSDB_CODE_SUCCESS) {
50!
5951
      modeFunctionCleanup(pInfo);
×
5952
      return code;
×
5953
    }
5954
    pInfo->nullTupleSaved = true;
50✔
5955
  }
5956

5957
  SET_VAL(pResInfo, numOfElems, 1);
2,107,873✔
5958

5959
  return TSDB_CODE_SUCCESS;
2,107,873✔
5960
}
5961

5962
int32_t modeFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
24,534✔
5963
  int32_t              code = TSDB_CODE_SUCCESS;
24,534✔
5964
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
24,534✔
5965
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
24,534✔
5966
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
24,534✔
5967
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
24,534✔
5968
  int32_t              currentRow = pBlock->info.rows;
24,534✔
5969
  if (NULL == pCol) {
24,534!
5970
    modeFunctionCleanup(pInfo);
×
5971
    return TSDB_CODE_OUT_OF_RANGE;
×
5972
  }
5973

5974
  STuplePos resDataPos, resTuplePos;
5975
  int32_t maxCount = 0;
24,534✔
5976

5977
  void *pIter = taosHashIterate(pInfo->pHash, NULL);
24,534✔
5978
  while (pIter != NULL) {
82,885,197✔
5979
    SModeItem *pItem = (SModeItem *)pIter;
82,860,663✔
5980
    if (pItem->count >= maxCount) {
82,860,663✔
5981
      maxCount = pItem->count;
73,330,109✔
5982
      resDataPos = pItem->dataPos;
73,330,109✔
5983
      resTuplePos = pItem->tuplePos;
73,330,109✔
5984
    }
5985

5986
    pIter = taosHashIterate(pInfo->pHash, pIter);
82,860,663✔
5987
  }
5988

5989
  if (maxCount != 0) {
24,534✔
5990
    char* pData = NULL;
21,895✔
5991
    code = loadTupleData(pCtx, &resDataPos, &pData);
21,895✔
5992
    if (pData == NULL || TSDB_CODE_SUCCESS != code) {
21,895!
5993
      code = terrno = TSDB_CODE_NOT_FOUND;
×
5994
      qError("Load tuple data failed since %s, groupId:%" PRIu64 ", ts:%" PRId64, terrstr(),
×
5995
             resDataPos.streamTupleKey.groupId, resDataPos.streamTupleKey.ts);
5996
      modeFunctionCleanup(pInfo);
×
5997
      return code;
×
5998
    }
5999

6000
    code = colDataSetVal(pCol, currentRow, pData, false);
21,895✔
6001
    if (TSDB_CODE_SUCCESS != code) {
21,895!
6002
      modeFunctionCleanup(pInfo);
×
6003
     return code;
×
6004
    }
6005
    code = setSelectivityValue(pCtx, pBlock, &resTuplePos, currentRow);
21,895✔
6006
  } else {
6007
    colDataSetNULL(pCol, currentRow);
2,639✔
6008
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
2,639✔
6009
  }
6010

6011
  modeFunctionCleanup(pInfo);
24,534✔
6012

6013
  return code;
24,535✔
6014
}
6015

6016
bool getTwaFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
77,121✔
6017
  pEnv->calcMemSize = sizeof(STwaInfo);
77,121✔
6018
  return true;
77,121✔
6019
}
6020

6021
int32_t twaFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
12,222,531✔
6022
  if (pResultInfo->initialized) {
12,222,531!
6023
    return TSDB_CODE_SUCCESS;
×
6024
  }
6025
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
12,222,531!
6026
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6027
  }
6028

6029
  STwaInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
12,222,531✔
6030
  pInfo->numOfElems = 0;
12,222,531✔
6031
  pInfo->p.key = INT64_MIN;
12,222,531✔
6032
  pInfo->win = TSWINDOW_INITIALIZER;
12,222,531✔
6033
  return TSDB_CODE_SUCCESS;
12,222,531✔
6034
}
6035

6036
static double twa_get_area(SPoint1 s, SPoint1 e) {
36,749,735✔
6037
  if (e.key == INT64_MAX || s.key == INT64_MIN) {
36,749,735!
6038
    return 0;
×
6039
  }
6040

6041
  if ((s.val >= 0 && e.val >= 0) || (s.val <= 0 && e.val <= 0)) {
36,750,093✔
6042
    return (s.val + e.val) * (e.key - s.key) / 2;
19,653,387✔
6043
  }
6044

6045
  double x = (s.key * e.val - e.key * s.val) / (e.val - s.val);
17,096,706✔
6046
  double val = (s.val * (x - s.key) + e.val * (e.key - x)) / 2;
17,096,706✔
6047
  return val;
17,096,706✔
6048
}
6049

6050
int32_t twaFunction(SqlFunctionCtx* pCtx) {
12,237,398✔
6051
  int32_t               code = TSDB_CODE_SUCCESS;
12,237,398✔
6052
  SInputColumnInfoData* pInput = &pCtx->input;
12,237,398✔
6053
  SColumnInfoData*      pInputCol = pInput->pData[0];
12,237,398✔
6054

6055
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
12,237,398✔
6056
  STwaInfo*            pInfo = GET_ROWCELL_INTERBUF(pResInfo);
12,237,398✔
6057
  SPoint1*             last = &pInfo->p;
12,237,398✔
6058

6059
  if (IS_NULL_TYPE(pInputCol->info.type)) {
12,237,398!
6060
    pInfo->numOfElems = 0;
×
6061
    goto _twa_over;
×
6062
  }
6063

6064
  funcInputUpdate(pCtx);
12,237,398✔
6065
  SFuncInputRow row = {0};
12,237,393✔
6066
  bool          result = false;
12,237,393✔
6067
  if (pCtx->start.key != INT64_MIN && last->key == INT64_MIN) {
12,237,393!
6068
    while (1) {
6069
      code = funcInputGetNextRow(pCtx, &row, &result);
4,759,353✔
6070
      if (TSDB_CODE_SUCCESS != code) {
4,759,348!
6071
        return code;
×
6072
      }
6073
      if (!result) {
4,759,348✔
6074
        break;
2✔
6075
      }
6076
      if (row.isDataNull) {
4,759,346✔
6077
        continue;
2✔
6078
      }
6079

6080
      last->key = row.ts;
4,759,344✔
6081

6082
      GET_TYPED_DATA(last->val, double, pInputCol->info.type, row.pData);
4,759,344!
6083

6084
      pInfo->dOutput += twa_get_area(pCtx->start, *last);
4,759,344✔
6085
      pInfo->win.skey = pCtx->start.key;
4,759,344✔
6086
      pInfo->numOfElems++;
4,759,344✔
6087
      break;
4,759,344✔
6088
    }
6089
  } else if (pInfo->p.key == INT64_MIN) {
7,478,042✔
6090
    while (1) {
6091
      code = funcInputGetNextRow(pCtx, &row, &result);
7,584,620✔
6092
      if (TSDB_CODE_SUCCESS != code) {
7,583,886!
6093
        return code;
×
6094
      }
6095
      if (!result) {
7,583,886✔
6096
        break;
14,284✔
6097
      }
6098
      if (row.isDataNull) {
7,569,602✔
6099
        continue;
119,953✔
6100
      }
6101

6102
      last->key = row.ts;
7,449,649✔
6103

6104
      GET_TYPED_DATA(last->val, double, pInputCol->info.type, row.pData);
7,449,649!
6105

6106
      pInfo->win.skey = last->key;
7,449,649✔
6107
      pInfo->numOfElems++;
7,449,649✔
6108
      break;
7,449,649✔
6109
    }
6110
  }
6111

6112
  SPoint1 st = {0};
12,236,654✔
6113

6114
  // calculate the value of
6115
  while (1) {
6116
    code = funcInputGetNextRow(pCtx, &row, &result);
39,426,379✔
6117
    if (TSDB_CODE_SUCCESS != code) {
39,424,760!
6118
      return code;
×
6119
    }
6120
    if (!result) {
39,424,760✔
6121
      break;
12,236,709✔
6122
    }
6123
    if (row.isDataNull) {
27,188,051✔
6124
      continue;
630✔
6125
    }
6126
    pInfo->numOfElems++;
27,187,421✔
6127
    switch (pInputCol->info.type) {
27,187,421!
6128
      case TSDB_DATA_TYPE_TINYINT: {
22,903,697✔
6129
        INIT_INTP_POINT(st, row.ts, *(int8_t*)row.pData);
22,903,697✔
6130
        break;
22,903,697✔
6131
      }
6132
      case TSDB_DATA_TYPE_SMALLINT: {
85,636✔
6133
        INIT_INTP_POINT(st, row.ts, *(int16_t*)row.pData);
85,636✔
6134
        break;
85,636✔
6135
      }
6136
      case TSDB_DATA_TYPE_INT: {
114,536✔
6137
        INIT_INTP_POINT(st, row.ts, *(int32_t*)row.pData);
114,536✔
6138
        break;
114,536✔
6139
      }
6140
      case TSDB_DATA_TYPE_BIGINT: {
381,087✔
6141
        INIT_INTP_POINT(st, row.ts, *(int64_t*)row.pData);
381,087✔
6142
        break;
381,087✔
6143
      }
6144
      case TSDB_DATA_TYPE_FLOAT: {
3,354,139✔
6145
        INIT_INTP_POINT(st, row.ts, *(float_t*)row.pData);
3,354,139✔
6146
        break;
3,354,139✔
6147
      }
6148
      case TSDB_DATA_TYPE_DOUBLE: {
83,365✔
6149
        INIT_INTP_POINT(st, row.ts, *(double*)row.pData);
83,365✔
6150
        break;
83,365✔
6151
      }
6152
      case TSDB_DATA_TYPE_UTINYINT: {
68,666✔
6153
        INIT_INTP_POINT(st, row.ts, *(uint8_t*)row.pData);
68,666✔
6154
        break;
68,666✔
6155
      }
6156
      case TSDB_DATA_TYPE_USMALLINT: {
68,567✔
6157
        INIT_INTP_POINT(st, row.ts, *(uint16_t*)row.pData);
68,567✔
6158
        break;
68,567✔
6159
      }
6160
      case TSDB_DATA_TYPE_UINT: {
70,683✔
6161
        INIT_INTP_POINT(st, row.ts, *(uint32_t*)row.pData);
70,683✔
6162
        break;
70,683✔
6163
      }
6164
      case TSDB_DATA_TYPE_UBIGINT: {
59,015✔
6165
        INIT_INTP_POINT(st, row.ts, *(uint64_t*)row.pData);
59,015✔
6166
        break;
59,015✔
6167
      }
6168
      default: {
×
6169
        return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
6170
      }
6171
    }
6172
    if (pInfo->p.key == st.key) {
27,189,391!
6173
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6174
    }
6175

6176
    pInfo->dOutput += twa_get_area(pInfo->p, st);
27,189,391✔
6177
    pInfo->p = st;
27,189,095✔
6178
  }
6179

6180
  // the last interpolated time window value
6181
  if (pCtx->end.key != INT64_MIN) {
12,236,709✔
6182
    pInfo->dOutput += twa_get_area(pInfo->p, pCtx->end);
4,803,403✔
6183
    pInfo->p = pCtx->end;
4,803,405✔
6184
    pInfo->numOfElems += 1;
4,803,405✔
6185
  }
6186

6187
  pInfo->win.ekey = pInfo->p.key;
12,236,711✔
6188

6189
_twa_over:
12,236,711✔
6190
  SET_VAL(pResInfo, 1, 1);
12,236,711✔
6191
  return TSDB_CODE_SUCCESS;
12,236,711✔
6192
}
6193

6194
/*
6195
 * To copy the input to interResBuf to avoid the input buffer space be over writen
6196
 * by next input data. The TWA function only applies to each table, so no merge procedure
6197
 * is required, we simply copy to the resut ot interResBuffer.
6198
 */
6199
// void twa_function_copy(SQLFunctionCtx *pCtx) {
6200
//   SResultRowEntryInfo *pResInfo = GET_RES_INFO(pCtx);
6201
//
6202
//   memcpy(GET_ROWCELL_INTERBUF(pResInfo), pCtx->pInput, (size_t)pCtx->inputBytes);
6203
//   pResInfo->hasResult = ((STwaInfo *)pCtx->pInput)->hasResult;
6204
// }
6205

6206
int32_t twaFinalize(struct SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
12,202,997✔
6207
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
12,202,997✔
6208

6209
  STwaInfo* pInfo = (STwaInfo*)GET_ROWCELL_INTERBUF(pResInfo);
12,202,997✔
6210
  if (pInfo->numOfElems == 0) {
12,202,997✔
6211
    pResInfo->numOfRes = 0;
14,061✔
6212
  } else {
6213
    if (pInfo->win.ekey == pInfo->win.skey) {
12,188,936✔
6214
      pInfo->dTwaRes = pInfo->p.val;
5,894,282✔
6215
    } else if (pInfo->win.ekey == INT64_MAX || pInfo->win.skey == INT64_MIN) {  // no data in timewindow
6,294,654!
6216
      pInfo->dTwaRes = 0;
×
6217
    } else {
6218
      pInfo->dTwaRes = pInfo->dOutput / (pInfo->win.ekey - pInfo->win.skey);
6,294,910✔
6219
    }
6220

6221
    pResInfo->numOfRes = 1;
12,188,936✔
6222
  }
6223

6224
  return functionFinalize(pCtx, pBlock);
12,202,997✔
6225
}
6226

6227
int32_t blockDistSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
1,626✔
6228
  if (pResultInfo->initialized) {
1,626!
6229
    return TSDB_CODE_SUCCESS;
×
6230
  }
6231
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
1,626!
6232
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6233
  }
6234

6235
  STableBlockDistInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,626✔
6236
  pInfo->minRows = INT32_MAX;
1,626✔
6237
  return TSDB_CODE_SUCCESS;
1,626✔
6238
}
6239

6240
int32_t blockDistFunction(SqlFunctionCtx* pCtx) {
3,250✔
6241
  const int32_t BLOCK_DIST_RESULT_ROWS = 25;
3,250✔
6242

6243
  SInputColumnInfoData* pInput = &pCtx->input;
3,250✔
6244
  SColumnInfoData*      pInputCol = pInput->pData[0];
3,250✔
6245
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
3,250✔
6246
  STableBlockDistInfo*  pDistInfo = GET_ROWCELL_INTERBUF(pResInfo);
3,250✔
6247

6248
  STableBlockDistInfo p1 = {0};
3,250✔
6249
  if (tDeserializeBlockDistInfo(varDataVal(pInputCol->pData), varDataLen(pInputCol->pData), &p1) < 0) {
3,250!
6250
    qError("failed to deserialize block dist info");
×
6251
    return TSDB_CODE_FAILED;
×
6252
  }
6253

6254
  pDistInfo->numOfBlocks += p1.numOfBlocks;
3,250✔
6255
  pDistInfo->numOfTables += p1.numOfTables;
3,250✔
6256
  pDistInfo->numOfInmemRows += p1.numOfInmemRows;
3,250✔
6257
  pDistInfo->numOfSttRows += p1.numOfSttRows;
3,250✔
6258
  pDistInfo->totalSize += p1.totalSize;
3,250✔
6259
  pDistInfo->totalRows += p1.totalRows;
3,250✔
6260
  pDistInfo->numOfFiles += p1.numOfFiles;
3,250✔
6261

6262
  pDistInfo->defMinRows = p1.defMinRows;
3,250✔
6263
  pDistInfo->defMaxRows = p1.defMaxRows;
3,250✔
6264
  pDistInfo->rowSize = p1.rowSize;
3,250✔
6265

6266
  if (pDistInfo->minRows > p1.minRows) {
3,250✔
6267
    pDistInfo->minRows = p1.minRows;
1✔
6268
  }
6269
  if (pDistInfo->maxRows < p1.maxRows) {
3,250✔
6270
    pDistInfo->maxRows = p1.maxRows;
1✔
6271
  }
6272
  pDistInfo->numOfVgroups += (p1.numOfTables != 0 ? 1 : 0);
3,250✔
6273
  for (int32_t i = 0; i < tListLen(pDistInfo->blockRowsHisto); ++i) {
68,250✔
6274
    pDistInfo->blockRowsHisto[i] += p1.blockRowsHisto[i];
65,000✔
6275
  }
6276

6277
  pResInfo->numOfRes = BLOCK_DIST_RESULT_ROWS;  // default output rows
3,250✔
6278
  return TSDB_CODE_SUCCESS;
3,250✔
6279
}
6280

6281
int32_t tSerializeBlockDistInfo(void* buf, int32_t bufLen, const STableBlockDistInfo* pInfo) {
6,484✔
6282
  SEncoder encoder = {0};
6,484✔
6283
  int32_t  code = 0;
6,484✔
6284
  int32_t  lino;
6285
  int32_t  tlen;
6286
  tEncoderInit(&encoder, buf, bufLen);
6,484✔
6287

6288
  TAOS_CHECK_EXIT(tStartEncode(&encoder));
6,495!
6289
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->rowSize));
12,964!
6290

6291
  TAOS_CHECK_EXIT(tEncodeU16(&encoder, pInfo->numOfFiles));
12,964!
6292
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfBlocks));
12,964!
6293
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfTables));
12,964!
6294

6295
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalSize));
12,964!
6296
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalRows));
12,964!
6297
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->maxRows));
12,964!
6298
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->minRows));
12,964!
6299
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMaxRows));
12,964!
6300
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMinRows));
12,964!
6301
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfInmemRows));
12,964!
6302
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfSttRows));
12,964!
6303
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfVgroups));
12,964!
6304

6305
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
136,084✔
6306
    TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->blockRowsHisto[i]));
259,204!
6307
  }
6308

6309
  tEndEncode(&encoder);
6,482✔
6310

6311
_exit:
6,490✔
6312
  if (code) {
6,490!
6313
    tlen = code;
×
6314
  } else {
6315
    tlen = encoder.pos;
6,490✔
6316
  }
6317
  tEncoderClear(&encoder);
6,490✔
6318
  return tlen;
6,484✔
6319
}
6320

6321
int32_t tDeserializeBlockDistInfo(void* buf, int32_t bufLen, STableBlockDistInfo* pInfo) {
3,250✔
6322
  SDecoder decoder = {0};
3,250✔
6323
  int32_t  code = 0;
3,250✔
6324
  int32_t  lino;
6325
  tDecoderInit(&decoder, buf, bufLen);
3,250✔
6326

6327
  TAOS_CHECK_EXIT(tStartDecode(&decoder));
3,250!
6328
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->rowSize));
6,500!
6329

6330
  TAOS_CHECK_EXIT(tDecodeU16(&decoder, &pInfo->numOfFiles));
6,500!
6331
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfBlocks));
6,500!
6332
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfTables));
6,500!
6333

6334
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->totalSize));
6,500!
6335
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->totalRows));
6,500!
6336
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->maxRows));
6,500!
6337
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->minRows));
6,500!
6338
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->defMaxRows));
6,500!
6339
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->defMinRows));
6,500!
6340
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfInmemRows));
6,500!
6341
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfSttRows));
6,500!
6342
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfVgroups));
6,500!
6343

6344
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
68,250✔
6345
    TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->blockRowsHisto[i]));
130,000!
6346
  }
6347

6348
_exit:
3,250✔
6349
  tDecoderClear(&decoder);
3,250✔
6350
  return code;
3,250✔
6351
}
6352

6353
int32_t blockDistFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1,626✔
6354
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,626✔
6355
  STableBlockDistInfo* pData = GET_ROWCELL_INTERBUF(pResInfo);
1,626✔
6356

6357
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);
1,626✔
6358
  if (NULL == pColInfo) {
1,626!
6359
    return TSDB_CODE_OUT_OF_RANGE;
×
6360
  }
6361

6362
  if (pData->totalRows == 0) {
1,626✔
6363
    pData->minRows = 0;
1,625✔
6364
  }
6365

6366
  int32_t row = 0;
1,626✔
6367
  char    st[256] = {0};
1,626✔
6368
  double  averageSize = 0;
1,626✔
6369
  if (pData->numOfBlocks != 0) {
1,626✔
6370
    averageSize = ((double)pData->totalSize) / pData->numOfBlocks;
1✔
6371
  }
6372
  uint64_t totalRawSize = pData->totalRows * pData->rowSize;
1,626✔
6373
  double   compRatio = 0;
1,626✔
6374
  if (totalRawSize != 0) {
1,626✔
6375
    compRatio = pData->totalSize * 100 / (double)totalRawSize;
1✔
6376
  }
6377

6378
  int32_t len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
3,252✔
6379
                        "Total_Blocks=[%d] Total_Size=[%.2f KiB] Average_size=[%.2f KiB] Compression_Ratio=[%.2f %c]",
6380
                        pData->numOfBlocks, pData->totalSize / 1024.0, averageSize / 1024.0, compRatio, '%');
1,626✔
6381

6382
  varDataSetLen(st, len);
1,626✔
6383
  int32_t code = colDataSetVal(pColInfo, row++, st, false);
1,626✔
6384
  if (TSDB_CODE_SUCCESS != code) {
1,626!
6385
    return code;
×
6386
  }
6387

6388
  int64_t avgRows = 0;
1,626✔
6389
  if (pData->numOfBlocks > 0) {
1,626✔
6390
    avgRows = pData->totalRows / pData->numOfBlocks;
1✔
6391
  }
6392

6393
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Block_Rows=[%" PRId64 "] MinRows=[%d] MaxRows=[%d] AvgRows=[%" PRId64 "]",
1,626✔
6394
                pData->totalRows, pData->minRows, pData->maxRows, avgRows);
6395
  varDataSetLen(st, len);
1,626✔
6396
  code = colDataSetVal(pColInfo, row++, st, false);
1,626✔
6397
  if (TSDB_CODE_SUCCESS != code) {
1,626!
6398
    return code;
×
6399
  }
6400

6401
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Inmem_Rows=[%d] Stt_Rows=[%d] ", pData->numOfInmemRows, pData->numOfSttRows);
1,626✔
6402
  varDataSetLen(st, len);
1,626✔
6403
  code = colDataSetVal(pColInfo, row++, st, false);
1,626✔
6404
  if (TSDB_CODE_SUCCESS != code) {
1,626!
6405
    return code;
×
6406
  }
6407

6408
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Total_Tables=[%d] Total_Filesets=[%d] Total_Vgroups=[%d]", pData->numOfTables,
3,252✔
6409
                pData->numOfFiles, pData->numOfVgroups);
1,626✔
6410

6411
  varDataSetLen(st, len);
1,626✔
6412
  code = colDataSetVal(pColInfo, row++, st, false);
1,626✔
6413
  if (TSDB_CODE_SUCCESS != code) {
1,626!
6414
    return code;
×
6415
  }
6416

6417
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
1,626✔
6418
                "--------------------------------------------------------------------------------");
6419
  varDataSetLen(st, len);
1,626✔
6420
  code = colDataSetVal(pColInfo, row++, st, false);
1,626✔
6421
  if (TSDB_CODE_SUCCESS != code) {
1,626!
6422
    return code;
×
6423
  }
6424

6425
  int32_t maxVal = 0;
1,626✔
6426
  int32_t minVal = INT32_MAX;
1,626✔
6427
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
34,146✔
6428
    if (maxVal < pData->blockRowsHisto[i]) {
32,520✔
6429
      maxVal = pData->blockRowsHisto[i];
1✔
6430
    }
6431

6432
    if (minVal > pData->blockRowsHisto[i]) {
32,520✔
6433
      minVal = pData->blockRowsHisto[i];
1,627✔
6434
    }
6435
  }
6436

6437
  // maximum number of step is 80
6438
  double factor = pData->numOfBlocks / 80.0;
1,626✔
6439

6440
  int32_t numOfBuckets = sizeof(pData->blockRowsHisto) / sizeof(pData->blockRowsHisto[0]);
1,626✔
6441
  int32_t bucketRange = ceil(((double) (pData->defMaxRows - pData->defMinRows)) / numOfBuckets);
1,626✔
6442

6443
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
34,146✔
6444
    len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "%04d |", pData->defMinRows + bucketRange * (i + 1));
32,520✔
6445

6446
    int32_t num = 0;
32,520✔
6447
    if (pData->blockRowsHisto[i] > 0) {
32,520✔
6448
      num = (pData->blockRowsHisto[i]) / factor;
1✔
6449
    }
6450

6451
    for (int32_t j = 0; j < num; ++j) {
32,600✔
6452
      int32_t x = tsnprintf(varDataVal(st) + len, sizeof(st) - VARSTR_HEADER_SIZE - len, "%c", '|');
80✔
6453
      len += x;
80✔
6454
    }
6455

6456
    if (pData->blockRowsHisto[i] > 0) {
32,520✔
6457
      double v = pData->blockRowsHisto[i] * 100.0 / pData->numOfBlocks;
1✔
6458
      len += tsnprintf(varDataVal(st) + len, sizeof(st) - VARSTR_HEADER_SIZE - len, "  %d (%.2f%c)", pData->blockRowsHisto[i], v, '%');
1✔
6459
    }
6460

6461
    varDataSetLen(st, len);
32,520✔
6462
    code = colDataSetVal(pColInfo, row++, st, false);
32,520✔
6463
    if (TSDB_CODE_SUCCESS != code) {
32,520!
6464
      return code;
×
6465
    }
6466
  }
6467

6468
  return TSDB_CODE_SUCCESS;
1,626✔
6469
}
6470

6471
bool getDerivativeFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
31,241✔
6472
  pEnv->calcMemSize = sizeof(SDerivInfo);
31,241✔
6473
  return true;
31,241✔
6474
}
6475

6476
int32_t derivativeFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
87,063✔
6477
  if (pResInfo->initialized) {
87,063✔
6478
    return TSDB_CODE_SUCCESS;
55,683✔
6479
  }
6480
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
31,380!
6481
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6482
  }
6483

6484
  SDerivInfo* pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
31,380✔
6485

6486
  pDerivInfo->ignoreNegative = pCtx->param[2].param.i;
31,380✔
6487
  pDerivInfo->prevTs = -1;
31,380✔
6488
  pDerivInfo->tsWindow = pCtx->param[1].param.i;
31,380✔
6489
  pDerivInfo->valueSet = false;
31,380✔
6490
  return TSDB_CODE_SUCCESS;
31,380✔
6491
}
6492

6493
int32_t derivativeFunction(SqlFunctionCtx* pCtx) {
55,822✔
6494
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
55,822✔
6495
  SDerivInfo*          pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
55,822✔
6496

6497
  SInputColumnInfoData* pInput = &pCtx->input;
55,822✔
6498
  SColumnInfoData*      pInputCol = pInput->pData[0];
55,822✔
6499

6500
  int32_t          numOfElems = 0;
55,822✔
6501
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
55,822✔
6502
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
55,822✔
6503
  int32_t          code = TSDB_CODE_SUCCESS;
55,822✔
6504

6505
  funcInputUpdate(pCtx);
55,822✔
6506

6507
  double v = 0;
55,822✔
6508
  if (pCtx->order == TSDB_ORDER_ASC) {
55,822✔
6509
    SFuncInputRow row = {0};
52,451✔
6510
    bool result = false;
52,451✔
6511
    while (1) {
3,538,231✔
6512
      code = funcInputGetNextRow(pCtx, &row, &result);
3,590,682✔
6513
      if (TSDB_CODE_SUCCESS != code) {
3,590,682!
6514
        return code;
×
6515
      }
6516
      if (!result) {
3,590,682✔
6517
        break;
52,451✔
6518
      }
6519
      if (row.isDataNull) {
3,538,231✔
6520
        continue;
35,701✔
6521
      }
6522

6523
      char* d = row.pData;
3,502,530✔
6524
      GET_TYPED_DATA(v, double, pInputCol->info.type, d);
3,502,530!
6525

6526
      int32_t pos = pCtx->offset + numOfElems;
3,502,530✔
6527
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
3,502,530✔
6528
        pDerivInfo->valueSet = true;
27,649✔
6529
      } else {
6530
        if (row.ts == pDerivInfo->prevTs) {
3,474,881!
6531
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6532
        }
6533
        double r = ((v - pDerivInfo->prevValue) * pDerivInfo->tsWindow) / (row.ts - pDerivInfo->prevTs);
3,474,881✔
6534
        if (pDerivInfo->ignoreNegative && r < 0) {
3,474,881✔
6535
        } else {
6536
          if (isinf(r) || isnan(r)) {
2,209,627!
6537
            colDataSetNULL(pOutput, pos);
×
6538
          } else {
6539
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
2,209,627✔
6540
            if (code != TSDB_CODE_SUCCESS) {
2,209,627!
6541
              return code;
×
6542
            }
6543
          }
6544

6545
          if (pTsOutput != NULL) {
2,209,627!
6546
            colDataSetInt64(pTsOutput, pos, &row.ts);
×
6547
          }
6548

6549
          // handle selectivity
6550
          if (pCtx->subsidiaries.num > 0) {
2,209,627✔
6551
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
1,721,257✔
6552
            if (code != TSDB_CODE_SUCCESS) {
1,721,257!
6553
              return code;
×
6554
            }
6555
          }
6556

6557
          numOfElems++;
2,209,627✔
6558
        }
6559
      }
6560

6561
      pDerivInfo->prevValue = v;
3,502,530✔
6562
      pDerivInfo->prevTs = row.ts;
3,502,530✔
6563
    }
6564
  } else {
6565
    SFuncInputRow row = {0};
3,371✔
6566
    bool          result = false;
3,371✔
6567
    while (1) {
334,255✔
6568
      code = funcInputGetNextRow(pCtx, &row, &result);
337,626✔
6569
      if (TSDB_CODE_SUCCESS != code) {
337,626!
6570
        return code;
×
6571
      }
6572
      if (!result) {
337,626✔
6573
        break;
3,371✔
6574
      }
6575
      if (row.isDataNull) {
334,255✔
6576
        continue;
45✔
6577
      }
6578

6579
      char* d = row.pData;
334,210✔
6580
      GET_TYPED_DATA(v, double, pInputCol->info.type, d);
334,210!
6581

6582
      int32_t pos = pCtx->offset + numOfElems;
334,210✔
6583
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
334,210✔
6584
        pDerivInfo->valueSet = true;
3,347✔
6585
      } else {
6586
        if (row.ts == pDerivInfo->prevTs) {
330,863!
6587
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6588
        }
6589
        double r = ((pDerivInfo->prevValue - v) * pDerivInfo->tsWindow) / (pDerivInfo->prevTs - row.ts);
330,863✔
6590
        if (pDerivInfo->ignoreNegative && r < 0) {
330,863✔
6591
        } else {
6592
          if (isinf(r) || isnan(r)) {
257,456!
6593
            colDataSetNULL(pOutput, pos);
×
6594
          } else {
6595
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
257,456✔
6596
            if (code != TSDB_CODE_SUCCESS) {
257,456!
6597
              return code;
×
6598
            }
6599
          }
6600

6601
          if (pTsOutput != NULL) {
257,456!
6602
            colDataSetInt64(pTsOutput, pos, &pDerivInfo->prevTs);
×
6603
          }
6604

6605
          // handle selectivity
6606
          if (pCtx->subsidiaries.num > 0) {
257,456✔
6607
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
78,486✔
6608
            if (code != TSDB_CODE_SUCCESS) {
78,486!
6609
              return code;
×
6610
            }
6611
          }
6612
          numOfElems++;
257,456✔
6613
        }
6614
      }
6615

6616
      pDerivInfo->prevValue = v;
334,210✔
6617
      pDerivInfo->prevTs = row.ts;
334,210✔
6618
    }
6619
  }
6620

6621
  pResInfo->numOfRes = numOfElems;
55,822✔
6622

6623
  return TSDB_CODE_SUCCESS;
55,822✔
6624
}
6625

6626
int32_t getIrateInfoSize(int32_t pkBytes) { return (int32_t)sizeof(SRateInfo) + 2 * pkBytes; }
36,930✔
6627

6628
bool getIrateFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
35,228✔
6629
  int32_t pkBytes = (pFunc->hasPk) ? pFunc->pkBytes : 0;
35,228✔
6630
  pEnv->calcMemSize = getIrateInfoSize(pkBytes);
35,228✔
6631
  return true;
35,252✔
6632
}
6633

6634
int32_t irateFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
2,483,985✔
6635
  if (pResInfo->initialized) {
2,483,985!
6636
    return TSDB_CODE_SUCCESS;
×
6637
  }
6638
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
2,483,985!
6639
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6640
  }
6641

6642
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,483,984✔
6643

6644
  pInfo->firstKey = INT64_MIN;
2,483,984✔
6645
  pInfo->lastKey = INT64_MIN;
2,483,984✔
6646
  pInfo->firstValue = (double)INT64_MIN;
2,483,984✔
6647
  pInfo->lastValue = (double)INT64_MIN;
2,483,984✔
6648

6649
  pInfo->hasResult = 0;
2,483,984✔
6650
  return TSDB_CODE_SUCCESS;
2,483,984✔
6651
}
6652

6653
static void doSaveRateInfo(SRateInfo* pRateInfo, bool isFirst, int64_t ts, char* pk, double v) {
13,568,702✔
6654
  if (isFirst) {
13,568,702✔
6655
    pRateInfo->firstValue = v;
5,550,314✔
6656
    pRateInfo->firstKey = ts;
5,550,314✔
6657
    if (pRateInfo->firstPk) {
5,550,314✔
6658
      int32_t pkBytes = IS_VAR_DATA_TYPE(pRateInfo->pkType) ? varDataTLen(pk) : pRateInfo->pkBytes;
35!
6659
      (void)memcpy(pRateInfo->firstPk, pk, pkBytes);
35✔
6660
    }
6661
  } else {
6662
    pRateInfo->lastValue = v;
8,018,388✔
6663
    pRateInfo->lastKey = ts;
8,018,388✔
6664
    if (pRateInfo->lastPk) {
8,018,388✔
6665
      int32_t pkBytes = IS_VAR_DATA_TYPE(pRateInfo->pkType) ? varDataTLen(pk) : pRateInfo->pkBytes;
52!
6666
      (void)memcpy(pRateInfo->lastPk, pk, pkBytes);
52✔
6667
    }
6668
  }
6669
}
13,568,702✔
6670

6671
static void initializeRateInfo(SqlFunctionCtx* pCtx, SRateInfo* pRateInfo, bool isMerge) {
2,511,289✔
6672
  if (pCtx->hasPrimaryKey) {
2,511,289✔
6673
    if (!isMerge) {
19✔
6674
      pRateInfo->pkType = pCtx->input.pPrimaryKey->info.type;
17✔
6675
      pRateInfo->pkBytes = pCtx->input.pPrimaryKey->info.bytes;
17✔
6676
      pRateInfo->firstPk = pRateInfo->pkData;
17✔
6677
      pRateInfo->lastPk = pRateInfo->pkData + pRateInfo->pkBytes;
17✔
6678
    } else {
6679
      pRateInfo->firstPk = pRateInfo->pkData;
2✔
6680
      pRateInfo->lastPk = pRateInfo->pkData + pRateInfo->pkBytes;
2✔
6681
    }
6682
  } else {
6683
    pRateInfo->firstPk = NULL;
2,511,270✔
6684
    pRateInfo->lastPk = NULL;
2,511,270✔
6685
  }  
6686
}
2,511,289✔
6687

6688
int32_t irateFunction(SqlFunctionCtx* pCtx) {
2,508,103✔
6689
  int32_t              code = TSDB_CODE_SUCCESS;
2,508,103✔
6690
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,508,103✔
6691
  SRateInfo*           pRateInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,508,103✔
6692

6693
  SInputColumnInfoData* pInput = &pCtx->input;
2,508,103✔
6694
  SColumnInfoData*      pInputCol = pInput->pData[0];
2,508,103✔
6695

6696
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
2,508,103✔
6697

6698
  funcInputUpdate(pCtx);
2,508,103✔
6699
  
6700
  initializeRateInfo(pCtx, pRateInfo, false);
2,508,105✔
6701

6702
  int32_t numOfElems = 0;
2,508,104✔
6703
  int32_t type = pInputCol->info.type;
2,508,104✔
6704
  SFuncInputRow row = {0};
2,508,104✔
6705
  bool          result = false;
2,508,104✔
6706
  while (1)  {
8,554,692✔
6707
    code = funcInputGetNextRow(pCtx, &row, &result);
11,062,796✔
6708
    if (TSDB_CODE_SUCCESS != code) {
11,062,663!
6709
      return code;
×
6710
    }
6711
    if (!result) {
11,062,663✔
6712
      break;
2,508,111✔
6713
    }
6714
    if (row.isDataNull) {
8,554,552✔
6715
      continue;
130,657✔
6716
    }
6717

6718
    char*  data = row.pData;
8,423,895✔
6719
    double v = 0;
8,423,895✔
6720
    GET_TYPED_DATA(v, double, type, data);
8,423,895!
6721

6722
    if (INT64_MIN == pRateInfo->lastKey) {
8,423,895✔
6723
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
2,469,046✔
6724
      pRateInfo->hasResult = 1;
2,469,047✔
6725
      continue;
2,469,047✔
6726
    }
6727

6728
    if (row.ts > pRateInfo->lastKey) {
5,954,849✔
6729
      if ((INT64_MIN == pRateInfo->firstKey) || pRateInfo->lastKey > pRateInfo->firstKey) {
5,548,103!
6730
        doSaveRateInfo(pRateInfo, true, pRateInfo->lastKey, pRateInfo->lastPk, pRateInfo->lastValue);
5,548,104✔
6731
      }
6732
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
5,548,113✔
6733
      continue;
5,548,096✔
6734
    } else if (row.ts == pRateInfo->lastKey) {
406,746!
6735
        return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6736
    }
6737
    
6738

6739
    if ((INT64_MIN == pRateInfo->firstKey) || row.ts > pRateInfo->firstKey) {
406,746!
6740
      doSaveRateInfo(pRateInfo, true, row.ts, row.pPk, v);    
141✔
6741
    } else if (row.ts == pRateInfo->firstKey) {
406,605!
6742
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6743
    }
6744
  }
6745

6746
  numOfElems++;
2,508,111✔
6747
  
6748
  SET_VAL(pResInfo, numOfElems, 1);
2,508,111!
6749
  return TSDB_CODE_SUCCESS;
2,508,111✔
6750
}
6751

6752
static double doCalcRate(const SRateInfo* pRateInfo, double tickPerSec) {
2,481,112✔
6753
  if ((INT64_MIN == pRateInfo->lastKey) || (INT64_MIN == pRateInfo->firstKey) ||
2,481,112✔
6754
      (pRateInfo->firstKey >= pRateInfo->lastKey)) {
221,602!
6755
    return 0.0;
2,259,510✔
6756
  }
6757

6758
  double diff = 0;
221,602✔
6759
  // If the previous value of the last is greater than the last value, only keep the last point instead of the delta
6760
  // value between two values.
6761
  diff = pRateInfo->lastValue;
221,602✔
6762
  if (diff >= pRateInfo->firstValue) {
221,602✔
6763
    diff -= pRateInfo->firstValue;
106,700✔
6764
  }
6765

6766
  int64_t duration = pRateInfo->lastKey - pRateInfo->firstKey;
221,602✔
6767
  if (duration == 0) {
221,602!
6768
    return 0;
×
6769
  }
6770

6771
  return (duration > 0) ? ((double)diff) / (duration / tickPerSec) : 0.0;
221,602!
6772
}
6773

6774
static void irateTransferInfoImpl(TSKEY inputKey, SRateInfo* pInput, SRateInfo* pOutput, bool isFirstKey) {
518✔
6775
  if (inputKey > pOutput->lastKey) {
518✔
6776
    doSaveRateInfo(pOutput, true, pOutput->lastKey, pOutput->lastPk, pOutput->lastValue);
270✔
6777
    if (isFirstKey) {
270✔
6778
      doSaveRateInfo(pOutput, false, pInput->firstKey, pInput->firstPk, pInput->firstValue);
89✔
6779
    } else {
6780
      doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
181✔
6781
    }
6782
  } else if ((inputKey < pOutput->lastKey) && (inputKey > pOutput->firstKey)) {
248!
6783
    if (isFirstKey) {
140✔
6784
      doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
88✔
6785
    } else {
6786
      doSaveRateInfo(pOutput, true, pInput->lastKey, pInput->lastPk, pInput->lastValue);
52✔
6787
    }
6788
  } else {
6789
    // inputKey < pOutput->firstKey
6790
  }
6791
}
518✔
6792

6793
static void irateCopyInfo(SRateInfo* pInput, SRateInfo* pOutput) {
1,321✔
6794
  doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
1,321✔
6795
  doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
1,321✔
6796
}
1,321✔
6797

6798
static int32_t irateTransferInfo(SRateInfo* pInput, SRateInfo* pOutput) {
1,580✔
6799
  if ((pInput->firstKey != INT64_MIN && (pInput->firstKey == pOutput->firstKey || pInput->firstKey == pOutput->lastKey)) ||
1,580!
6800
      (pInput->lastKey != INT64_MIN && (pInput->lastKey  == pOutput->firstKey || pInput->lastKey  == pOutput->lastKey))) {
1,580!
6801
    return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6802
  }
6803

6804
  if (pOutput->hasResult == 0) {
1,580✔
6805
    irateCopyInfo(pInput, pOutput);
1,321✔
6806
    pOutput->hasResult = pInput->hasResult;
1,321✔
6807
    return TSDB_CODE_SUCCESS;
1,321✔
6808
  }
6809

6810
  if (pInput->firstKey != INT64_MIN) {
259!
6811
    irateTransferInfoImpl(pInput->firstKey, pInput, pOutput, true);
259✔
6812
  }
6813

6814
  if (pInput->lastKey != INT64_MIN) {
259!
6815
    irateTransferInfoImpl(pInput->lastKey, pInput, pOutput, false);
259✔
6816
  }
6817

6818
  pOutput->hasResult = pInput->hasResult;
259✔
6819
  return TSDB_CODE_SUCCESS;
259✔
6820
}
6821

6822
int32_t irateFunctionMerge(SqlFunctionCtx* pCtx) {
1,592✔
6823
  SInputColumnInfoData* pInput = &pCtx->input;
1,592✔
6824
  SColumnInfoData*      pCol = pInput->pData[0];
1,592✔
6825
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
1,592!
6826
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
6827
  }
6828

6829
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,592✔
6830
  initializeRateInfo(pCtx, pInfo, true);
1,592✔
6831

6832
  int32_t start = pInput->startRowIndex;
1,592✔
6833
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
3,184✔
6834
    char*        data = colDataGetData(pCol, i);
1,592!
6835
    SRateInfo*   pInputInfo = (SRateInfo*)varDataVal(data);
1,592✔
6836
    initializeRateInfo(pCtx, pInfo, true);
1,592✔
6837
    if (pInputInfo->hasResult) {
1,592✔
6838
      int32_t code = irateTransferInfo(pInputInfo, pInfo);
1,580✔
6839
      if (code != TSDB_CODE_SUCCESS) {
1,580!
6840
        return code;
×
6841
      }
6842
    }
6843
  }
6844

6845
  if (pInfo->hasResult) {
1,592✔
6846
    GET_RES_INFO(pCtx)->numOfRes = 1;
1,580✔
6847
  }
6848

6849
  return TSDB_CODE_SUCCESS;
1,592✔
6850
}
6851

6852
int32_t iratePartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1,591✔
6853
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,591✔
6854
  SRateInfo*           pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,591✔
6855
  int32_t              resultBytes = getIrateInfoSize(pInfo->pkBytes);
1,591✔
6856
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
1,591✔
6857

6858
  if (NULL == res) {
1,591!
6859
    return terrno;
×
6860
  }
6861
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
1,591✔
6862
  varDataSetLen(res, resultBytes);
1,591✔
6863

6864
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
1,591✔
6865
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
1,591✔
6866
  if (NULL == pCol) {
1,591!
6867
      taosMemoryFree(res);
×
6868
      return TSDB_CODE_OUT_OF_RANGE;
×
6869
  }
6870

6871
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
1,591✔
6872

6873
  taosMemoryFree(res);
1,592✔
6874
  return code;
1,591✔
6875
}
6876

6877
int32_t irateFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
2,481,113✔
6878
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
2,481,113✔
6879
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
2,481,113✔
6880
  if (NULL == pCol) {
2,481,112!
6881
    return TSDB_CODE_OUT_OF_RANGE;
×
6882
  }
6883

6884
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,481,112✔
6885
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
2,481,112✔
6886

6887
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,481,112✔
6888
  double     result = doCalcRate(pInfo, (double)TSDB_TICK_PER_SECOND(pCtx->param[1].param.i));
2,481,112!
6889
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, (const char*)&result, pResInfo->isNullRes);
2,481,112✔
6890

6891
  return code;
2,481,111✔
6892
}
6893

6894
int32_t groupConstValueFunction(SqlFunctionCtx* pCtx) {
107,776,349✔
6895
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
107,776,349✔
6896
  SGroupKeyInfo*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
107,776,349✔
6897

6898
  SInputColumnInfoData* pInput = &pCtx->input;
107,776,349✔
6899
  SColumnInfoData*      pInputCol = pInput->pData[0];
107,776,349✔
6900

6901
  int32_t startIndex = pInput->startRowIndex;
107,776,349✔
6902

6903
  // escape rest of data blocks to avoid first entry to be overwritten.
6904
  if (pInfo->hasResult) {
107,776,349✔
6905
    goto _group_value_over;
12,360,255✔
6906
  }
6907

6908
  if (pInputCol->pData == NULL || colDataIsNull_s(pInputCol, startIndex)) {
190,404,841✔
6909
    pInfo->isNull = true;
2,700,663✔
6910
    pInfo->hasResult = true;
2,700,663✔
6911
    goto _group_value_over;
2,700,663✔
6912
  }
6913

6914
  char* data = colDataGetData(pInputCol, startIndex);
92,715,431!
6915
  if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
92,715,431!
6916
    (void)memcpy(pInfo->data, data,
72,694,964✔
6917
                 (pInputCol->info.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(data) : varDataTLen(data));
72,694,964✔
6918
  } else {
6919
    (void)memcpy(pInfo->data, data, pInputCol->info.bytes);
20,020,467✔
6920
  }
6921
  pInfo->hasResult = true;
92,715,431✔
6922

6923
_group_value_over:
107,776,349✔
6924

6925
  SET_VAL(pResInfo, 1, 1);
107,776,349✔
6926
  return TSDB_CODE_SUCCESS;
107,776,349✔
6927
}
6928

6929
int32_t groupKeyFunction(SqlFunctionCtx* pCtx) {
106,169,349✔
6930
  return groupConstValueFunction(pCtx);
106,169,349✔
6931
}
6932

6933
int32_t groupConstValueFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
93,018,047✔
6934
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
93,018,047✔
6935
  int32_t          code = TSDB_CODE_SUCCESS;
93,018,047✔
6936
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
93,018,047✔
6937
  if (NULL == pCol) {
92,945,923!
6938
    return TSDB_CODE_OUT_OF_RANGE;
×
6939
  }
6940

6941
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
92,945,923✔
6942

6943
  SGroupKeyInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
92,945,923✔
6944

6945
  if (pInfo->hasResult) {
92,945,923!
6946
    int32_t currentRow = pBlock->info.rows;
92,973,005✔
6947
    for (; currentRow < pBlock->info.rows + pResInfo->numOfRes; ++currentRow) {
186,743,472✔
6948
      code = colDataSetVal(pCol, currentRow, pInfo->data, pInfo->isNull ? true : false);
92,985,700✔
6949
      if (TSDB_CODE_SUCCESS != code) {
93,770,467!
6950
        return code;
×
6951
      }
6952
    }
6953
  } else {
6954
    pResInfo->numOfRes = 0;
×
6955
  }
6956

6957
  return code;
93,730,690✔
6958
}
6959

6960
int32_t groupKeyFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock){
92,791,941✔
6961
  return groupConstValueFinalize(pCtx, pBlock);
92,791,941✔
6962
}
6963

6964
int32_t groupKeyCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
6965
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
6966
  SGroupKeyInfo*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
6967

6968
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
6969
  SGroupKeyInfo*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
6970

6971
  // escape rest of data blocks to avoid first entry to be overwritten.
6972
  if (pDBuf->hasResult) {
×
6973
    goto _group_key_over;
×
6974
  }
6975

6976
  if (pSBuf->isNull) {
×
6977
    pDBuf->isNull = true;
×
6978
    pDBuf->hasResult = true;
×
6979
    goto _group_key_over;
×
6980
  }
6981

6982
  if (IS_VAR_DATA_TYPE(pSourceCtx->resDataInfo.type)) {
×
6983
    (void)memcpy(pDBuf->data, pSBuf->data,
×
6984
           (pSourceCtx->resDataInfo.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(pSBuf->data) : varDataTLen(pSBuf->data));
×
6985
  } else {
6986
    (void)memcpy(pDBuf->data, pSBuf->data, pSourceCtx->resDataInfo.bytes);
×
6987
  }
6988

6989
  pDBuf->hasResult = true;
×
6990

6991
_group_key_over:
×
6992

6993
  SET_VAL(pDResInfo, 1, 1);
×
6994
  return TSDB_CODE_SUCCESS;
×
6995
}
6996

6997
int32_t cachedLastRowFunction(SqlFunctionCtx* pCtx) {
11,012✔
6998
  int32_t numOfElems = 0;
11,012✔
6999

7000
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
11,012✔
7001
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
11,012✔
7002

7003
  SInputColumnInfoData* pInput = &pCtx->input;
11,012✔
7004
  SColumnInfoData*      pInputCol = pInput->pData[0];
11,012✔
7005

7006
  int32_t bytes = pInputCol->info.bytes;
11,012✔
7007
  pInfo->bytes = bytes;
11,012✔
7008

7009
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
11,012✔
7010
  pInfo->pkType = -1;
11,012✔
7011
  __compar_fn_t  pkCompareFn = NULL;
11,012✔
7012
  if (pCtx->hasPrimaryKey) {
11,012✔
7013
    pInfo->pkType = pkCol->info.type;
3,662✔
7014
    pInfo->pkBytes = pkCol->info.bytes;
3,662✔
7015
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
3,662✔
7016
  }
7017

7018
  // TODO it traverse the different way.
7019
  // last_row function does not ignore the null value
7020
  for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
22,036✔
7021
    numOfElems++;
11,021✔
7022

7023
    bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
11,021✔
7024
    char* data = isNull ? NULL : colDataGetData(pInputCol, i);
11,021!
7025

7026
    TSKEY cts = getRowPTs(pInput->pPTS, i);
11,021!
7027
    if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
11,021✔
7028
      int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
8,205✔
7029
      if (code != TSDB_CODE_SUCCESS) {
8,208!
7030
        return code;
×
7031
      }
7032
      pResInfo->numOfRes = 1;
8,208✔
7033
    }
7034
  }
7035

7036
  SET_VAL(pResInfo, numOfElems, 1);
11,015!
7037
  return TSDB_CODE_SUCCESS;
11,015✔
7038
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc