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

taosdata / TDengine / #3525

10 Nov 2024 03:50AM UTC coverage: 60.818% (-0.08%) from 60.898%
#3525

push

travis-ci

web-flow
Merge pull request #28709 from taosdata/main

merge: from main to 3.0 branch

118634 of 249004 branches covered (47.64%)

Branch coverage included in aggregate %.

136 of 169 new or added lines in 23 files covered. (80.47%)

542 existing lines in 129 files now uncovered.

199071 of 273386 relevant lines covered (72.82%)

15691647.46 hits per line

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

73.94
/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){
48,821,664✔
32
  return (ignoreOption & 0x1) == 0x1;
48,821,664✔
33
}
34
bool ignoreNull(int8_t ignoreOption){
423,068✔
35
  return (ignoreOption & 0x2) == 0x2;
423,068✔
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) {
23,553,727✔
198
  SFuncInputRowIter* pIter = &pCtx->rowIter;
23,553,727✔
199

200
  if (!pCtx->bInputFinished) {
23,553,727!
201
    pIter->pInput = &pCtx->input;
23,553,763✔
202
    pIter->tsList = (TSKEY*)pIter->pInput->pPTS->pData;
23,553,763✔
203
    pIter->pDataCol = pIter->pInput->pData[0];
23,553,763✔
204
    pIter->pPkCol = pIter->pInput->pPrimaryKey;
23,553,763✔
205
    pIter->rowIndex = pIter->pInput->startRowIndex;
23,553,763✔
206
    pIter->inputEndIndex = pIter->rowIndex + pIter->pInput->numOfRows - 1;
23,553,763✔
207
    pIter->pSrcBlock = pCtx->pSrcBlock;
23,553,763✔
208
    if (!pIter->hasGroupId || pIter->groupId != pIter->pSrcBlock->info.id.groupId) {
23,553,763✔
209
      pIter->hasGroupId = true;
228,963✔
210
      pIter->groupId = pIter->pSrcBlock->info.id.groupId;
228,963✔
211
      pIter->hasPrev = false;
228,963✔
212
    }
213
  } else {
214
    pIter->finalRow = true;
×
215
  }
216
}
23,553,727✔
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) {
30,176✔
332
  int32_t idx = rowIndex + 1;
30,176✔
333
  while (idx <= pIter->inputEndIndex && pIter->tsList[idx] == pIter->tsList[rowIndex]) {
407,859!
334
    ++idx;
377,683✔
335
  }
336
  pIter->rowIndex = idx;
30,176✔
337
}
30,176✔
338

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

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

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

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

385
bool funcInputGetNextRowNoPk(SFuncInputRowIter *pIter, SFuncInputRow* pRow) {
138,412,990✔
386
  if (pIter->rowIndex <= pIter->inputEndIndex) {
138,412,990✔
387
    setInputRowInfo(pRow, pIter, pIter->rowIndex, false);
114,855,450✔
388
    ++pIter->rowIndex;
114,855,081✔
389
    return true;    
114,855,081✔
390
  } else {
391
    return false;    
23,557,540✔
392
  }
393
}
394

395
int32_t funcInputGetNextRow(SqlFunctionCtx* pCtx, SFuncInputRow* pRow, bool *res) {
138,448,965✔
396
  SFuncInputRowIter* pIter = &pCtx->rowIter;
138,448,965✔
397
  if (pCtx->hasPrimaryKey) {
138,448,965✔
398
    if (pCtx->order == TSDB_ORDER_ASC) {
33,718!
399
      *res = funcInputGetNextRowAscPk(pIter, pRow);
33,718✔
400
      return TSDB_CODE_SUCCESS;
33,718✔
401
    } else {
402
      return funcInputGetNextRowDescPk(pIter, pRow, res);
×
403
    }
404
  } else {
405
    *res = funcInputGetNextRowNoPk(pIter, pRow);
138,415,247✔
406
    return TSDB_CODE_SUCCESS;
138,413,033✔
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) {
36,335,906✔
414
  if (pCtx->subsidiaries.num <= 0) {
36,335,906!
415
    return TSDB_CODE_SUCCESS;
×
416
  }
417

418
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
98,377,496✔
419
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
62,041,789✔
420

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

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

430
    char* pData = colDataGetData(pSrcCol, rowIndex);
62,041,659!
431

432
    // append to dest col
433
    int32_t dstSlotId = pc->pExpr->base.resSchema.slotId;
62,041,659✔
434

435
    SColumnInfoData* pDstCol = taosArrayGet(pCtx->pDstBlock->pDataBlock, dstSlotId);
62,041,659✔
436
    if (NULL == pDstCol) {
62,041,553!
437
      return TSDB_CODE_OUT_OF_RANGE;
×
438
    }
439
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
124,083,106✔
440
      colDataSetNULL(pDstCol, pos);
2,580,095✔
441
    } else {
442
      int32_t code = colDataSetVal(pDstCol, pos, pData, false);
59,461,458✔
443
      if (TSDB_CODE_SUCCESS != code) {
59,461,495!
444
        return code;
×
445
      }
446
    }
447
  }
448
  return TSDB_CODE_SUCCESS;
36,335,707✔
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) {
733,637,809✔
456
  if (pResultInfo->initialized) {
733,637,809✔
457
    return TSDB_CODE_SUCCESS;  // already initialized
68,686✔
458
  }
459

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

464
  initResultRowEntry(pResultInfo, pCtx->resDataInfo.interBufSize);
733,569,123✔
465
  return TSDB_CODE_SUCCESS;
733,569,123✔
466
}
467

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

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

481
  return code;
193,156,388✔
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) {
222,282✔
515
  SNode* pParam = nodesListGetNode(pFunc->pParameterList, 0);
222,282✔
516
  if (QUERY_NODE_COLUMN == nodeType(pParam) && PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)pParam)->colId) {
222,387!
517
    return FUNC_DATA_REQUIRED_NOT_LOAD;
162,615✔
518
  }
519
  return FUNC_DATA_REQUIRED_SMA_LOAD;
59,772✔
520
}
521

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

527
static int64_t getNumOfElems(SqlFunctionCtx* pCtx) {
116,198,286✔
528
  int64_t numOfElem = 0;
116,198,286✔
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;
116,198,286✔
536
  SColumnInfoData*      pInputCol = pInput->pData[0];
116,198,286✔
537
  if(1 == pInput->numOfRows && pInput->blankFill) {
116,198,286✔
538
    return 0;
454,261✔
539
  }
540
  if (pInput->colDataSMAIsSet && pInput->totalRows == pInput->numOfRows) {
115,744,025✔
541
    numOfElem = pInput->numOfRows - pInput->pColumnDataAgg[0]->numOfNull;
6,662✔
542
  } else {
543
    if (pInputCol->hasNull) {
115,737,363✔
544
      for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
326,238,115✔
545
        if (colDataIsNull(pInputCol, pInput->totalRows, i, NULL)) {
595,132,828!
546
          continue;
4,931,252✔
547
        }
548
        numOfElem += 1;
292,635,162✔
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;
87,065,662✔
554
    }
555
  }
556
  return numOfElem;
115,744,025✔
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) {
116,218,231✔
564
  int64_t numOfElem = 0;
116,218,231✔
565

566
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
116,218,231✔
567
  SInputColumnInfoData* pInput = &pCtx->input;
116,218,231✔
568

569
  int32_t type = pInput->pData[0]->info.type;
116,218,231✔
570

571
  char* buf = GET_ROWCELL_INTERBUF(pResInfo);
116,218,231✔
572
  if (IS_NULL_TYPE(type)) {
116,218,231✔
573
    // select count(NULL) returns 0
574
    numOfElem = 1;
19,690✔
575
    *((int64_t*)buf) += 0;
19,690✔
576
  } else {
577
    numOfElem = getNumOfElems(pCtx);
116,198,541✔
578
    *((int64_t*)buf) += numOfElem;
115,683,829✔
579
  }
580

581
  if (tsCountAlwaysReturnValue) {
115,703,519!
582
    pResInfo->numOfRes = 1;
115,717,288✔
583
  } else {
584
    SET_VAL(pResInfo, *((int64_t*)buf), 1);
×
585
  }
586

587
  return TSDB_CODE_SUCCESS;
115,703,519✔
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) {
91,620,096✔
616
  int32_t numOfElem = 0;
91,620,096✔
617

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

623
  SSumRes* pSumRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
91,620,096✔
624
  pSumRes->type = type;
91,620,096✔
625

626
  if (IS_NULL_TYPE(type)) {
91,620,096✔
627
    numOfElem = 0;
255✔
628
    goto _sum_over;
255✔
629
  }
630

631
  if (pInput->colDataSMAIsSet) {
91,619,841✔
632
    numOfElem = pInput->numOfRows - pAgg->numOfNull;
2,874✔
633

634
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
2,874!
635
      pSumRes->isum += pAgg->sum;
2,873✔
636
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
1!
637
      pSumRes->usum += pAgg->sum;
×
638
    } else if (IS_FLOAT_TYPE(type)) {
1!
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];
91,616,967✔
643

644
    int32_t start = pInput->startRowIndex;
91,616,967✔
645
    int32_t numOfRows = pInput->numOfRows;
91,616,967✔
646

647
    if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
91,616,967!
648
      if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
91,415,087!
649
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int8_t, numOfElem);
1,880,705✔
650
      } else if (type == TSDB_DATA_TYPE_SMALLINT) {
91,043,240✔
651
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int16_t, numOfElem);
554,475✔
652
      } else if (type == TSDB_DATA_TYPE_INT) {
90,998,043✔
653
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int32_t, numOfElem);
413,428,488✔
654
      } else if (type == TSDB_DATA_TYPE_BIGINT) {
21,394,234!
655
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int64_t, numOfElem);
81,507,106✔
656
      }
657
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
201,880!
658
      if (type == TSDB_DATA_TYPE_UTINYINT) {
786✔
659
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint8_t, numOfElem);
130,039!
660
      } else if (type == TSDB_DATA_TYPE_USMALLINT) {
747✔
661
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint16_t, numOfElem);
130,047✔
662
      } else if (type == TSDB_DATA_TYPE_UINT) {
707✔
663
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint32_t, numOfElem);
133,570!
664
      } else if (type == TSDB_DATA_TYPE_UBIGINT) {
437!
665
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint64_t, numOfElem);
134,311✔
666
      }
667
    } else if (type == TSDB_DATA_TYPE_DOUBLE) {
201,094✔
668
      LIST_ADD_N(pSumRes->dsum, pCol, start, numOfRows, double, numOfElem);
3,042,443✔
669
    } else if (type == TSDB_DATA_TYPE_FLOAT) {
99,672✔
670
      LIST_ADD_N(pSumRes->dsum, pCol, start, numOfRows, float, numOfElem);
653,541✔
671
    }
672
  }
673

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

679
_sum_over:
92,006,421✔
680
  if (numOfElem == 0) {
91,620,096✔
681
    if (tsCountAlwaysReturnValue && pCtx->pExpr->pExpr->_function.pFunctNode->hasOriginalFunc &&
111,586✔
682
        fmIsCountLikeFunc(pCtx->pExpr->pExpr->_function.pFunctNode->originalFuncId)) {
11,882✔
683
      numOfElem = 1;
19✔
684
    }
685
  }
686
  // data in the check operation are all null, not output
687
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
91,620,096✔
688
  return TSDB_CODE_SUCCESS;
91,620,096✔
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) {
46✔
752
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
46✔
753
  SSumRes*             pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
46✔
754

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

759
  if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
46!
760
    pDBuf->isum += pSBuf->isum;
46✔
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);
46✔
767
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
46✔
768
  return TSDB_CODE_SUCCESS;
46✔
769
}
770

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

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

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

788
  SMinmaxResInfo* buf = GET_ROWCELL_INTERBUF(pResultInfo);
65,291,064✔
789
  buf->assign = false;
65,291,064✔
790
  buf->tuplePos.pageId = -1;
65,291,064✔
791

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

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

803
int32_t minFunction(SqlFunctionCtx* pCtx) {
24,763,882✔
804
  int32_t numOfElems = 0;
24,763,882✔
805
  int32_t code = doMinMaxHelper(pCtx, 1, &numOfElems);
24,763,882✔
806
  if (code != TSDB_CODE_SUCCESS) {
24,890,327!
807
    return code;
×
808
  }
809
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
24,890,327✔
810
  return TSDB_CODE_SUCCESS;
24,890,327✔
811
}
812

813
int32_t maxFunction(SqlFunctionCtx* pCtx) {
48,669,813✔
814
  int32_t numOfElems = 0;
48,669,813✔
815
  int32_t code = doMinMaxHelper(pCtx, 0, &numOfElems);
48,669,813✔
816
  if (code != TSDB_CODE_SUCCESS) {
48,780,502!
817
    return code;
×
818
  }
819
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
48,780,502✔
820
  return TSDB_CODE_SUCCESS;
48,780,502✔
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) {
63,736,918✔
828
  int32_t code = TSDB_CODE_SUCCESS;
63,736,918✔
829

830
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
63,736,918✔
831
  SMinmaxResInfo*      pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
63,736,918✔
832

833
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
63,736,918✔
834
  int32_t currentRow = pBlock->info.rows;
63,736,918✔
835

836
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
63,736,918✔
837
  if (NULL == pCol) {
63,742,794!
838
    return TSDB_CODE_OUT_OF_RANGE;
×
839
  }
840
  pEntryInfo->isNullRes = (pEntryInfo->numOfRes == 0) ? 1 : 0;
63,742,794✔
841

842
  // NOTE: do nothing change it, for performance issue
843
  if (!pEntryInfo->isNullRes) {
63,742,794✔
844
    switch (pCol->info.type) {
56,787,943!
845
      case TSDB_DATA_TYPE_UBIGINT:
13,946,393✔
846
      case TSDB_DATA_TYPE_BIGINT:
847
        ((int64_t*)pCol->pData)[currentRow] = pRes->v;
13,946,393✔
848
        break;
13,946,393✔
849
      case TSDB_DATA_TYPE_UINT:
21,448,760✔
850
      case TSDB_DATA_TYPE_INT:
851
        colDataSetInt32(pCol, currentRow, (int32_t*)&pRes->v);
21,448,760✔
852
        break;
21,448,760✔
853
      case TSDB_DATA_TYPE_USMALLINT:
4,090,508✔
854
      case TSDB_DATA_TYPE_SMALLINT:
855
        colDataSetInt16(pCol, currentRow, (int16_t*)&pRes->v);
4,090,508✔
856
        break;
4,090,508✔
857
      case TSDB_DATA_TYPE_BOOL:
189,262✔
858
      case TSDB_DATA_TYPE_UTINYINT:
859
      case TSDB_DATA_TYPE_TINYINT:
860
        colDataSetInt8(pCol, currentRow, (int8_t*)&pRes->v);
189,262✔
861
        break;
189,262✔
862
      case TSDB_DATA_TYPE_DOUBLE:
209,601✔
863
        colDataSetDouble(pCol, currentRow, (double*)&pRes->v);
209,601✔
864
        break;
209,601✔
865
      case TSDB_DATA_TYPE_FLOAT: {
8,533,244✔
866
        float v = GET_FLOAT_VAL(&pRes->v);
8,533,244✔
867
        colDataSetFloat(pCol, currentRow, &v);
8,533,244✔
868
        break;
8,533,244✔
869
      }
870
      case TSDB_DATA_TYPE_VARBINARY:
8,401,121✔
871
      case TSDB_DATA_TYPE_VARCHAR:
872
      case TSDB_DATA_TYPE_NCHAR: {
873
        code = colDataSetVal(pCol, currentRow, pRes->str, false);
8,401,121✔
874
        if (TSDB_CODE_SUCCESS != code) {
8,401,121!
875
          return code;
×
876
        }
877
        break;
8,401,121✔
878
      }
879
    }
880
  } else {
881
    colDataSetNULL(pCol, currentRow);
6,954,851!
882
  }
883

884
  taosMemoryFreeClear(pRes->str);
63,742,794✔
885
  if (pCtx->subsidiaries.num > 0) {
63,742,794✔
886
    if (pEntryInfo->numOfRes > 0) {
16,928,335✔
887
      code = setSelectivityValue(pCtx, pBlock, &pRes->tuplePos, currentRow);
16,926,079✔
888
    } else {
889
      code = setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, currentRow);
2,256✔
890
    }
891
  }
892

893
  return code;
63,750,016✔
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) {
273,975,972✔
915
  if (pCtx->subsidiaries.num <= 0) {
273,975,972✔
916
    return TSDB_CODE_SUCCESS;
130,133,580✔
917
  }
918

919
  if ((pCtx->saveHandle.pBuf != NULL && pTuplePos->pageId != -1) ||
143,842,392!
920
      (pCtx->saveHandle.pState && pTuplePos->streamTupleKey.ts > 0)) {
×
921
    int32_t     numOfCols = pCtx->subsidiaries.num;
143,862,269✔
922
    char* p = NULL;
143,862,269✔
923
    int32_t code = loadTupleData(pCtx, pTuplePos, &p);
143,862,269✔
924
    if (p == NULL || TSDB_CODE_SUCCESS != code) {
144,121,212!
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;
144,123,878✔
931
    char* pStart = (char*)(nullList + numOfCols * sizeof(bool));
144,123,878✔
932

933
    // todo set the offset value to optimize the performance.
934
    for (int32_t j = 0; j < numOfCols; ++j) {
288,199,348✔
935
      SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
144,163,502✔
936
      int32_t         dstSlotId = pc->pExpr->base.resSchema.slotId;
144,163,502✔
937

938
      // group_key function has its own process function
939
      // do not process there
940
      if (fmIsGroupKeyFunc(pc->functionId)) {
144,163,502✔
941
        continue;
40,714✔
942
      }
943

944
      SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId);
144,124,676✔
945
      if (NULL == pDstCol) {
144,068,145!
946
        return TSDB_CODE_OUT_OF_RANGE;
×
947
      }
948
      if (nullList[j]) {
144,068,145✔
949
        colDataSetNULL(pDstCol, rowIndex);
314!
950
      } else {
951
        code = colDataSetVal(pDstCol, rowIndex, pStart, false);
144,067,831✔
952
        if (TSDB_CODE_SUCCESS != code) {
144,034,442!
953
          return code;
×
954
        }
955
      }
956
      pStart += pDstCol->info.bytes;
144,034,756✔
957
    }
958
  }
959

960
  return TSDB_CODE_SUCCESS;
144,015,969✔
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) {
56,177,924✔
966
  if (pCtx->subsidiaries.num <= 0) {
56,177,924!
967
    return TSDB_CODE_SUCCESS;
×
968
  }
969

970
  int32_t code = TSDB_CODE_SUCCESS;
56,177,924✔
971
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
112,355,022✔
972
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
56,180,715✔
973

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

978
    SColumnInfoData* pSrcCol = taosArrayGet(pCtx->pSrcBlock->pDataBlock, srcSlotId);
56,180,715✔
979
    if (NULL == pSrcCol) {
56,178,172!
980
      return TSDB_CODE_OUT_OF_RANGE;
×
981
    }
982

983
    char* pData = colDataGetData(pSrcCol, rowIndex);
56,178,172!
984

985
    // append to dest col
986
    int32_t dstSlotId = pc->pExpr->base.resSchema.slotId;
56,178,172✔
987

988
    SColumnInfoData* pDstCol = taosArrayGet(pCtx->pDstBlock->pDataBlock, dstSlotId);
56,178,172✔
989
    if (NULL == pDstCol) {
56,175,420!
990
      return TSDB_CODE_OUT_OF_RANGE;
×
991
    }
992

993
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
112,350,840✔
994
      colDataSetNULL(pDstCol, pos);
560✔
995
    } else {
996
      code = colDataSetVal(pDstCol, pos, pData, false);
56,174,860✔
997
      if (TSDB_CODE_SUCCESS != code) {
56,176,538!
998
        return code;
×
999
      }
1000
    }
1001
  }
1002
  return code;
56,174,307✔
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); }
1,251,591✔
1080

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

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

1094
  SStdRes* pRes = GET_ROWCELL_INTERBUF(pResultInfo);
6,824,887✔
1095
  (void)memset(pRes, 0, sizeof(SStdRes));
6,824,887✔
1096
  return TSDB_CODE_SUCCESS;
6,824,887✔
1097
}
1098

1099
int32_t stdFunction(SqlFunctionCtx* pCtx) {
5,599,572✔
1100
  int32_t numOfElem = 0;
5,599,572✔
1101

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

1106
  SStdRes* pStdRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
5,599,572✔
1107
  pStdRes->type = type;
5,599,572✔
1108

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

1112
  int32_t start = pInput->startRowIndex;
5,599,572✔
1113
  int32_t numOfRows = pInput->numOfRows;
5,599,572✔
1114

1115
  if (IS_NULL_TYPE(type)) {
5,599,572✔
1116
    numOfElem = 0;
34✔
1117
    goto _stddev_over;
34✔
1118
  }
1119

1120
  switch (type) {
5,599,538!
1121
    case TSDB_DATA_TYPE_TINYINT: {
2,557,148✔
1122
      int8_t* plist = (int8_t*)pCol->pData;
2,557,148✔
1123
      for (int32_t i = start; i < numOfRows + start; ++i) {
8,129,256✔
1124
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
5,572,108✔
1125
          continue;
29,210✔
1126
        }
1127

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

1134
      break;
2,557,148✔
1135
    }
1136

1137
    case TSDB_DATA_TYPE_SMALLINT: {
239,679✔
1138
      int16_t* plist = (int16_t*)pCol->pData;
239,679✔
1139
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
1,557,508✔
1140
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
1,317,829✔
1141
          continue;
199,302✔
1142
        }
1143

1144
        numOfElem += 1;
1,118,527✔
1145
        pStdRes->count += 1;
1,118,527✔
1146
        pStdRes->isum += plist[i];
1,118,527✔
1147
        pStdRes->quadraticISum += plist[i] * plist[i];
1,118,527✔
1148
      }
1149
      break;
239,679✔
1150
    }
1151

1152
    case TSDB_DATA_TYPE_INT: {
2,695,942✔
1153
      int32_t* plist = (int32_t*)pCol->pData;
2,695,942✔
1154
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
8,265,378✔
1155
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
5,569,436✔
1156
          continue;
26,321✔
1157
        }
1158

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

1165
      break;
2,695,942✔
1166
    }
1167

1168
    case TSDB_DATA_TYPE_BIGINT: {
27,869✔
1169
      int64_t* plist = (int64_t*)pCol->pData;
27,869✔
1170
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
1,583,664✔
1171
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
1,555,795✔
1172
          continue;
308,134✔
1173
        }
1174

1175
        numOfElem += 1;
1,247,661✔
1176
        pStdRes->count += 1;
1,247,661✔
1177
        pStdRes->isum += plist[i];
1,247,661✔
1178
        pStdRes->quadraticISum += plist[i] * plist[i];
1,247,661✔
1179
      }
1180
      break;
27,869✔
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: {
17,234✔
1246
      float* plist = (float*)pCol->pData;
17,234✔
1247
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
1,286,953✔
1248
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
1,269,719✔
1249
          continue;
110,611✔
1250
        }
1251

1252
        numOfElem += 1;
1,159,108✔
1253
        pStdRes->count += 1;
1,159,108✔
1254
        pStdRes->dsum += plist[i];
1,159,108✔
1255
        pStdRes->quadraticDSum += plist[i] * plist[i];
1,159,108✔
1256
      }
1257
      break;
17,234✔
1258
    }
1259

1260
    case TSDB_DATA_TYPE_DOUBLE: {
61,793✔
1261
      double* plist = (double*)pCol->pData;
61,793✔
1262
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
4,395,161✔
1263
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
4,333,368✔
1264
          continue;
1,025,155✔
1265
        }
1266

1267
        numOfElem += 1;
3,308,213✔
1268
        pStdRes->count += 1;
3,308,213✔
1269
        pStdRes->dsum += plist[i];
3,308,213✔
1270
        pStdRes->quadraticDSum += plist[i] * plist[i];
3,308,213✔
1271
      }
1272
      break;
61,793✔
1273
    }
1274

1275
    default:
×
1276
      break;
×
1277
  }
1278

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

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

1301
  pOutput->count += pInput->count;
1,246,728✔
1302
}
1303

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

1308
  if (IS_NULL_TYPE(pCol->info.type)) {
1,246,661!
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) {
1,246,661!
1314
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
1315
  }
1316

1317
  SStdRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,246,661✔
1318

1319
  for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
2,493,386✔
1320
    if (colDataIsNull_s(pCol, i)) continue;
2,493,450!
1321
    char*       data = colDataGetData(pCol, i);
1,246,725!
1322
    SStdRes*    pInputInfo = (SStdRes*)varDataVal(data);
1,246,725✔
1323
    stdTransferInfo(pInputInfo, pInfo);
1,246,725✔
1324
  }
1325

1326
  SET_VAL(GET_RES_INFO(pCtx), 1, 1);
1,246,661✔
1327
  return TSDB_CODE_SUCCESS;
1,246,661✔
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) {
5,527,385✔
1398
  SInputColumnInfoData* pInput = &pCtx->input;
5,527,385✔
1399
  SStdRes*              pStddevRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
5,527,385✔
1400
  int32_t               type = pStddevRes->type;
5,527,385✔
1401
  double                avg;
1402

1403
  if (pStddevRes->count == 0) {
5,527,385✔
1404
    GET_RES_INFO(pCtx)->numOfRes = 0;
64,360✔
1405
    return functionFinalize(pCtx, pBlock);
64,360✔
1406
  }
1407

1408
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
5,463,025!
1409
    avg = pStddevRes->isum / ((double)pStddevRes->count);
5,423,213✔
1410
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticISum / ((double)pStddevRes->count) - avg * avg));
5,423,213✔
1411
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
39,812!
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,802✔
1416
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticDSum / ((double)pStddevRes->count) - avg * avg));
39,802✔
1417
  }
1418

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

1424
  return functionFinalize(pCtx, pBlock);
5,463,025✔
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) {
1,250,246✔
1458
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,250,246✔
1459
  SStdRes*             pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,250,246✔
1460
  int32_t              resultBytes = getStdInfoSize();
1,250,246✔
1461
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
1,250,247✔
1462

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

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

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

1478
  taosMemoryFree(res);
1,250,247✔
1479
  return code;
1,250,247✔
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) {
46,281✔
1498
  pEnv->calcMemSize = sizeof(SLeastSQRInfo);
46,281✔
1499
  return true;
46,281✔
1500
}
1501

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

1510
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
4,205,210✔
1511

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

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

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

1523
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
4,240,509✔
1524

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

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

1530
  int32_t start = pInput->startRowIndex;
4,240,509✔
1531
  int32_t numOfRows = pInput->numOfRows;
4,240,509✔
1532

1533
  switch (type) {
4,240,509!
1534
    case TSDB_DATA_TYPE_TINYINT: {
7,862✔
1535
      int8_t* plist = (int8_t*)pCol->pData;
7,862✔
1536
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
436,992✔
1537
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
429,130✔
1538
          continue;
2,660✔
1539
        }
1540
        numOfElem++;
426,470✔
1541
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
426,470✔
1542
      }
1543
      break;
7,862✔
1544
    }
1545
    case TSDB_DATA_TYPE_SMALLINT: {
10,421✔
1546
      int16_t* plist = (int16_t*)pCol->pData;
10,421✔
1547
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
516,478✔
1548
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
506,057✔
1549
          continue;
286,297✔
1550
        }
1551

1552
        numOfElem++;
219,760✔
1553
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
219,760✔
1554
      }
1555
      break;
10,421✔
1556
    }
1557

1558
    case TSDB_DATA_TYPE_INT: {
8,826✔
1559
      int32_t* plist = (int32_t*)pCol->pData;
8,826✔
1560
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
433,305✔
1561
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
424,479✔
1562
          continue;
2,815✔
1563
        }
1564

1565
        numOfElem++;
421,664✔
1566
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
421,664✔
1567
      }
1568
      break;
8,826✔
1569
    }
1570

1571
    case TSDB_DATA_TYPE_BIGINT: {
17,102✔
1572
      int64_t* plist = (int64_t*)pCol->pData;
17,102✔
1573
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
859,654✔
1574
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
842,552✔
1575
          continue;
570,026✔
1576
        }
1577

1578
        numOfElem++;
272,526✔
1579
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
272,526✔
1580
      }
1581
      break;
17,102✔
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,189,873✔
1635
      float* plist = (float*)pCol->pData;
4,189,873✔
1636
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
12,503,102✔
1637
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
8,313,229✔
1638
          continue;
139,221✔
1639
        }
1640

1641
        numOfElem++;
8,174,008✔
1642
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
8,174,008✔
1643
      }
1644
      break;
4,189,873✔
1645
    }
1646

1647
    case TSDB_DATA_TYPE_DOUBLE: {
5,808✔
1648
      double* plist = (double*)pCol->pData;
5,808✔
1649
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
104,942✔
1650
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
99,134✔
1651
          continue;
2,460✔
1652
        }
1653

1654
        numOfElem++;
96,674✔
1655
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
96,674✔
1656
      }
1657
      break;
5,808✔
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;
4,240,509✔
1670
  pInfo->num += numOfElem;
4,240,509✔
1671

1672
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
4,240,509✔
1673

1674
  return TSDB_CODE_SUCCESS;
4,240,509✔
1675
}
1676

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

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

1688
  if (0 == pInfo->num) {
4,193,267✔
1689
    colDataSetNULL(pCol, currentRow);
29,574!
1690
    return TSDB_CODE_SUCCESS;
29,574✔
1691
  }
1692

1693
  double(*param)[3] = pInfo->matrix;
4,163,693✔
1694

1695
  param[1][1] = (double)pInfo->num;
4,163,693✔
1696
  param[1][0] = param[0][1];
4,163,693✔
1697

1698
  double param00 = param[0][0] - param[1][0] * (param[0][1] / param[1][1]);
4,163,693✔
1699
  double param02 = param[0][2] - param[1][2] * (param[0][1] / param[1][1]);
4,163,693✔
1700

1701
  if (0 == param00) {
4,163,693✔
1702
    colDataSetNULL(pCol, currentRow);
3,833,074!
1703
    return TSDB_CODE_SUCCESS;
3,833,074✔
1704
  }
1705

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

1711
  param12 /= param[1][1];
330,619✔
1712

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

1728
  int32_t code = colDataSetVal(pCol, currentRow, buf, pResInfo->isNullRes);
330,621✔
1729

1730
  return code;
330,621✔
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) {
940✔
1756
  pEnv->calcMemSize = sizeof(SPercentileInfo);
940✔
1757
  return true;
940✔
1758
}
1759

1760
int32_t percentileFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
6,326✔
1761
  if (pResultInfo->initialized) {
6,326!
1762
    return TSDB_CODE_SUCCESS;
×
1763
  }
1764
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
6,326!
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);
6,326✔
1770
  SET_DOUBLE_VAL(&pInfo->minval, DBL_MAX);
6,326✔
1771
  SET_DOUBLE_VAL(&pInfo->maxval, -DBL_MAX);
6,326✔
1772
  pInfo->numOfElems = 0;
6,326✔
1773

1774
  return TSDB_CODE_SUCCESS;
6,326✔
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) {
14,736✔
1789
  int32_t              code = TSDB_CODE_SUCCESS;
14,736✔
1790
  int32_t              numOfElems = 0;
14,736✔
1791
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
14,736✔
1792

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

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

1799
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
14,736✔
1800
  if (pCtx->scanFlag == MAIN_SCAN && pInfo->stage == 0) {
14,736✔
1801
    pInfo->stage += 1;
6,326✔
1802

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

1815
  // the first stage, only acquire the min/max value
1816
  if (pInfo->stage == 0) {
11,960✔
1817
    if (pCtx->input.colDataSMAIsSet) {
7,382!
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;
7,382✔
1842
      for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
523,800✔
1843
        if (colDataIsNull_f(pCol->nullbitmap, i)) {
516,418✔
1844
          continue;
3,400✔
1845
        }
1846

1847
        char* data = colDataGetData(pCol, i);
513,018!
1848

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

1855
        if (v > GET_DOUBLE_VAL(&pInfo->maxval)) {
513,018✔
1856
          SET_DOUBLE_VAL(&pInfo->maxval, v);
410,880✔
1857
        }
1858

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

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

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

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

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

1890
  int32_t code = 0;
6,326✔
1891
  double  v = 0;
6,326✔
1892

1893
  tMemBucket** pMemBucket = &ppInfo->pMemBucket;
6,326✔
1894
  if ((*pMemBucket) != NULL && (*pMemBucket)->total > 0) {  // check for null
6,326!
1895
    if (pCtx->numOfParams > 2) {
3,550✔
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;
3,520✔
1935

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

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

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

1950
_fin_error:
×
1951

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

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

1964
int32_t getApercentileMaxSize() {
9,553✔
1965
  int32_t bytesHist =
9,553✔
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,553✔
1968
  return TMAX(bytesHist, bytesDigest);
9,553✔
1969
}
1970

1971
static int8_t getApercentileAlgo(char* algoStr) {
29,362✔
1972
  int8_t algoType;
1973
  if (strcasecmp(algoStr, "default") == 0) {
29,362✔
1974
    algoType = APERCT_ALGO_DEFAULT;
13,272✔
1975
  } else if (strcasecmp(algoStr, "t-digest") == 0) {
16,090!
1976
    algoType = APERCT_ALGO_TDIGEST;
16,090✔
1977
  } else {
UNCOV
1978
    algoType = APERCT_ALGO_UNKNOWN;
×
1979
  }
1980

1981
  return algoType;
29,362✔
1982
}
1983

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

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

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

2001
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
310,184✔
2002

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

2007
  if (pCtx->numOfParams == 2) {
310,184✔
2008
    pInfo->algo = APERCT_ALGO_DEFAULT;
280,829✔
2009
  } else if (pCtx->numOfParams == 3) {
29,355!
2010
    pInfo->algo = getApercentileAlgo(varDataVal(pCtx->param[2].param.pz));
29,368✔
2011
    if (pInfo->algo == APERCT_ALGO_UNKNOWN) {
29,367!
2012
      return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
2013
    }
2014
  }
2015

2016
  char* tmp = (char*)pInfo + sizeof(SAPercentileInfo);
310,183✔
2017
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
310,183✔
2018
    pInfo->pTDigest = tdigestNewFrom(tmp, COMPRESSION);
16,095✔
2019
  } else {
2020
    buildHistogramInfo(pInfo);
294,088✔
2021
    pInfo->pHisto = tHistogramCreateFrom(tmp, MAX_HISTOGRAM_BIN);
294,101✔
2022
    qDebug("%s set up histogram, numOfElems:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
294,097✔
2023
           pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2024
  }
2025

2026
  return TSDB_CODE_SUCCESS;
310,195✔
2027
}
2028

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

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

2037
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
326,021✔
2038

2039
  int32_t start = pInput->startRowIndex;
326,021✔
2040
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
326,021✔
2041
    buildTDigestInfo(pInfo);
19,859✔
2042
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
19,858✔
2043
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
1,478,400✔
2044
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
1,458,546✔
2045
        continue;
493,296✔
2046
      }
2047
      numOfElems += 1;
965,250✔
2048
      char* data = colDataGetData(pCol, i);
965,250!
2049

2050
      double  v = 0;  // value
965,250✔
2051
      int64_t w = 1;  // weigth
965,250✔
2052
      GET_TYPED_DATA(v, double, type, data);
965,250✔
2053
      int32_t code = tdigestAdd(pInfo->pTDigest, v, w);
965,250✔
2054
      if (code != TSDB_CODE_SUCCESS) {
965,247!
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);
306,162✔
2062
    qDebug("%s before add %d elements into histogram, total:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems: %p",
306,155✔
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,549,089✔
2066
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
3,242,849✔
2067
        continue;
1,272,958✔
2068
      }
2069
      numOfElems += 1;
1,969,891✔
2070
      char* data = colDataGetData(pCol, i);
1,969,891!
2071

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

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

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

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

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

2100
    if (hasRes) {
913✔
2101
      *hasRes = true;
911✔
2102
    }
2103

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

2108
    if (pTDigest->num_centroids <= 0 && pTDigest->num_buffered_pts == 0) {
913!
2109
      (void)memcpy(pTDigest, pInput->pTDigest, (size_t)TDIGEST_SIZE(COMPRESSION));
911✔
2110
      tdigestAutoFill(pTDigest, COMPRESSION);
911✔
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);
7,459✔
2119
    if (pInput->pHisto->numOfElems <= 0) {
7,459✔
2120
      return TSDB_CODE_SUCCESS;
168✔
2121
    }
2122

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

2198
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
274,564✔
2199
    buildTDigestInfo(pInfo);
15,184✔
2200
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
15,184✔
2201
    if (pInfo->pTDigest->size > 0) {
15,180!
2202
      pInfo->result = tdigestQuantile(pInfo->pTDigest, pInfo->percent / 100);
15,180✔
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,380✔
2209
    if (pInfo->pHisto->numOfElems > 0) {
259,383✔
2210
      qDebug("%s get the final res, elements:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
204,753✔
2211
             pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2212

2213
      double  ratio[] = {pInfo->percent};
204,754✔
2214
      double* res = NULL;
204,754✔
2215
      int32_t code = tHistogramUniform(pInfo->pHisto, ratio, 1, &res);
204,754✔
2216
      if (TSDB_CODE_SUCCESS != code) {
204,759!
2217
        taosMemoryFree(res);
×
2218
        return code;
×
2219
      }
2220
      pInfo->result = *res;
204,759✔
2221
      // memcpy(pCtx->pOutput, res, sizeof(double));
2222
      taosMemoryFree(res);
204,759✔
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__,
54,630✔
2227
             pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries);
2228
    }
2229
  }
2230

2231
  return functionFinalize(pCtx, pBlock);
274,565✔
2232
}
2233

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

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

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

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

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

2261
  taosMemoryFree(res);
8,031✔
2262
  return code;
8,031✔
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) {
5,869✔
2285
  char numVal[8] = {0};
5,869✔
2286
  switch (pkType) {
5,869✔
2287
    case TSDB_DATA_TYPE_INT:
941✔
2288
      *(int32_t*)numVal = (int32_t)pVal->val;
941✔
2289
      break;
941✔
2290
    case TSDB_DATA_TYPE_UINT:
914✔
2291
      *(uint32_t*)numVal = (uint32_t)pVal->val;
914✔
2292
      break;
914✔
2293
    case TSDB_DATA_TYPE_BIGINT:
1,074✔
2294
      *(int64_t*)numVal = (int64_t)pVal->val;
1,074✔
2295
      break;
1,074✔
2296
    case TSDB_DATA_TYPE_UBIGINT:
1,056✔
2297
      *(uint64_t*)numVal = (uint64_t)pVal->val;
1,056✔
2298
      break;
1,056✔
2299
    default:
1,884✔
2300
      break;
1,884✔
2301
  }
2302
  char*         blockData = (IS_NUMERIC_TYPE(pkType)) ? (char*) numVal : (char*)pVal->pData;
5,869!
2303
  __compar_fn_t fn = getKeyComparFunc(pkType, order);
5,869✔
2304
  return fn(pkData, blockData);
5,871✔
2305
}
2306

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

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

2315
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
19,118✔
2316
  if (pResult->hasResult) {
19,118✔
2317
    if (pResult->pkBytes > 0) {
19,051✔
2318
      pResult->pkData = pResult->buf + pResult->bytes;
5,180✔
2319
    } else {
2320
      pResult->pkData = NULL;
13,871✔
2321
    }    
2322
    if (pResult->ts < pBlockInfo->window.skey) {
19,051✔
2323
      return FUNC_DATA_REQUIRED_NOT_LOAD;
13,959✔
2324
    } else if (pResult->ts == pBlockInfo->window.skey) {
5,092✔
2325
      if (NULL == pResult->pkData) {
2,187✔
2326
        return FUNC_DATA_REQUIRED_NOT_LOAD;
196✔
2327
      }
2328
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 0, TSDB_ORDER_ASC) < 0) {
1,991✔
2329
        return FUNC_DATA_REQUIRED_NOT_LOAD;
385✔
2330
      }
2331
    }
2332
    return FUNC_DATA_REQUIRED_DATA_LOAD;
4,512✔
2333
  } else {
2334
    return FUNC_DATA_REQUIRED_DATA_LOAD;
67✔
2335
  }
2336
}
2337

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

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

2346
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
59,914✔
2347
  if (pResult->hasResult) {
59,914✔
2348
    if (pResult->pkBytes > 0) {
57,259✔
2349
      pResult->pkData = pResult->buf + pResult->bytes;
9,156✔
2350
    } else {
2351
      pResult->pkData = NULL;
48,103✔
2352
    }
2353
    if (pResult->ts > pBlockInfo->window.ekey) {
57,259✔
2354
      return FUNC_DATA_REQUIRED_NOT_LOAD;
51,066✔
2355
    } else if (pResult->ts == pBlockInfo->window.ekey && pResult->pkData) {
6,193✔
2356
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 1, TSDB_ORDER_DESC) < 0) {
3,880✔
2357
        return FUNC_DATA_REQUIRED_NOT_LOAD;
1,313✔
2358
      }
2359
    }
2360
    return FUNC_DATA_REQUIRED_DATA_LOAD;
4,879✔
2361
  } else {
2362
    return FUNC_DATA_REQUIRED_DATA_LOAD;
2,655✔
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; }
67,162,624✔
2368

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

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

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

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

2394
  return *(TSKEY*)colDataGetData(pTsColInfo, rowIndex);
293,606,542!
2395
}
2396

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

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

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

2413
static int32_t prepareBuf(SqlFunctionCtx* pCtx) {
262,016,783✔
2414
  if (pCtx->subsidiaries.rowLen == 0) {
262,016,783✔
2415
    int32_t rowLen = 0;
646,368✔
2416
    for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
1,302,661✔
2417
      SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
656,293✔
2418
      rowLen += pc->pExpr->base.resSchema.bytes;
656,293✔
2419
    }
2420

2421
    pCtx->subsidiaries.rowLen = rowLen + pCtx->subsidiaries.num * sizeof(bool);
646,368✔
2422
    pCtx->subsidiaries.buf = taosMemoryMalloc(pCtx->subsidiaries.rowLen);
646,368✔
2423
    if (NULL == pCtx->subsidiaries.buf) {
646,393!
2424
      return terrno;
×
2425
    }
2426
  }
2427
  return TSDB_CODE_SUCCESS;
262,017,070✔
2428
}
2429

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

2434
  if (pCtx->subsidiaries.num <= 0) {
218,314,354✔
2435
    return TSDB_CODE_SUCCESS;
123,004,296✔
2436
  }
2437

2438
  if (!pInfo->hasResult) {
95,310,058✔
2439
    code = saveTupleData(pCtx, rowIndex, pSrcBlock, noElements ? &pInfo->nullTuplePos : &pInfo->pos);
73,446,785✔
2440
  } else {
2441
    code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pInfo->pos);
21,863,273✔
2442
  }
2443

2444
  return code;
95,195,728✔
2445
}
2446

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

2451
  if (IS_VAR_DATA_TYPE(type)) {
94,168,446!
2452
    pInfo->bytes = varDataTLen(pData);
11,700,772✔
2453
  }
2454

2455
  (void)memcpy(pInfo->buf, pData, pInfo->bytes);
94,168,446✔
2456
  if (pkData != NULL) {
94,168,446✔
2457
    if (IS_VAR_DATA_TYPE(pInfo->pkType)) {
1,396,701!
2458
      pInfo->pkBytes = varDataTLen(pkData);
455,182✔
2459
    }
2460
    (void)memcpy(pInfo->buf + pInfo->bytes, pkData, pInfo->pkBytes);
1,396,701✔
2461
    pInfo->pkData = pInfo->buf + pInfo->bytes;
1,396,701✔
2462
  }
2463

2464
  pInfo->ts = currentTs;
94,168,446✔
2465
  int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pInfo, false);
94,168,446✔
2466
  if (code != TSDB_CODE_SUCCESS) {
94,214,465!
2467
    return code;
×
2468
  }
2469

2470
  pInfo->hasResult = true;
94,214,465✔
2471
  return TSDB_CODE_SUCCESS;
94,214,465✔
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) {
56,365,857✔
2477
  int32_t numOfElems = 0;
56,365,857✔
2478

2479
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
56,365,857✔
2480
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
56,365,857✔
2481

2482
  SInputColumnInfoData* pInput = &pCtx->input;
56,365,857✔
2483
  SColumnInfoData*      pInputCol = pInput->pData[0];
56,365,857✔
2484

2485
  pInfo->bytes = pInputCol->info.bytes;
56,365,857✔
2486

2487
  if (IS_NULL_TYPE(pInputCol->info.type)) {
56,365,857✔
2488
    return TSDB_CODE_SUCCESS;
4,869✔
2489
  }
2490

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

2500
  // All null data column, return directly.
2501
  if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) &&
56,416,337!
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;
56,416,337!
2513

2514
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
56,416,337!
2515
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
56,416,337!
2516

2517
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
56,416,337✔
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;
56,416,337✔
2571

2572
  int from = -1;
56,416,337✔
2573
  int32_t i = -1;
56,416,337✔
2574
  while (funcInputGetNextRowIndex(pInput, from, true, &i, &from)) {
192,749,514✔
2575
    if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
184,614,023!
2576
      continue;
83,616✔
2577
    }
2578

2579
    numOfElems++;
136,313,450✔
2580
    char* data = colDataGetData(pInputCol, i);
136,313,450!
2581
    char* pkData = NULL;
136,313,450✔
2582
    if (pCtx->hasPrimaryKey) {
136,313,450✔
2583
      pkData = colDataGetData(pkCol, i);
1,328,062!
2584
    }
2585
    TSKEY cts = pts[i];
136,313,450✔
2586
    if (pResInfo->numOfRes == 0 || pInfo->ts > cts || 
136,313,450✔
2587
         (pInfo->ts == cts && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
87,707,450!
2588
      int32_t code = doSaveCurrentVal(pCtx, i, cts, pkData, pInputCol->info.type, data);
48,606,000✔
2589
      if (code != TSDB_CODE_SUCCESS) {
48,542,114!
2590
        return code;
×
2591
      }
2592
      pResInfo->numOfRes = 1;
48,542,114✔
2593
    }
2594
  }
2595
#endif
2596

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

2609
int32_t lastFunction(SqlFunctionCtx* pCtx) {
43,458,747✔
2610
  int32_t numOfElems = 0;
43,458,747✔
2611

2612
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
43,458,747✔
2613
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
43,458,747✔
2614

2615
  SInputColumnInfoData* pInput = &pCtx->input;
43,458,747✔
2616
  SColumnInfoData*      pInputCol = pInput->pData[0];
43,458,747✔
2617

2618
  int32_t type = pInputCol->info.type;
43,458,747✔
2619
  int32_t bytes = pInputCol->info.bytes;
43,458,747✔
2620
  pInfo->bytes = bytes;
43,458,747✔
2621

2622
  if (IS_NULL_TYPE(type)) {
43,458,747✔
2623
    return TSDB_CODE_SUCCESS;
4,871✔
2624
  }
2625

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

2635
  // All null data column, return directly.
2636
  if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) &&
43,509,603!
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;
43,509,603!
2648

2649
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
43,509,603!
2650
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
43,509,603!
2651

2652
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
43,509,603✔
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;
43,509,603✔
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) {
67,237,949✔
2708
    numOfElems = 1;
23,770,946✔
2709

2710
    int32_t round = pInput->numOfRows >> 2;
23,770,946✔
2711
    int32_t reminder = pInput->numOfRows & 0x03;
23,770,946✔
2712

2713
    for (int32_t i = pInput->startRowIndex, tick = 0; tick < round; i += 4, tick += 1) {
39,738,372✔
2714
      int64_t cts = pts[i];
15,964,593✔
2715
      int32_t chosen = i;
15,964,593✔
2716

2717
      if (cts < pts[i + 1]) {
15,964,593✔
2718
        cts = pts[i + 1];
4,397,802✔
2719
        chosen = i + 1;
4,397,802✔
2720
      }
2721

2722
      if (cts < pts[i + 2]) {
15,964,593✔
2723
        cts = pts[i + 2];
4,396,568✔
2724
        chosen = i + 2;
4,396,568✔
2725
      }
2726

2727
      if (cts < pts[i + 3]) {
15,964,593✔
2728
        cts = pts[i + 3];
4,396,511✔
2729
        chosen = i + 3;
4,396,511✔
2730
      }
2731

2732
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
15,964,593✔
2733
        char*   data = colDataGetData(pInputCol, chosen);
3,801,734!
2734
        int32_t code = doSaveCurrentVal(pCtx, i, cts, NULL, type, data);
3,801,734✔
2735
        if (code != TSDB_CODE_SUCCESS) {
3,804,567!
2736
          return code;
×
2737
        }
2738
        pResInfo->numOfRes = 1;
3,804,567✔
2739
      }
2740
    }
2741

2742
    for (int32_t i = pInput->startRowIndex + round * 4; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
52,968,045✔
2743
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i]) {
29,239,699✔
2744
        char*   data = colDataGetData(pInputCol, i);
15,824,518!
2745
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], NULL, type, data);
15,824,518✔
2746
        if (code != TSDB_CODE_SUCCESS) {
15,779,085!
2747
          return code;
×
2748
        }
2749
        pResInfo->numOfRes = 1;
15,779,085✔
2750
      }
2751
    }
2752
  } else {
2753
    int from = -1;
19,738,657✔
2754
    int32_t i = -1;
19,738,657✔
2755
    while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
245,864,385✔
2756
      if (colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
452,289,430✔
2757
        continue;
16,608,863✔
2758
      }
2759

2760
      numOfElems++;
209,535,852✔
2761
      char* pkData = NULL;
209,535,852✔
2762
      if (pCtx->hasPrimaryKey) {
209,535,852✔
2763
        pkData = colDataGetData(pkCol, i);
101,457,113!
2764
      }
2765
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i] ||
209,535,852✔
2766
          (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
183,890,888!
2767
        char*   data = colDataGetData(pInputCol, i);
25,957,157!
2768
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], pkData, type, data);
25,957,157✔
2769
        if (code != TSDB_CODE_SUCCESS) {
25,938,175!
2770
          return code;
×
2771
        }
2772
        pResInfo->numOfRes = 1;
25,938,175✔
2773
      }
2774
    }
2775
  }
2776
#endif
2777

2778
#endif
2779

2780
  // save selectivity value for column consisted of all null values
2781
  if (numOfElems == 0) {
43,486,107✔
2782
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, !pInfo->nullTupleSaved);
4,118,439✔
2783
    if (code != TSDB_CODE_SUCCESS) {
4,114,614!
2784
      return code;
×
2785
    }
2786
    pInfo->nullTupleSaved = true;
4,114,614✔
2787
  }
2788

2789
  return TSDB_CODE_SUCCESS;
43,482,282✔
2790
}
2791

2792
static bool firstLastTransferInfoImpl(SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst) {
61,376,009✔
2793
  if (!pInput->hasResult) {
61,376,009✔
2794
    return false;
2✔
2795
  }
2796
  __compar_fn_t pkCompareFn = NULL;
61,376,007✔
2797
  if (pInput->pkData) {
61,376,007✔
2798
    pkCompareFn = getKeyComparFunc(pInput->pkType, (isFirst) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC);
34,018✔
2799
  }
2800
  if (pOutput->hasResult) {
61,379,888✔
2801
    if (isFirst) {
18,771,120✔
2802
      if (pInput->ts > pOutput->ts ||
9,449,703✔
2803
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
9,089,904✔
2804
        return false;
360,111✔
2805
      }
2806
    } else {
2807
      if (pInput->ts < pOutput->ts ||
9,321,417✔
2808
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
6,896,414✔
2809
        return false;
2,426,701✔
2810
      }
2811
    }
2812
  }
2813

2814
  pOutput->isNull = pInput->isNull;
58,593,076✔
2815
  pOutput->ts = pInput->ts;
58,593,076✔
2816
  pOutput->bytes = pInput->bytes;
58,593,076✔
2817
  pOutput->pkType = pInput->pkType;
58,593,076✔
2818

2819
  (void)memcpy(pOutput->buf, pInput->buf, pOutput->bytes);
58,593,076✔
2820
  if (pInput->pkData) {
58,593,076✔
2821
    pOutput->pkBytes = pInput->pkBytes;
31,903✔
2822
    (void)memcpy(pOutput->buf + pOutput->bytes, pInput->pkData, pOutput->pkBytes);
31,903✔
2823
    pOutput->pkData = pOutput->buf + pOutput->bytes;
31,903✔
2824
  }
2825
  return true;
58,593,076✔
2826
}
2827

2828
static int32_t firstLastTransferInfo(SqlFunctionCtx* pCtx, SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst,
61,376,075✔
2829
                                     int32_t rowIndex) {
2830
  if (firstLastTransferInfoImpl(pInput, pOutput, isFirst)) {
61,376,075✔
2831
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pOutput, pOutput->nullTupleSaved);
58,592,021✔
2832
    if (TSDB_CODE_SUCCESS != code) {
58,577,185!
2833
      return code;
×
2834
    }
2835
    pOutput->hasResult = true;
58,577,185✔
2836
  }
2837
  return TSDB_CODE_SUCCESS;
61,362,561✔
2838
}
2839

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

2844
  if (IS_NULL_TYPE(pCol->info.type)) {
43,508,144!
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) {
43,508,144!
2850
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
2851
  }
2852

2853
  SFirstLastRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
43,508,144✔
2854

2855
  int32_t start = pInput->startRowIndex;
43,508,144✔
2856
  int32_t numOfElems = 0;
43,508,144✔
2857

2858
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
107,161,809✔
2859
    if (colDataIsNull_s(pCol, i)) {
127,345,092✔
2860
      continue;
2,291,892✔
2861
    }
2862
    char*          data = colDataGetData(pCol, i);
61,380,654!
2863
    SFirstLastRes* pInputInfo = (SFirstLastRes*)varDataVal(data);
61,380,654✔
2864
    if (pCtx->hasPrimaryKey) {
61,380,654✔
2865
      pInputInfo->pkData = pInputInfo->buf + pInputInfo->bytes;
34,018✔
2866
    } else {
2867
      pInputInfo->pkData = NULL;
61,346,636✔
2868
    }
2869

2870
    int32_t code = firstLastTransferInfo(pCtx, pInputInfo, pInfo, isFirstQuery, i);
61,380,654✔
2871
    if (code != TSDB_CODE_SUCCESS) {
61,361,773!
2872
      return code;
×
2873
    }
2874
    if (!numOfElems) {
61,361,773✔
2875
      numOfElems = pInputInfo->hasResult ? 1 : 0;
43,484,540✔
2876
    }
2877
  }
2878

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

2887
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
43,489,263✔
2888
  return TSDB_CODE_SUCCESS;
43,489,263✔
2889
}
2890

2891
int32_t firstFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, true); }
11,698,754✔
2892

2893
int32_t lastFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, false); }
31,815,728✔
2894

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

2903
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
86,499,909✔
2904
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
86,499,909✔
2905

2906
  SFirstLastRes* pRes = GET_ROWCELL_INTERBUF(pResInfo);
86,499,909✔
2907

2908
  if (pResInfo->isNullRes) {
86,499,909✔
2909
    colDataSetNULL(pCol, pBlock->info.rows);
49,543✔
2910
    return setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, pBlock->info.rows);
49,543✔
2911
  }
2912
  code = colDataSetVal(pCol, pBlock->info.rows, pRes->buf, pRes->isNull || pResInfo->isNullRes);
86,450,366!
2913
  if (TSDB_CODE_SUCCESS != code) {
86,397,651!
2914
    return code;
×
2915
  }
2916

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

2920
  return code;
86,401,593✔
2921
}
2922

2923
int32_t firstLastPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
65,141,882✔
2924
  int32_t code = TSDB_CODE_SUCCESS;
65,141,882✔
2925

2926
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
65,141,882✔
2927
  SFirstLastRes*       pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
65,141,882✔
2928

2929
  int32_t resultBytes = getFirstLastInfoSize(pRes->bytes, pRes->pkBytes);
65,141,882✔
2930

2931
  // todo check for failure
2932
  char* res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
65,055,234✔
2933
  if (NULL == res) {
65,878,080!
2934
    return terrno;
×
2935
  }
2936
  (void)memcpy(varDataVal(res), pRes, resultBytes);
65,878,080✔
2937

2938
  varDataSetLen(res, resultBytes);
65,878,080✔
2939

2940
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
65,878,080✔
2941
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
65,878,080✔
2942
  if (NULL == pCol) {
65,662,059!
2943
    taosMemoryFree(res);
×
2944
    return TSDB_CODE_OUT_OF_RANGE;
×
2945
  }
2946

2947
  if (pEntryInfo->numOfRes == 0) {
65,691,661✔
2948
    colDataSetNULL(pCol, pBlock->info.rows);
2,387,977!
2949
    code = setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, pBlock->info.rows);
2,387,977✔
2950
  } else {
2951
    code = colDataSetVal(pCol, pBlock->info.rows, res, false);
63,303,684✔
2952
    if (TSDB_CODE_SUCCESS != code) {
62,766,316!
2953
      taosMemoryFree(res);
×
2954
      return code;
×
2955
    }
2956
    code = setSelectivityValue(pCtx, pBlock, &pRes->pos, pBlock->info.rows);
62,766,316✔
2957
  }
2958
  taosMemoryFree(res);
65,086,465✔
2959
  return code;
65,730,976✔
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) {
61,578,468✔
2977
  SInputColumnInfoData* pInput = &pCtx->input;
61,578,468✔
2978
  SColumnInfoData*      pInputCol = pInput->pData[0];
61,578,468✔
2979
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
61,578,468✔
2980

2981

2982
  if (colDataIsNull_s(pInputCol, rowIndex)) {
123,156,936✔
2983
    pInfo->isNull = true;
6,001✔
2984
  } else {
2985
    pInfo->isNull = false;
61,572,467✔
2986

2987
    if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
61,572,467!
2988
      pInfo->bytes = varDataTLen(pData);
24,810,386✔
2989
    }
2990

2991
    (void)memcpy(pInfo->buf, pData, pInfo->bytes);
61,572,467✔
2992
  }
2993

2994
  if (pCtx->hasPrimaryKey && !colDataIsNull_s(pkCol, rowIndex)) {
61,648,719✔
2995
    char* pkData = colDataGetData(pkCol, rowIndex);
70,250!
2996
    if (IS_VAR_DATA_TYPE(pInfo->pkType)) {
70,250!
2997
      pInfo->pkBytes = varDataTLen(pkData);
23,181✔
2998
    }
2999
    (void)memcpy(pInfo->buf + pInfo->bytes, pkData, pInfo->pkBytes);
70,250✔
3000
    pInfo->pkData = pInfo->buf + pInfo->bytes;
70,250✔
3001
  }
3002
  pInfo->ts = cts;
61,578,468✔
3003
  int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pInfo, false);
61,578,468✔
3004
  if (code != TSDB_CODE_SUCCESS) {
61,580,878!
3005
    return code;
×
3006
  }
3007

3008
  pInfo->hasResult = true;
61,580,878✔
3009

3010
  return TSDB_CODE_SUCCESS;
61,580,878✔
3011
}
3012

3013
int32_t lastRowFunction(SqlFunctionCtx* pCtx) {
46,691,470✔
3014
  int32_t numOfElems = 0;
46,691,470✔
3015

3016
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
46,691,470✔
3017
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
46,691,470✔
3018

3019
  SInputColumnInfoData* pInput = &pCtx->input;
46,691,470✔
3020
  SColumnInfoData*      pInputCol = pInput->pData[0];
46,691,470✔
3021

3022
  int32_t type = pInputCol->info.type;
46,691,470✔
3023
  int32_t bytes = pInputCol->info.bytes;
46,691,470✔
3024
  pInfo->bytes = bytes;
46,691,470✔
3025

3026
  if (IS_NULL_TYPE(type)) {
46,691,470✔
3027
    return TSDB_CODE_SUCCESS;
40✔
3028
  }
3029
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
46,691,430✔
3030
  pInfo->pkType = -1;
46,691,430✔
3031
  __compar_fn_t  pkCompareFn = NULL;
46,691,430✔
3032
  if (pCtx->hasPrimaryKey) {
46,691,430✔
3033
    pInfo->pkType = pkCol->info.type;
82,986✔
3034
    pInfo->pkBytes = pkCol->info.bytes;
82,986✔
3035
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
82,986✔
3036
  }
3037
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
46,699,801✔
3038
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
46,699,801!
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;
46,699,801✔
3072
  int from = -1;
46,699,801✔
3073
  int32_t i = -1;
46,699,801✔
3074
  while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
151,969,726✔
3075
    bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
105,291,359✔
3076
    char* data = isNull ? NULL : colDataGetData(pInputCol, i);
105,291,359!
3077
    TSKEY cts = pts[i];
105,291,359✔
3078

3079
    numOfElems++;
105,291,359✔
3080
    char* pkData = NULL;
105,291,359✔
3081
    if (pCtx->hasPrimaryKey) {
105,291,359✔
3082
      pkData = colDataGetData(pkCol, i);
1,363,284!
3083
    }
3084
    if (pResInfo->numOfRes == 0 || pInfo->ts < cts ||
105,291,359✔
3085
        (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
43,703,891✔
3086
      int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
61,587,474✔
3087
      if (code != TSDB_CODE_SUCCESS) {
61,566,043!
3088
        return code;
×
3089
      }
3090
      pResInfo->numOfRes = 1;
61,566,043✔
3091
    }
3092
  }
3093

3094
#endif
3095

3096
  SET_VAL(pResInfo, numOfElems, 1);
46,590,321!
3097
  return TSDB_CODE_SUCCESS;
46,590,321✔
3098
}
3099

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

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

3125
static int32_t doSetPrevVal(SDiffInfo* pDiffInfo, int32_t type, const char* pv, int64_t ts) {
2,120,442✔
3126
  switch (type) {
2,120,442!
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:
412,647✔
3131
    case TSDB_DATA_TYPE_TINYINT:
3132
      pDiffInfo->prev.i64 = *(int8_t*)pv;
412,647✔
3133
      break;
412,647✔
3134
    case TSDB_DATA_TYPE_UINT:
1,226,976✔
3135
    case TSDB_DATA_TYPE_INT:
3136
      pDiffInfo->prev.i64 = *(int32_t*)pv;
1,226,976✔
3137
      break;
1,226,976✔
3138
    case TSDB_DATA_TYPE_USMALLINT:
479,461✔
3139
    case TSDB_DATA_TYPE_SMALLINT:
3140
      pDiffInfo->prev.i64 = *(int16_t*)pv;
479,461✔
3141
      break;
479,461✔
3142
    case TSDB_DATA_TYPE_TIMESTAMP:
625✔
3143
    case TSDB_DATA_TYPE_UBIGINT:
3144
    case TSDB_DATA_TYPE_BIGINT:
3145
      pDiffInfo->prev.i64 = *(int64_t*)pv;
625✔
3146
      break;
625✔
3147
    case TSDB_DATA_TYPE_FLOAT:
240✔
3148
      pDiffInfo->prev.d64 = *(float*)pv;
240✔
3149
      break;
240✔
3150
    case TSDB_DATA_TYPE_DOUBLE:
455✔
3151
      pDiffInfo->prev.d64 = *(double*)pv;
455✔
3152
      break;
455✔
3153
    default:
×
3154
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3155
  }
3156
  pDiffInfo->prevTs = ts;
2,120,442✔
3157
  pDiffInfo->hasPrev = true;
2,120,442✔
3158
  return TSDB_CODE_SUCCESS;
2,120,442✔
3159
}
3160

3161
static bool diffIsNegtive(SDiffInfo* pDiffInfo, int32_t type, const char* pv) {
8,064,079✔
3162
  switch (type) {
8,064,079!
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: {
4,983,638✔
3168
      int64_t v = *(int32_t*)pv;
4,983,638✔
3169
      return v < pDiffInfo->prev.i64;
4,983,638✔
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: {
1,254,510✔
3180
      int64_t v = *(int8_t*)pv;
1,254,510✔
3181
      return v < pDiffInfo->prev.i64;
1,254,510✔
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: {
1,808,193✔
3188
      int64_t v = *(int16_t*)pv;
1,808,193✔
3189
      return v < pDiffInfo->prev.i64;
1,808,193✔
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:
6,660✔
3196
    case TSDB_DATA_TYPE_BIGINT: {
3197
      int64_t v = *(int64_t*)pv;
6,660✔
3198
      return v < pDiffInfo->prev.i64;
6,660✔
3199
    }
3200
    case TSDB_DATA_TYPE_FLOAT: {
4,564✔
3201
      float v = *(float*)pv;
4,564✔
3202
      return v < pDiffInfo->prev.d64;
4,564✔
3203
    }
3204
    case TSDB_DATA_TYPE_DOUBLE: {
6,474✔
3205
      double v = *(double*)pv;
6,474✔
3206
      return v < pDiffInfo->prev.d64;
6,474✔
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) {
38,275,423✔
3216
  bool isNegative = v < pDiffInfo->prev.i64;
38,275,423✔
3217
  if(type == TSDB_DATA_TYPE_UBIGINT){
38,275,423✔
3218
    isNegative = (uint64_t)v < (uint64_t)pDiffInfo->prev.i64;
3,745✔
3219
  }
3220
  int64_t delta = v - pDiffInfo->prev.i64;
38,275,423✔
3221
  if (isNegative && ignoreNegative(pDiffInfo->ignoreOption)) {
38,275,423✔
3222
    colDataSetNull_f_s(pOutput, pos);
1,915,278✔
3223
    pOutput->hasNull = true;
1,915,278✔
3224
  } else {
3225
    colDataSetInt64(pOutput, pos, &delta);
36,360,145✔
3226
  }
3227
  pDiffInfo->prev.i64 = v;
38,275,423✔
3228
}
38,275,423✔
3229

3230
static void tryToSetDouble(SDiffInfo* pDiffInfo, SColumnInfoData* pOutput, double v, int32_t pos) {
92,824✔
3231
  double delta = v - pDiffInfo->prev.d64;
92,824✔
3232
  if (delta < 0 && ignoreNegative(pDiffInfo->ignoreOption)) {
92,824✔
3233
    colDataSetNull_f_s(pOutput, pos);
5,546✔
3234
  } else {
3235
    colDataSetDouble(pOutput, pos, &delta);
87,278✔
3236
  }
3237
  pDiffInfo->prev.d64 = v;
92,824✔
3238
}
92,824✔
3239

3240
static int32_t doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, SColumnInfoData* pOutput, int32_t pos,
38,368,862✔
3241
                            int64_t ts) {
3242
  if (!pDiffInfo->hasPrev) {
38,368,862✔
3243
    colDataSetNull_f_s(pOutput, pos);
615✔
3244
    return doSetPrevVal(pDiffInfo, type, pv, ts);
615✔
3245
  }
3246
  pDiffInfo->prevTs = ts;
38,368,247✔
3247
  switch (type) {
38,368,247!
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: {
30,070,329✔
3254
      int64_t v = *(int32_t*)pv;
30,070,329✔
3255
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
30,070,329✔
3256
      break;
30,070,329✔
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: {
877,487✔
3269
      int64_t v = *(int8_t*)pv;
877,487✔
3270
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
877,487✔
3271
      break;
877,487✔
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: {
2,065,903✔
3279
      int64_t v = *(int16_t*)pv;
2,065,903✔
3280
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
2,065,903✔
3281
      break;
2,065,903✔
3282
    }
3283
    case TSDB_DATA_TYPE_TIMESTAMP:
5,245,802✔
3284
    case TSDB_DATA_TYPE_UBIGINT:
3285
    case TSDB_DATA_TYPE_BIGINT: {
3286
      int64_t v = *(int64_t*)pv;
5,245,802✔
3287
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
5,245,802✔
3288
      break;
5,245,802✔
3289
    }
3290
    case TSDB_DATA_TYPE_FLOAT: {
43,647✔
3291
      double v = *(float*)pv;
43,647✔
3292
      tryToSetDouble(pDiffInfo, pOutput, v, pos);
43,647✔
3293
      break;
43,647✔
3294
    }
3295
    case TSDB_DATA_TYPE_DOUBLE: {
49,177✔
3296
      double v = *(double*)pv;
49,177✔
3297
      tryToSetDouble(pDiffInfo, pOutput, v, pos);
49,177✔
3298
      break;
49,177✔
3299
    }
3300
    default:
×
3301
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3302
  }
3303
  pDiffInfo->hasPrev = true;
38,368,247✔
3304
  return TSDB_CODE_SUCCESS;
38,368,247✔
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) {
589,488,473✔
3310
  if (pInput->pPrimaryKey == NULL) {
589,488,473✔
3311
    if (from == -1) {
485,201,800✔
3312
      from = pInput->startRowIndex;
124,024,648✔
3313
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
361,177,152✔
3314
      return false;
123,625,598✔
3315
    }
3316
    *pRowIndex = from;
361,576,202✔
3317
    *nextFrom = from + 1;
361,576,202✔
3318
    return true;
361,576,202✔
3319
  } else {
3320
    if (from == -1) {
104,286,673✔
3321
      from = pInput->startRowIndex;
282,516✔
3322
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
104,004,157✔
3323
      return false;
282,562✔
3324
    }
3325
    TSKEY* tsList = (int64_t*)pInput->pPTS->pData;
104,004,111✔
3326
    SColumnInfoData* pkCol = pInput->pPrimaryKey;
104,004,111✔
3327
    int8_t pkType = pkCol->info.type;
104,004,111✔
3328
    int32_t order = (firstOccur) ? TSDB_ORDER_ASC: TSDB_ORDER_DESC;
104,004,111✔
3329
    __compar_fn_t compareFunc = getKeyComparFunc(pkType, order);
104,004,111✔
3330
    int32_t select = from;
104,127,076✔
3331
    char* val = colDataGetData(pkCol, select);
104,127,076!
3332
    while (from < pInput->numOfRows + pInput->startRowIndex - 1  &&  tsList[from + 1] == tsList[from]) {
110,345,757✔
3333
      char* val1 = colDataGetData(pkCol, from + 1);
6,221,324!
3334
      if (compareFunc(val1, val) < 0)  {
6,221,324✔
3335
        select = from + 1;
1,921,745✔
3336
        val = val1;
1,921,745✔
3337
      }
3338
      from = from + 1;
6,218,681✔
3339
    }
3340
    *pRowIndex = select;
104,124,433✔
3341
    *nextFrom = from + 1;
104,124,433✔
3342
    return true;
104,124,433✔
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,583,103✔
3352
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
40,583,103✔
3353
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
40,583,103✔
3354

3355
  if (pRow->isDataNull || !pDiffInfo->hasPrev ) {
40,583,103✔
3356
    return true;
184,829✔
3357
  }  else if (ignoreNegative(pDiffInfo->ignoreOption)){
40,398,274✔
3358
    return diffIsNegtive(pDiffInfo, pCtx->input.pData[0]->info.type, pRow->pData);
8,064,079✔
3359
  }
3360
  return false;
32,334,195✔
3361
}
3362

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

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

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

3381
  char*   pv = pRow->pData;
2,119,827✔
3382
  return doSetPrevVal(pDiffInfo, inputType, pv, pRow->ts);
2,119,827✔
3383
}
3384

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

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

3398
    // handle selectivity
3399
    if (pCtx->subsidiaries.num > 0) {
92,411✔
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;
92,411✔
3406
  }
3407

3408
  char* pv = pRow->pData;
38,368,885✔
3409

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

3425
  return TSDB_CODE_SUCCESS;
38,368,862✔
3426
}
3427

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

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

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

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

3460
  SqlFunctionCtx* pCtx0 = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, 0);
422,810✔
3461
  SFuncInputRow* pRow0 = (SFuncInputRow*)taosArrayGet(pRows, 0);
422,810✔
3462
  if (NULL == pCtx0 || NULL == pRow0) {
422,810!
3463
    code = terrno;
×
3464
    goto _exit;
×
3465
  }
3466
  int32_t startOffset = pCtx0->offset;
422,810✔
3467
  bool    result = false;
422,810✔
3468
  while (1) {
40,565,590✔
3469
    code = funcInputGetNextRow(pCtx0, pRow0, &result);
40,988,400✔
3470
    if (TSDB_CODE_SUCCESS != code) {
40,988,400!
3471
      goto _exit;
×
3472
    }
3473
    if (!result) {
40,988,400✔
3474
      break;
422,787✔
3475
    }
3476
    bool hasNotNullValue = !diffResultIsNull(pCtx0, pRow0);
40,565,613✔
3477
    for (int i = 1; i < diffColNum; ++i) {
40,583,103✔
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,565,613✔
3498

3499
    bool newRow = false;
40,565,613✔
3500
    for (int i = 0; i < diffColNum; ++i) {
81,148,693✔
3501
      SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
40,583,103✔
3502
      SFuncInputRow*  pRow = (SFuncInputRow*)taosArrayGet(pRows, i);
40,583,103✔
3503
      if (NULL == pCtx || NULL == pRow) {
40,583,103!
3504
        code = terrno;
×
3505
        goto _exit;
×
3506
      }
3507
      if ((keepNull || hasNotNullValue) && !isFirstRow(pCtx, pRow)){
40,583,103✔
3508
        code = setDoDiffResult(pCtx, pRow, pos);
38,461,296✔
3509
        if (code != TSDB_CODE_SUCCESS) {
38,461,296✔
3510
          goto _exit;
23✔
3511
        }
3512
        newRow = true;
38,461,273✔
3513
      } else {
3514
        code = trySetPreVal(pCtx, pRow);
2,121,807✔
3515
        if (code != TSDB_CODE_SUCCESS) {
2,121,807!
3516
          goto _exit;
×
3517
        } 
3518
      }
3519
    }
3520
    if (newRow) ++numOfElems;
40,565,590✔
3521
  }
3522

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

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

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

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

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

3557
  STopBotRes*           pRes = GET_ROWCELL_INTERBUF(pResInfo);
51,533,341✔
3558
  SInputColumnInfoData* pInput = &pCtx->input;
51,533,341✔
3559

3560
  pRes->maxSize = pCtx->param[1].param.i;
51,533,341✔
3561

3562
  pRes->nullTupleSaved = false;
51,533,341✔
3563
  pRes->nullTuplePos.pageId = -1;
51,533,341✔
3564
  return TSDB_CODE_SUCCESS;
51,533,341✔
3565
}
3566

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

3572
  return pRes;
247,914,570✔
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) {
40,073,177✔
3581
  int32_t              numOfElems = 0;
40,073,177✔
3582
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
40,073,177✔
3583

3584
  SInputColumnInfoData* pInput = &pCtx->input;
40,073,177✔
3585
  SColumnInfoData*      pCol = pInput->pData[0];
40,073,177✔
3586

3587
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
40,073,177✔
3588
  pRes->type = pInput->pData[0]->info.type;
40,073,208✔
3589

3590
  int32_t start = pInput->startRowIndex;
40,073,208✔
3591
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
149,978,554✔
3592
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
109,817,741✔
3593
      continue;
21,744✔
3594
    }
3595

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

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

3614
int32_t bottomFunction(SqlFunctionCtx* pCtx) {
12,979,936✔
3615
  int32_t              numOfElems = 0;
12,979,936✔
3616
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
12,979,936✔
3617

3618
  SInputColumnInfoData* pInput = &pCtx->input;
12,979,936✔
3619
  SColumnInfoData*      pCol = pInput->pData[0];
12,979,936✔
3620

3621
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
12,979,936✔
3622
  pRes->type = pInput->pData[0]->info.type;
12,979,940✔
3623

3624
  int32_t start = pInput->startRowIndex;
12,979,940✔
3625
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
47,217,514✔
3626
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
34,237,501✔
3627
      continue;
23,689✔
3628
    }
3629

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

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

3646
  return TSDB_CODE_SUCCESS;
12,980,013✔
3647
}
3648

3649
static int32_t topBotResComparFn(const void* p1, const void* p2, const void* param) {
441,090,922✔
3650
  uint16_t type = *(uint16_t*)param;
441,090,922✔
3651

3652
  STopBotResItem* val1 = (STopBotResItem*)p1;
441,090,922✔
3653
  STopBotResItem* val2 = (STopBotResItem*)p2;
441,090,922✔
3654

3655
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
441,090,922!
3656
    if (val1->v.i == val2->v.i) {
290,334,544✔
3657
      return 0;
253,334✔
3658
    }
3659

3660
    return (val1->v.i > val2->v.i) ? 1 : -1;
290,081,210✔
3661
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
150,756,378✔
3662
    if (val1->v.u == val2->v.u) {
837,310✔
3663
      return 0;
180,688✔
3664
    }
3665

3666
    return (val1->v.u > val2->v.u) ? 1 : -1;
656,622✔
3667
  } else if (TSDB_DATA_TYPE_FLOAT == type) {
149,919,068!
3668
    if (val1->v.f == val2->v.f) {
150,033,897✔
3669
      return 0;
63✔
3670
    }
3671

3672
    return (val1->v.f > val2->v.f) ? 1 : -1;
150,033,834✔
3673
  }
3674

UNCOV
3675
  if (val1->v.d == val2->v.d) {
×
3676
    return 0;
11✔
3677
  }
3678

UNCOV
3679
  return (val1->v.d > val2->v.d) ? 1 : -1;
×
3680
}
3681

3682
int32_t doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, uint16_t type,
144,001,860✔
3683
                        uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery) {
3684
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
144,001,860✔
3685
  int32_t     code = TSDB_CODE_SUCCESS;
143,933,627✔
3686

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

3690
  STopBotResItem* pItems = pRes->pItems;
144,023,637✔
3691

3692
  // not full yet
3693
  if (pEntryInfo->numOfRes < pRes->maxSize) {
144,023,637✔
3694
    STopBotResItem* pItem = &pItems[pEntryInfo->numOfRes];
94,626,849✔
3695
    pItem->v = val;
94,626,849✔
3696
    pItem->uid = uid;
94,626,849✔
3697

3698
    // save the data of this tuple
3699
    if (pCtx->subsidiaries.num > 0) {
94,626,849✔
3700
      code = saveTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
53,012,703✔
3701
      if (code != TSDB_CODE_SUCCESS) {
52,836,270!
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++;
94,450,416✔
3711
    code = taosheapsort((void*)pItems, sizeof(STopBotResItem), pEntryInfo->numOfRes, (const void*)&type,
94,450,416✔
3712
                        topBotResComparFn, !isTopQuery);
94,450,416✔
3713
    if (code != TSDB_CODE_SUCCESS) {
94,759,081!
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) ||
49,396,788!
3718
                        (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u > pItems[0].v.u) ||
28,290,487✔
3719
                        (TSDB_DATA_TYPE_FLOAT == type && val.f > pItems[0].v.f) ||
28,196,884✔
3720
                        (TSDB_DATA_TYPE_DOUBLE == type && val.d > pItems[0].v.d))) ||
27,259,183✔
3721
        (!isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i < pItems[0].v.i) ||
42,169,270!
3722
                         (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u < pItems[0].v.u) ||
14,393,119!
3723
                         (TSDB_DATA_TYPE_FLOAT == type && val.f < pItems[0].v.f) ||
14,389,505✔
3724
                         (TSDB_DATA_TYPE_DOUBLE == type && val.d < pItems[0].v.d)))) {
12,179,907!
3725
      // replace the old data and the coresponding tuple data
3726
      STopBotResItem* pItem = &pItems[0];
10,122,671✔
3727
      pItem->v = val;
10,122,671✔
3728
      pItem->uid = uid;
10,122,671✔
3729

3730
      // save the data of this tuple by over writing the old data
3731
      if (pCtx->subsidiaries.num > 0) {
10,122,671✔
3732
        code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
6,279,616✔
3733
        if (code != TSDB_CODE_SUCCESS) {
6,269,841!
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,
10,112,896✔
3741
                     topBotResComparFn, NULL, !isTopQuery);
10,112,896✔
3742
      if (code != TSDB_CODE_SUCCESS) {
10,057,789!
3743
        return code;
×
3744
      }
3745
    }
3746
  }
3747

3748
  return TSDB_CODE_SUCCESS;
144,090,987✔
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,
262,000,591✔
3758
                         char* buf, char** res) {
3759
  char* nullList = buf;
262,000,591✔
3760
  char* pStart = (char*)(nullList + sizeof(bool) * pSubsidiaryies->num);
262,000,591✔
3761

3762
  int32_t offset = 0;
262,000,591✔
3763
  for (int32_t i = 0; i < pSubsidiaryies->num; ++i) {
523,996,499✔
3764
    SqlFunctionCtx* pc = pSubsidiaryies->pCtx[i];
262,106,708✔
3765

3766
    // group_key function has its own process function
3767
    // do not process there
3768
    if (fmIsGroupKeyFunc(pc->functionId)) {
262,106,708✔
3769
      continue;
8,259,934✔
3770
    }
3771

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

3775
    SColumnInfoData* pCol = taosArrayGet(pSrcBlock->pDataBlock, srcSlotId);
253,824,763✔
3776
    if (NULL == pCol) {
253,735,974!
3777
      return TSDB_CODE_OUT_OF_RANGE;
×
3778
    }
3779
    if ((nullList[i] = colDataIsNull_s(pCol, rowIndex)) == true) {
507,471,948✔
3780
      offset += pCol->info.bytes;
432✔
3781
      continue;
432✔
3782
    }
3783

3784
    char* p = colDataGetData(pCol, rowIndex);
253,735,542!
3785
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
253,735,542!
3786
      (void)memcpy(pStart + offset, p, (pCol->info.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(p) : varDataTLen(p));
61,451!
3787
    } else {
3788
      (void)memcpy(pStart + offset, p, pCol->info.bytes);
253,674,091✔
3789
    }
3790

3791
    offset += pCol->info.bytes;
253,735,542✔
3792
  }
3793

3794
  *res = buf;
261,889,791✔
3795
  return TSDB_CODE_SUCCESS;
261,889,791✔
3796
}
3797

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

3804
    if (pHandle->currentPage == -1) {
274,463,104✔
3805
      pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
653,224✔
3806
      if (pPage == NULL) {
653,235!
UNCOV
3807
        return terrno;
×
3808
      }
3809
      pPage->num = sizeof(SFilePage);
653,235✔
3810
    } else {
3811
      pPage = getBufPage(pHandle->pBuf, pHandle->currentPage);
273,809,880✔
3812
      if (pPage == NULL) {
273,755,061!
3813
        return terrno;
×
3814
      }
3815
      if (pPage->num + length > getBufPageSize(pHandle->pBuf)) {
273,755,061✔
3816
        // current page is all used, let's prepare a new buffer page
3817
        releaseBufPage(pHandle->pBuf, pPage);
1,096,079✔
3818
        pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
1,096,079✔
3819
        if (pPage == NULL) {
1,096,079!
3820
          return terrno;
×
3821
        }
3822
        pPage->num = sizeof(SFilePage);
1,096,079✔
3823
      }
3824
    }
3825

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

3829
    pPage->num += length;
274,389,686✔
3830
    setBufPageDirty(pPage, true);
274,389,686✔
3831
    releaseBufPage(pHandle->pBuf, pPage);
274,294,909✔
3832
  } else { // other tuple save policy
3833
    if (pStore->streamStateFuncPut(pHandle->pState, key, pBuf, length) >= 0) {
129,568!
3834
      p.streamTupleKey = *key;
133,257✔
3835
    }
3836
  }
3837

3838
  *pPos = p;
274,328,900✔
3839
  return TSDB_CODE_SUCCESS;
274,328,900✔
3840
}
3841

3842
int32_t saveTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
198,255,051✔
3843
  int32_t code = prepareBuf(pCtx);
198,255,051✔
3844
  if (TSDB_CODE_SUCCESS != code) {
198,238,684!
3845
    return code;
×
3846
  }
3847

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

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

3869
static int32_t doUpdateTupleData(SSerializeDataHandle* pHandle, const void* pBuf, size_t length, STuplePos* pPos, SFunctionStateStore* pStore) {
63,802,509✔
3870
  if (pHandle->pBuf != NULL) {
63,802,509✔
3871
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
63,500,148✔
3872
    if (pPage == NULL) {
63,497,564!
3873
      return terrno;
×
3874
    }
3875
    (void)memcpy(pPage->data + pPos->offset, pBuf, length);
63,497,564✔
3876
    setBufPageDirty(pPage, true);
63,497,564✔
3877
    releaseBufPage(pHandle->pBuf, pPage);
63,491,462✔
3878
  } else {
3879
    int32_t code = pStore->streamStateFuncPut(pHandle->pState, &pPos->streamTupleKey, pBuf, length);
302,361✔
3880
    if (TSDB_CODE_SUCCESS != code) {
302,629!
3881
      return code;
×
3882
    }
3883
  }
3884

3885
  return TSDB_CODE_SUCCESS;
63,785,759✔
3886
}
3887

3888
int32_t updateTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
63,806,741✔
3889
  int32_t code = prepareBuf(pCtx);
63,806,741✔
3890
  if (TSDB_CODE_SUCCESS != code) {
63,805,844!
3891
    return code;
×
3892
  }
3893

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

3902
static int32_t doLoadTupleData(SSerializeDataHandle* pHandle, const STuplePos* pPos, SFunctionStateStore* pStore, char** value) {
144,202,472✔
3903
  if (pHandle->pBuf != NULL) {
144,202,472✔
3904
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
144,059,759✔
3905
    if (pPage == NULL) {
144,077,313!
3906
      *value = NULL;
×
3907
      return terrno;
×
3908
    }
3909
    *value = pPage->data + pPos->offset;
144,077,313✔
3910
    releaseBufPage(pHandle->pBuf, pPage);
144,077,313✔
3911
    return TSDB_CODE_SUCCESS;
144,005,825✔
3912
  } else {
3913
    *value = NULL;
142,713✔
3914
    int32_t vLen;
3915
    int32_t code = pStore->streamStateFuncGet(pHandle->pState, &pPos->streamTupleKey, (void **)(value), &vLen);
142,713✔
3916
    if (TSDB_CODE_SUCCESS != code) {
148,325!
3917
      return code;
×
3918
    }
3919
    return TSDB_CODE_SUCCESS;
148,325✔
3920
  }
3921
}
3922

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

3927
int32_t topBotFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
51,349,624✔
3928
  int32_t code = TSDB_CODE_SUCCESS;
51,349,624✔
3929

3930
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
51,349,624✔
3931
  STopBotRes*          pRes = getTopBotOutputInfo(pCtx);
51,349,624✔
3932

3933
  int16_t type = pCtx->pExpr->base.resSchema.type;
51,339,273✔
3934
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
51,339,273✔
3935

3936
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
51,339,273✔
3937
  if (NULL == pCol) {
51,329,236!
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;
51,329,236✔
3943
  if (pEntryInfo->numOfRes <= 0) {
51,329,236✔
3944
    colDataSetNULL(pCol, currentRow);
522!
3945
    code = setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, currentRow);
522✔
3946
    return code;
522✔
3947
  }
3948
  for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
145,360,429✔
3949
    STopBotResItem* pItem = &pRes->pItems[i];
94,058,599✔
3950
    code = colDataSetVal(pCol, currentRow, (const char*)&pItem->v.i, false);
94,058,599✔
3951
    if (TSDB_CODE_SUCCESS != code) {
94,069,870!
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);
94,069,870✔
3959
    if (TSDB_CODE_SUCCESS != code) {
94,031,715!
3960
      return code;
×
3961
    }
3962
    currentRow += 1;
94,031,715✔
3963
  }
3964

3965
  return code;
51,301,830✔
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); }
830,838✔
4042

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

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

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

4063
int32_t spreadFunction(SqlFunctionCtx* pCtx) {
2,252,028✔
4064
  int32_t numOfElems = 0;
2,252,028✔
4065

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

4071
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,252,028✔
4072

4073
  if (pInput->colDataSMAIsSet) {
2,252,028!
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];
2,252,028✔
4100

4101
    int32_t start = pInput->startRowIndex;
2,252,028✔
4102
    // check the valid data one by one
4103
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
13,576,884✔
4104
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
11,324,856✔
4105
        continue;
2,244,214✔
4106
      }
4107

4108
      char* data = colDataGetData(pCol, i);
9,080,642!
4109

4110
      double v = 0;
9,080,642✔
4111
      GET_TYPED_DATA(v, double, type, data);
9,080,642!
4112
      if (v < GET_DOUBLE_VAL(&pInfo->min)) {
9,080,642✔
4113
        SET_DOUBLE_VAL(&pInfo->min, v);
2,468,792✔
4114
      }
4115

4116
      if (v > GET_DOUBLE_VAL(&pInfo->max)) {
9,080,642✔
4117
        SET_DOUBLE_VAL(&pInfo->max, v);
2,902,441✔
4118
      }
4119

4120
      numOfElems += 1;
9,080,642✔
4121
    }
4122
  }
4123

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

4131
  return TSDB_CODE_SUCCESS;
2,252,028✔
4132
}
4133

4134
static void spreadTransferInfo(SSpreadInfo* pInput, SSpreadInfo* pOutput) {
829,394✔
4135
  pOutput->hasResult = pInput->hasResult;
829,394✔
4136
  if (pInput->max > pOutput->max) {
829,394✔
4137
    pOutput->max = pInput->max;
824,673✔
4138
  }
4139

4140
  if (pInput->min < pOutput->min) {
829,394✔
4141
    pOutput->min = pInput->min;
824,673✔
4142
  }
4143
}
829,394✔
4144

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

4149
  if (IS_NULL_TYPE(pCol->info.type)) {
825,453!
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) {
825,453!
4155
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
4156
  }
4157

4158
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
825,453✔
4159

4160
  int32_t start = pInput->startRowIndex;
825,453✔
4161
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
1,655,087✔
4162
    if(colDataIsNull_s(pCol, i)) continue;
1,659,268!
4163
    char*        data = colDataGetData(pCol, i);
829,634!
4164
    SSpreadInfo* pInputInfo = (SSpreadInfo*)varDataVal(data);
829,634✔
4165
    if (pInputInfo->hasResult) {
829,634✔
4166
      spreadTransferInfo(pInputInfo, pInfo);
829,393✔
4167
    }
4168
  }
4169

4170
  if (pInfo->hasResult) {
825,453✔
4171
    GET_RES_INFO(pCtx)->numOfRes = 1;
825,278✔
4172
  }
4173

4174
  return TSDB_CODE_SUCCESS;
825,453✔
4175
}
4176

4177
int32_t spreadFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
2,182,305✔
4178
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,182,305✔
4179
  if (pInfo->hasResult == true) {
2,182,305✔
4180
    SET_DOUBLE_VAL(&pInfo->result, pInfo->max - pInfo->min);
2,142,665✔
4181
  } else {
4182
    GET_RES_INFO(pCtx)->isNullRes = 1;
39,640✔
4183
  }
4184
  return functionFinalize(pCtx, pBlock);
2,182,305✔
4185
}
4186

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

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

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

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

4212
_exit:
829,469✔
4213
  taosMemoryFree(res);
829,469✔
4214
  return code;
829,470✔
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) {
108,222✔
4232
  pEnv->calcMemSize = sizeof(SElapsedInfo);
108,222✔
4233
  return true;
108,222✔
4234
}
4235

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

4244
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
13,912,721✔
4245
  pInfo->result = 0;
13,912,721✔
4246
  pInfo->min = TSKEY_MAX;
13,912,721✔
4247
  pInfo->max = 0;
13,912,721✔
4248

4249
  if (pCtx->numOfParams > 1) {
13,912,721✔
4250
    pInfo->timeUnit = pCtx->param[1].param.i;
13,893,616✔
4251
  } else {
4252
    pInfo->timeUnit = 1;
19,105✔
4253
  }
4254

4255
  return TSDB_CODE_SUCCESS;
13,912,721✔
4256
}
4257

4258
int32_t elapsedFunction(SqlFunctionCtx* pCtx) {
13,912,884✔
4259
  int32_t numOfElems = 0;
13,912,884✔
4260

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

4265
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
13,912,884✔
4266

4267
  numOfElems = pInput->numOfRows;  // since this is the primary timestamp, no need to exclude NULL values
13,912,884✔
4268
  if (numOfElems == 0) {
13,912,884✔
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) {
13,912,828!
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) {
13,912,828!
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];
13,912,828✔
4302

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

4312
      if (pCtx->end.key == INT64_MIN) {
784!
4313
        pInfo->min =
784✔
4314
            (pInfo->min > ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->min;
784✔
4315
      } else {
4316
        pInfo->min = pCtx->end.key;
×
4317
      }
4318
    } else {
4319
      if (pCtx->start.key == INT64_MIN) {
13,912,044✔
4320
        pInfo->min = (pInfo->min > ptsList[start]) ? ptsList[start] : pInfo->min;
7,735,317✔
4321
      } else {
4322
        pInfo->min = pCtx->start.key;
6,176,727✔
4323
      }
4324

4325
      if (pCtx->end.key == INT64_MIN) {
13,912,044✔
4326
        pInfo->max =
7,478,664✔
4327
            (pInfo->max < ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->max;
7,478,664✔
4328
      } else {
4329
        pInfo->max = pCtx->end.key + 1;
6,433,380✔
4330
      }
4331
    }
4332
  }
4333

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

4338
  return TSDB_CODE_SUCCESS;
13,912,884✔
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) {
13,897,828✔
4374
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
13,897,828✔
4375
  double        result = (double)pInfo->max - (double)pInfo->min;
13,897,828✔
4376
  result = (result >= 0) ? result : -result;
13,897,828✔
4377
  pInfo->result = result / pInfo->timeUnit;
13,897,828✔
4378
  return functionFinalize(pCtx, pBlock);
13,897,828✔
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,641,924✔
4424
  return (int32_t)sizeof(SHistoFuncInfo) + HISTOGRAM_MAX_BINS_NUM * sizeof(SHistoFuncBin);
2,641,924✔
4425
}
4426

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

4432
static int8_t getHistogramBinType(char* binTypeStr) {
14,670,714✔
4433
  int8_t binType;
4434
  if (strcasecmp(binTypeStr, "user_input") == 0) {
14,670,714✔
4435
    binType = USER_INPUT_BIN;
4,001✔
4436
  } else if (strcasecmp(binTypeStr, "linear_bin") == 0) {
14,666,713✔
4437
    binType = LINEAR_BIN;
2,713✔
4438
  } else if (strcasecmp(binTypeStr, "log_bin") == 0) {
14,664,000!
4439
    binType = LOG_BIN;
14,664,326✔
4440
  } else {
4441
    binType = UNKNOWN_BIN;
×
4442
  }
4443

4444
  return binType;
14,670,714✔
4445
}
4446

4447
static int32_t getHistogramBinDesc(SHistoFuncInfo* pInfo, char* binDescStr, int8_t binType, bool normalized) {
14,670,430✔
4448
  cJSON*  binDesc = cJSON_Parse(binDescStr);
14,670,430✔
4449
  int32_t numOfBins;
4450
  double* intervals;
4451
  if (cJSON_IsObject(binDesc)) { /* linaer/log bins */
14,670,734✔
4452
    int32_t numOfParams = cJSON_GetArraySize(binDesc);
14,666,689✔
4453
    int32_t startIndex;
4454
    if (numOfParams != 4) {
14,666,654!
4455
      cJSON_Delete(binDesc);
×
4456
      return TSDB_CODE_FAILED;
×
4457
    }
4458

4459
    cJSON* start = cJSON_GetObjectItem(binDesc, "start");
14,666,654✔
4460
    cJSON* factor = cJSON_GetObjectItem(binDesc, "factor");
14,666,774✔
4461
    cJSON* width = cJSON_GetObjectItem(binDesc, "width");
14,666,678✔
4462
    cJSON* count = cJSON_GetObjectItem(binDesc, "count");
14,665,478✔
4463
    cJSON* infinity = cJSON_GetObjectItem(binDesc, "infinity");
14,666,400✔
4464

4465
    if (!cJSON_IsNumber(start) || !cJSON_IsNumber(count) || !cJSON_IsBool(infinity)) {
14,666,699!
UNCOV
4466
      cJSON_Delete(binDesc);
×
4467
      return TSDB_CODE_FAILED;
×
4468
    }
4469

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

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

4481
    int32_t counter = (int32_t)count->valueint;
14,666,529✔
4482
    if (infinity->valueint == false) {
14,666,529✔
4483
      startIndex = 0;
14,659,178✔
4484
      numOfBins = counter + 1;
14,659,178✔
4485
    } else {
4486
      startIndex = 1;
7,351✔
4487
      numOfBins = counter + 3;
7,351✔
4488
    }
4489

4490
    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
14,666,529✔
4491
    if (NULL == intervals) {
14,666,935!
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) {
14,666,935!
4497
      // linear bin process
4498
      if (width->valuedouble == 0) {
2,713!
4499
        taosMemoryFree(intervals);
×
4500
        cJSON_Delete(binDesc);
×
4501
        return TSDB_CODE_FAILED;
×
4502
      }
4503
      for (int i = 0; i < counter + 1; ++i) {
26,591✔
4504
        intervals[startIndex] = start->valuedouble + i * width->valuedouble;
23,878✔
4505
        if (isinf(intervals[startIndex])) {
23,878!
4506
          taosMemoryFree(intervals);
×
4507
          cJSON_Delete(binDesc);
×
4508
          return TSDB_CODE_FAILED;
×
4509
        }
4510
        startIndex++;
23,878✔
4511
      }
4512
    } else if (cJSON_IsNumber(factor) && width == NULL && binType == LOG_BIN) {
14,664,159!
4513
      // log bin process
4514
      if (start->valuedouble == 0) {
14,664,144!
4515
        taosMemoryFree(intervals);
×
4516
        cJSON_Delete(binDesc);
×
4517
        return TSDB_CODE_FAILED;
×
4518
      }
4519
      if (factor->valuedouble < 0 || factor->valuedouble == 0 || factor->valuedouble == 1) {
14,664,144!
4520
        taosMemoryFree(intervals);
×
4521
        cJSON_Delete(binDesc);
×
4522
        return TSDB_CODE_FAILED;
×
4523
      }
4524
      for (int i = 0; i < counter + 1; ++i) {
102,636,936✔
4525
        intervals[startIndex] = start->valuedouble * pow(factor->valuedouble, i * 1.0);
87,972,791✔
4526
        if (isinf(intervals[startIndex])) {
87,972,791!
4527
          taosMemoryFree(intervals);
×
4528
          cJSON_Delete(binDesc);
×
4529
          return TSDB_CODE_FAILED;
×
4530
        }
4531
        startIndex++;
87,972,791✔
4532
      }
4533
    } else {
UNCOV
4534
      taosMemoryFree(intervals);
×
4535
      cJSON_Delete(binDesc);
×
4536
      return TSDB_CODE_FAILED;
×
4537
    }
4538

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

4589
  pInfo->numOfBins = numOfBins - 1;
14,670,859✔
4590
  pInfo->normalized = normalized;
14,670,859✔
4591
  for (int32_t i = 0; i < pInfo->numOfBins; ++i) {
88,031,503✔
4592
    pInfo->bins[i].lower = intervals[i] < intervals[i + 1] ? intervals[i] : intervals[i + 1];
73,360,644✔
4593
    pInfo->bins[i].upper = intervals[i + 1] > intervals[i] ? intervals[i + 1] : intervals[i];
73,360,644✔
4594
    pInfo->bins[i].count = 0;
73,360,644✔
4595
  }
4596

4597
  taosMemoryFree(intervals);
14,670,859✔
4598
  cJSON_Delete(binDesc);
14,670,927✔
4599

4600
  return TSDB_CODE_SUCCESS;
14,670,792✔
4601
}
4602

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

4611
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
14,670,734✔
4612
  pInfo->numOfBins = 0;
14,670,734✔
4613
  pInfo->totalCount = 0;
14,670,734✔
4614
  pInfo->normalized = 0;
14,670,734✔
4615

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

4623
  if (binType == UNKNOWN_BIN) {
14,670,448!
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));
14,670,448✔
4627
  if (binDesc == NULL) {
14,670,376!
4628
    return terrno;
×
4629
  }
4630
  int64_t normalized = pCtx->param[3].param.i;
14,670,376✔
4631
  if (normalized != 0 && normalized != 1) {
14,670,376!
4632
    taosMemoryFree(binDesc);
×
4633
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
4634
  }
4635
  int32_t code = getHistogramBinDesc(pInfo, binDesc, binType, (bool)normalized);
14,670,376✔
4636
  if (TSDB_CODE_SUCCESS != code) {
14,670,788!
4637
    taosMemoryFree(binDesc);
×
4638
    return code;
×
4639
  }
4640
  taosMemoryFree(binDesc);
14,670,788✔
4641

4642
  return TSDB_CODE_SUCCESS;
14,670,749✔
4643
}
4644

4645
static int32_t histogramFunctionImpl(SqlFunctionCtx* pCtx, bool isPartial) {
17,277,615✔
4646
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
17,277,615✔
4647

4648
  SInputColumnInfoData* pInput = &pCtx->input;
17,277,615✔
4649
  SColumnInfoData*      pCol = pInput->pData[0];
17,277,615✔
4650

4651
  int32_t type = pInput->pData[0]->info.type;
17,277,615✔
4652

4653
  int32_t start = pInput->startRowIndex;
17,277,615✔
4654
  int32_t numOfRows = pInput->numOfRows;
17,277,615✔
4655

4656
  int32_t numOfElems = 0;
17,277,615✔
4657
  for (int32_t i = start; i < numOfRows + start; ++i) {
61,723,856✔
4658
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
44,446,241✔
4659
      continue;
830,298✔
4660
    }
4661

4662
    numOfElems++;
43,615,943✔
4663

4664
    char*  data = colDataGetData(pCol, i);
43,615,943!
4665
    double v;
4666
    GET_TYPED_DATA(v, double, type, data);
43,615,943!
4667

4668
    for (int32_t k = 0; k < pInfo->numOfBins; ++k) {
241,451,736✔
4669
      if (v > pInfo->bins[k].lower && v <= pInfo->bins[k].upper) {
203,573,538✔
4670
        pInfo->bins[k].count++;
5,737,745✔
4671
        pInfo->totalCount++;
5,737,745✔
4672
        break;
5,737,745✔
4673
      }
4674
    }
4675
  }
4676

4677
  if (!isPartial) {
17,277,615✔
4678
    GET_RES_INFO(pCtx)->numOfRes = pInfo->numOfBins;
12,049,103✔
4679
  } else {
4680
    GET_RES_INFO(pCtx)->numOfRes = 1;
5,228,512✔
4681
  }
4682
  return TSDB_CODE_SUCCESS;
17,277,615✔
4683
}
4684

4685
int32_t histogramFunction(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, false); }
12,049,312✔
4686

4687
int32_t histogramFunctionPartial(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, true); }
5,228,609✔
4688

4689
static void histogramTransferInfo(SHistoFuncInfo* pInput, SHistoFuncInfo* pOutput) {
2,602,883✔
4690
  pOutput->normalized = pInput->normalized;
2,602,883✔
4691
  pOutput->numOfBins = pInput->numOfBins;
2,602,883✔
4692
  pOutput->totalCount += pInput->totalCount;
2,602,883✔
4693
  for (int32_t k = 0; k < pOutput->numOfBins; ++k) {
15,633,155✔
4694
    pOutput->bins[k].lower = pInput->bins[k].lower;
13,030,272✔
4695
    pOutput->bins[k].upper = pInput->bins[k].upper;
13,030,272✔
4696
    pOutput->bins[k].count += pInput->bins[k].count;
13,030,272✔
4697
  }
4698
}
2,602,883✔
4699

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

4707
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,602,883✔
4708

4709
  int32_t start = pInput->startRowIndex;
2,602,883✔
4710

4711
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
5,205,766✔
4712
    char*           data = colDataGetData(pCol, i);
2,602,883!
4713
    SHistoFuncInfo* pInputInfo = (SHistoFuncInfo*)varDataVal(data);
2,602,883✔
4714
    histogramTransferInfo(pInputInfo, pInfo);
2,602,883✔
4715
  }
4716

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

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

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

4733
  if (pInfo->normalized) {
14,563,787✔
4734
    for (int32_t k = 0; k < pResInfo->numOfRes; ++k) {
63,916,920✔
4735
      if (pInfo->totalCount != 0) {
53,264,774✔
4736
        pInfo->bins[k].percentage = pInfo->bins[k].count / (double)pInfo->totalCount;
51,461✔
4737
      } else {
4738
        pInfo->bins[k].percentage = 0;
53,213,313✔
4739
      }
4740
    }
4741
  }
4742

4743
  for (int32_t i = 0; i < pResInfo->numOfRes; ++i) {
87,359,752✔
4744
    int32_t len;
4745
    char    buf[512] = {0};
72,825,532✔
4746
    if (!pInfo->normalized) {
72,825,532✔
4747
      len = tsnprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE, "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%" PRId64 "}",
19,560,758✔
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,
53,264,774✔
4751
                    pInfo->bins[i].upper, pInfo->bins[i].percentage);
4752
    }
4753
    varDataSetLen(buf, len);
72,825,531✔
4754
    code = colDataSetVal(pCol, currentRow, buf, false);
72,825,531✔
4755
    if (TSDB_CODE_SUCCESS != code) {
72,795,965!
4756
      return code;
×
4757
    }
4758
    currentRow++;
72,795,965✔
4759
  }
4760

4761
  return code;
14,534,220✔
4762
}
4763

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

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

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

4785
_exit:
2,635,432✔
4786
  taosMemoryFree(res);
2,635,432✔
4787
  return code;
2,635,434✔
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,622✔
4804

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

4810
static uint8_t hllCountNum(void* data, int32_t bytes, int32_t* buk) {
4,886,120✔
4811
  uint64_t hash = MurmurHash3_64(data, bytes);
4,886,120✔
4812
  int32_t  index = hash & HLL_BUCKET_MASK;
4,884,957✔
4813
  hash >>= HLL_BUCKET_BITS;
4,884,957✔
4814
  hash |= ((uint64_t)1 << HLL_DATA_BITS);
4,884,957✔
4815
  uint64_t bit = 1;
4,884,957✔
4816
  uint8_t  count = 1;
4,884,957✔
4817
  while ((hash & bit) == 0) {
9,298,963✔
4818
    count++;
4,414,006✔
4819
    bit <<= 1;
4,414,006✔
4820
  }
4821
  *buk = index;
4,884,957✔
4822
  return count;
4,884,957✔
4823
}
4824

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

4829
  for (int32_t j = 0; j < HLL_BUCKETS >> 3; j++) {
494,220,101✔
4830
    if (*word == 0) {
493,974,487✔
4831
      bucketHisto[0] += 8;
492,905,712✔
4832
    } else {
4833
      bytes = (uint8_t*)word;
1,068,775✔
4834
      bucketHisto[bytes[0]]++;
1,068,775✔
4835
      bucketHisto[bytes[1]]++;
1,068,775✔
4836
      bucketHisto[bytes[2]]++;
1,068,775✔
4837
      bucketHisto[bytes[3]]++;
1,068,775✔
4838
      bucketHisto[bytes[4]]++;
1,068,775✔
4839
      bucketHisto[bytes[5]]++;
1,068,775✔
4840
      bucketHisto[bytes[6]]++;
1,068,775✔
4841
      bucketHisto[bytes[7]]++;
1,068,775✔
4842
    }
4843
    word++;
493,974,487✔
4844
  }
4845
}
245,614✔
4846
static double hllTau(double x) {
245,615✔
4847
  if (x == 0. || x == 1.) return 0.;
245,615!
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) {
245,629✔
4861
  if (x == 1.0) return INFINITY;
245,629✔
4862
  double zPrime;
4863
  double y = 1;
214,467✔
4864
  double z = x;
214,467✔
4865
  do {
4866
    x *= x;
4,193,365✔
4867
    zPrime = z;
4,193,365✔
4868
    z += x * y;
4,193,365✔
4869
    y += y;
4,193,365✔
4870
  } while (zPrime != z);
4,193,365✔
4871
  return z;
214,467✔
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) {
245,580✔
4877
  double  m = HLL_BUCKETS;
245,580✔
4878
  int32_t buckethisto[64] = {0};
245,580✔
4879
  hllBucketHisto(buckets, buckethisto);
245,580✔
4880

4881
  double z = m * hllTau((m - buckethisto[HLL_DATA_BITS + 1]) / (double)m);
245,615✔
4882
  for (int j = HLL_DATA_BITS; j >= 1; --j) {
12,522,579✔
4883
    z += buckethisto[j];
12,276,949✔
4884
    z *= 0.5;
12,276,949✔
4885
  }
4886

4887
  z += m * hllSigma(buckethisto[0] / (double)m);
245,630✔
4888
  double E = (double)llroundl(HLL_ALPHA_INF * m * m / z);
245,636✔
4889

4890
  return (uint64_t)E;
245,636✔
4891
}
4892

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

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

4899
  int32_t type = pCol->info.type;
270,241✔
4900
  int32_t bytes = pCol->info.bytes;
270,241✔
4901

4902
  int32_t start = pInput->startRowIndex;
270,241✔
4903
  int32_t numOfRows = pInput->numOfRows;
270,241✔
4904

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

4910
  for (int32_t i = start; i < numOfRows + start; ++i) {
6,455,410✔
4911
    if (pCol->hasNull && colDataIsNull_s(pCol, i)) {
8,548,149!
4912
      continue;
1,299,478✔
4913
    }
4914

4915
    numOfElems++;
4,888,611✔
4916

4917
    char* data = colDataGetData(pCol, i);
4,888,611!
4918
    if (IS_VAR_DATA_TYPE(type)) {
4,888,611!
4919
      bytes = varDataLen(data);
1,249,541✔
4920
      data = varDataVal(data);
1,249,541✔
4921
    }
4922

4923
    int32_t index = 0;
4,888,611✔
4924
    uint8_t count = hllCountNum(data, bytes, &index);
4,888,611✔
4925
    uint8_t oldcount = pInfo->buckets[index];
4,887,399✔
4926
    if (count > oldcount) {
4,887,399✔
4927
      pInfo->buckets[index] = count;
1,102,859✔
4928
    }
4929
  }
4930

4931
_hll_over:
267,321✔
4932
  pInfo->totalCount += numOfElems;
269,029✔
4933

4934
  if (pInfo->totalCount == 0 && !tsCountAlwaysReturnValue) {
269,029✔
4935
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
3,693✔
4936
  } else {
4937
    SET_VAL(GET_RES_INFO(pCtx), 1, 1);
265,336✔
4938
  }
4939

4940
  return TSDB_CODE_SUCCESS;
269,029✔
4941
}
4942

4943
static void hllTransferInfo(SHLLInfo* pInput, SHLLInfo* pOutput) {
10,916✔
4944
  for (int32_t k = 0; k < HLL_BUCKETS; ++k) {
175,136,623✔
4945
    if (pOutput->buckets[k] < pInput->buckets[k]) {
175,125,707✔
4946
      pOutput->buckets[k] = pInput->buckets[k];
133,103✔
4947
    }
4948
  }
4949
  pOutput->totalCount += pInput->totalCount;
10,916✔
4950
}
10,916✔
4951

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

4956
  if (IS_NULL_TYPE(pCol->info.type)) {
10,859!
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,859!
4962
    return TSDB_CODE_SUCCESS;
×
4963
  }
4964

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

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

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

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

4982
  return TSDB_CODE_SUCCESS;
10,862✔
4983
}
4984

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

4988
  SHLLInfo* pHllInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
245,584✔
4989
  pHllInfo->result = hllCountCnt(pHllInfo->buckets);
245,584✔
4990
  if (tsCountAlwaysReturnValue && pHllInfo->result == 0) {
245,638✔
4991
    pInfo->numOfRes = 1;
27,506✔
4992
  }
4993

4994
  return functionFinalize(pCtx, pBlock);
245,638✔
4995
}
4996

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

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

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

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

5019
_exit:
10,623✔
5020
  taosMemoryFree(res);
10,623✔
5021
  return code;
10,624✔
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) {
22,553✔
5038
  pEnv->calcMemSize = sizeof(SStateInfo);
22,553✔
5039
  return true;
22,553✔
5040
}
5041

5042
static int8_t getStateOpType(char* opStr) {
40,899✔
5043
  int8_t opType;
5044
  if (strncasecmp(opStr, "LT", 2) == 0) {
40,899✔
5045
    opType = STATE_OPER_LT;
2,021✔
5046
  } else if (strncasecmp(opStr, "GT", 2) == 0) {
38,878✔
5047
    opType = STATE_OPER_GT;
1,540✔
5048
  } else if (strncasecmp(opStr, "LE", 2) == 0) {
37,338✔
5049
    opType = STATE_OPER_LE;
992✔
5050
  } else if (strncasecmp(opStr, "GE", 2) == 0) {
36,346✔
5051
    opType = STATE_OPER_GE;
25,480✔
5052
  } else if (strncasecmp(opStr, "NE", 2) == 0) {
10,866✔
5053
    opType = STATE_OPER_NE;
2,791✔
5054
  } else if (strncasecmp(opStr, "EQ", 2) == 0) {
8,075!
5055
    opType = STATE_OPER_EQ;
8,075✔
5056
  } else {
5057
    opType = STATE_OPER_INVALID;
×
5058
  }
5059

5060
  return opType;
40,899✔
5061
}
5062

5063
static bool checkStateOp(int8_t op, SColumnInfoData* pCol, int32_t index, SVariant param) {
34,783,025✔
5064
  char* data = colDataGetData(pCol, index);
34,783,025!
5065
  switch (pCol->info.type) {
34,783,025!
5066
    case TSDB_DATA_TYPE_TINYINT: {
5,199,142✔
5067
      int8_t v = *(int8_t*)data;
5,199,142✔
5068
      STATE_COMP(op, v, param);
5,199,142!
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: {
37,112✔
5077
      int16_t v = *(int16_t*)data;
37,112✔
5078
      STATE_COMP(op, v, param);
37,112!
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: {
9,524✔
5087
      int32_t v = *(int32_t*)data;
9,524✔
5088
      STATE_COMP(op, v, param);
9,524!
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: {
72,368✔
5097
      int64_t v = *(int64_t*)data;
72,368✔
5098
      STATE_COMP(op, v, param);
72,368!
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: {
29,433,886✔
5107
      float v = *(float*)data;
29,433,886✔
5108
      STATE_COMP(op, v, param);
29,433,886!
5109
      break;
×
5110
    }
5111
    case TSDB_DATA_TYPE_DOUBLE: {
7,956✔
5112
      double v = *(double*)data;
7,956✔
5113
      STATE_COMP(op, v, param);
7,956!
5114
      break;
×
5115
    }
5116
    default: {
×
5117
      return false;
×
5118
    }
5119
  }
5120
  return false;
×
5121
}
5122

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

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

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

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

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

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

5148
    pInfo->isPrevTsSet = true;
29,799,298✔
5149
    numOfElems++;
29,799,298✔
5150

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

5163
    bool ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
29,450,383✔
5164

5165
    int64_t output = -1;
29,450,384✔
5166
    if (ret) {
29,450,384✔
5167
      output = ++pInfo->count;
9,255,369✔
5168
    } else {
5169
      pInfo->count = 0;
20,195,015✔
5170
    }
5171
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
29,450,384✔
5172
    if (TSDB_CODE_SUCCESS != code) {
29,450,379!
5173
      return code;
×
5174
    }
5175

5176
    // handle selectivity
5177
    if (pCtx->subsidiaries.num > 0) {
29,450,379✔
5178
      code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
20,051,152✔
5179
      if (TSDB_CODE_SUCCESS != code) {
20,051,152!
5180
        return code;
×
5181
      }
5182
    }
5183
  }
5184

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

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

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

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

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

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

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

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

5220
    pInfo->isPrevTsSet = true;
5,732,914✔
5221
    numOfElems++;
5,732,914✔
5222

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

5235
    bool    ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
5,332,642✔
5236
    int64_t output = -1;
5,332,642✔
5237
    if (ret) {
5,332,642✔
5238
      if (pInfo->durationStart == 0) {
75,053✔
5239
        output = 0;
19,931✔
5240
        pInfo->durationStart = tsList[i];
19,931✔
5241
      } else {
5242
        output = (tsList[i] - pInfo->durationStart) / timeUnit;
55,122✔
5243
      }
5244
    } else {
5245
      pInfo->durationStart = 0;
5,257,589✔
5246
    }
5247
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
5,332,642✔
5248
    if (TSDB_CODE_SUCCESS != code) {
5,332,642!
5249
      return code;
×
5250
    }
5251

5252
    // handle selectivity
5253
    if (pCtx->subsidiaries.num > 0) {
5,332,642✔
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;
14,058✔
5262
  return TSDB_CODE_SUCCESS;
14,058✔
5263
}
5264

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

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

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

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

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

5292
    int32_t pos = startOffset + numOfElems;
3,992,259✔
5293
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
3,992,259✔
5294
      // colDataSetNULL(pOutput, i);
5295
      continue;
416,707✔
5296
    }
5297

5298
    char* data = colDataGetData(pInputCol, i);
3,575,552!
5299
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
7,065,784!
5300
      int64_t v;
5301
      GET_TYPED_DATA(v, int64_t, type, data);
3,490,232!
5302
      pSumRes->isum += v;
3,490,232✔
5303
      code = colDataSetVal(pOutput, pos, (char*)&pSumRes->isum, false);
3,490,232✔
5304
      if (TSDB_CODE_SUCCESS != code) {
3,490,232!
5305
        return code;
×
5306
      }
5307
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
86,000!
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)) {
84,640!
5316
      double v;
5317
      GET_TYPED_DATA(v, double, type, data);
85,700!
5318
      pSumRes->dsum += v;
85,700✔
5319
      // check for overflow
5320
      if (isinf(pSumRes->dsum) || isnan(pSumRes->dsum)) {
85,700!
5321
        colDataSetNULL(pOutput, pos);
8!
5322
      } else {
5323
        code = colDataSetVal(pOutput, pos, (char*)&pSumRes->dsum, false);
85,692✔
5324
        if (TSDB_CODE_SUCCESS != code) {
85,692!
5325
          return code;
×
5326
        }
5327
      }
5328
    }
5329

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

5338
    numOfElems++;
3,575,552✔
5339
  }
5340

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

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

5350
int32_t mavgFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
271,138✔
5351
  if (pResultInfo->initialized) {
271,138✔
5352
    return TSDB_CODE_SUCCESS;
256,398✔
5353
  }
5354
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
14,740!
5355
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5356
  }
5357

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

5369
  return TSDB_CODE_SUCCESS;
14,740✔
5370
}
5371

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

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

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

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

5395
    int32_t pos = startOffset + numOfElems;
59,126,802✔
5396
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
59,126,802✔
5397
      // colDataSetNULL(pOutput, i);
5398
      continue;
360,441✔
5399
    }
5400

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

5405
    if (!pInfo->pointsMeet && (pInfo->pos < pInfo->numOfPoints - 1)) {
58,766,361✔
5406
      pInfo->points[pInfo->pos] = v;
4,322,219✔
5407
      pInfo->sum += v;
4,322,219✔
5408
    } else {
5409
      if (!pInfo->pointsMeet && (pInfo->pos == pInfo->numOfPoints - 1)) {
54,444,142!
5410
        pInfo->sum += v;
10,789✔
5411
        pInfo->pointsMeet = true;
10,789✔
5412
      } else {
5413
        pInfo->sum = pInfo->sum + v - pInfo->points[pInfo->pos];
54,433,353✔
5414
      }
5415

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

5428
      // handle selectivity
5429
      if (pCtx->subsidiaries.num > 0) {
54,444,156✔
5430
        code = appendSelectivityValue(pCtx, i, pos);
34,124,871✔
5431
        if (TSDB_CODE_SUCCESS != code) {
34,124,871!
5432
          return code;
×
5433
        }
5434
      }
5435

5436
      numOfElems++;
54,444,156✔
5437
    }
5438

5439
    pInfo->pos++;
58,766,375✔
5440
    if (pInfo->pos == pInfo->numOfPoints) {
58,766,375✔
5441
      pInfo->pos = 0;
318,517✔
5442
    }
5443
  }
5444

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

5449
static SSampleInfo* getSampleOutputInfo(SqlFunctionCtx* pCtx) {
14,202,721✔
5450
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
14,202,721✔
5451
  SSampleInfo*         pInfo = GET_ROWCELL_INTERBUF(pResInfo);
14,202,721✔
5452

5453
  pInfo->data = (char*)pInfo + sizeof(SSampleInfo);
14,202,721✔
5454
  pInfo->tuplePos = (STuplePos*)((char*)pInfo + sizeof(SSampleInfo) + pInfo->samples * pInfo->colBytes);
14,202,721✔
5455

5456
  return pInfo;
14,202,721✔
5457
}
5458

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

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

5475
  taosSeedRand(taosSafeRand());
7,115,681✔
5476

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

5488
  return TSDB_CODE_SUCCESS;
7,115,682✔
5489
}
5490

5491
static void sampleAssignResult(SSampleInfo* pInfo, char* data, int32_t index) {
13,547,702✔
5492
  assignVal(pInfo->data + index * pInfo->colBytes, data, pInfo->colBytes, pInfo->colType);
13,547,702✔
5493
}
13,547,633✔
5494

5495
static int32_t doReservoirSample(SqlFunctionCtx* pCtx, SSampleInfo* pInfo, char* data, int32_t index) {
16,500,951✔
5496
  pInfo->totalPoints++;
16,500,951✔
5497
  if (pInfo->numSampled < pInfo->samples) {
16,500,951✔
5498
    sampleAssignResult(pInfo, data, pInfo->numSampled);
11,920,671✔
5499
    if (pCtx->subsidiaries.num > 0) {
11,920,616✔
5500
      int32_t code = saveTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[pInfo->numSampled]);
1,020,969✔
5501
      if (code != TSDB_CODE_SUCCESS) {
1,021,040!
5502
        return code;
×
5503
      }
5504
    }
5505
    pInfo->numSampled++;
11,920,687✔
5506
  } else {
5507
    int32_t j = taosRand() % (pInfo->totalPoints);
4,580,280✔
5508
    if (j < pInfo->samples) {
4,581,409✔
5509
      sampleAssignResult(pInfo, data, j);
1,627,455✔
5510
      if (pCtx->subsidiaries.num > 0) {
1,627,442✔
5511
        int32_t code = updateTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[j]);
849,528✔
5512
        if (code != TSDB_CODE_SUCCESS) {
848,777!
5513
          return code;
×
5514
        }
5515
      }
5516
    }
5517
  }
5518

5519
  return TSDB_CODE_SUCCESS;
16,501,332✔
5520
}
5521

5522
int32_t sampleFunction(SqlFunctionCtx* pCtx) {
7,195,662✔
5523
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
7,195,662✔
5524
  SSampleInfo*         pInfo = getSampleOutputInfo(pCtx);
7,195,662✔
5525

5526
  SInputColumnInfoData* pInput = &pCtx->input;
7,195,662✔
5527

5528
  SColumnInfoData* pInputCol = pInput->pData[0];
7,195,662✔
5529
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
24,315,216✔
5530
    if (colDataIsNull_s(pInputCol, i)) {
34,238,076✔
5531
      continue;
618,334✔
5532
    }
5533

5534
    char*   data = colDataGetData(pInputCol, i);
16,500,704!
5535
    int32_t code = doReservoirSample(pCtx, pInfo, data, i);
16,500,704✔
5536
    if (code != TSDB_CODE_SUCCESS) {
16,501,220!
5537
      return code;
×
5538
    }
5539
  }
5540

5541
  if (pInfo->numSampled == 0 && pCtx->subsidiaries.num > 0 && !pInfo->nullTupleSaved) {
7,196,178✔
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);
7,196,178✔
5550
  return TSDB_CODE_SUCCESS;
7,196,178✔
5551
}
5552

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

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

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

5566
  int32_t currentRow = pBlock->info.rows;
7,007,060✔
5567
  if (pInfo->numSampled == 0) {
7,007,060✔
5568
    colDataSetNULL(pCol, currentRow);
3,584✔
5569
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
3,584✔
5570
    return code;
3,583✔
5571
  }
5572
  for (int32_t i = 0; i < pInfo->numSampled; ++i) {
18,733,028✔
5573
    code = colDataSetVal(pCol, currentRow + i, pInfo->data + i * pInfo->colBytes, false);
11,729,710✔
5574
    if (TSDB_CODE_SUCCESS != code) {
11,729,424!
5575
      return code;
×
5576
    }
5577
    code = setSelectivityValue(pCtx, pBlock, &pInfo->tuplePos[i], currentRow + i);
11,729,424✔
5578
    if (TSDB_CODE_SUCCESS != code) {
11,729,552!
5579
      return code;
×
5580
    }
5581
  }
5582

5583
  return code;
7,003,318✔
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) {
24,967✔
5825
  pEnv->calcMemSize = sizeof(SModeInfo);
24,967✔
5826
  return true;
24,967✔
5827
}
5828

5829
int32_t modeFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
25,960✔
5830
  if (pResInfo->initialized) {
25,960!
5831
    return TSDB_CODE_SUCCESS;
×
5832
  }
5833
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
25,960!
5834
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5835
  }
5836

5837
  SModeInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
25,960✔
5838
  pInfo->colType = pCtx->resDataInfo.type;
25,960✔
5839
  pInfo->colBytes = pCtx->resDataInfo.bytes;
25,960✔
5840
  if (pInfo->pHash != NULL) {
25,960!
5841
    taosHashClear(pInfo->pHash);
×
5842
  } else {
5843
    pInfo->pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
25,960✔
5844
    if (NULL == pInfo->pHash) {
25,959!
5845
      return terrno;
×
5846
    }
5847
  }
5848
  pInfo->nullTupleSaved = false;
25,959✔
5849
  pInfo->nullTuplePos.pageId = -1;
25,959✔
5850

5851
  pInfo->buf = taosMemoryMalloc(pInfo->colBytes);
25,959✔
5852
  if (NULL == pInfo->buf) {
25,960✔
5853
    taosHashCleanup(pInfo->pHash);
1✔
5854
    pInfo->pHash = NULL;
×
5855
    return terrno;
×
5856
  }
5857
  pCtx->needCleanup = true;
25,959✔
5858
  return TSDB_CODE_SUCCESS;
25,959✔
5859
}
5860

5861
static void modeFunctionCleanup(SModeInfo * pInfo) {
25,960✔
5862
  taosHashCleanup(pInfo->pHash);
25,960✔
5863
  pInfo->pHash = NULL;
25,961✔
5864
  taosMemoryFreeClear(pInfo->buf);
25,961!
5865
}
25,961✔
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) {
76,433,136✔
5875
  if (IS_VAR_DATA_TYPE(pInfo->colType)) {
76,433,136!
5876
    (void)memcpy(pInfo->buf, data, varDataTLen(data));
11,184,577✔
5877
  } else {
5878
    (void)memcpy(pInfo->buf, data, pInfo->colBytes);
65,248,559✔
5879
  }
5880

5881
  return doSaveTupleData(&pCtx->saveHandle, pInfo->buf, pInfo->colBytes, NULL, pPos, pCtx->pStore);
76,433,136✔
5882
}
5883

5884
static int32_t doModeAdd(SModeInfo* pInfo, int32_t rowIndex, SqlFunctionCtx* pCtx, char* data) {
122,939,080✔
5885
  int32_t code = TSDB_CODE_SUCCESS;
122,939,080✔
5886
  int32_t hashKeyBytes = IS_STR_DATA_TYPE(pInfo->colType) ? varDataTLen(data) : pInfo->colBytes;
122,939,080✔
5887

5888
  SModeItem* pHashItem = (SModeItem *)taosHashGet(pInfo->pHash, data, hashKeyBytes);
122,939,080✔
5889
  if (pHashItem == NULL) {
122,938,696✔
5890
    int32_t    size = sizeof(SModeItem);
76,433,120✔
5891
    SModeItem  item = {0};
76,433,120✔
5892

5893
    item.count += 1;
76,433,120✔
5894
    code = saveModeTupleData(pCtx, data, pInfo, &item.dataPos);
76,433,120✔
5895
    if (code != TSDB_CODE_SUCCESS) {
76,433,055!
5896
      return code;
×
5897
    }
5898

5899
    if (pCtx->subsidiaries.num > 0) {
76,433,055✔
5900
      code = saveTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &item.tuplePos);
51,137,362✔
5901
      if (code != TSDB_CODE_SUCCESS) {
51,137,362!
5902
        return code;
×
5903
      }
5904
    }
5905

5906
    code = taosHashPut(pInfo->pHash, data, hashKeyBytes, &item, sizeof(SModeItem));
76,433,055✔
5907
    if (code != TSDB_CODE_SUCCESS) {
76,433,613!
5908
      return code;
×
5909
    }
5910
  } else {
5911
    pHashItem->count += 1;
46,505,576✔
5912
    if (pCtx->subsidiaries.num > 0) {
46,505,576✔
5913
      code = updateTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &pHashItem->tuplePos);
29,584,023✔
5914
      if (code != TSDB_CODE_SUCCESS) {
29,584,023!
5915
        return code;
×
5916
      }
5917
    }
5918
  }
5919

5920
  return code;
122,939,189✔
5921
}
5922

5923
int32_t modeFunction(SqlFunctionCtx* pCtx) {
2,514,414✔
5924
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,514,414✔
5925
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,514,414✔
5926

5927
  SInputColumnInfoData* pInput = &pCtx->input;
2,514,414✔
5928

5929
  SColumnInfoData* pInputCol = pInput->pData[0];
2,514,414✔
5930
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
2,514,414✔
5931

5932
  int32_t numOfElems = 0;
2,514,414✔
5933
  int32_t startOffset = pCtx->offset;
2,514,414✔
5934
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
126,276,712✔
5935
    if (colDataIsNull_s(pInputCol, i)) {
247,524,560✔
5936
      continue;
823,182✔
5937
    }
5938
    numOfElems++;
122,939,098✔
5939

5940
    char*   data = colDataGetData(pInputCol, i);
122,939,098✔
5941
    int32_t code = doModeAdd(pInfo, i, pCtx, data);
122,939,098✔
5942
    if (code != TSDB_CODE_SUCCESS) {
122,939,182✔
5943
      modeFunctionCleanup(pInfo);
66✔
5944
      return code;
×
5945
    }
5946
  }
5947

5948
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pInfo->nullTupleSaved) {
2,514,432!
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,514,432✔
5958

5959
  return TSDB_CODE_SUCCESS;
2,514,432✔
5960
}
5961

5962
int32_t modeFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
25,959✔
5963
  int32_t              code = TSDB_CODE_SUCCESS;
25,959✔
5964
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
25,959✔
5965
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
25,959✔
5966
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
25,959✔
5967
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
25,959✔
5968
  int32_t              currentRow = pBlock->info.rows;
25,959✔
5969
  if (NULL == pCol) {
25,959!
5970
    modeFunctionCleanup(pInfo);
×
5971
    return TSDB_CODE_OUT_OF_RANGE;
×
5972
  }
5973

5974
  STuplePos resDataPos, resTuplePos;
5975
  int32_t maxCount = 0;
25,959✔
5976

5977
  void *pIter = taosHashIterate(pInfo->pHash, NULL);
25,959✔
5978
  while (pIter != NULL) {
76,459,573✔
5979
    SModeItem *pItem = (SModeItem *)pIter;
76,433,614✔
5980
    if (pItem->count >= maxCount) {
76,433,614✔
5981
      maxCount = pItem->count;
57,257,015✔
5982
      resDataPos = pItem->dataPos;
57,257,015✔
5983
      resTuplePos = pItem->tuplePos;
57,257,015✔
5984
    }
5985

5986
    pIter = taosHashIterate(pInfo->pHash, pIter);
76,433,614✔
5987
  }
5988

5989
  if (maxCount != 0) {
25,959✔
5990
    char* pData = NULL;
21,495✔
5991
    code = loadTupleData(pCtx, &resDataPos, &pData);
21,495✔
5992
    if (pData == NULL || TSDB_CODE_SUCCESS != code) {
21,495!
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,495✔
6001
    if (TSDB_CODE_SUCCESS != code) {
21,495!
6002
      modeFunctionCleanup(pInfo);
×
6003
     return code;
×
6004
    }
6005
    code = setSelectivityValue(pCtx, pBlock, &resTuplePos, currentRow);
21,495✔
6006
  } else {
6007
    colDataSetNULL(pCol, currentRow);
4,464✔
6008
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
4,464✔
6009
  }
6010

6011
  modeFunctionCleanup(pInfo);
25,960✔
6012

6013
  return code;
25,961✔
6014
}
6015

6016
bool getTwaFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
80,205✔
6017
  pEnv->calcMemSize = sizeof(STwaInfo);
80,205✔
6018
  return true;
80,205✔
6019
}
6020

6021
int32_t twaFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
11,976,828✔
6022
  if (pResultInfo->initialized) {
11,976,828!
6023
    return TSDB_CODE_SUCCESS;
×
6024
  }
6025
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
11,976,828!
6026
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6027
  }
6028

6029
  STwaInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
11,976,817✔
6030
  pInfo->numOfElems = 0;
11,976,817✔
6031
  pInfo->p.key = INT64_MIN;
11,976,817✔
6032
  pInfo->win = TSWINDOW_INITIALIZER;
11,976,817✔
6033
  return TSDB_CODE_SUCCESS;
11,976,817✔
6034
}
6035

6036
static double twa_get_area(SPoint1 s, SPoint1 e) {
35,784,012✔
6037
  if (e.key == INT64_MAX || s.key == INT64_MIN) {
35,784,012!
6038
    return 0;
×
6039
  }
6040

6041
  if ((s.val >= 0 && e.val >= 0) || (s.val <= 0 && e.val <= 0)) {
35,784,378✔
6042
    return (s.val + e.val) * (e.key - s.key) / 2;
18,922,509✔
6043
  }
6044

6045
  double x = (s.key * e.val - e.key * s.val) / (e.val - s.val);
16,861,869✔
6046
  double val = (s.val * (x - s.key) + e.val * (e.key - x)) / 2;
16,861,869✔
6047
  return val;
16,861,869✔
6048
}
6049

6050
int32_t twaFunction(SqlFunctionCtx* pCtx) {
11,983,094✔
6051
  int32_t               code = TSDB_CODE_SUCCESS;
11,983,094✔
6052
  SInputColumnInfoData* pInput = &pCtx->input;
11,983,094✔
6053
  SColumnInfoData*      pInputCol = pInput->pData[0];
11,983,094✔
6054

6055
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
11,983,094✔
6056
  STwaInfo*            pInfo = GET_ROWCELL_INTERBUF(pResInfo);
11,983,094✔
6057
  SPoint1*             last = &pInfo->p;
11,983,094✔
6058

6059
  if (IS_NULL_TYPE(pInputCol->info.type)) {
11,983,094!
6060
    pInfo->numOfElems = 0;
×
6061
    goto _twa_over;
×
6062
  }
6063

6064
  funcInputUpdate(pCtx);
11,983,094✔
6065
  SFuncInputRow row = {0};
11,983,147✔
6066
  bool          result = false;
11,983,147✔
6067
  if (pCtx->start.key != INT64_MIN && last->key == INT64_MIN) {
11,983,147!
6068
    while (1) {
6069
      code = funcInputGetNextRow(pCtx, &row, &result);
4,383,827✔
6070
      if (TSDB_CODE_SUCCESS != code) {
4,383,818!
6071
        return code;
×
6072
      }
6073
      if (!result) {
4,383,818✔
6074
        break;
2✔
6075
      }
6076
      if (row.isDataNull) {
4,383,816✔
6077
        continue;
2✔
6078
      }
6079

6080
      last->key = row.ts;
4,383,814✔
6081

6082
      GET_TYPED_DATA(last->val, double, pInputCol->info.type, row.pData);
4,383,814!
6083

6084
      pInfo->dOutput += twa_get_area(pCtx->start, *last);
4,383,814✔
6085
      pInfo->win.skey = pCtx->start.key;
4,383,812✔
6086
      pInfo->numOfElems++;
4,383,812✔
6087
      break;
4,383,812✔
6088
    }
6089
  } else if (pInfo->p.key == INT64_MIN) {
7,599,322✔
6090
    while (1) {
6091
      code = funcInputGetNextRow(pCtx, &row, &result);
7,714,866✔
6092
      if (TSDB_CODE_SUCCESS != code) {
7,714,655!
6093
        return code;
×
6094
      }
6095
      if (!result) {
7,714,655✔
6096
        break;
14,328✔
6097
      }
6098
      if (row.isDataNull) {
7,700,327✔
6099
        continue;
121,397✔
6100
      }
6101

6102
      last->key = row.ts;
7,578,930✔
6103

6104
      GET_TYPED_DATA(last->val, double, pInputCol->info.type, row.pData);
7,578,930!
6105

6106
      pInfo->win.skey = last->key;
7,578,930✔
6107
      pInfo->numOfElems++;
7,578,930✔
6108
      break;
7,578,930✔
6109
    }
6110
  }
6111

6112
  SPoint1 st = {0};
11,982,925✔
6113

6114
  // calculate the value of
6115
  while (1) {
6116
    code = funcInputGetNextRow(pCtx, &row, &result);
38,888,412✔
6117
    if (TSDB_CODE_SUCCESS != code) {
38,887,943!
6118
      return code;
×
6119
    }
6120
    if (!result) {
38,887,943✔
6121
      break;
11,983,007✔
6122
    }
6123
    if (row.isDataNull) {
26,904,936✔
6124
      continue;
630✔
6125
    }
6126
    pInfo->numOfElems++;
26,904,306✔
6127
    switch (pInputCol->info.type) {
26,904,306!
6128
      case TSDB_DATA_TYPE_TINYINT: {
22,714,627✔
6129
        INIT_INTP_POINT(st, row.ts, *(int8_t*)row.pData);
22,714,627✔
6130
        break;
22,714,627✔
6131
      }
6132
      case TSDB_DATA_TYPE_SMALLINT: {
3,553,277✔
6133
        INIT_INTP_POINT(st, row.ts, *(int16_t*)row.pData);
3,553,277✔
6134
        break;
3,553,277✔
6135
      }
6136
      case TSDB_DATA_TYPE_INT: {
118,279✔
6137
        INIT_INTP_POINT(st, row.ts, *(int32_t*)row.pData);
118,279✔
6138
        break;
118,279✔
6139
      }
6140
      case TSDB_DATA_TYPE_BIGINT: {
98,781✔
6141
        INIT_INTP_POINT(st, row.ts, *(int64_t*)row.pData);
98,781✔
6142
        break;
98,781✔
6143
      }
6144
      case TSDB_DATA_TYPE_FLOAT: {
70,476✔
6145
        INIT_INTP_POINT(st, row.ts, *(float_t*)row.pData);
70,476✔
6146
        break;
70,476✔
6147
      }
6148
      case TSDB_DATA_TYPE_DOUBLE: {
82,251✔
6149
        INIT_INTP_POINT(st, row.ts, *(double*)row.pData);
82,251✔
6150
        break;
82,251✔
6151
      }
6152
      case TSDB_DATA_TYPE_UTINYINT: {
68,649✔
6153
        INIT_INTP_POINT(st, row.ts, *(uint8_t*)row.pData);
68,649✔
6154
        break;
68,649✔
6155
      }
6156
      case TSDB_DATA_TYPE_USMALLINT: {
68,811✔
6157
        INIT_INTP_POINT(st, row.ts, *(uint16_t*)row.pData);
68,811✔
6158
        break;
68,811✔
6159
      }
6160
      case TSDB_DATA_TYPE_UINT: {
70,803✔
6161
        INIT_INTP_POINT(st, row.ts, *(uint32_t*)row.pData);
70,803✔
6162
        break;
70,803✔
6163
      }
6164
      case TSDB_DATA_TYPE_UBIGINT: {
58,828✔
6165
        INIT_INTP_POINT(st, row.ts, *(uint64_t*)row.pData);
58,828✔
6166
        break;
58,828✔
6167
      }
UNCOV
6168
      default: {
×
UNCOV
6169
        return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
6170
      }
6171
    }
6172
    if (pInfo->p.key == st.key) {
26,904,782!
6173
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6174
    }
6175

6176
    pInfo->dOutput += twa_get_area(pInfo->p, st);
26,904,782✔
6177
    pInfo->p = st;
26,904,857✔
6178
  }
6179

6180
  // the last interpolated time window value
6181
  if (pCtx->end.key != INT64_MIN) {
11,983,007✔
6182
    pInfo->dOutput += twa_get_area(pInfo->p, pCtx->end);
4,496,535✔
6183
    pInfo->p = pCtx->end;
4,496,537✔
6184
    pInfo->numOfElems += 1;
4,496,537✔
6185
  }
6186

6187
  pInfo->win.ekey = pInfo->p.key;
11,983,009✔
6188

6189
_twa_over:
11,983,009✔
6190
  SET_VAL(pResInfo, 1, 1);
11,983,009✔
6191
  return TSDB_CODE_SUCCESS;
11,983,009✔
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) {
11,964,556✔
6207
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
11,964,556✔
6208

6209
  STwaInfo* pInfo = (STwaInfo*)GET_ROWCELL_INTERBUF(pResInfo);
11,964,556✔
6210
  if (pInfo->numOfElems == 0) {
11,964,556✔
6211
    pResInfo->numOfRes = 0;
14,134✔
6212
  } else {
6213
    if (pInfo->win.ekey == pInfo->win.skey) {
11,950,422✔
6214
      pInfo->dTwaRes = pInfo->p.val;
6,203,847✔
6215
    } else if (pInfo->win.ekey == INT64_MAX || pInfo->win.skey == INT64_MIN) {  // no data in timewindow
5,746,575!
6216
      pInfo->dTwaRes = 0;
×
6217
    } else {
6218
      pInfo->dTwaRes = pInfo->dOutput / (pInfo->win.ekey - pInfo->win.skey);
5,746,827✔
6219
    }
6220

6221
    pResInfo->numOfRes = 1;
11,950,422✔
6222
  }
6223

6224
  return functionFinalize(pCtx, pBlock);
11,964,556✔
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,496✔
6282
  SEncoder encoder = {0};
6,496✔
6283
  int32_t  code = 0;
6,496✔
6284
  int32_t  lino;
6285
  int32_t  tlen;
6286
  tEncoderInit(&encoder, buf, bufLen);
6,496✔
6287

6288
  TAOS_CHECK_EXIT(tStartEncode(&encoder));
6,498!
6289
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->rowSize));
12,996!
6290

6291
  TAOS_CHECK_EXIT(tEncodeU16(&encoder, pInfo->numOfFiles));
12,996!
6292
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfBlocks));
12,996!
6293
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfTables));
12,996!
6294

6295
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalSize));
12,996!
6296
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalRows));
12,996!
6297
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->maxRows));
12,996!
6298
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->minRows));
12,996!
6299
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMaxRows));
12,996!
6300
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMinRows));
12,996!
6301
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfInmemRows));
12,996!
6302
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfSttRows));
12,996!
6303
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfVgroups));
12,996!
6304

6305
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
136,272✔
6306
    TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->blockRowsHisto[i]));
259,548!
6307
  }
6308

6309
  tEndEncode(&encoder);
6,498✔
6310

6311
_exit:
6,498✔
6312
  if (code) {
6,498!
6313
    tlen = code;
×
6314
  } else {
6315
    tlen = encoder.pos;
6,498✔
6316
  }
6317
  tEncoderClear(&encoder);
6,498✔
6318
  return tlen;
6,497✔
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,230✔
6472
  pEnv->calcMemSize = sizeof(SDerivInfo);
31,230✔
6473
  return true;
31,230✔
6474
}
6475

6476
int32_t derivativeFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
85,428✔
6477
  if (pResInfo->initialized) {
85,428✔
6478
    return TSDB_CODE_SUCCESS;
54,040✔
6479
  }
6480
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
31,388!
6481
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6482
  }
6483

6484
  SDerivInfo* pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
31,388✔
6485

6486
  pDerivInfo->ignoreNegative = pCtx->param[2].param.i;
31,388✔
6487
  pDerivInfo->prevTs = -1;
31,388✔
6488
  pDerivInfo->tsWindow = pCtx->param[1].param.i;
31,388✔
6489
  pDerivInfo->valueSet = false;
31,388✔
6490
  return TSDB_CODE_SUCCESS;
31,388✔
6491
}
6492

6493
int32_t derivativeFunction(SqlFunctionCtx* pCtx) {
54,198✔
6494
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
54,198✔
6495
  SDerivInfo*          pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
54,198✔
6496

6497
  SInputColumnInfoData* pInput = &pCtx->input;
54,198✔
6498
  SColumnInfoData*      pInputCol = pInput->pData[0];
54,198✔
6499

6500
  int32_t          numOfElems = 0;
54,198✔
6501
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
54,198✔
6502
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
54,198✔
6503
  int32_t          code = TSDB_CODE_SUCCESS;
54,198✔
6504

6505
  funcInputUpdate(pCtx);
54,198✔
6506

6507
  double v = 0;
54,198✔
6508
  if (pCtx->order == TSDB_ORDER_ASC) {
54,198✔
6509
    SFuncInputRow row = {0};
50,811✔
6510
    bool result = false;
50,811✔
6511
    while (1) {
2,745,711✔
6512
      code = funcInputGetNextRow(pCtx, &row, &result);
2,796,522✔
6513
      if (TSDB_CODE_SUCCESS != code) {
2,796,522!
6514
        return code;
×
6515
      }
6516
      if (!result) {
2,796,522✔
6517
        break;
50,811✔
6518
      }
6519
      if (row.isDataNull) {
2,745,711✔
6520
        continue;
42,734✔
6521
      }
6522

6523
      char* d = row.pData;
2,702,977✔
6524
      GET_TYPED_DATA(v, double, pInputCol->info.type, d);
2,702,977!
6525

6526
      int32_t pos = pCtx->offset + numOfElems;
2,702,977✔
6527
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
2,702,977✔
6528
        pDerivInfo->valueSet = true;
27,582✔
6529
      } else {
6530
        if (row.ts == pDerivInfo->prevTs) {
2,675,395!
6531
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6532
        }
6533
        double r = ((v - pDerivInfo->prevValue) * pDerivInfo->tsWindow) / (row.ts - pDerivInfo->prevTs);
2,675,395✔
6534
        if (pDerivInfo->ignoreNegative && r < 0) {
2,675,395✔
6535
        } else {
6536
          if (isinf(r) || isnan(r)) {
1,487,805!
6537
            colDataSetNULL(pOutput, pos);
×
6538
          } else {
6539
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
1,487,805✔
6540
            if (code != TSDB_CODE_SUCCESS) {
1,487,805!
6541
              return code;
×
6542
            }
6543
          }
6544

6545
          if (pTsOutput != NULL) {
1,487,805!
6546
            colDataSetInt64(pTsOutput, pos, &row.ts);
×
6547
          }
6548

6549
          // handle selectivity
6550
          if (pCtx->subsidiaries.num > 0) {
1,487,805✔
6551
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
1,044,655✔
6552
            if (code != TSDB_CODE_SUCCESS) {
1,044,655!
6553
              return code;
×
6554
            }
6555
          }
6556

6557
          numOfElems++;
1,487,805✔
6558
        }
6559
      }
6560

6561
      pDerivInfo->prevValue = v;
2,702,977✔
6562
      pDerivInfo->prevTs = row.ts;
2,702,977✔
6563
    }
6564
  } else {
6565
    SFuncInputRow row = {0};
3,387✔
6566
    bool          result = false;
3,387✔
6567
    while (1) {
335,373✔
6568
      code = funcInputGetNextRow(pCtx, &row, &result);
338,760✔
6569
      if (TSDB_CODE_SUCCESS != code) {
338,760!
6570
        return code;
×
6571
      }
6572
      if (!result) {
338,760✔
6573
        break;
3,387✔
6574
      }
6575
      if (row.isDataNull) {
335,373✔
6576
        continue;
163✔
6577
      }
6578

6579
      char* d = row.pData;
335,210✔
6580
      GET_TYPED_DATA(v, double, pInputCol->info.type, d);
335,210!
6581

6582
      int32_t pos = pCtx->offset + numOfElems;
335,210✔
6583
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
335,210✔
6584
        pDerivInfo->valueSet = true;
3,357✔
6585
      } else {
6586
        if (row.ts == pDerivInfo->prevTs) {
331,853!
6587
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6588
        }
6589
        double r = ((pDerivInfo->prevValue - v) * pDerivInfo->tsWindow) / (pDerivInfo->prevTs - row.ts);
331,853✔
6590
        if (pDerivInfo->ignoreNegative && r < 0) {
331,853✔
6591
        } else {
6592
          if (isinf(r) || isnan(r)) {
262,574!
6593
            colDataSetNULL(pOutput, pos);
×
6594
          } else {
6595
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
262,574✔
6596
            if (code != TSDB_CODE_SUCCESS) {
262,574!
6597
              return code;
×
6598
            }
6599
          }
6600

6601
          if (pTsOutput != NULL) {
262,574!
6602
            colDataSetInt64(pTsOutput, pos, &pDerivInfo->prevTs);
×
6603
          }
6604

6605
          // handle selectivity
6606
          if (pCtx->subsidiaries.num > 0) {
262,574✔
6607
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
80,114✔
6608
            if (code != TSDB_CODE_SUCCESS) {
80,114!
6609
              return code;
×
6610
            }
6611
          }
6612
          numOfElems++;
262,574✔
6613
        }
6614
      }
6615

6616
      pDerivInfo->prevValue = v;
335,210✔
6617
      pDerivInfo->prevTs = row.ts;
335,210✔
6618
    }
6619
  }
6620

6621
  pResInfo->numOfRes = numOfElems;
54,198✔
6622

6623
  return TSDB_CODE_SUCCESS;
54,198✔
6624
}
6625

6626
int32_t getIrateInfoSize(int32_t pkBytes) { return (int32_t)sizeof(SRateInfo) + 2 * pkBytes; }
2,170,086✔
6627

6628
bool getIrateFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
121,878✔
6629
  int32_t pkBytes = (pFunc->hasPk) ? pFunc->pkBytes : 0;
121,878✔
6630
  pEnv->calcMemSize = getIrateInfoSize(pkBytes);
121,878✔
6631
  return true;
122,120✔
6632
}
6633

6634
int32_t irateFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
13,125,917✔
6635
  if (pResInfo->initialized) {
13,125,917!
6636
    return TSDB_CODE_SUCCESS;
×
6637
  }
6638
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
13,125,917!
6639
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6640
  }
6641

6642
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
13,125,917✔
6643

6644
  pInfo->firstKey = INT64_MIN;
13,125,917✔
6645
  pInfo->lastKey = INT64_MIN;
13,125,917✔
6646
  pInfo->firstValue = (double)INT64_MIN;
13,125,917✔
6647
  pInfo->lastValue = (double)INT64_MIN;
13,125,917✔
6648

6649
  pInfo->hasResult = 0;
13,125,917✔
6650
  return TSDB_CODE_SUCCESS;
13,125,917✔
6651
}
6652

6653
static void doSaveRateInfo(SRateInfo* pRateInfo, bool isFirst, int64_t ts, char* pk, double v) {
56,974,494✔
6654
  if (isFirst) {
56,974,494✔
6655
    pRateInfo->firstValue = v;
22,956,167✔
6656
    pRateInfo->firstKey = ts;
22,956,167✔
6657
    if (pRateInfo->firstPk) {
22,956,167✔
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;
34,018,327✔
6663
    pRateInfo->lastKey = ts;
34,018,327✔
6664
    if (pRateInfo->lastPk) {
34,018,327✔
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
}
56,974,494✔
6670

6671
static void initializeRateInfo(SqlFunctionCtx* pCtx, SRateInfo* pRateInfo, bool isMerge) {
15,190,602✔
6672
  if (pCtx->hasPrimaryKey) {
15,190,602✔
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;
15,190,583✔
6684
    pRateInfo->lastPk = NULL;
15,190,583✔
6685
  }  
6686
}
15,190,602✔
6687

6688
int32_t irateFunction(SqlFunctionCtx* pCtx) {
11,094,814✔
6689
  int32_t              code = TSDB_CODE_SUCCESS;
11,094,814✔
6690
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
11,094,814✔
6691
  SRateInfo*           pRateInfo = GET_ROWCELL_INTERBUF(pResInfo);
11,094,814✔
6692

6693
  SInputColumnInfoData* pInput = &pCtx->input;
11,094,814✔
6694
  SColumnInfoData*      pInputCol = pInput->pData[0];
11,094,814✔
6695

6696
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
11,094,814✔
6697

6698
  funcInputUpdate(pCtx);
11,094,814✔
6699
  
6700
  initializeRateInfo(pCtx, pRateInfo, false);
11,094,823✔
6701

6702
  int32_t numOfElems = 0;
11,094,797✔
6703
  int32_t type = pInputCol->info.type;
11,094,797✔
6704
  SFuncInputRow row = {0};
11,094,797✔
6705
  bool          result = false;
11,094,797✔
6706
  while (1)  {
32,245,380✔
6707
    code = funcInputGetNextRow(pCtx, &row, &result);
43,340,177✔
6708
    if (TSDB_CODE_SUCCESS != code) {
43,338,976!
6709
      return code;
×
6710
    }
6711
    if (!result) {
43,338,976✔
6712
      break;
11,094,749✔
6713
    }
6714
    if (row.isDataNull) {
32,244,227✔
6715
      continue;
130,281✔
6716
    }
6717

6718
    char*  data = row.pData;
32,113,946✔
6719
    double v = 0;
32,113,946✔
6720
    GET_TYPED_DATA(v, double, type, data);
32,113,946!
6721

6722
    if (INT64_MIN == pRateInfo->lastKey) {
32,113,946✔
6723
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
11,064,037✔
6724
      pRateInfo->hasResult = 1;
11,064,026✔
6725
      continue;
11,064,026✔
6726
    }
6727

6728
    if (row.ts > pRateInfo->lastKey) {
21,049,909✔
6729
      if ((INT64_MIN == pRateInfo->firstKey) || pRateInfo->lastKey > pRateInfo->firstKey) {
20,907,800!
6730
        doSaveRateInfo(pRateInfo, true, pRateInfo->lastKey, pRateInfo->lastPk, pRateInfo->lastValue);
20,907,803✔
6731
      }
6732
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
20,907,828✔
6733
      continue;
20,907,755✔
6734
    } else if (row.ts == pRateInfo->lastKey) {
142,109!
6735
        return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6736
    }
6737
    
6738

6739
    if ((INT64_MIN == pRateInfo->firstKey) || row.ts > pRateInfo->firstKey) {
142,109!
6740
      doSaveRateInfo(pRateInfo, true, row.ts, row.pPk, v);    
×
6741
    } else if (row.ts == pRateInfo->firstKey) {
143,433!
6742
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6743
    }
6744
  }
6745

6746
  numOfElems++;
11,094,749✔
6747
  
6748
  SET_VAL(pResInfo, numOfElems, 1);
11,094,749!
6749
  return TSDB_CODE_SUCCESS;
11,094,749✔
6750
}
6751

6752
static double doCalcRate(const SRateInfo* pRateInfo, double tickPerSec) {
11,075,547✔
6753
  if ((INT64_MIN == pRateInfo->lastKey) || (INT64_MIN == pRateInfo->firstKey) ||
11,075,547✔
6754
      (pRateInfo->firstKey >= pRateInfo->lastKey)) {
3,818,438!
6755
    return 0.0;
7,257,108✔
6756
  }
6757

6758
  double diff = 0;
3,818,439✔
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;
3,818,439✔
6762
  if (diff >= pRateInfo->firstValue) {
3,818,439✔
6763
    diff -= pRateInfo->firstValue;
1,696,638✔
6764
  }
6765

6766
  int64_t duration = pRateInfo->lastKey - pRateInfo->firstKey;
3,818,439✔
6767
  if (duration == 0) {
3,818,439!
6768
    return 0;
×
6769
  }
6770

6771
  return (duration > 0) ? ((double)diff) / (duration / tickPerSec) : 0.0;
3,818,439!
6772
}
6773

6774
static void irateTransferInfoImpl(TSKEY inputKey, SRateInfo* pInput, SRateInfo* pOutput, bool isFirstKey) {
290✔
6775
  if (inputKey > pOutput->lastKey) {
290✔
6776
    doSaveRateInfo(pOutput, true, pOutput->lastKey, pOutput->lastPk, pOutput->lastValue);
114✔
6777
    if (isFirstKey) {
114✔
6778
      doSaveRateInfo(pOutput, false, pInput->firstKey, pInput->firstPk, pInput->firstValue);
50✔
6779
    } else {
6780
      doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
64✔
6781
    }
6782
  } else if ((inputKey < pOutput->lastKey) && (inputKey > pOutput->firstKey)) {
176!
6783
    if (isFirstKey) {
32✔
6784
      doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
16✔
6785
    } else {
6786
      doSaveRateInfo(pOutput, true, pInput->lastKey, pInput->lastPk, pInput->lastValue);
16✔
6787
    }
6788
  } else {
6789
    // inputKey < pOutput->firstKey
6790
  }
6791
}
290✔
6792

6793
static void irateCopyInfo(SRateInfo* pInput, SRateInfo* pOutput) {
2,047,741✔
6794
  doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
2,047,741✔
6795
  doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
2,047,741✔
6796
}
2,047,741✔
6797

6798
static int32_t irateTransferInfo(SRateInfo* pInput, SRateInfo* pOutput) {
2,047,886✔
6799
  if ((pInput->firstKey != INT64_MIN && (pInput->firstKey == pOutput->firstKey || pInput->firstKey == pOutput->lastKey)) ||
2,047,886!
6800
      (pInput->lastKey != INT64_MIN && (pInput->lastKey  == pOutput->firstKey || pInput->lastKey  == pOutput->lastKey))) {
2,047,886!
6801
    return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6802
  }
6803

6804
  if (pOutput->hasResult == 0) {
2,047,886✔
6805
    irateCopyInfo(pInput, pOutput);
2,047,741✔
6806
    pOutput->hasResult = pInput->hasResult;
2,047,741✔
6807
    return TSDB_CODE_SUCCESS;
2,047,741✔
6808
  }
6809

6810
  if (pInput->firstKey != INT64_MIN) {
145!
6811
    irateTransferInfoImpl(pInput->firstKey, pInput, pOutput, true);
145✔
6812
  }
6813

6814
  if (pInput->lastKey != INT64_MIN) {
145!
6815
    irateTransferInfoImpl(pInput->lastKey, pInput, pOutput, false);
145✔
6816
  }
6817

6818
  pOutput->hasResult = pInput->hasResult;
145✔
6819
  return TSDB_CODE_SUCCESS;
145✔
6820
}
6821

6822
int32_t irateFunctionMerge(SqlFunctionCtx* pCtx) {
2,047,898✔
6823
  SInputColumnInfoData* pInput = &pCtx->input;
2,047,898✔
6824
  SColumnInfoData*      pCol = pInput->pData[0];
2,047,898✔
6825
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
2,047,898!
6826
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
6827
  }
6828

6829
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,047,898✔
6830
  initializeRateInfo(pCtx, pInfo, true);
2,047,898✔
6831

6832
  int32_t start = pInput->startRowIndex;
2,047,898✔
6833
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
4,095,796✔
6834
    char*        data = colDataGetData(pCol, i);
2,047,898!
6835
    SRateInfo*   pInputInfo = (SRateInfo*)varDataVal(data);
2,047,898✔
6836
    initializeRateInfo(pCtx, pInfo, true);
2,047,898✔
6837
    if (pInputInfo->hasResult) {
2,047,898✔
6838
      int32_t code = irateTransferInfo(pInputInfo, pInfo);
2,047,886✔
6839
      if (code != TSDB_CODE_SUCCESS) {
2,047,886!
6840
        return code;
×
6841
      }
6842
    }
6843
  }
6844

6845
  if (pInfo->hasResult) {
2,047,898✔
6846
    GET_RES_INFO(pCtx)->numOfRes = 1;
2,047,886✔
6847
  }
6848

6849
  return TSDB_CODE_SUCCESS;
2,047,898✔
6850
}
6851

6852
int32_t iratePartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
2,047,898✔
6853
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,047,898✔
6854
  SRateInfo*           pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,047,898✔
6855
  int32_t              resultBytes = getIrateInfoSize(pInfo->pkBytes);
2,047,898✔
6856
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
2,047,898✔
6857

6858
  if (NULL == res) {
2,047,898!
6859
    return terrno;
×
6860
  }
6861
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
2,047,898✔
6862
  varDataSetLen(res, resultBytes);
2,047,898✔
6863

6864
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
2,047,898✔
6865
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
2,047,898✔
6866
  if (NULL == pCol) {
2,047,898!
6867
      taosMemoryFree(res);
×
6868
      return TSDB_CODE_OUT_OF_RANGE;
×
6869
  }
6870

6871
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
2,047,898✔
6872

6873
  taosMemoryFree(res);
2,047,898✔
6874
  return code;
2,047,898✔
6875
}
6876

6877
int32_t irateFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
11,075,572✔
6878
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
11,075,572✔
6879
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
11,075,572✔
6880
  if (NULL == pCol) {
11,075,544!
6881
    return TSDB_CODE_OUT_OF_RANGE;
×
6882
  }
6883

6884
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
11,075,544✔
6885
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
11,075,544✔
6886

6887
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
11,075,544✔
6888
  double     result = doCalcRate(pInfo, (double)TSDB_TICK_PER_SECOND(pCtx->param[1].param.i));
11,075,544!
6889
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, (const char*)&result, pResInfo->isNullRes);
11,075,556✔
6890

6891
  return code;
11,075,566✔
6892
}
6893

6894
int32_t groupConstValueFunction(SqlFunctionCtx* pCtx) {
106,075,045✔
6895
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
106,075,045✔
6896
  SGroupKeyInfo*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
106,075,045✔
6897

6898
  SInputColumnInfoData* pInput = &pCtx->input;
106,075,045✔
6899
  SColumnInfoData*      pInputCol = pInput->pData[0];
106,075,045✔
6900

6901
  int32_t startIndex = pInput->startRowIndex;
106,075,045✔
6902

6903
  // escape rest of data blocks to avoid first entry to be overwritten.
6904
  if (pInfo->hasResult) {
106,075,045✔
6905
    goto _group_value_over;
10,695,982✔
6906
  }
6907

6908
  if (pInputCol->pData == NULL || colDataIsNull_s(pInputCol, startIndex)) {
190,338,867✔
6909
    pInfo->isNull = true;
2,671,697✔
6910
    pInfo->hasResult = true;
2,671,697✔
6911
    goto _group_value_over;
2,671,697✔
6912
  }
6913

6914
  char* data = colDataGetData(pInputCol, startIndex);
92,707,366!
6915
  if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
92,707,366!
6916
    (void)memcpy(pInfo->data, data,
72,799,499✔
6917
                 (pInputCol->info.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(data) : varDataTLen(data));
72,799,499✔
6918
  } else {
6919
    (void)memcpy(pInfo->data, data, pInputCol->info.bytes);
19,907,867✔
6920
  }
6921
  pInfo->hasResult = true;
92,707,366✔
6922

6923
_group_value_over:
106,075,045✔
6924

6925
  SET_VAL(pResInfo, 1, 1);
106,075,045✔
6926
  return TSDB_CODE_SUCCESS;
106,075,045✔
6927
}
6928

6929
int32_t groupKeyFunction(SqlFunctionCtx* pCtx) {
105,820,481✔
6930
  return groupConstValueFunction(pCtx);
105,820,481✔
6931
}
6932

6933
int32_t groupConstValueFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
93,526,088✔
6934
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
93,526,088✔
6935
  int32_t          code = TSDB_CODE_SUCCESS;
93,526,088✔
6936
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
93,526,088✔
6937
  if (NULL == pCol) {
93,470,949!
6938
    return TSDB_CODE_OUT_OF_RANGE;
×
6939
  }
6940

6941
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
93,470,949✔
6942

6943
  SGroupKeyInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
93,470,949✔
6944

6945
  if (pInfo->hasResult) {
93,470,949!
6946
    int32_t currentRow = pBlock->info.rows;
93,498,407✔
6947
    for (; currentRow < pBlock->info.rows + pResInfo->numOfRes; ++currentRow) {
187,536,674✔
6948
      code = colDataSetVal(pCol, currentRow, pInfo->data, pInfo->isNull ? true : false);
93,516,819✔
6949
      if (TSDB_CODE_SUCCESS != code) {
94,038,267!
6950
        return code;
×
6951
      }
6952
    }
6953
  } else {
6954
    pResInfo->numOfRes = 0;
×
6955
  }
6956

6957
  return code;
93,992,397✔
6958
}
6959

6960
int32_t groupKeyFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock){
93,297,347✔
6961
  return groupConstValueFinalize(pCtx, pBlock);
93,297,347✔
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) {
7,743✔
6998
  int32_t numOfElems = 0;
7,743✔
6999

7000
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
7,743✔
7001
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
7,743✔
7002

7003
  SInputColumnInfoData* pInput = &pCtx->input;
7,743✔
7004
  SColumnInfoData*      pInputCol = pInput->pData[0];
7,743✔
7005

7006
  int32_t bytes = pInputCol->info.bytes;
7,743✔
7007
  pInfo->bytes = bytes;
7,743✔
7008

7009
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
7,743✔
7010
  pInfo->pkType = -1;
7,743✔
7011
  __compar_fn_t  pkCompareFn = NULL;
7,743✔
7012
  if (pCtx->hasPrimaryKey) {
7,743✔
7013
    pInfo->pkType = pkCol->info.type;
2,525✔
7014
    pInfo->pkBytes = pkCol->info.bytes;
2,525✔
7015
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
2,525✔
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) {
15,499✔
7021
    numOfElems++;
7,754✔
7022

7023
    bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
7,754✔
7024
    char* data = isNull ? NULL : colDataGetData(pInputCol, i);
7,754!
7025

7026
    TSKEY cts = getRowPTs(pInput->pPTS, i);
7,754!
7027
    if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
7,754✔
7028
      int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
5,705✔
7029
      if (code != TSDB_CODE_SUCCESS) {
5,706!
7030
        return code;
×
7031
      }
7032
      pResInfo->numOfRes = 1;
5,706✔
7033
    }
7034
  }
7035

7036
  SET_VAL(pResInfo, numOfElems, 1);
7,745!
7037
  return TSDB_CODE_SUCCESS;
7,745✔
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