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

taosdata / TDengine / #3627

02 Mar 2025 11:16PM UTC coverage: 63.596% (-0.2%) from 63.764%
#3627

push

travis-ci

GitHub
Merge pull request #29973 from taosdata/doc/internal

148665 of 299855 branches covered (49.58%)

Branch coverage included in aggregate %.

233076 of 300407 relevant lines covered (77.59%)

17543856.65 hits per line

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

71.96
/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) { return (ignoreOption & 0x1) == 0x1; }
1,542,574,386✔
32
bool ignoreNull(int8_t ignoreOption) { return (ignoreOption & 0x2) == 0x2; }
1,867,629✔
33

34
typedef enum {
35
  APERCT_ALGO_UNKNOWN = 0,
36
  APERCT_ALGO_DEFAULT,
37
  APERCT_ALGO_TDIGEST,
38
} EAPerctAlgoType;
39

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

42
typedef enum {
43
  STATE_OPER_INVALID = 0,
44
  STATE_OPER_LT,
45
  STATE_OPER_GT,
46
  STATE_OPER_LE,
47
  STATE_OPER_GE,
48
  STATE_OPER_NE,
49
  STATE_OPER_EQ,
50
} EStateOperType;
51

52
#define SET_VAL(_info, numOfElem, res) \
53
  do {                                 \
54
    if ((numOfElem) <= 0) {            \
55
      break;                           \
56
    }                                  \
57
    (_info)->numOfRes = (res);         \
58
  } while (0)
59

60
#define GET_TS_LIST(x)    ((TSKEY*)((x)->ptsList))
61
#define GET_TS_DATA(x, y) (GET_TS_LIST(x)[(y)])
62

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

75
#define UPDATE_DATA(ctx, left, right, num, sign, _ts) \
76
  do {                                                \
77
    if (((left) < (right)) ^ (sign)) {                \
78
      (left) = (right);                               \
79
      DO_UPDATE_SUBSID_RES(ctx, _ts);                 \
80
      (num) += 1;                                     \
81
    }                                                 \
82
  } while (0)
83

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

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

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

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

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

148
#define LEASTSQR_CAL(p, x, y, index, step) \
149
  do {                                     \
150
    (p)[0][0] += (double)(x) * (x);        \
151
    (p)[0][1] += (double)(x);              \
152
    (p)[0][2] += (double)(x) * (y)[index]; \
153
    (p)[1][2] += (y)[index];               \
154
    (x) += step;                           \
155
  } while (0)
156

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

159
#define GET_STATE_VAL(param) ((param.nType == TSDB_DATA_TYPE_BIGINT) ? (param.i) : (param.d))
160

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

187
#define INIT_INTP_POINT(_p, _k, _v) \
188
  do {                              \
189
    (_p).key = (_k);                \
190
    (_p).val = (_v);                \
191
  } while (0)
192

193
void funcInputUpdate(SqlFunctionCtx* pCtx) {
12,578,504✔
194
  SFuncInputRowIter* pIter = &pCtx->rowIter;
12,578,504✔
195

196
  if (!pCtx->bInputFinished) {
12,578,504!
197
    pIter->pInput = &pCtx->input;
12,578,545✔
198
    pIter->tsList = (TSKEY*)pIter->pInput->pPTS->pData;
12,578,545✔
199
    pIter->pDataCol = pIter->pInput->pData[0];
12,578,545✔
200
    pIter->pPkCol = pIter->pInput->pPrimaryKey;
12,578,545✔
201
    pIter->rowIndex = pIter->pInput->startRowIndex;
12,578,545✔
202
    pIter->inputEndIndex = pIter->rowIndex + pIter->pInput->numOfRows - 1;
12,578,545✔
203
    pIter->pSrcBlock = pCtx->pSrcBlock;
12,578,545✔
204
    if (!pIter->hasGroupId || pIter->groupId != pIter->pSrcBlock->info.id.groupId) {
12,578,545✔
205
      pIter->hasGroupId = true;
184,733✔
206
      pIter->groupId = pIter->pSrcBlock->info.id.groupId;
184,733✔
207
      pIter->hasPrev = false;
184,733✔
208
    }
209
  } else {
210
    pIter->finalRow = true;
×
211
  }
212
}
12,578,504✔
213

214
int32_t funcInputGetNextRowDescPk(SFuncInputRowIter* pIter, SFuncInputRow* pRow, bool* res) {
×
215
  if (pIter->finalRow) {
×
216
    if (pIter->hasPrev) {
×
217
      pRow->ts = pIter->prevBlockTsEnd;
×
218
      pRow->isDataNull = pIter->prevIsDataNull;
×
219
      pRow->pData = pIter->pPrevData;
×
220
      pRow->block = pIter->pPrevRowBlock;
×
221
      pRow->rowIndex = 0;
×
222

223
      pIter->hasPrev = false;
×
224
      *res = true;
×
225
      return TSDB_CODE_SUCCESS;
×
226
    } else {
227
      *res = false;
×
228
      return TSDB_CODE_SUCCESS;
×
229
    }
230
  }
231
  if (pIter->hasPrev) {
×
232
    if (pIter->prevBlockTsEnd == pIter->tsList[pIter->inputEndIndex]) {
×
233
      blockDataDestroy(pIter->pPrevRowBlock);
×
234
      int32_t code = blockDataExtractBlock(pIter->pSrcBlock, pIter->inputEndIndex, 1, &pIter->pPrevRowBlock);
×
235
      if (code) {
×
236
        return code;
×
237
      }
238

239
      pIter->prevIsDataNull = colDataIsNull_f(pIter->pDataCol->nullbitmap, pIter->inputEndIndex);
×
240

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

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

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

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

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

328
static void forwardToNextDiffTsRow(SFuncInputRowIter* pIter, int32_t rowIndex) {
162✔
329
  int32_t idx = rowIndex + 1;
162✔
330
  while (idx <= pIter->inputEndIndex && pIter->tsList[idx] == pIter->tsList[rowIndex]) {
364!
331
    ++idx;
202✔
332
  }
333
  pIter->rowIndex = idx;
162✔
334
}
162✔
335

336
static void setInputRowInfo(SFuncInputRow* pRow, SFuncInputRowIter* pIter, int32_t rowIndex, bool setPk) {
1,560,231,126✔
337
  pRow->ts = pIter->tsList[rowIndex];
1,560,231,126✔
338
  pRow->ts = pIter->tsList[rowIndex];
1,560,231,126✔
339
  pRow->isDataNull = colDataIsNull_f(pIter->pDataCol->nullbitmap, rowIndex);
1,560,231,126✔
340
  pRow->pData = colDataGetData(pIter->pDataCol, rowIndex);
1,560,231,126!
341
  pRow->pPk = setPk ? colDataGetData(pIter->pPkCol, rowIndex) : NULL;
1,560,231,126!
342
  pRow->block = pIter->pSrcBlock;
1,560,231,126✔
343
  pRow->rowIndex = rowIndex;
1,560,231,126✔
344
}
1,560,231,126✔
345

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

357
      pIter->hasPrev = false;
×
358
      setInputRowInfo(pRow, pIter, idx, true);
×
359
      forwardToNextDiffTsRow(pIter, idx);
×
360
      return true;
×
361
    }
362
  } else {
363
    if (pIter->rowIndex <= pIter->inputEndIndex) {
332✔
364
      setInputRowInfo(pRow, pIter, pIter->rowIndex, true);
250✔
365

366
      TSKEY tsEnd = pIter->tsList[pIter->inputEndIndex];
250✔
367
      if (pIter->tsList[pIter->rowIndex] != tsEnd) {
250✔
368
        forwardToNextDiffTsRow(pIter, pIter->rowIndex);
162✔
369
      } else {
370
        pIter->rowIndex = pIter->inputEndIndex + 1;
88✔
371
      }
372
      return true;
250✔
373
    } else {
374
      TSKEY tsEnd = pIter->tsList[pIter->inputEndIndex];
82✔
375
      pIter->hasPrev = true;
82✔
376
      pIter->prevBlockTsEnd = tsEnd;
82✔
377
      return false;
82✔
378
    }
379
  }
380
}
381

382
bool funcInputGetNextRowNoPk(SFuncInputRowIter* pIter, SFuncInputRow* pRow) {
1,572,706,415✔
383
  if (pIter->rowIndex <= pIter->inputEndIndex) {
1,572,706,415✔
384
    setInputRowInfo(pRow, pIter, pIter->rowIndex, false);
1,560,215,066✔
385
    ++pIter->rowIndex;
1,560,308,605✔
386
    return true;
1,560,308,605✔
387
  } else {
388
    return false;
12,491,349✔
389
  }
390
}
391

392
int32_t funcInputGetNextRow(SqlFunctionCtx* pCtx, SFuncInputRow* pRow, bool* res) {
1,572,658,018✔
393
  SFuncInputRowIter* pIter = &pCtx->rowIter;
1,572,658,018✔
394
  if (pCtx->hasPrimaryKey) {
1,572,658,018✔
395
    if (pCtx->order == TSDB_ORDER_ASC) {
332!
396
      *res = funcInputGetNextRowAscPk(pIter, pRow);
332✔
397
      return TSDB_CODE_SUCCESS;
332✔
398
    } else {
399
      return funcInputGetNextRowDescPk(pIter, pRow, res);
×
400
    }
401
  } else {
402
    *res = funcInputGetNextRowNoPk(pIter, pRow);
1,572,657,686✔
403
    return TSDB_CODE_SUCCESS;
1,572,766,017✔
404
  }
405
  return TSDB_CODE_SUCCESS;
406
}
407

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

415
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
63,393,190✔
416
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
31,696,595✔
417

418
    // get data from source col
419
    SFunctParam* pFuncParam = &pc->pExpr->base.pParam[0];
31,696,595✔
420
    int32_t      srcSlotId = pFuncParam->pCol->slotId;
31,696,595✔
421

422
    SColumnInfoData* pSrcCol = taosArrayGet(pSrcBlock->pDataBlock, srcSlotId);
31,696,595✔
423
    if (NULL == pSrcCol) {
31,696,595!
424
      return TSDB_CODE_OUT_OF_RANGE;
×
425
    }
426

427
    char* pData = colDataGetData(pSrcCol, rowIndex);
31,696,595!
428

429
    // append to dest col
430
    int32_t dstSlotId = pc->pExpr->base.resSchema.slotId;
31,696,595✔
431

432
    SColumnInfoData* pDstCol = taosArrayGet(pCtx->pDstBlock->pDataBlock, dstSlotId);
31,696,595✔
433
    if (NULL == pDstCol) {
31,696,595!
434
      return TSDB_CODE_OUT_OF_RANGE;
×
435
    }
436
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
63,393,190✔
437
      colDataSetNULL(pDstCol, pos);
20!
438
    } else {
439
      int32_t code = colDataSetVal(pDstCol, pos, pData, false);
31,696,575✔
440
      if (TSDB_CODE_SUCCESS != code) {
31,696,575!
441
        return code;
×
442
      }
443
    }
444
  }
445
  return TSDB_CODE_SUCCESS;
31,696,595✔
446
}
447

448
bool funcInputGetNextRowIndex(SInputColumnInfoData* pInput, int32_t from, bool firstOccur, int32_t* pRowIndex,
449
                              int32_t* nextFrom);
450

451
static bool firstLastTransferInfoImpl(SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst);
452

453
int32_t functionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
770,995,511✔
454
  if (pResultInfo->initialized) {
770,995,511✔
455
    return TSDB_CODE_SUCCESS;  // already initialized
62,406✔
456
  }
457

458
  if (pCtx->pOutput != NULL) {
770,933,105!
459
    (void)memset(pCtx->pOutput, 0, (size_t)pCtx->resDataInfo.bytes);
×
460
  }
461

462
  initResultRowEntry(pResultInfo, pCtx->resDataInfo.interBufSize);
770,933,105✔
463
  return TSDB_CODE_SUCCESS;
770,933,105✔
464
}
465

466
int32_t functionFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
180,261,849✔
467
  int32_t          code = TSDB_CODE_SUCCESS;
180,261,849✔
468
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
180,261,849✔
469
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
180,261,849✔
470
  if (NULL == pCol) {
179,863,757!
471
    return TSDB_CODE_OUT_OF_RANGE;
×
472
  }
473
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
179,863,757✔
474
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
179,863,757✔
475

476
  char* in = GET_ROWCELL_INTERBUF(pResInfo);
179,863,757✔
477
  code = colDataSetVal(pCol, pBlock->info.rows, in, pResInfo->isNullRes);
179,863,757✔
478

479
  return code;
181,144,033✔
480
}
481

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

487
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
3✔
488
  SFirstLastRes*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
3✔
489

490
  pDBuf->hasResult = firstLastTransferInfoImpl(pSBuf, pDBuf, true);
3✔
491

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

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

506
  char*   in = finalResult;
39✔
507
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, in, pResInfo->isNullRes);
39✔
508

509
  return code;
39✔
510
}
511

512
EFuncDataRequired countDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
217,389✔
513
  SNode* pParam = nodesListGetNode(pFunc->pParameterList, 0);
217,389✔
514
  if (QUERY_NODE_COLUMN == nodeType(pParam) && PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)pParam)->colId) {
217,418!
515
    return FUNC_DATA_REQUIRED_NOT_LOAD;
164,712✔
516
  }
517
  return FUNC_DATA_REQUIRED_SMA_LOAD;
52,706✔
518
}
519

520
bool getCountFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
1,768,307✔
521
  pEnv->calcMemSize = sizeof(int64_t);
1,768,307✔
522
  return true;
1,768,307✔
523
}
524

525
static int64_t getNumOfElems(SqlFunctionCtx* pCtx) {
112,120,949✔
526
  int64_t numOfElem = 0;
112,120,949✔
527

528
  /*
529
   * 1. column data missing (schema modified) causes pInputCol->hasNull == true. pInput->colDataSMAIsSet == true;
530
   * 2. for general non-primary key columns, pInputCol->hasNull may be true or false, pInput->colDataSMAIsSet == true;
531
   * 3. for primary key column, pInputCol->hasNull always be false, pInput->colDataSMAIsSet == false;
532
   */
533
  SInputColumnInfoData* pInput = &pCtx->input;
112,120,949✔
534
  SColumnInfoData*      pInputCol = pInput->pData[0];
112,120,949✔
535
  if (1 == pInput->numOfRows && pInput->blankFill) {
112,120,949✔
536
    return 0;
455,587✔
537
  }
538
  if (pInput->colDataSMAIsSet && pInput->totalRows == pInput->numOfRows) {
111,665,362!
539
    numOfElem = pInput->numOfRows - pInput->pColumnDataAgg[0]->numOfNull;
2,270✔
540
  } else {
541
    if (pInputCol->hasNull) {
111,663,092✔
542
      for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
321,430,784✔
543
        if (colDataIsNull(pInputCol, pInput->totalRows, i, NULL)) {
588,346,848!
544
          continue;
1,860,435✔
545
        }
546
        numOfElem += 1;
292,312,989✔
547
      }
548
    } else {
549
      // when counting on the primary time stamp column and no statistics data is presented, use the size value
550
      // directly.
551
      numOfElem = pInput->numOfRows;
84,405,732✔
552
    }
553
  }
554
  return numOfElem;
111,665,362✔
555
}
556

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

564
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
112,152,960✔
565
  SInputColumnInfoData* pInput = &pCtx->input;
112,152,960✔
566

567
  int32_t type = pInput->pData[0]->info.type;
112,152,960✔
568

569
  char* buf = GET_ROWCELL_INTERBUF(pResInfo);
112,152,960✔
570
  if (IS_NULL_TYPE(type)) {
112,152,960✔
571
    // select count(NULL) returns 0
572
    numOfElem = 1;
136,470✔
573
    *((int64_t*)buf) += 0;
136,470✔
574
  } else {
575
    numOfElem = getNumOfElems(pCtx);
112,016,490✔
576
    *((int64_t*)buf) += numOfElem;
111,865,411✔
577
  }
578

579
  if (tsCountAlwaysReturnValue) {
112,001,881!
580
    pResInfo->numOfRes = 1;
112,102,415✔
581
  } else {
582
    SET_VAL(pResInfo, *((int64_t*)buf), 1);
×
583
  }
584

585
  return TSDB_CODE_SUCCESS;
112,001,881✔
586
}
587

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

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

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

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

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

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

613
int32_t sumFunction(SqlFunctionCtx* pCtx) {
89,514,216✔
614
  int32_t numOfElem = 0;
89,514,216✔
615

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

621
  SSumRes* pSumRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
89,514,216✔
622
  pSumRes->type = type;
89,514,216✔
623

624
  if (IS_NULL_TYPE(type)) {
89,514,216✔
625
    numOfElem = 0;
212✔
626
    goto _sum_over;
212✔
627
  }
628

629
  if (pInput->colDataSMAIsSet) {
89,514,004✔
630
    numOfElem = pInput->numOfRows - pAgg->numOfNull;
530✔
631

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

642
    int32_t start = pInput->startRowIndex;
89,513,474✔
643
    int32_t numOfRows = pInput->numOfRows;
89,513,474✔
644

645
    if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
89,513,474!
646
      if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
85,826,500!
647
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int8_t, numOfElem);
1,520,651✔
648
      } else if (type == TSDB_DATA_TYPE_SMALLINT) {
85,490,969✔
649
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int16_t, numOfElem);
330,436✔
650
      } else if (type == TSDB_DATA_TYPE_INT) {
85,444,551✔
651
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int32_t, numOfElem);
384,398,827✔
652
      } else if (type == TSDB_DATA_TYPE_BIGINT) {
19,896,547✔
653
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int64_t, numOfElem);
72,906,452✔
654
      }
655
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
3,686,974!
656
      if (type == TSDB_DATA_TYPE_UTINYINT) {
106✔
657
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint8_t, numOfElem);
50,015!
658
      } else if (type == TSDB_DATA_TYPE_USMALLINT) {
91✔
659
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint16_t, numOfElem);
50,023✔
660
      } else if (type == TSDB_DATA_TYPE_UINT) {
75✔
661
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint32_t, numOfElem);
50,015!
662
      } else if (type == TSDB_DATA_TYPE_UBIGINT) {
60!
663
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint64_t, numOfElem);
50,600✔
664
      }
665
    } else if (type == TSDB_DATA_TYPE_DOUBLE) {
3,686,868✔
666
      LIST_ADD_N(pSumRes->dsum, pCol, start, numOfRows, double, numOfElem);
4,031,350✔
667
    } else if (type == TSDB_DATA_TYPE_FLOAT) {
2,717,504✔
668
      LIST_ADD_N(pSumRes->dsum, pCol, start, numOfRows, float, numOfElem);
7,324,950✔
669
    }
670
  }
671

672
  // check for overflow
673
  if (IS_FLOAT_TYPE(type) && (isinf(pSumRes->dsum) || isnan(pSumRes->dsum))) {
89,514,004!
674
    numOfElem = 0;
×
675
  }
676

677
_sum_over:
89,838,353✔
678
  if (numOfElem == 0) {
89,514,216✔
679
    if (tsCountAlwaysReturnValue && pCtx->pExpr->pExpr->_function.pFunctNode->hasOriginalFunc &&
100,107✔
680
        fmIsCountLikeFunc(pCtx->pExpr->pExpr->_function.pFunctNode->originalFuncId)) {
11,446✔
681
      numOfElem = 1;
31✔
682
    }
683
  }
684
  // data in the check operation are all null, not output
685
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
89,514,217✔
686
  return TSDB_CODE_SUCCESS;
89,514,217✔
687
}
688

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

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

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

700
  if (pInput->colDataSMAIsSet) {
701
    numOfElem = pInput->numOfRows - pAgg->numOfNull;
702

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

713
    int32_t start = pInput->startRowIndex;
714
    int32_t numOfRows = pInput->numOfRows;
715

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

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

749
int32_t sumCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
47✔
750
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
47✔
751
  SSumRes*             pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
47✔
752

753
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
47✔
754
  SSumRes*             pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
47✔
755
  int16_t              type = pDBuf->type == TSDB_DATA_TYPE_NULL ? pSBuf->type : pDBuf->type;
47✔
756

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

769
bool getSumFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
227,522✔
770
  pEnv->calcMemSize = sizeof(SSumRes);
227,522✔
771
  return true;
227,522✔
772
}
773

774
static bool funcNotSupportStringSma(SFunctionNode* pFunc) {
170,441✔
775
  SNode* pParam;
776
  switch (pFunc->funcType) {
170,441!
777
    case FUNCTION_TYPE_MAX:
170,441✔
778
    case FUNCTION_TYPE_MIN:
779
    case FUNCTION_TYPE_SUM:
780
    case FUNCTION_TYPE_AVG:
781
    case FUNCTION_TYPE_AVG_PARTIAL:
782
    case FUNCTION_TYPE_PERCENTILE:
783
    case FUNCTION_TYPE_SPREAD:
784
    case FUNCTION_TYPE_SPREAD_PARTIAL:
785
    case FUNCTION_TYPE_SPREAD_MERGE:
786
    case FUNCTION_TYPE_TWA:
787
    case FUNCTION_TYPE_ELAPSED:
788
      pParam = nodesListGetNode(pFunc->pParameterList, 0);
170,441✔
789
      if (pParam && nodesIsExprNode(pParam) && (IS_VAR_DATA_TYPE(((SExprNode*)pParam)->resType.type))) {
170,441!
790
        return true;
86✔
791
      }
792
      break;
170,355✔
793
    default:
×
794
      break;
×
795
  }
796
  return false;
170,355✔
797
}
798

799
EFuncDataRequired statisDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
170,441✔
800
  if(funcNotSupportStringSma(pFunc)) {
170,441✔
801
    return FUNC_DATA_REQUIRED_DATA_LOAD;
86✔
802
  }
803
  return FUNC_DATA_REQUIRED_SMA_LOAD;
170,355✔
804
}
805

806
int32_t minmaxFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
50,127,246✔
807
  if (pResultInfo->initialized) {
50,127,246!
808
    return TSDB_CODE_SUCCESS;
×
809
  }
810
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
50,127,246!
811
    return TSDB_CODE_FUNC_SETUP_ERROR;  // not initialized since it has been initialized
×
812
  }
813

814
  SMinmaxResInfo* buf = GET_ROWCELL_INTERBUF(pResultInfo);
50,135,490✔
815
  buf->assign = false;
50,135,490✔
816
  buf->tuplePos.pageId = -1;
50,135,490✔
817

818
  buf->nullTupleSaved = false;
50,135,490✔
819
  buf->nullTuplePos.pageId = -1;
50,135,490✔
820
  buf->str = NULL;
50,135,490✔
821
  return TSDB_CODE_SUCCESS;
50,135,490✔
822
}
823

824
bool getMinmaxFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
423,322✔
825
  pEnv->calcMemSize = sizeof(SMinmaxResInfo);
423,322✔
826
  return true;
423,322✔
827
}
828

829
int32_t minFunction(SqlFunctionCtx* pCtx) {
26,041,087✔
830
  int32_t numOfElems = 0;
26,041,087✔
831
  int32_t code = doMinMaxHelper(pCtx, 1, &numOfElems);
26,041,087✔
832
  if (code != TSDB_CODE_SUCCESS) {
26,175,761!
833
    return code;
×
834
  }
835
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
26,175,761✔
836
  return TSDB_CODE_SUCCESS;
26,175,761✔
837
}
838

839
int32_t maxFunction(SqlFunctionCtx* pCtx) {
29,187,252✔
840
  int32_t numOfElems = 0;
29,187,252✔
841
  int32_t code = doMinMaxHelper(pCtx, 0, &numOfElems);
29,187,252✔
842
  if (code != TSDB_CODE_SUCCESS) {
29,355,657!
843
    return code;
×
844
  }
845
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
29,355,657✔
846
  return TSDB_CODE_SUCCESS;
29,355,657✔
847
}
848

849
static int32_t setNullSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t rowIndex);
850
static int32_t setSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, const STuplePos* pTuplePos,
851
                                   int32_t rowIndex);
852

853
int32_t minmaxFunctionFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
48,790,029✔
854
  int32_t code = TSDB_CODE_SUCCESS;
48,790,029✔
855

856
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
48,790,029✔
857
  SMinmaxResInfo*      pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
48,790,029✔
858

859
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
48,790,029✔
860
  int32_t currentRow = pBlock->info.rows;
48,790,029✔
861

862
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
48,790,029✔
863
  if (NULL == pCol) {
48,799,766!
864
    return TSDB_CODE_OUT_OF_RANGE;
×
865
  }
866
  pEntryInfo->isNullRes = (pEntryInfo->numOfRes == 0) ? 1 : 0;
48,799,766✔
867

868
  // NOTE: do nothing change it, for performance issue
869
  if (!pEntryInfo->isNullRes) {
48,799,766✔
870
    switch (pCol->info.type) {
41,391,562!
871
      case TSDB_DATA_TYPE_UBIGINT:
16,075,894✔
872
      case TSDB_DATA_TYPE_BIGINT:
873
        ((int64_t*)pCol->pData)[currentRow] = pRes->v;
16,075,894✔
874
        break;
16,075,894✔
875
      case TSDB_DATA_TYPE_UINT:
17,818,512✔
876
      case TSDB_DATA_TYPE_INT:
877
        colDataSetInt32(pCol, currentRow, (int32_t*)&pRes->v);
17,818,512✔
878
        break;
17,818,512✔
879
      case TSDB_DATA_TYPE_USMALLINT:
220,299✔
880
      case TSDB_DATA_TYPE_SMALLINT:
881
        colDataSetInt16(pCol, currentRow, (int16_t*)&pRes->v);
220,299✔
882
        break;
220,299✔
883
      case TSDB_DATA_TYPE_BOOL:
205,624✔
884
      case TSDB_DATA_TYPE_UTINYINT:
885
      case TSDB_DATA_TYPE_TINYINT:
886
        colDataSetInt8(pCol, currentRow, (int8_t*)&pRes->v);
205,624✔
887
        break;
205,624✔
888
      case TSDB_DATA_TYPE_DOUBLE:
2,665,821✔
889
        colDataSetDouble(pCol, currentRow, (double*)&pRes->v);
2,665,821✔
890
        break;
2,665,821✔
891
      case TSDB_DATA_TYPE_FLOAT: {
3,209✔
892
        float v = GET_FLOAT_VAL(&pRes->v);
3,209✔
893
        colDataSetFloat(pCol, currentRow, &v);
3,209✔
894
        break;
3,209✔
895
      }
896
      case TSDB_DATA_TYPE_VARBINARY:
4,459,461✔
897
      case TSDB_DATA_TYPE_VARCHAR:
898
      case TSDB_DATA_TYPE_NCHAR: {
899
        code = colDataSetVal(pCol, currentRow, pRes->str, false);
4,459,461✔
900
        if (TSDB_CODE_SUCCESS != code) {
4,459,462!
901
          return code;
×
902
        }
903
        break;
4,459,462✔
904
      }
905
    }
906
  } else {
907
    colDataSetNULL(pCol, currentRow);
7,408,204!
908
  }
909

910
  taosMemoryFreeClear(pRes->str);
48,799,767!
911
  if (pCtx->subsidiaries.num > 0) {
48,799,766✔
912
    if (pEntryInfo->numOfRes > 0) {
10,591,216✔
913
      code = setSelectivityValue(pCtx, pBlock, &pRes->tuplePos, currentRow);
10,588,653✔
914
    } else {
915
      code = setNullSelectivityValue(pCtx, pBlock, currentRow);
2,563✔
916
    }
917
  }
918

919
  return code;
48,810,033✔
920
}
921

922
int32_t setNullSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t rowIndex) {
2,419,462✔
923
  if (pCtx->subsidiaries.num <= 0) {
2,419,462✔
924
    return TSDB_CODE_SUCCESS;
2,416,830✔
925
  }
926

927
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
7,182✔
928
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
4,550✔
929
    int32_t         dstSlotId = pc->pExpr->base.resSchema.slotId;
4,550✔
930

931
    SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId);
4,550✔
932
    if (NULL == pDstCol) {
4,550!
933
      return terrno;
×
934
    }
935
    colDataSetNULL(pDstCol, rowIndex);
4,550✔
936
  }
937

938
  return TSDB_CODE_SUCCESS;
2,632✔
939
}
940

941
int32_t setSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, const STuplePos* pTuplePos, int32_t rowIndex) {
303,484,231✔
942
  if (pCtx->subsidiaries.num <= 0) {
303,484,231✔
943
    return TSDB_CODE_SUCCESS;
141,292,277✔
944
  }
945

946
  if ((pCtx->saveHandle.pBuf != NULL && pTuplePos->pageId != -1) ||
162,191,954!
947
      (pCtx->saveHandle.pState && pTuplePos->streamTupleKey.ts > 0)) {
×
948
    int32_t numOfCols = pCtx->subsidiaries.num;
162,206,184✔
949
    char*   p = NULL;
162,206,184✔
950
    int32_t code = loadTupleData(pCtx, pTuplePos, &p);
162,206,184✔
951
    if (p == NULL || TSDB_CODE_SUCCESS != code) {
163,711,144!
952
      qError("Load tuple data failed since %s, groupId:%" PRIu64 ", ts:%" PRId64, terrstr(),
×
953
             pTuplePos->streamTupleKey.groupId, pTuplePos->streamTupleKey.ts);
954
      return TSDB_CODE_NOT_FOUND;
×
955
    }
956

957
    bool* nullList = (bool*)p;
163,715,359✔
958
    char* pStart = (char*)(nullList + numOfCols * sizeof(bool));
163,715,359✔
959

960
    // todo set the offset value to optimize the performance.
961
    for (int32_t j = 0; j < numOfCols; ++j) {
326,633,817✔
962
      SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
163,720,035✔
963
      int32_t         dstSlotId = pc->pExpr->base.resSchema.slotId;
163,720,035✔
964

965
      SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId);
163,720,035✔
966
      if (NULL == pDstCol) {
163,406,176!
967
        return terrno;
×
968
      }
969
      if (nullList[j]) {
163,413,909✔
970
        colDataSetNULL(pDstCol, rowIndex);
152!
971
      } else {
972
        code = colDataSetValOrCover(pDstCol, rowIndex, pStart, false);
163,413,757✔
973
        if (TSDB_CODE_SUCCESS != code) {
162,918,306!
974
          return code;
×
975
        }
976
      }
977
      pStart += pDstCol->info.bytes;
162,918,458✔
978
    }
979
  }
980

981
  return TSDB_CODE_SUCCESS;
162,899,552✔
982
}
983

984
// This function append the selectivity to subsidiaries function context directly, without fetching data
985
// from intermediate disk based buf page
986
int32_t appendSelectivityValue(SqlFunctionCtx* pCtx, int32_t rowIndex, int32_t pos) {
55,054,974✔
987
  if (pCtx->subsidiaries.num <= 0) {
55,054,974!
988
    return TSDB_CODE_SUCCESS;
×
989
  }
990

991
  int32_t code = TSDB_CODE_SUCCESS;
55,054,974✔
992
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
110,100,883✔
993
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
55,056,292✔
994

995
    // get data from source col
996
    SFunctParam* pFuncParam = &pc->pExpr->base.pParam[0];
55,056,292✔
997
    int32_t      srcSlotId = pFuncParam->pCol->slotId;
55,056,292✔
998

999
    SColumnInfoData* pSrcCol = taosArrayGet(pCtx->pSrcBlock->pDataBlock, srcSlotId);
55,056,292✔
1000
    if (NULL == pSrcCol) {
55,051,452!
1001
      return TSDB_CODE_OUT_OF_RANGE;
×
1002
    }
1003

1004
    char* pData = colDataGetData(pSrcCol, rowIndex);
55,051,452!
1005

1006
    // append to dest col
1007
    int32_t dstSlotId = pc->pExpr->base.resSchema.slotId;
55,051,452✔
1008

1009
    SColumnInfoData* pDstCol = taosArrayGet(pCtx->pDstBlock->pDataBlock, dstSlotId);
55,051,452✔
1010
    if (NULL == pDstCol) {
55,043,862!
1011
      return TSDB_CODE_OUT_OF_RANGE;
×
1012
    }
1013

1014
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
110,087,724✔
1015
      colDataSetNULL(pDstCol, pos);
392✔
1016
    } else {
1017
      code = colDataSetVal(pDstCol, pos, pData, false);
55,043,470✔
1018
      if (TSDB_CODE_SUCCESS != code) {
55,045,517!
1019
        return code;
×
1020
      }
1021
    }
1022
  }
1023
  return code;
55,044,591✔
1024
}
1025

1026
void replaceTupleData(STuplePos* pDestPos, STuplePos* pSourcePos) { *pDestPos = *pSourcePos; }
32✔
1027

1028
#define COMPARE_MINMAX_DATA(type) (((*(type*)&pDBuf->v) < (*(type*)&pSBuf->v)) ^ isMinFunc)
1029
int32_t minMaxCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx, int32_t isMinFunc) {
58✔
1030
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
58✔
1031
  SMinmaxResInfo*      pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
58✔
1032

1033
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
58✔
1034
  SMinmaxResInfo*      pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
58✔
1035
  int16_t              type = pDBuf->type == TSDB_DATA_TYPE_NULL ? pSBuf->type : pDBuf->type;
58✔
1036

1037
  switch (type) {
58!
1038
    case TSDB_DATA_TYPE_DOUBLE:
3✔
1039
    case TSDB_DATA_TYPE_UBIGINT:
1040
    case TSDB_DATA_TYPE_BIGINT:
1041
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(int64_t) || !pDBuf->assign)) {
3!
1042
        pDBuf->v = pSBuf->v;
1✔
1043
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
1✔
1044
        pDBuf->assign = true;
1✔
1045
      }
1046
      break;
3✔
1047
    case TSDB_DATA_TYPE_UINT:
55✔
1048
    case TSDB_DATA_TYPE_INT:
1049
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(int32_t) || !pDBuf->assign)) {
55!
1050
        pDBuf->v = pSBuf->v;
31✔
1051
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
31✔
1052
        pDBuf->assign = true;
31✔
1053
      }
1054
      break;
55✔
1055
    case TSDB_DATA_TYPE_USMALLINT:
×
1056
    case TSDB_DATA_TYPE_SMALLINT:
1057
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(int16_t) || !pDBuf->assign)) {
×
1058
        pDBuf->v = pSBuf->v;
×
1059
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1060
        pDBuf->assign = true;
×
1061
      }
1062
      break;
×
1063
    case TSDB_DATA_TYPE_BOOL:
×
1064
    case TSDB_DATA_TYPE_UTINYINT:
1065
    case TSDB_DATA_TYPE_TINYINT:
1066
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(int8_t) || !pDBuf->assign)) {
×
1067
        pDBuf->v = pSBuf->v;
×
1068
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1069
        pDBuf->assign = true;
×
1070
      }
1071
      break;
×
1072
    case TSDB_DATA_TYPE_FLOAT: {
×
1073
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(double) || !pDBuf->assign)) {
×
1074
        pDBuf->v = pSBuf->v;
×
1075
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1076
        pDBuf->assign = true;
×
1077
      }
1078
      break;
×
1079
    }
1080
    default:
×
1081
      if (pSBuf->assign && (strcmp((char*)&pDBuf->v, (char*)&pSBuf->v) || !pDBuf->assign)) {
×
1082
        pDBuf->v = pSBuf->v;
×
1083
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1084
        pDBuf->assign = true;
×
1085
      }
1086
      break;
×
1087
  }
1088
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
58✔
1089
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
58✔
1090
  return TSDB_CODE_SUCCESS;
58✔
1091
}
1092

1093
int32_t minCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
11✔
1094
  return minMaxCombine(pDestCtx, pSourceCtx, 1);
11✔
1095
}
1096
int32_t maxCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
47✔
1097
  return minMaxCombine(pDestCtx, pSourceCtx, 0);
47✔
1098
}
1099

1100
int32_t getStdInfoSize() { return (int32_t)sizeof(SStdRes); }
869,628✔
1101

1102
bool getStdFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
156,897✔
1103
  pEnv->calcMemSize = sizeof(SStdRes);
156,897✔
1104
  return true;
156,897✔
1105
}
1106

1107
int32_t stdFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
7,584,554✔
1108
  if (pResultInfo->initialized) {
7,584,554!
1109
    return TSDB_CODE_SUCCESS;
×
1110
  }
1111
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
7,584,554!
1112
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1113
  }
1114

1115
  SStdRes* pRes = GET_ROWCELL_INTERBUF(pResultInfo);
7,584,584✔
1116
  (void)memset(pRes, 0, sizeof(SStdRes));
7,584,584✔
1117
  return TSDB_CODE_SUCCESS;
7,584,584✔
1118
}
1119

1120
int32_t stdFunction(SqlFunctionCtx* pCtx) {
7,570,519✔
1121
  int32_t numOfElem = 0;
7,570,519✔
1122

1123
  // Only the pre-computing information loaded and actual data does not loaded
1124
  SInputColumnInfoData* pInput = &pCtx->input;
7,570,519✔
1125
  int32_t               type = pInput->pData[0]->info.type;
7,570,519✔
1126

1127
  SStdRes* pStdRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
7,570,519✔
1128
  pStdRes->type = type;
7,570,519✔
1129

1130
  // computing based on the true data block
1131
  SColumnInfoData* pCol = pInput->pData[0];
7,570,519✔
1132

1133
  int32_t start = pInput->startRowIndex;
7,570,519✔
1134
  int32_t numOfRows = pInput->numOfRows;
7,570,519✔
1135

1136
  if (IS_NULL_TYPE(type)) {
7,570,519✔
1137
    numOfElem = 0;
130✔
1138
    goto _stddev_over;
130✔
1139
  }
1140

1141
  switch (type) {
7,570,389!
1142
    case TSDB_DATA_TYPE_TINYINT: {
15,874✔
1143
      int8_t* plist = (int8_t*)pCol->pData;
15,874✔
1144
      for (int32_t i = start; i < numOfRows + start; ++i) {
690,405✔
1145
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
674,531✔
1146
          continue;
21,490✔
1147
        }
1148

1149
        numOfElem += 1;
653,041✔
1150
        pStdRes->count += 1;
653,041✔
1151
        pStdRes->isum += plist[i];
653,041✔
1152
        pStdRes->quadraticISum += plist[i] * plist[i];
653,041✔
1153
      }
1154

1155
      break;
15,874✔
1156
    }
1157

1158
    case TSDB_DATA_TYPE_SMALLINT: {
5,210,413✔
1159
      int16_t* plist = (int16_t*)pCol->pData;
5,210,413✔
1160
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
21,403,422✔
1161
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
16,193,009✔
1162
          continue;
116,218✔
1163
        }
1164

1165
        numOfElem += 1;
16,076,791✔
1166
        pStdRes->count += 1;
16,076,791✔
1167
        pStdRes->isum += plist[i];
16,076,791✔
1168
        pStdRes->quadraticISum += plist[i] * plist[i];
16,076,791✔
1169
      }
1170
      break;
5,210,413✔
1171
    }
1172

1173
    case TSDB_DATA_TYPE_INT: {
22,199✔
1174
      int32_t* plist = (int32_t*)pCol->pData;
22,199✔
1175
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
175,162✔
1176
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
152,963✔
1177
          continue;
100,132✔
1178
        }
1179

1180
        numOfElem += 1;
52,831✔
1181
        pStdRes->count += 1;
52,831✔
1182
        pStdRes->isum += plist[i];
52,831✔
1183
        pStdRes->quadraticISum += plist[i] * plist[i];
52,831✔
1184
      }
1185

1186
      break;
22,199✔
1187
    }
1188

1189
    case TSDB_DATA_TYPE_BIGINT: {
27,529✔
1190
      int64_t* plist = (int64_t*)pCol->pData;
27,529✔
1191
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
833,934✔
1192
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
806,405✔
1193
          continue;
124,616✔
1194
        }
1195

1196
        numOfElem += 1;
681,789✔
1197
        pStdRes->count += 1;
681,789✔
1198
        pStdRes->isum += plist[i];
681,789✔
1199
        pStdRes->quadraticISum += plist[i] * plist[i];
681,789✔
1200
      }
1201
      break;
27,529✔
1202
    }
1203

1204
    case TSDB_DATA_TYPE_UTINYINT: {
1✔
1205
      uint8_t* plist = (uint8_t*)pCol->pData;
1✔
1206
      for (int32_t i = start; i < numOfRows + start; ++i) {
8✔
1207
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
7!
1208
          continue;
4✔
1209
        }
1210

1211
        numOfElem += 1;
3✔
1212
        pStdRes->count += 1;
3✔
1213
        pStdRes->usum += plist[i];
3✔
1214
        pStdRes->quadraticUSum += plist[i] * plist[i];
3✔
1215
      }
1216

1217
      break;
1✔
1218
    }
1219

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

1227
        numOfElem += 1;
×
1228
        pStdRes->count += 1;
×
1229
        pStdRes->usum += plist[i];
×
1230
        pStdRes->quadraticUSum += plist[i] * plist[i];
×
1231
      }
1232
      break;
×
1233
    }
1234

1235
    case TSDB_DATA_TYPE_UINT: {
1✔
1236
      uint32_t* plist = (uint32_t*)pCol->pData;
1✔
1237
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
6✔
1238
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
5!
1239
          continue;
×
1240
        }
1241

1242
        numOfElem += 1;
5✔
1243
        pStdRes->count += 1;
5✔
1244
        pStdRes->usum += plist[i];
5✔
1245
        pStdRes->quadraticUSum += plist[i] * plist[i];
5✔
1246
      }
1247

1248
      break;
1✔
1249
    }
1250

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

1258
        numOfElem += 1;
×
1259
        pStdRes->count += 1;
×
1260
        pStdRes->usum += plist[i];
×
1261
        pStdRes->quadraticUSum += plist[i] * plist[i];
×
1262
      }
1263
      break;
×
1264
    }
1265

1266
    case TSDB_DATA_TYPE_FLOAT: {
21,557✔
1267
      float* plist = (float*)pCol->pData;
21,557✔
1268
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
1,348,640✔
1269
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
1,327,083✔
1270
          continue;
25,866✔
1271
        }
1272

1273
        numOfElem += 1;
1,301,217✔
1274
        pStdRes->count += 1;
1,301,217✔
1275
        pStdRes->dsum += plist[i];
1,301,217✔
1276
        pStdRes->quadraticDSum += plist[i] * plist[i];
1,301,217✔
1277
      }
1278
      break;
21,557✔
1279
    }
1280

1281
    case TSDB_DATA_TYPE_DOUBLE: {
2,273,052✔
1282
      double* plist = (double*)pCol->pData;
2,273,052✔
1283
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
9,337,221✔
1284
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
7,064,169✔
1285
          continue;
660,056✔
1286
        }
1287

1288
        numOfElem += 1;
6,404,113✔
1289
        pStdRes->count += 1;
6,404,113✔
1290
        pStdRes->dsum += plist[i];
6,404,113✔
1291
        pStdRes->quadraticDSum += plist[i] * plist[i];
6,404,113✔
1292
      }
1293
      break;
2,273,052✔
1294
    }
1295

1296
    default:
×
1297
      break;
×
1298
  }
1299

1300
_stddev_over:
7,570,519✔
1301
  // data in the check operation are all null, not output
1302
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
7,570,519✔
1303
  return TSDB_CODE_SUCCESS;
7,570,519✔
1304
}
1305

1306
static void stdTransferInfo(SStdRes* pInput, SStdRes* pOutput) {
865,490✔
1307
  if (IS_NULL_TYPE(pInput->type)) {
865,490✔
1308
    return;
80✔
1309
  }
1310
  pOutput->type = pInput->type;
865,410✔
1311
  if (IS_SIGNED_NUMERIC_TYPE(pOutput->type)) {
865,410!
1312
    pOutput->quadraticISum += pInput->quadraticISum;
864,019✔
1313
    pOutput->isum += pInput->isum;
864,019✔
1314
  } else if (IS_UNSIGNED_NUMERIC_TYPE(pOutput->type)) {
1,391!
1315
    pOutput->quadraticUSum += pInput->quadraticUSum;
1✔
1316
    pOutput->usum += pInput->usum;
1✔
1317
  } else {
1318
    pOutput->quadraticDSum += pInput->quadraticDSum;
1,390✔
1319
    pOutput->dsum += pInput->dsum;
1,390✔
1320
  }
1321

1322
  pOutput->count += pInput->count;
865,410✔
1323
}
1324

1325
int32_t stdFunctionMerge(SqlFunctionCtx* pCtx) {
865,415✔
1326
  SInputColumnInfoData* pInput = &pCtx->input;
865,415✔
1327
  SColumnInfoData*      pCol = pInput->pData[0];
865,415✔
1328

1329
  if (IS_NULL_TYPE(pCol->info.type)) {
865,415!
1330
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
1331
    return TSDB_CODE_SUCCESS;
×
1332
  }
1333

1334
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
865,415!
1335
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
1336
  }
1337

1338
  SStdRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
865,415✔
1339

1340
  for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
1,730,902✔
1341
    if (colDataIsNull_s(pCol, i)) continue;
1,730,974!
1342
    char*    data = colDataGetData(pCol, i);
865,487!
1343
    SStdRes* pInputInfo = (SStdRes*)varDataVal(data);
865,487✔
1344
    stdTransferInfo(pInputInfo, pInfo);
865,487✔
1345
  }
1346

1347
  SET_VAL(GET_RES_INFO(pCtx), 1, 1);
865,415✔
1348
  return TSDB_CODE_SUCCESS;
865,415✔
1349
}
1350

1351
#ifdef BUILD_NO_CALL
1352
int32_t stdInvertFunction(SqlFunctionCtx* pCtx) {
1353
  int32_t numOfElem = 0;
1354

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

1359
  SStdRes* pStdRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1360

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

1364
  int32_t start = pInput->startRowIndex;
1365
  int32_t numOfRows = pInput->numOfRows;
1366

1367
  switch (type) {
1368
    case TSDB_DATA_TYPE_TINYINT: {
1369
      LIST_STDDEV_SUB_N(pStdRes->isum, int8_t);
1370
      break;
1371
    }
1372
    case TSDB_DATA_TYPE_SMALLINT: {
1373
      LIST_STDDEV_SUB_N(pStdRes->isum, int16_t);
1374
      break;
1375
    }
1376
    case TSDB_DATA_TYPE_INT: {
1377
      LIST_STDDEV_SUB_N(pStdRes->isum, int32_t);
1378
      break;
1379
    }
1380
    case TSDB_DATA_TYPE_BIGINT: {
1381
      LIST_STDDEV_SUB_N(pStdRes->isum, int64_t);
1382
      break;
1383
    }
1384
    case TSDB_DATA_TYPE_UTINYINT: {
1385
      LIST_STDDEV_SUB_N(pStdRes->isum, uint8_t);
1386
      break;
1387
    }
1388
    case TSDB_DATA_TYPE_USMALLINT: {
1389
      LIST_STDDEV_SUB_N(pStdRes->isum, uint16_t);
1390
      break;
1391
    }
1392
    case TSDB_DATA_TYPE_UINT: {
1393
      LIST_STDDEV_SUB_N(pStdRes->isum, uint32_t);
1394
      break;
1395
    }
1396
    case TSDB_DATA_TYPE_UBIGINT: {
1397
      LIST_STDDEV_SUB_N(pStdRes->isum, uint64_t);
1398
      break;
1399
    }
1400
    case TSDB_DATA_TYPE_FLOAT: {
1401
      LIST_STDDEV_SUB_N(pStdRes->dsum, float);
1402
      break;
1403
    }
1404
    case TSDB_DATA_TYPE_DOUBLE: {
1405
      LIST_STDDEV_SUB_N(pStdRes->dsum, double);
1406
      break;
1407
    }
1408
    default:
1409
      break;
1410
  }
1411

1412
  // data in the check operation are all null, not output
1413
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
1414
  return TSDB_CODE_SUCCESS;
1415
}
1416
#endif
1417

1418
int32_t stddevFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
6,681,435✔
1419
  SInputColumnInfoData* pInput = &pCtx->input;
6,681,435✔
1420
  SStdRes*              pStddevRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
6,681,435✔
1421
  int32_t               type = pStddevRes->type;
6,681,435✔
1422
  double                avg;
1423

1424
  if (pStddevRes->count == 0) {
6,681,435✔
1425
    GET_RES_INFO(pCtx)->numOfRes = 0;
56,969✔
1426
    return functionFinalize(pCtx, pBlock);
56,969✔
1427
  }
1428

1429
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
6,624,466!
1430
    avg = pStddevRes->isum / ((double)pStddevRes->count);
4,385,942✔
1431
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticISum / ((double)pStddevRes->count) - avg * avg));
4,385,942✔
1432
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
2,238,524!
1433
    avg = pStddevRes->usum / ((double)pStddevRes->count);
2✔
1434
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticUSum / ((double)pStddevRes->count) - avg * avg));
2✔
1435
  } else {
1436
    avg = pStddevRes->dsum / ((double)pStddevRes->count);
2,238,522✔
1437
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticDSum / ((double)pStddevRes->count) - avg * avg));
2,238,522✔
1438
  }
1439

1440
  // check for overflow
1441
  if (isinf(pStddevRes->result) || isnan(pStddevRes->result)) {
6,624,466!
1442
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1443
  }
1444

1445
  return functionFinalize(pCtx, pBlock);
6,624,466✔
1446
}
1447

1448
int32_t stdvarFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
×
1449
  SInputColumnInfoData* pInput = &pCtx->input;
×
1450
  SStdRes*              pStdvarRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
×
1451
  int32_t               type = pStdvarRes->type;
×
1452
  double                avg;
1453

1454
  if (pStdvarRes->count == 0) {
×
1455
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1456
    return functionFinalize(pCtx, pBlock);
×
1457
  }
1458

1459
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
×
1460
    avg = pStdvarRes->isum / ((double)pStdvarRes->count);
×
1461
    pStdvarRes->result = fabs(pStdvarRes->quadraticISum / ((double)pStdvarRes->count) - avg * avg);
×
1462
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
1463
    avg = pStdvarRes->usum / ((double)pStdvarRes->count);
×
1464
    pStdvarRes->result = fabs(pStdvarRes->quadraticUSum / ((double)pStdvarRes->count) - avg * avg);
×
1465
  } else {
1466
    avg = pStdvarRes->dsum / ((double)pStdvarRes->count);
×
1467
    pStdvarRes->result = fabs(pStdvarRes->quadraticDSum / ((double)pStdvarRes->count) - avg * avg);
×
1468
  }
1469

1470
  // check for overflow
1471
  if (isinf(pStdvarRes->result) || isnan(pStdvarRes->result)) {
×
1472
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1473
  }
1474

1475
  return functionFinalize(pCtx, pBlock);
×
1476
}
1477

1478
int32_t stdPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
867,992✔
1479
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
867,992✔
1480
  SStdRes*             pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
867,992✔
1481
  int32_t              resultBytes = getStdInfoSize();
867,992✔
1482
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
867,992!
1483

1484
  if (NULL == res) {
867,992!
1485
    return terrno;
×
1486
  }
1487
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
867,992✔
1488
  varDataSetLen(res, resultBytes);
867,992✔
1489

1490
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
867,992✔
1491
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
867,992✔
1492
  if (NULL == pCol) {
867,992!
1493
    taosMemoryFree(res);
×
1494
    return TSDB_CODE_OUT_OF_RANGE;
×
1495
  }
1496

1497
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
867,992✔
1498

1499
  taosMemoryFree(res);
867,992!
1500
  return code;
867,992✔
1501
}
1502

1503
int32_t stdCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
3✔
1504
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
3✔
1505
  SStdRes*             pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
3✔
1506

1507
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
3✔
1508
  SStdRes*             pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
3✔
1509
  int16_t              type = pDBuf->type == TSDB_DATA_TYPE_NULL ? pSBuf->type : pDBuf->type;
3!
1510

1511
  stdTransferInfo(pSBuf, pDBuf);
3✔
1512

1513
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
3✔
1514
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
3✔
1515
  return TSDB_CODE_SUCCESS;
3✔
1516
}
1517

1518
bool getLeastSQRFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
42,018✔
1519
  pEnv->calcMemSize = sizeof(SLeastSQRInfo);
42,018✔
1520
  return true;
42,018✔
1521
}
1522

1523
int32_t leastSQRFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
5,629,916✔
1524
  if (pResultInfo->initialized) {
5,629,916!
1525
    return TSDB_CODE_SUCCESS;
×
1526
  }
1527
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
5,629,916!
1528
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1529
  }
1530

1531
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
5,629,915✔
1532

1533
  GET_TYPED_DATA(pInfo->startVal, double, pCtx->param[1].param.nType, &pCtx->param[1].param.i);
5,629,915!
1534
  GET_TYPED_DATA(pInfo->stepVal, double, pCtx->param[2].param.nType, &pCtx->param[2].param.i);
5,629,915!
1535
  return TSDB_CODE_SUCCESS;
5,629,915✔
1536
}
1537

1538
int32_t leastSQRFunction(SqlFunctionCtx* pCtx) {
6,863,630✔
1539
  int32_t numOfElem = 0;
6,863,630✔
1540

1541
  SInputColumnInfoData* pInput = &pCtx->input;
6,863,630✔
1542
  int32_t               type = pInput->pData[0]->info.type;
6,863,630✔
1543

1544
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
6,863,630✔
1545

1546
  SColumnInfoData* pCol = pInput->pData[0];
6,863,630✔
1547

1548
  double(*param)[3] = pInfo->matrix;
6,863,630✔
1549
  double x = pInfo->startVal;
6,863,630✔
1550

1551
  int32_t start = pInput->startRowIndex;
6,863,630✔
1552
  int32_t numOfRows = pInput->numOfRows;
6,863,630✔
1553

1554
  switch (type) {
6,863,630!
1555
    case TSDB_DATA_TYPE_TINYINT: {
5,800✔
1556
      int8_t* plist = (int8_t*)pCol->pData;
5,800✔
1557
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
148,624✔
1558
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
142,824✔
1559
          continue;
3,636✔
1560
        }
1561
        numOfElem++;
139,188✔
1562
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
139,188✔
1563
      }
1564
      break;
5,800✔
1565
    }
1566
    case TSDB_DATA_TYPE_SMALLINT: {
5,057,933✔
1567
      int16_t* plist = (int16_t*)pCol->pData;
5,057,933✔
1568
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
17,652,162✔
1569
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
12,594,229✔
1570
          continue;
139,728✔
1571
        }
1572

1573
        numOfElem++;
12,454,501✔
1574
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
12,454,501✔
1575
      }
1576
      break;
5,057,933✔
1577
    }
1578

1579
    case TSDB_DATA_TYPE_INT: {
12,033✔
1580
      int32_t* plist = (int32_t*)pCol->pData;
12,033✔
1581
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
731,453✔
1582
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
719,420✔
1583
          continue;
149,311✔
1584
        }
1585

1586
        numOfElem++;
570,109✔
1587
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
570,109✔
1588
      }
1589
      break;
12,033✔
1590
    }
1591

1592
    case TSDB_DATA_TYPE_BIGINT: {
1,763,310✔
1593
      int64_t* plist = (int64_t*)pCol->pData;
1,763,310✔
1594
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
6,020,354✔
1595
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
4,257,044✔
1596
          continue;
151,094✔
1597
        }
1598

1599
        numOfElem++;
4,105,950✔
1600
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
4,105,950✔
1601
      }
1602
      break;
1,763,310✔
1603
    }
1604

1605
    case TSDB_DATA_TYPE_UTINYINT: {
78✔
1606
      uint8_t* plist = (uint8_t*)pCol->pData;
78✔
1607
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
330✔
1608
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
252!
1609
          continue;
66✔
1610
        }
1611
        numOfElem++;
186✔
1612
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
186✔
1613
      }
1614
      break;
78✔
1615
    }
1616
    case TSDB_DATA_TYPE_USMALLINT: {
78✔
1617
      uint16_t* plist = (uint16_t*)pCol->pData;
78✔
1618
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
330✔
1619
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
252!
1620
          continue;
60✔
1621
        }
1622

1623
        numOfElem++;
192✔
1624
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
192✔
1625
      }
1626
      break;
78✔
1627
    }
1628

1629
    case TSDB_DATA_TYPE_UINT: {
78✔
1630
      uint32_t* plist = (uint32_t*)pCol->pData;
78✔
1631
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
330✔
1632
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
252!
1633
          continue;
60✔
1634
        }
1635

1636
        numOfElem++;
192✔
1637
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
192✔
1638
      }
1639
      break;
78✔
1640
    }
1641

1642
    case TSDB_DATA_TYPE_UBIGINT: {
78✔
1643
      uint64_t* plist = (uint64_t*)pCol->pData;
78✔
1644
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
330✔
1645
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
252!
1646
          continue;
60✔
1647
        }
1648

1649
        numOfElem++;
192✔
1650
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
192✔
1651
      }
1652
      break;
78✔
1653
    }
1654

1655
    case TSDB_DATA_TYPE_FLOAT: {
14,249✔
1656
      float* plist = (float*)pCol->pData;
14,249✔
1657
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
543,852✔
1658
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
529,603✔
1659
          continue;
3,236✔
1660
        }
1661

1662
        numOfElem++;
526,367✔
1663
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
526,367✔
1664
      }
1665
      break;
14,249✔
1666
    }
1667

1668
    case TSDB_DATA_TYPE_DOUBLE: {
9,993✔
1669
      double* plist = (double*)pCol->pData;
9,993✔
1670
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
301,169✔
1671
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
291,176✔
1672
          continue;
138,628✔
1673
        }
1674

1675
        numOfElem++;
152,548✔
1676
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
152,548✔
1677
      }
1678
      break;
9,993✔
1679
    }
1680
    case TSDB_DATA_TYPE_NULL: {
×
1681
      GET_RES_INFO(pCtx)->isNullRes = 1;
×
1682
      numOfElem = 1;
×
1683
      break;
×
1684
    }
1685

1686
    default:
×
1687
      break;
×
1688
  }
1689

1690
  pInfo->startVal = x;
6,863,630✔
1691
  pInfo->num += numOfElem;
6,863,630✔
1692

1693
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
6,863,630✔
1694

1695
  return TSDB_CODE_SUCCESS;
6,863,630✔
1696
}
1697

1698
int32_t leastSQRFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
5,625,189✔
1699
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5,625,189✔
1700
  SLeastSQRInfo*       pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
5,625,189✔
1701
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
5,625,189✔
1702
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
5,625,189✔
1703

1704
  if (NULL == pCol) {
5,625,188!
1705
    return TSDB_CODE_OUT_OF_RANGE;
×
1706
  }
1707
  int32_t currentRow = pBlock->info.rows;
5,625,188✔
1708

1709
  if (0 == pInfo->num) {
5,625,188✔
1710
    colDataSetNULL(pCol, currentRow);
26,079!
1711
    return TSDB_CODE_SUCCESS;
26,079✔
1712
  }
1713

1714
  double(*param)[3] = pInfo->matrix;
5,599,109✔
1715

1716
  param[1][1] = (double)pInfo->num;
5,599,109✔
1717
  param[1][0] = param[0][1];
5,599,109✔
1718

1719
  double param00 = param[0][0] - param[1][0] * (param[0][1] / param[1][1]);
5,599,109✔
1720
  double param02 = param[0][2] - param[1][2] * (param[0][1] / param[1][1]);
5,599,109✔
1721

1722
  if (0 == param00) {
5,599,109✔
1723
    colDataSetNULL(pCol, currentRow);
3,725,080!
1724
    return TSDB_CODE_SUCCESS;
3,725,080✔
1725
  }
1726

1727
  // param[0][1] = 0;
1728
  double param12 = param[1][2] - param02 * (param[1][0] / param00);
1,874,029✔
1729
  // param[1][0] = 0;
1730
  param02 /= param00;
1,874,029✔
1731

1732
  param12 /= param[1][1];
1,874,029✔
1733

1734
  char buf[LEASTSQUARES_BUFF_LENGTH] = {0};
1,874,029✔
1735
  char slopBuf[64] = {0};
1,874,029✔
1736
  char interceptBuf[64] = {0};
1,874,029✔
1737
  int  n = tsnprintf(slopBuf, 64, "%.6lf", param02);
1,874,029✔
1738
  if (n > LEASTSQUARES_DOUBLE_ITEM_LENGTH) {
1,874,031✔
1739
    (void)snprintf(slopBuf, 64, "%." DOUBLE_PRECISION_DIGITS, param02);
6✔
1740
  }
1741
  n = tsnprintf(interceptBuf, 64, "%.6lf", param12);
1,874,031✔
1742
  if (n > LEASTSQUARES_DOUBLE_ITEM_LENGTH) {
1,874,031✔
1743
    (void)snprintf(interceptBuf, 64, "%." DOUBLE_PRECISION_DIGITS, param12);
153,541✔
1744
  }
1745
  size_t len =
1,874,031✔
1746
      snprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE, "{slop:%s, intercept:%s}", slopBuf, interceptBuf);
1,874,031✔
1747
  varDataSetLen(buf, len);
1,874,031✔
1748

1749
  int32_t code = colDataSetVal(pCol, currentRow, buf, pResInfo->isNullRes);
1,874,031✔
1750

1751
  return code;
1,874,031✔
1752
}
1753

1754
int32_t leastSQRCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
1755
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
1756
  SLeastSQRInfo*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
1757
  int32_t              type = pDestCtx->input.pData[0]->info.type;
×
1758
  double(*pDparam)[3] = pDBuf->matrix;
×
1759

1760
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
1761
  SLeastSQRInfo*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
1762
  double(*pSparam)[3] = pSBuf->matrix;
×
1763
  for (int32_t i = 0; i < pSBuf->num; i++) {
×
1764
    pDparam[0][0] += pDBuf->startVal * pDBuf->startVal;
×
1765
    pDparam[0][1] += pDBuf->startVal;
×
1766
    pDBuf->startVal += pDBuf->stepVal;
×
1767
  }
1768
  pDparam[0][2] += pSparam[0][2] + pDBuf->num * pDBuf->stepVal * pSparam[1][2];
×
1769
  pDparam[1][2] += pSparam[1][2];
×
1770
  pDBuf->num += pSBuf->num;
×
1771
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
1772
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
1773
  return TSDB_CODE_SUCCESS;
×
1774
}
1775

1776
bool getPercentileFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
639✔
1777
  pEnv->calcMemSize = sizeof(SPercentileInfo);
639✔
1778
  return true;
639✔
1779
}
1780

1781
int32_t percentileFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
5,889✔
1782
  if (pResultInfo->initialized) {
5,889!
1783
    return TSDB_CODE_SUCCESS;
×
1784
  }
1785
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
5,889!
1786
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1787
  }
1788

1789
  // in the first round, get the min-max value of all involved data
1790
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
5,889✔
1791
  SET_DOUBLE_VAL(&pInfo->minval, DBL_MAX);
5,889✔
1792
  SET_DOUBLE_VAL(&pInfo->maxval, -DBL_MAX);
5,889✔
1793
  pInfo->numOfElems = 0;
5,889✔
1794

1795
  return TSDB_CODE_SUCCESS;
5,889✔
1796
}
1797

1798
void percentileFunctionCleanupExt(SqlFunctionCtx* pCtx) {
×
1799
  if (pCtx == NULL || GET_RES_INFO(pCtx) == NULL || GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)) == NULL) {
×
1800
    return;
×
1801
  }
1802
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
×
1803
  if (pInfo->pMemBucket != NULL) {
×
1804
    tMemBucketDestroy(&(pInfo->pMemBucket));
×
1805
    pInfo->pMemBucket = NULL;
×
1806
  }
1807
}
1808

1809
int32_t percentileFunction(SqlFunctionCtx* pCtx) {
2,579,586✔
1810
  int32_t              code = TSDB_CODE_SUCCESS;
2,579,586✔
1811
  int32_t              numOfElems = 0;
2,579,586✔
1812
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,579,586✔
1813

1814
  SInputColumnInfoData* pInput = &pCtx->input;
2,579,586✔
1815
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
2,579,586✔
1816

1817
  SColumnInfoData* pCol = pInput->pData[0];
2,579,586✔
1818
  int32_t          type = pCol->info.type;
2,579,586✔
1819

1820
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,579,586✔
1821
  if (pCtx->scanFlag == MAIN_SCAN && pInfo->stage == 0) {
2,579,586✔
1822
    pInfo->stage += 1;
5,889✔
1823

1824
    // all data are null, set it completed
1825
    if (pInfo->numOfElems == 0) {
5,889✔
1826
      pResInfo->complete = true;
2,006✔
1827
      return TSDB_CODE_SUCCESS;
2,006✔
1828
    } else {
1829
      code = tMemBucketCreate(pCol->info.bytes, type, pInfo->minval, pInfo->maxval, pCtx->hasWindowOrGroup,
3,883✔
1830
                              &pInfo->pMemBucket, pInfo->numOfElems);
3,883✔
1831
      if (TSDB_CODE_SUCCESS != code) {
3,883!
1832
        return code;
×
1833
      }
1834
    }
1835
  }
1836

1837
  // the first stage, only acquire the min/max value
1838
  if (pInfo->stage == 0) {
2,577,580✔
1839
    if (pCtx->input.colDataSMAIsSet) {
1,289,793✔
1840
      double tmin = 0.0, tmax = 0.0;
1,280,657✔
1841
      if (IS_SIGNED_NUMERIC_TYPE(type)) {
1,280,657!
1842
        tmin = (double)GET_INT64_VAL(&pAgg->min);
×
1843
        tmax = (double)GET_INT64_VAL(&pAgg->max);
×
1844
      } else if (IS_FLOAT_TYPE(type)) {
1,280,657!
1845
        tmin = GET_DOUBLE_VAL(&pAgg->min);
1,280,657✔
1846
        tmax = GET_DOUBLE_VAL(&pAgg->max);
1,280,657✔
1847
      } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
1848
        tmin = (double)GET_UINT64_VAL(&pAgg->min);
×
1849
        tmax = (double)GET_UINT64_VAL(&pAgg->max);
×
1850
      }
1851

1852
      if (GET_DOUBLE_VAL(&pInfo->minval) > tmin) {
1,280,657✔
1853
        SET_DOUBLE_VAL(&pInfo->minval, tmin);
14✔
1854
      }
1855

1856
      if (GET_DOUBLE_VAL(&pInfo->maxval) < tmax) {
1,280,657✔
1857
        SET_DOUBLE_VAL(&pInfo->maxval, tmax);
14✔
1858
      }
1859

1860
      pInfo->numOfElems += (pInput->numOfRows - pAgg->numOfNull);
1,280,657✔
1861
    } else {
1862
      // check the valid data one by one
1863
      int32_t start = pInput->startRowIndex;
9,136✔
1864
      for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
9,762,239✔
1865
        if (colDataIsNull_f(pCol->nullbitmap, i)) {
9,753,103✔
1866
          continue;
2,600✔
1867
        }
1868

1869
        char* data = colDataGetData(pCol, i);
9,750,503!
1870

1871
        double v = 0;
9,750,503✔
1872
        GET_TYPED_DATA(v, double, type, data);
9,750,503!
1873
        if (v < GET_DOUBLE_VAL(&pInfo->minval)) {
9,750,503✔
1874
          SET_DOUBLE_VAL(&pInfo->minval, v);
4,147✔
1875
        }
1876

1877
        if (v > GET_DOUBLE_VAL(&pInfo->maxval)) {
9,750,503✔
1878
          SET_DOUBLE_VAL(&pInfo->maxval, v);
409,443✔
1879
        }
1880

1881
        pInfo->numOfElems += 1;
9,750,503✔
1882
      }
1883
    }
1884
  } else {
1885
    // the second stage, calculate the true percentile value
1886
    int32_t start = pInput->startRowIndex;
1,287,787✔
1887
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
2,147,483,647✔
1888
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
2,147,483,647!
1889
        continue;
×
1890
      }
1891

1892
      char* data = colDataGetData(pCol, i);
2,147,483,647!
1893
      numOfElems += 1;
2,147,483,647✔
1894
      code = tMemBucketPut(pInfo->pMemBucket, data, 1);
2,147,483,647✔
1895
      if (code != TSDB_CODE_SUCCESS) {
2,147,483,647!
1896
        tMemBucketDestroy(&(pInfo->pMemBucket));
×
1897
        return code;
×
1898
      }
1899
    }
1900

1901
    SET_VAL(pResInfo, numOfElems, 1);
1,287,787!
1902
  }
1903

1904
  pCtx->needCleanup = true;
2,577,580✔
1905
  return TSDB_CODE_SUCCESS;
2,577,580✔
1906
}
1907

1908
int32_t percentileFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
5,889✔
1909
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5,889✔
1910
  SPercentileInfo*     ppInfo = (SPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
5,889✔
1911

1912
  int32_t code = 0;
5,889✔
1913
  double  v = 0;
5,889✔
1914

1915
  tMemBucket** pMemBucket = &ppInfo->pMemBucket;
5,889✔
1916
  if ((*pMemBucket) != NULL && (*pMemBucket)->total > 0) {  // check for null
5,889!
1917
    if (pCtx->numOfParams > 2) {
3,883✔
1918
      char buf[3200] = {0};
22✔
1919
      // max length of double num is 317, e.g. use %.6lf to print -1.0e+308, consider the comma and bracket, 3200 is
1920
      // enough.
1921
      size_t len = 1;
22✔
1922

1923
      varDataVal(buf)[0] = '[';
22✔
1924
      for (int32_t i = 1; i < pCtx->numOfParams; ++i) {
210✔
1925
        SVariant* pVal = &pCtx->param[i].param;
188✔
1926

1927
        GET_TYPED_DATA(v, double, pVal->nType, &pVal->i);
188!
1928

1929
        code = getPercentile((*pMemBucket), v, &ppInfo->result);
188✔
1930
        if (code != TSDB_CODE_SUCCESS) {
188!
1931
          goto _fin_error;
×
1932
        }
1933

1934
        if (i == pCtx->numOfParams - 1) {
188✔
1935
          len += tsnprintf(varDataVal(buf) + len, sizeof(buf) - VARSTR_HEADER_SIZE - len, "%.6lf]", ppInfo->result);
22✔
1936
        } else {
1937
          len += tsnprintf(varDataVal(buf) + len, sizeof(buf) - VARSTR_HEADER_SIZE - len, "%.6lf, ", ppInfo->result);
166✔
1938
        }
1939
      }
1940

1941
      int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
22✔
1942
      SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
22✔
1943
      if (NULL == pCol) {
22!
1944
        code = terrno;
×
1945
        goto _fin_error;
×
1946
      }
1947

1948
      varDataSetLen(buf, len);
22✔
1949
      code = colDataSetVal(pCol, pBlock->info.rows, buf, false);
22✔
1950
      if (code != TSDB_CODE_SUCCESS) {
22!
1951
        goto _fin_error;
×
1952
      }
1953

1954
      tMemBucketDestroy(pMemBucket);
22✔
1955
      return TSDB_CODE_SUCCESS;
22✔
1956
    } else {
1957
      SVariant* pVal = &pCtx->param[1].param;
3,861✔
1958

1959
      GET_TYPED_DATA(v, double, pVal->nType, &pVal->i);
3,861!
1960

1961
      code = getPercentile((*pMemBucket), v, &ppInfo->result);
3,861✔
1962
      if (code != TSDB_CODE_SUCCESS) {
3,861!
1963
        goto _fin_error;
×
1964
      }
1965

1966
      tMemBucketDestroy(pMemBucket);
3,861✔
1967
      return functionFinalize(pCtx, pBlock);
3,861✔
1968
    }
1969
  } else {
1970
    return functionFinalize(pCtx, pBlock);
2,006✔
1971
  }
1972

1973
_fin_error:
×
1974

1975
  tMemBucketDestroy(pMemBucket);
×
1976
  return code;
×
1977
}
1978

1979
bool getApercentileFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
96,685✔
1980
  int32_t bytesHist =
96,685✔
1981
      (int32_t)(sizeof(SAPercentileInfo) + sizeof(SHistogramInfo) + sizeof(SHistBin) * (MAX_HISTOGRAM_BIN + 1));
1982
  int32_t bytesDigest = (int32_t)(sizeof(SAPercentileInfo) + TDIGEST_SIZE(COMPRESSION));
96,685✔
1983
  pEnv->calcMemSize = TMAX(bytesHist, bytesDigest);
96,685✔
1984
  return true;
96,685✔
1985
}
1986

1987
int32_t getApercentileMaxSize() {
42,404✔
1988
  int32_t bytesHist =
42,404✔
1989
      (int32_t)(sizeof(SAPercentileInfo) + sizeof(SHistogramInfo) + sizeof(SHistBin) * (MAX_HISTOGRAM_BIN + 1));
1990
  int32_t bytesDigest = (int32_t)(sizeof(SAPercentileInfo) + TDIGEST_SIZE(COMPRESSION));
42,404✔
1991
  return TMAX(bytesHist, bytesDigest);
42,404✔
1992
}
1993

1994
static int8_t getApercentileAlgo(char* algoStr) {
4,852,420✔
1995
  int8_t algoType;
1996
  if (strcasecmp(algoStr, "default") == 0) {
4,852,420✔
1997
    algoType = APERCT_ALGO_DEFAULT;
11,146✔
1998
  } else if (strcasecmp(algoStr, "t-digest") == 0) {
4,841,274!
1999
    algoType = APERCT_ALGO_TDIGEST;
4,841,274✔
2000
  } else {
2001
    algoType = APERCT_ALGO_UNKNOWN;
×
2002
  }
2003

2004
  return algoType;
4,852,420✔
2005
}
2006

2007
static void buildHistogramInfo(SAPercentileInfo* pInfo) {
898,510✔
2008
  pInfo->pHisto = (SHistogramInfo*)((char*)pInfo + sizeof(SAPercentileInfo));
898,510✔
2009
  pInfo->pHisto->elems = (SHistBin*)((char*)pInfo->pHisto + sizeof(SHistogramInfo));
898,510✔
2010
}
898,510✔
2011

2012
static void buildTDigestInfo(SAPercentileInfo* pInfo) {
9,705,789✔
2013
  pInfo->pTDigest = (TDigest*)((char*)pInfo + sizeof(SAPercentileInfo));
9,705,789✔
2014
}
9,705,789✔
2015

2016
int32_t apercentileFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
5,141,714✔
2017
  if (pResultInfo->initialized) {
5,141,714!
2018
    return TSDB_CODE_SUCCESS;
×
2019
  }
2020
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
5,141,714!
2021
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
2022
  }
2023

2024
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
5,141,765✔
2025

2026
  SVariant* pVal = &pCtx->param[1].param;
5,141,765✔
2027
  pInfo->percent = 0;
5,141,765✔
2028
  GET_TYPED_DATA(pInfo->percent, double, pVal->nType, &pVal->i);
5,141,765!
2029

2030
  if (pCtx->numOfParams == 2) {
5,141,765✔
2031
    pInfo->algo = APERCT_ALGO_DEFAULT;
289,345✔
2032
  } else if (pCtx->numOfParams == 3) {
4,852,420!
2033
    pInfo->algo = getApercentileAlgo(varDataVal(pCtx->param[2].param.pz));
4,852,424✔
2034
    if (pInfo->algo == APERCT_ALGO_UNKNOWN) {
4,852,421!
2035
      return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
2036
    }
2037
  }
2038

2039
  char* tmp = (char*)pInfo + sizeof(SAPercentileInfo);
5,141,762✔
2040
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
5,141,762✔
2041
    pInfo->pTDigest = tdigestNewFrom(tmp, COMPRESSION);
4,841,275✔
2042
  } else {
2043
    buildHistogramInfo(pInfo);
300,487✔
2044
    pInfo->pHisto = tHistogramCreateFrom(tmp, MAX_HISTOGRAM_BIN);
300,489✔
2045
    qDebug("%s set up histogram, numOfElems:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
300,490✔
2046
           pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2047
  }
2048

2049
  return TSDB_CODE_SUCCESS;
5,141,772✔
2050
}
2051

2052
int32_t apercentileFunction(SqlFunctionCtx* pCtx) {
5,139,252✔
2053
  int32_t               numOfElems = 0;
5,139,252✔
2054
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
5,139,252✔
2055
  SInputColumnInfoData* pInput = &pCtx->input;
5,139,252✔
2056

2057
  SColumnInfoData* pCol = pInput->pData[0];
5,139,252✔
2058
  int32_t          type = pCol->info.type;
5,139,252✔
2059

2060
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5,139,252✔
2061

2062
  int32_t start = pInput->startRowIndex;
5,139,252✔
2063
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
5,139,252✔
2064
    buildTDigestInfo(pInfo);
4,832,309✔
2065
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
4,832,305✔
2066
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
17,961,691✔
2067
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
13,129,357✔
2068
        continue;
284,025✔
2069
      }
2070
      numOfElems += 1;
12,845,332✔
2071
      char* data = colDataGetData(pCol, i);
12,845,332!
2072

2073
      double  v = 0;  // value
12,845,332✔
2074
      int64_t w = 1;  // weigth
12,845,332✔
2075
      GET_TYPED_DATA(v, double, type, data);
12,845,332!
2076
      int32_t code = tdigestAdd(pInfo->pTDigest, v, w);
12,845,332✔
2077
      if (code != TSDB_CODE_SUCCESS) {
12,845,364!
2078
        return code;
×
2079
      }
2080
    }
2081
  } else {
2082
    // might be a race condition here that pHisto can be overwritten or setup function
2083
    // has not been called, need to relink the buffer pHisto points to.
2084
    buildHistogramInfo(pInfo);
306,943✔
2085
    qDebug("%s before add %d elements into histogram, total:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems: %p",
306,938✔
2086
           __FUNCTION__, numOfElems, pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto,
2087
           pInfo->pHisto->elems);
2088
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
2,811,736✔
2089
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
2,504,504✔
2090
        continue;
809,720✔
2091
      }
2092
      numOfElems += 1;
1,694,784✔
2093
      char* data = colDataGetData(pCol, i);
1,694,784!
2094

2095
      double v = 0;
1,694,784✔
2096
      GET_TYPED_DATA(v, double, type, data);
1,694,784!
2097
      int32_t code = tHistogramAdd(&pInfo->pHisto, v);
1,694,784✔
2098
      if (code != TSDB_CODE_SUCCESS) {
1,695,074!
2099
        return code;
×
2100
      }
2101
    }
2102

2103
    qDebug("%s after add %d elements into histogram, total:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems: %p",
307,232✔
2104
           __FUNCTION__, numOfElems, pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto,
2105
           pInfo->pHisto->elems);
2106
  }
2107

2108
  SET_VAL(pResInfo, numOfElems, 1);
5,139,274✔
2109
  return TSDB_CODE_SUCCESS;
5,139,274✔
2110
}
2111

2112
static int32_t apercentileTransferInfo(SAPercentileInfo* pInput, SAPercentileInfo* pOutput, bool* hasRes) {
41,211✔
2113
  pOutput->percent = pInput->percent;
41,211✔
2114
  pOutput->algo = pInput->algo;
41,211✔
2115
  if (pOutput->algo == APERCT_ALGO_TDIGEST) {
41,211✔
2116
    buildTDigestInfo(pInput);
33,710✔
2117
    tdigestAutoFill(pInput->pTDigest, COMPRESSION);
33,710✔
2118

2119
    if (pInput->pTDigest->num_centroids == 0 && pInput->pTDigest->num_buffered_pts == 0) {
33,710✔
2120
      return TSDB_CODE_SUCCESS;
1✔
2121
    }
2122

2123
    if (hasRes) {
33,709✔
2124
      *hasRes = true;
33,707✔
2125
    }
2126

2127
    buildTDigestInfo(pOutput);
33,709✔
2128
    TDigest* pTDigest = pOutput->pTDigest;
33,709✔
2129
    tdigestAutoFill(pTDigest, COMPRESSION);
33,709✔
2130

2131
    if (pTDigest->num_centroids <= 0 && pTDigest->num_buffered_pts == 0) {
33,709✔
2132
      (void)memcpy(pTDigest, pInput->pTDigest, (size_t)TDIGEST_SIZE(COMPRESSION));
17,271✔
2133
      tdigestAutoFill(pTDigest, COMPRESSION);
17,271✔
2134
    } else {
2135
      int32_t code = tdigestMerge(pTDigest, pInput->pTDigest);
16,438✔
2136
      if (TSDB_CODE_SUCCESS != code) {
16,438!
2137
        return code;
×
2138
      }
2139
    }
2140
  } else {
2141
    buildHistogramInfo(pInput);
7,501✔
2142
    if (pInput->pHisto->numOfElems <= 0) {
7,501✔
2143
      return TSDB_CODE_SUCCESS;
159✔
2144
    }
2145

2146
    if (hasRes) {
7,342✔
2147
      *hasRes = true;
7,340✔
2148
    }
2149

2150
    buildHistogramInfo(pOutput);
7,342✔
2151
    SHistogramInfo* pHisto = pOutput->pHisto;
7,342✔
2152

2153
    if (pHisto->numOfElems <= 0) {
7,342✔
2154
      (void)memcpy(pHisto, pInput->pHisto, sizeof(SHistogramInfo) + sizeof(SHistBin) * (MAX_HISTOGRAM_BIN + 1));
6,871✔
2155
      pHisto->elems = (SHistBin*)((char*)pHisto + sizeof(SHistogramInfo));
6,871✔
2156

2157
      qDebug("%s merge histo, total:%" PRId64 ", entry:%d, %p", __FUNCTION__, pHisto->numOfElems, pHisto->numOfEntries,
6,871✔
2158
             pHisto);
2159
    } else {
2160
      pHisto->elems = (SHistBin*)((char*)pHisto + sizeof(SHistogramInfo));
471✔
2161
      qDebug("%s input histogram, elem:%" PRId64 ", entry:%d, %p", __FUNCTION__, pHisto->numOfElems,
471✔
2162
             pHisto->numOfEntries, pInput->pHisto);
2163

2164
      SHistogramInfo* pRes = NULL;
471✔
2165
      int32_t         code = tHistogramMerge(pHisto, pInput->pHisto, MAX_HISTOGRAM_BIN, &pRes);
471✔
2166
      if (TSDB_CODE_SUCCESS != code) {
471!
2167
        tHistogramDestroy(&pRes);
×
2168
        return code;
×
2169
      }
2170
      (void)memcpy(pHisto, pRes, sizeof(SHistogramInfo) + sizeof(SHistBin) * MAX_HISTOGRAM_BIN);
471✔
2171
      pHisto->elems = (SHistBin*)((char*)pHisto + sizeof(SHistogramInfo));
471✔
2172

2173
      qDebug("%s merge histo, total:%" PRId64 ", entry:%d, %p", __FUNCTION__, pHisto->numOfElems, pHisto->numOfEntries,
471✔
2174
             pHisto);
2175
      tHistogramDestroy(&pRes);
471✔
2176
    }
2177
  }
2178
  return TSDB_CODE_SUCCESS;
41,051✔
2179
}
2180

2181
int32_t apercentileFunctionMerge(SqlFunctionCtx* pCtx) {
24,689✔
2182
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
24,689✔
2183

2184
  SInputColumnInfoData* pInput = &pCtx->input;
24,689✔
2185

2186
  SColumnInfoData* pCol = pInput->pData[0];
24,689✔
2187
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
24,689!
2188
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
2189
  }
2190

2191
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
24,689✔
2192

2193
  qDebug("%s total %" PRId64 " rows will merge, %p", __FUNCTION__, pInput->numOfRows, pInfo->pHisto);
24,689✔
2194

2195
  bool    hasRes = false;
24,689✔
2196
  int32_t start = pInput->startRowIndex;
24,689✔
2197
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
65,896✔
2198
    char* data = colDataGetData(pCol, i);
41,207!
2199

2200
    SAPercentileInfo* pInputInfo = (SAPercentileInfo*)varDataVal(data);
41,207✔
2201
    int32_t           code = apercentileTransferInfo(pInputInfo, pInfo, &hasRes);
41,207✔
2202
    if (TSDB_CODE_SUCCESS != code) {
41,207!
2203
      return code;
×
2204
    }
2205
  }
2206

2207
  if (pInfo->algo != APERCT_ALGO_TDIGEST) {
24,689✔
2208
    buildHistogramInfo(pInfo);
7,417✔
2209
    qDebug("%s after merge, total:%" PRId64 ", numOfEntry:%d, %p", __FUNCTION__, pInfo->pHisto->numOfElems,
7,417✔
2210
           pInfo->pHisto->numOfEntries, pInfo->pHisto);
2211
  }
2212

2213
  SET_VAL(pResInfo, hasRes ? 1 : 0, 1);
24,689✔
2214
  return TSDB_CODE_SUCCESS;
24,689✔
2215
}
2216

2217
int32_t apercentileFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
5,074,943✔
2218
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5,074,943✔
2219
  SAPercentileInfo*    pInfo = (SAPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
5,074,943✔
2220

2221
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
5,074,943✔
2222
    buildTDigestInfo(pInfo);
4,806,066✔
2223
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
4,806,065✔
2224
    if (pInfo->pTDigest->size > 0) {
4,806,066!
2225
      pInfo->result = tdigestQuantile(pInfo->pTDigest, pInfo->percent / 100);
4,806,066✔
2226
    } else {  // no need to free
2227
      // setNull(pCtx->pOutput, pCtx->outputType, pCtx->outputBytes);
2228
      return TSDB_CODE_SUCCESS;
×
2229
    }
2230
  } else {
2231
    buildHistogramInfo(pInfo);
268,877✔
2232
    if (pInfo->pHisto->numOfElems > 0) {
268,880✔
2233
      qDebug("%s get the final res, elements:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
219,967✔
2234
             pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2235

2236
      double  ratio[] = {pInfo->percent};
219,967✔
2237
      double* res = NULL;
219,967✔
2238
      int32_t code = tHistogramUniform(pInfo->pHisto, ratio, 1, &res);
219,967✔
2239
      if (TSDB_CODE_SUCCESS != code) {
219,972!
2240
        taosMemoryFree(res);
×
2241
        return code;
×
2242
      }
2243
      pInfo->result = *res;
219,972✔
2244
      // memcpy(pCtx->pOutput, res, sizeof(double));
2245
      taosMemoryFree(res);
219,972!
2246
    } else {  // no need to free
2247
      // setNull(pCtx->pOutput, pCtx->outputType, pCtx->outputBytes);
2248
      // return TSDB_CODE_SUCCESS;
2249
      qDebug("%s get the final res, elements:%" PRId64 ", numOfEntry:%d. result is null", __FUNCTION__,
48,913✔
2250
             pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries);
2251
    }
2252
  }
2253

2254
  return functionFinalize(pCtx, pBlock);
5,074,948✔
2255
}
2256

2257
int32_t apercentilePartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
40,818✔
2258
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
40,818✔
2259
  SAPercentileInfo*    pInfo = (SAPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
40,818✔
2260

2261
  int32_t resultBytes = getApercentileMaxSize();
40,818✔
2262
  char*   res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
40,833!
2263
  if (NULL == res) {
40,861!
2264
    return terrno;
×
2265
  }
2266

2267
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
40,861✔
2268
    (void)memcpy(varDataVal(res), pInfo, resultBytes);
33,689✔
2269
    varDataSetLen(res, resultBytes);
33,689✔
2270
  } else {
2271
    (void)memcpy(varDataVal(res), pInfo, resultBytes);
7,172✔
2272
    varDataSetLen(res, resultBytes);
7,172✔
2273
  }
2274

2275
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
40,861✔
2276
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
40,861✔
2277
  if (NULL == pCol) {
40,860!
2278
    taosMemoryFree(res);
×
2279
    return TSDB_CODE_OUT_OF_RANGE;
×
2280
  }
2281

2282
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
40,860✔
2283

2284
  taosMemoryFree(res);
40,824!
2285
  return code;
40,871✔
2286
}
2287

2288
int32_t apercentileCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
4✔
2289
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
4✔
2290
  SAPercentileInfo*    pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
4✔
2291

2292
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
4✔
2293
  SAPercentileInfo*    pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
4✔
2294

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

2297
  int32_t code = apercentileTransferInfo(pSBuf, pDBuf, NULL);
4✔
2298
  if (TSDB_CODE_SUCCESS != code) {
4!
2299
    return code;
×
2300
  }
2301
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
4✔
2302
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
4✔
2303
  return TSDB_CODE_SUCCESS;
4✔
2304
}
2305

2306
// TODO: change this function when block data info pks changed
2307
static int32_t comparePkDataWithSValue(int8_t pkType, char* pkData, SValue* pVal, int32_t order) {
11✔
2308
  char numVal[8] = {0};
11✔
2309
  switch (pkType) {
11!
2310
    case TSDB_DATA_TYPE_INT:
11✔
2311
      *(int32_t*)numVal = (int32_t)pVal->val;
11✔
2312
      break;
11✔
2313
    case TSDB_DATA_TYPE_UINT:
×
2314
      *(uint32_t*)numVal = (uint32_t)pVal->val;
×
2315
      break;
×
2316
    case TSDB_DATA_TYPE_BIGINT:
×
2317
      *(int64_t*)numVal = (int64_t)pVal->val;
×
2318
      break;
×
2319
    case TSDB_DATA_TYPE_UBIGINT:
×
2320
      *(uint64_t*)numVal = (uint64_t)pVal->val;
×
2321
      break;
×
2322
    default:
×
2323
      break;
×
2324
  }
2325
  char*         blockData = (IS_NUMERIC_TYPE(pkType)) ? (char*)numVal : (char*)pVal->pData;
11!
2326
  __compar_fn_t fn = getKeyComparFunc(pkType, order);
11✔
2327
  return fn(pkData, blockData);
11✔
2328
}
2329

2330
EFuncDataRequired firstDynDataReq(void* pRes, SDataBlockInfo* pBlockInfo) {
4,137✔
2331
  SResultRowEntryInfo* pEntry = (SResultRowEntryInfo*)pRes;
4,137✔
2332

2333
  // not initialized yet, data is required
2334
  if (pEntry == NULL) {
4,137!
2335
    return FUNC_DATA_REQUIRED_DATA_LOAD;
×
2336
  }
2337

2338
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
4,137✔
2339
  if (pResult->hasResult) {
4,137✔
2340
    if (pResult->pkBytes > 0) {
4,086✔
2341
      pResult->pkData = pResult->buf + pResult->bytes;
6✔
2342
    } else {
2343
      pResult->pkData = NULL;
4,080✔
2344
    }
2345
    if (pResult->ts < pBlockInfo->window.skey) {
4,086✔
2346
      return FUNC_DATA_REQUIRED_NOT_LOAD;
2,839✔
2347
    } else if (pResult->ts == pBlockInfo->window.skey) {
1,247✔
2348
      if (NULL == pResult->pkData) {
251✔
2349
        return FUNC_DATA_REQUIRED_NOT_LOAD;
245✔
2350
      }
2351
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 0, TSDB_ORDER_ASC) < 0) {
6!
2352
        return FUNC_DATA_REQUIRED_NOT_LOAD;
6✔
2353
      }
2354
    }
2355
    return FUNC_DATA_REQUIRED_DATA_LOAD;
996✔
2356
  } else {
2357
    return FUNC_DATA_REQUIRED_DATA_LOAD;
51✔
2358
  }
2359
}
2360

2361
EFuncDataRequired lastDynDataReq(void* pRes, SDataBlockInfo* pBlockInfo) {
10,844✔
2362
  SResultRowEntryInfo* pEntry = (SResultRowEntryInfo*)pRes;
10,844✔
2363

2364
  // not initialized yet, data is required
2365
  if (pEntry == NULL) {
10,844!
2366
    return FUNC_DATA_REQUIRED_DATA_LOAD;
×
2367
  }
2368

2369
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
10,844✔
2370
  if (pResult->hasResult) {
10,844✔
2371
    if (pResult->pkBytes > 0) {
10,762✔
2372
      pResult->pkData = pResult->buf + pResult->bytes;
5✔
2373
    } else {
2374
      pResult->pkData = NULL;
10,757✔
2375
    }
2376
    if (pResult->ts > pBlockInfo->window.ekey) {
10,762✔
2377
      return FUNC_DATA_REQUIRED_NOT_LOAD;
8,456✔
2378
    } else if (pResult->ts == pBlockInfo->window.ekey && pResult->pkData) {
2,306✔
2379
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 1, TSDB_ORDER_DESC) < 0) {
5!
2380
        return FUNC_DATA_REQUIRED_NOT_LOAD;
×
2381
      }
2382
    }
2383
    return FUNC_DATA_REQUIRED_DATA_LOAD;
2,306✔
2384
  } else {
2385
    return FUNC_DATA_REQUIRED_DATA_LOAD;
82✔
2386
  }
2387
}
2388

2389
// TODO modify it to include primary key bytes
2390
int32_t getFirstLastInfoSize(int32_t resBytes, int32_t pkBytes) { return sizeof(SFirstLastRes) + resBytes + pkBytes; }
88,665,308✔
2391

2392
bool getFirstLastFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
1,794,789✔
2393
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
1,794,789✔
2394
  // TODO: change SFunctionNode to add pk info
2395
  int32_t pkBytes = (pFunc->hasPk) ? pFunc->pkBytes : 0;
1,796,693✔
2396
  pEnv->calcMemSize = getFirstLastInfoSize(pNode->node.resType.bytes, pkBytes);
1,796,693✔
2397
  return true;
1,798,014✔
2398
}
2399

2400
bool getSelectivityFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
1,208,465✔
2401
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
1,208,465✔
2402
  pEnv->calcMemSize = pNode->node.resType.bytes;
1,209,843✔
2403
  return true;
1,209,843✔
2404
}
2405

2406
bool getGroupKeyFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
252,843✔
2407
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
252,843✔
2408
  pEnv->calcMemSize = sizeof(SGroupKeyInfo) + pNode->node.resType.bytes;
253,154✔
2409
  return true;
253,154✔
2410
}
2411

2412
static FORCE_INLINE TSKEY getRowPTs(SColumnInfoData* pTsColInfo, int32_t rowIndex) {
2413
  if (pTsColInfo == NULL || pTsColInfo->pData == NULL) {
473,868,134!
2414
    return 0;
×
2415
  }
2416

2417
  return *(TSKEY*)colDataGetData(pTsColInfo, rowIndex);
473,920,500!
2418
}
2419

2420
int32_t firstLastFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
22,409,905✔
2421
  if (pResInfo->initialized) {
22,409,905!
2422
    return TSDB_CODE_SUCCESS;
×
2423
  }
2424
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
22,409,905!
2425
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
2426
  }
2427

2428
  SFirstLastRes*        pRes = GET_ROWCELL_INTERBUF(pResInfo);
22,410,524✔
2429
  pRes->nullTupleSaved = false;
22,410,524✔
2430
  pRes->nullTuplePos.pageId = -1;
22,410,524✔
2431
  return TSDB_CODE_SUCCESS;
22,410,524✔
2432
}
2433

2434
static int32_t prepareBuf(SqlFunctionCtx* pCtx) {
267,314,703✔
2435
  if (pCtx->subsidiaries.rowLen == 0) {
267,314,703✔
2436
    int32_t rowLen = 0;
660,876✔
2437
    for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
1,327,569✔
2438
      SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
666,693✔
2439
      rowLen += pc->pExpr->base.resSchema.bytes;
666,693✔
2440
    }
2441

2442
    pCtx->subsidiaries.rowLen = rowLen + pCtx->subsidiaries.num * sizeof(bool);
660,876✔
2443
    pCtx->subsidiaries.buf = taosMemoryMalloc(pCtx->subsidiaries.rowLen);
660,876!
2444
    if (NULL == pCtx->subsidiaries.buf) {
660,105!
2445
      return terrno;
×
2446
    }
2447
  }
2448
  return TSDB_CODE_SUCCESS;
267,313,932✔
2449
}
2450

2451
static int32_t firstlastSaveTupleData(const SSDataBlock* pSrcBlock, int32_t rowIndex, SqlFunctionCtx* pCtx,
262,272,331✔
2452
                                      SFirstLastRes* pInfo, bool noElements) {
2453
  int32_t code = TSDB_CODE_SUCCESS;
262,272,331✔
2454

2455
  if (pCtx->subsidiaries.num <= 0) {
262,272,331✔
2456
    return TSDB_CODE_SUCCESS;
124,933,173✔
2457
  }
2458

2459
  if (!pInfo->hasResult) {
137,339,158✔
2460
    code = saveTupleData(pCtx, rowIndex, pSrcBlock, &pInfo->pos);
113,957,741✔
2461
  } else if (!noElements) {
23,381,417!
2462
    code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pInfo->pos);
23,501,706✔
2463
  } else { } // dothing
2464

2465
  return code;
136,937,524✔
2466
}
2467

2468
static int32_t doSaveCurrentVal(SqlFunctionCtx* pCtx, int32_t rowIndex, int64_t currentTs, char* pkData, int32_t type,
92,317,717✔
2469
                                char* pData) {
2470
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
92,317,717✔
2471
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
92,317,717✔
2472

2473
  if (IS_VAR_DATA_TYPE(type)) {
92,317,717!
2474
    if (type == TSDB_DATA_TYPE_JSON) {
3,905,697!
2475
      pInfo->bytes = getJsonValueLen(pData);
×
2476
    } else {
2477
      pInfo->bytes = varDataTLen(pData);
3,905,697✔
2478
    }
2479
  }
2480

2481
  (void)memcpy(pInfo->buf, pData, pInfo->bytes);
92,317,717✔
2482
  if (pkData != NULL) {
92,317,717✔
2483
    if (IS_VAR_DATA_TYPE(pInfo->pkType)) {
30,118!
2484
      if (pInfo->pkType == TSDB_DATA_TYPE_JSON) {
24!
2485
        pInfo->pkBytes = getJsonValueLen(pkData);
×
2486
      } else {
2487
        pInfo->pkBytes = varDataTLen(pkData);
24✔
2488
      }
2489
    }
2490
    (void)memcpy(pInfo->buf + pInfo->bytes, pkData, pInfo->pkBytes);
30,118✔
2491
    pInfo->pkData = pInfo->buf + pInfo->bytes;
30,118✔
2492
  }
2493

2494
  pInfo->ts = currentTs;
92,317,717✔
2495
  int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pInfo, false);
92,317,717✔
2496
  if (code != TSDB_CODE_SUCCESS) {
92,370,509!
2497
    return code;
×
2498
  }
2499

2500
  pInfo->hasResult = true;
92,370,509✔
2501
  return TSDB_CODE_SUCCESS;
92,370,509✔
2502
}
2503

2504
// This ordinary first function does not care if current scan is ascending order or descending order scan
2505
// the OPTIMIZED version of first function will only handle the ascending order scan
2506
int32_t firstFunction(SqlFunctionCtx* pCtx) {
47,428,016✔
2507
  int32_t numOfElems = 0;
47,428,016✔
2508

2509
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
47,428,016✔
2510
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
47,428,016✔
2511

2512
  SInputColumnInfoData* pInput = &pCtx->input;
47,428,016✔
2513
  SColumnInfoData*      pInputCol = pInput->pData[0];
47,428,016✔
2514

2515
  pInfo->bytes = pInputCol->info.bytes;
47,428,016✔
2516

2517
  if (IS_NULL_TYPE(pInputCol->info.type)) {
47,428,016✔
2518
    return TSDB_CODE_SUCCESS;
4,949✔
2519
  }
2520

2521
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
47,423,067✔
2522
  pInfo->pkType = -1;
47,423,067✔
2523
  __compar_fn_t pkCompareFn = NULL;
47,423,067✔
2524
  if (pCtx->hasPrimaryKey) {
47,423,067✔
2525
    pInfo->pkType = pkCol->info.type;
51✔
2526
    pInfo->pkBytes = pkCol->info.bytes;
51✔
2527
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_ASC);
51✔
2528
  }
2529

2530
  // All null data column, return directly.
2531
  if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) &&
47,506,769!
2532
      pInputCol->hasNull == true) {
×
2533
    // save selectivity value for column consisted of all null values
2534
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
×
2535
    if (code != TSDB_CODE_SUCCESS) {
×
2536
      return code;
×
2537
    }
2538
    pInfo->nullTupleSaved = true;
×
2539
    return TSDB_CODE_SUCCESS;
×
2540
  }
2541

2542
  SColumnDataAgg* pColAgg = (pInput->colDataSMAIsSet) ? pInput->pColumnDataAgg[0] : NULL;
47,506,769!
2543

2544
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
47,506,769!
2545
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
47,506,769!
2546

2547
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
47,506,769✔
2548

2549
  //  please ref. to the comment in lastRowFunction for the reason why disabling the opt version of last/first
2550
  //  function. we will use this opt implementation in an new version that is only available in scan subplan
2551
#if 0
2552
  if (blockDataOrder == TSDB_ORDER_ASC) {
2553
    // filter according to current result firstly
2554
    if (pResInfo->numOfRes > 0) {
2555
      if (pInfo->ts < startKey) {
2556
        return TSDB_CODE_SUCCESS;
2557
      }
2558
    }
2559

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

2565
      numOfElems++;
2566

2567
      char* data = colDataGetData(pInputCol, i);
2568
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2569
      if (pResInfo->numOfRes == 0 || pInfo->ts > cts) {
2570
        doSaveCurrentVal(pCtx, i, cts, pInputCol->info.type, data);
2571
        break;
2572
      }
2573
    }
2574
  } else {
2575
    // in case of descending order time stamp serial, which usually happens as the results of the nest query,
2576
    // all data needs to be check.
2577
    if (pResInfo->numOfRes > 0) {
2578
      if (pInfo->ts < endKey) {
2579
        return TSDB_CODE_SUCCESS;
2580
      }
2581
    }
2582

2583
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
2584
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2585
        continue;
2586
      }
2587

2588
      numOfElems++;
2589

2590
      char* data = colDataGetData(pInputCol, i);
2591
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2592

2593
      if (pResInfo->numOfRes == 0 || pInfo->ts > cts) {
2594
        doSaveCurrentVal(pCtx, i, cts, pInputCol->info.type, data);
2595
        break;
2596
      }
2597
    }
2598
  }
2599
#else
2600
  int64_t* pts = (int64_t*)pInput->pPTS->pData;
47,506,769✔
2601

2602
  int     from = -1;
47,506,769✔
2603
  int32_t i = -1;
47,506,769✔
2604
  while (funcInputGetNextRowIndex(pInput, from, true, &i, &from)) {
144,227,048✔
2605
    if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
126,755,380!
2606
      continue;
69,828✔
2607
    }
2608

2609
    numOfElems++;
96,677,798✔
2610
    char* data = colDataGetData(pInputCol, i);
96,677,798!
2611
    char* pkData = NULL;
96,677,798✔
2612
    if (pCtx->hasPrimaryKey) {
96,677,798✔
2613
      pkData = colDataGetData(pkCol, i);
153!
2614
    }
2615
    TSKEY cts = pts[i];
96,677,798✔
2616
    if (pResInfo->numOfRes == 0 || pInfo->ts > cts ||
96,677,798✔
2617
        (pInfo->ts == cts && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
57,590,868!
2618
      int32_t code = doSaveCurrentVal(pCtx, i, cts, pkData, pInputCol->info.type, data);
39,086,930✔
2619
      if (code != TSDB_CODE_SUCCESS) {
39,059,583!
2620
        return code;
×
2621
      }
2622
      pResInfo->numOfRes = 1;
39,059,583✔
2623
    }
2624
  }
2625
#endif
2626

2627
  if (numOfElems == 0) {
46,816,567✔
2628
    // save selectivity value for column consisted of all null values
2629
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
24,443✔
2630
    if (code != TSDB_CODE_SUCCESS) {
24,443!
2631
      return code;
×
2632
    }
2633
    pInfo->nullTupleSaved = true;
24,443✔
2634
  }
2635
  SET_VAL(pResInfo, numOfElems, 1);
46,816,567✔
2636
  return TSDB_CODE_SUCCESS;
46,816,567✔
2637
}
2638

2639
int32_t lastFunction(SqlFunctionCtx* pCtx) {
46,211,184✔
2640
  int32_t numOfElems = 0;
46,211,184✔
2641

2642
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
46,211,184✔
2643
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
46,211,184✔
2644

2645
  SInputColumnInfoData* pInput = &pCtx->input;
46,211,184✔
2646
  SColumnInfoData*      pInputCol = pInput->pData[0];
46,211,184✔
2647

2648
  int32_t type = pInputCol->info.type;
46,211,184✔
2649
  int32_t bytes = pInputCol->info.bytes;
46,211,184✔
2650

2651
  if (IS_NULL_TYPE(type)) {
46,211,184✔
2652
    return TSDB_CODE_SUCCESS;
4,954✔
2653
  }
2654
  pInfo->bytes = bytes;
46,206,230✔
2655

2656
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
46,206,230✔
2657
  pInfo->pkType = -1;
46,206,230✔
2658
  __compar_fn_t pkCompareFn = NULL;
46,206,230✔
2659
  if (pCtx->hasPrimaryKey) {
46,206,230✔
2660
    pInfo->pkType = pkCol->info.type;
30,067✔
2661
    pInfo->pkBytes = pkCol->info.bytes;
30,067✔
2662
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
30,067✔
2663
  }
2664

2665
  // All null data column, return directly.
2666
  if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) &&
46,283,299!
2667
      pInputCol->hasNull == true) {
×
2668
    // save selectivity value for column consisted of all null values
2669
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
×
2670
    if (code != TSDB_CODE_SUCCESS) {
×
2671
      return code;
×
2672
    }
2673
    pInfo->nullTupleSaved = true;
×
2674
    return TSDB_CODE_SUCCESS;
×
2675
  }
2676

2677
  SColumnDataAgg* pColAgg = (pInput->colDataSMAIsSet) ? pInput->pColumnDataAgg[0] : NULL;
46,283,299!
2678

2679
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
46,283,299!
2680
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
46,283,299!
2681

2682
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
46,283,299✔
2683

2684
  //  please ref. to the comment in lastRowFunction for the reason why disabling the opt version of last/first function.
2685
#if 0
2686
  if (blockDataOrder == TSDB_ORDER_ASC) {
2687
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
2688
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2689
        continue;
2690
      }
2691

2692
      numOfElems++;
2693

2694
      char* data = colDataGetData(pInputCol, i);
2695
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2696
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
2697
        doSaveCurrentVal(pCtx, i, cts, type, data);
2698
      }
2699

2700
      break;
2701
    }
2702
  } else {  // descending order
2703
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
2704
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2705
        continue;
2706
      }
2707

2708
      numOfElems++;
2709

2710
      char* data = colDataGetData(pInputCol, i);
2711
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2712
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
2713
        doSaveCurrentVal(pCtx, i, cts, type, data);
2714
      }
2715
      break;
2716
    }
2717
  }
2718
#else
2719
  int64_t* pts = (int64_t*)pInput->pPTS->pData;
46,283,299✔
2720

2721
#if 0
2722
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
2723
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2724
        continue;
2725
      }
2726

2727
      numOfElems++;
2728
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i]) {
2729
        char* data = colDataGetData(pInputCol, i);
2730
        doSaveCurrentVal(pCtx, i, pts[i], type, data);
2731
        pResInfo->numOfRes = 1;
2732
      }
2733
    }
2734
#else
2735

2736
  // todo refactor
2737
  if (!pInputCol->hasNull && !pCtx->hasPrimaryKey) {
75,246,685✔
2738
    numOfElems = 1;
29,022,891✔
2739

2740
    int32_t round = pInput->numOfRows >> 2;
29,022,891✔
2741
    int32_t reminder = pInput->numOfRows & 0x03;
29,022,891✔
2742

2743
    for (int32_t i = pInput->startRowIndex, tick = 0; tick < round; i += 4, tick += 1) {
43,912,823✔
2744
      int64_t cts = pts[i];
14,894,147✔
2745
      int32_t chosen = i;
14,894,147✔
2746

2747
      if (cts < pts[i + 1]) {
14,894,147✔
2748
        cts = pts[i + 1];
4,846,093✔
2749
        chosen = i + 1;
4,846,093✔
2750
      }
2751

2752
      if (cts < pts[i + 2]) {
14,894,147✔
2753
        cts = pts[i + 2];
4,846,972✔
2754
        chosen = i + 2;
4,846,972✔
2755
      }
2756

2757
      if (cts < pts[i + 3]) {
14,894,147✔
2758
        cts = pts[i + 3];
4,847,133✔
2759
        chosen = i + 3;
4,847,133✔
2760
      }
2761

2762
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
14,894,147✔
2763
        char*   data = colDataGetData(pInputCol, chosen);
3,931,137!
2764
        int32_t code = doSaveCurrentVal(pCtx, chosen, cts, NULL, type, data);
3,931,137✔
2765
        if (code != TSDB_CODE_SUCCESS) {
3,926,922!
2766
          return code;
×
2767
        }
2768
        pResInfo->numOfRes = 1;
3,926,922✔
2769
      }
2770
    }
2771

2772
    for (int32_t i = pInput->startRowIndex + round * 4; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
62,554,457✔
2773
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i]) {
33,591,071✔
2774
        char*   data = colDataGetData(pInputCol, i);
21,688,952!
2775
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], NULL, type, data);
21,688,952✔
2776
        if (code != TSDB_CODE_SUCCESS) {
21,633,662!
2777
          return code;
×
2778
        }
2779
        pResInfo->numOfRes = 1;
21,633,662✔
2780
      }
2781
    }
2782
  } else {
2783
    int     from = -1;
17,260,408✔
2784
    int32_t i = -1;
17,260,408✔
2785
    while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
159,752,114✔
2786
      if (colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
284,994,900✔
2787
        continue;
5,560,755✔
2788
      }
2789

2790
      numOfElems++;
136,936,695✔
2791
      char* pkData = NULL;
136,936,695✔
2792
      if (pCtx->hasPrimaryKey) {
136,936,695✔
2793
        pkData = colDataGetData(pkCol, i);
100,000,193!
2794
      }
2795
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i] ||
136,936,695✔
2796
          (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
109,423,405!
2797
        char*   data = colDataGetData(pInputCol, i);
27,589,463!
2798
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], pkData, type, data);
27,589,463✔
2799
        if (code != TSDB_CODE_SUCCESS) {
27,583,719!
2800
          return code;
×
2801
        }
2802
        pResInfo->numOfRes = 1;
27,583,719✔
2803
      }
2804
    }
2805
  }
2806
#endif
2807

2808
#endif
2809

2810
  // save selectivity value for column consisted of all null values
2811
  if (numOfElems == 0) {
46,406,843✔
2812
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
4,075,414✔
2813
    if (code != TSDB_CODE_SUCCESS) {
4,066,644!
2814
      return code;
×
2815
    }
2816
    pInfo->nullTupleSaved = true;
4,066,644✔
2817
  }
2818

2819
  return TSDB_CODE_SUCCESS;
46,398,073✔
2820
}
2821

2822
static bool firstLastTransferInfoImpl(SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst) {
83,609,796✔
2823
  if (!pInput->hasResult) {
83,609,796✔
2824
    return false;
2✔
2825
  }
2826
  __compar_fn_t pkCompareFn = NULL;
83,609,794✔
2827
  if (pInput->pkData) {
83,609,794✔
2828
    pkCompareFn = getKeyComparFunc(pInput->pkType, (isFirst) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC);
52✔
2829
  }
2830
  if (pOutput->hasResult) {
83,615,487✔
2831
    if (isFirst) {
34,332,577✔
2832
      if (pInput->ts > pOutput->ts ||
8,571,788✔
2833
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
8,571,183!
2834
        return false;
605✔
2835
      }
2836
    } else {
2837
      if (pInput->ts < pOutput->ts ||
25,760,789✔
2838
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
13,812,463!
2839
        return false;
11,950,335✔
2840
      }
2841
    }
2842
  }
2843

2844
  pOutput->isNull = pInput->isNull;
71,664,547✔
2845
  pOutput->ts = pInput->ts;
71,664,547✔
2846
  pOutput->bytes = pInput->bytes;
71,664,547✔
2847
  pOutput->pkType = pInput->pkType;
71,664,547✔
2848

2849
  (void)memcpy(pOutput->buf, pInput->buf, pOutput->bytes);
71,664,547✔
2850
  if (pInput->pkData) {
71,664,547✔
2851
    pOutput->pkBytes = pInput->pkBytes;
47✔
2852
    (void)memcpy(pOutput->buf + pOutput->bytes, pInput->pkData, pOutput->pkBytes);
47✔
2853
    pOutput->pkData = pOutput->buf + pOutput->bytes;
47✔
2854
  }
2855
  return true;
71,664,547✔
2856
}
2857

2858
static int32_t firstLastTransferInfo(SqlFunctionCtx* pCtx, SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst,
83,608,905✔
2859
                                     int32_t rowIndex) {
2860
  if (firstLastTransferInfoImpl(pInput, pOutput, isFirst)) {
83,608,905✔
2861
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pOutput, false);
71,664,681✔
2862
    if (TSDB_CODE_SUCCESS != code) {
71,655,046!
2863
      return code;
×
2864
    }
2865
    pOutput->hasResult = true;
71,655,046✔
2866
  }
2867
  return TSDB_CODE_SUCCESS;
83,598,433✔
2868
}
2869

2870
static int32_t firstLastFunctionMergeImpl(SqlFunctionCtx* pCtx, bool isFirstQuery) {
49,303,128✔
2871
  SInputColumnInfoData* pInput = &pCtx->input;
49,303,128✔
2872
  SColumnInfoData*      pCol = pInput->pData[0];
49,303,128✔
2873

2874
  if (IS_NULL_TYPE(pCol->info.type)) {
49,303,128!
2875
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
2876
    return TSDB_CODE_SUCCESS;
×
2877
  }
2878

2879
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
49,303,128!
2880
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
2881
  }
2882

2883
  SFirstLastRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
49,303,128✔
2884

2885
  int32_t start = pInput->startRowIndex;
49,303,128✔
2886
  int32_t numOfElems = 0;
49,303,128✔
2887

2888
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
135,185,437✔
2889
    if (colDataIsNull_s(pCol, i)) {
171,806,530✔
2890
      continue;
2,285,301✔
2891
    }
2892
    char*          data = colDataGetData(pCol, i);
83,617,964!
2893
    SFirstLastRes* pInputInfo = (SFirstLastRes*)varDataVal(data);
83,617,964✔
2894
    if (pCtx->hasPrimaryKey) {
83,617,964✔
2895
      pInputInfo->pkData = pInputInfo->buf + pInputInfo->bytes;
52✔
2896
    } else {
2897
      pInputInfo->pkData = NULL;
83,617,912✔
2898
    }
2899

2900
    int32_t code = firstLastTransferInfo(pCtx, pInputInfo, pInfo, isFirstQuery, i);
83,617,964✔
2901
    if (code != TSDB_CODE_SUCCESS) {
83,597,008!
2902
      return code;
×
2903
    }
2904
    if (!numOfElems) {
83,597,008✔
2905
      numOfElems = pInputInfo->hasResult ? 1 : 0;
49,292,855✔
2906
    }
2907
  }
2908

2909
  if (numOfElems == 0) {
49,282,172✔
2910
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
8,109✔
2911
    if (code != TSDB_CODE_SUCCESS) {
8,109!
2912
      return code;
×
2913
    }
2914
    pInfo->nullTupleSaved = true;
8,109✔
2915
  }
2916

2917
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
49,282,172✔
2918
  return TSDB_CODE_SUCCESS;
49,282,172✔
2919
}
2920

2921
int32_t firstFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, true); }
11,568,339✔
2922

2923
int32_t lastFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, false); }
37,742,634✔
2924

2925
int32_t firstLastFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
114,115,780✔
2926
  int32_t          code = TSDB_CODE_SUCCESS;
114,115,780✔
2927
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
114,115,780✔
2928
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
114,115,780✔
2929
  if (NULL == pCol) {
114,055,788!
2930
    return TSDB_CODE_OUT_OF_RANGE;
×
2931
  }
2932

2933
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
114,055,788✔
2934
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
114,055,788✔
2935

2936
  SFirstLastRes* pRes = GET_ROWCELL_INTERBUF(pResInfo);
114,055,788✔
2937

2938
  if (pResInfo->isNullRes) {
114,055,788✔
2939
    colDataSetNULL(pCol, pBlock->info.rows);
40,121✔
2940
    return setNullSelectivityValue(pCtx, pBlock, pBlock->info.rows);
40,121✔
2941
  }
2942
  code = colDataSetVal(pCol, pBlock->info.rows, pRes->buf, pRes->isNull || pResInfo->isNullRes);
114,015,667!
2943
  if (TSDB_CODE_SUCCESS != code) {
113,781,792!
2944
    return code;
×
2945
  }
2946

2947
  // handle selectivity
2948
  code = setSelectivityValue(pCtx, pBlock, &pRes->pos, pBlock->info.rows);
113,781,792✔
2949

2950
  return code;
113,780,120✔
2951
}
2952

2953
int32_t firstLastPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
86,829,548✔
2954
  int32_t code = TSDB_CODE_SUCCESS;
86,829,548✔
2955

2956
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
86,829,548✔
2957
  SFirstLastRes*       pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
86,829,548✔
2958

2959
  int32_t resultBytes = getFirstLastInfoSize(pRes->bytes, pRes->pkBytes);
86,829,548✔
2960

2961
  // todo check for failure
2962
  char* res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
86,813,169!
2963
  if (NULL == res) {
87,988,750!
2964
    return terrno;
×
2965
  }
2966
  (void)memcpy(varDataVal(res), pRes, resultBytes);
87,988,750✔
2967

2968
  varDataSetLen(res, resultBytes);
87,988,750✔
2969

2970
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
87,988,750✔
2971
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
87,988,750✔
2972
  if (NULL == pCol) {
87,393,288!
2973
    taosMemoryFree(res);
×
2974
    return TSDB_CODE_OUT_OF_RANGE;
×
2975
  }
2976

2977
  if (pEntryInfo->numOfRes == 0) {
87,456,183✔
2978
    colDataSetNULL(pCol, pBlock->info.rows);
2,377,792!
2979
    code = setNullSelectivityValue(pCtx, pBlock, pBlock->info.rows);
2,377,792✔
2980
  } else {
2981
    code = colDataSetVal(pCol, pBlock->info.rows, res, false);
85,078,391✔
2982
    if (TSDB_CODE_SUCCESS != code) {
84,068,027!
2983
      taosMemoryFree(res);
×
2984
      return code;
×
2985
    }
2986
    code = setSelectivityValue(pCtx, pBlock, &pRes->pos, pBlock->info.rows);
84,068,027✔
2987
  }
2988
  taosMemoryFree(res);
86,344,716!
2989
  return code;
87,713,272✔
2990
}
2991

2992
int32_t lastCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
3✔
2993
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
3✔
2994
  SFirstLastRes*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
3✔
2995
  int32_t              bytes = pDBuf->bytes;
3✔
2996

2997
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
3✔
2998
  SFirstLastRes*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
3✔
2999

3000
  pDBuf->hasResult = firstLastTransferInfoImpl(pSBuf, pDBuf, false);
3✔
3001
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
3✔
3002
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
3✔
3003
  return TSDB_CODE_SUCCESS;
3✔
3004
}
3005

3006
static int32_t doSaveLastrow(SqlFunctionCtx* pCtx, char* pData, int32_t rowIndex, int64_t cts, SFirstLastRes* pInfo) {
94,314,725✔
3007
  SInputColumnInfoData* pInput = &pCtx->input;
94,314,725✔
3008
  SColumnInfoData*      pInputCol = pInput->pData[0];
94,314,725✔
3009
  SColumnInfoData*      pkCol = pInput->pPrimaryKey;
94,314,725✔
3010

3011
  if (colDataIsNull_s(pInputCol, rowIndex)) {
188,629,450✔
3012
    pInfo->isNull = true;
2,145✔
3013
  } else {
3014
    pInfo->isNull = false;
94,312,580✔
3015

3016
    if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
94,312,580!
3017
      if (pInputCol->info.type == TSDB_DATA_TYPE_JSON) {
819!
3018
        pInfo->bytes = getJsonValueLen(pData);
×
3019
      } else {
3020
        pInfo->bytes = varDataTLen(pData);
819✔
3021
      }
3022
    }
3023

3024
    (void)memcpy(pInfo->buf, pData, pInfo->bytes);
94,312,580✔
3025
  }
3026

3027
  if (pCtx->hasPrimaryKey && !colDataIsNull_s(pkCol, rowIndex)) {
94,314,799!
3028
    char* pkData = colDataGetData(pkCol, rowIndex);
74!
3029
    if (IS_VAR_DATA_TYPE(pInfo->pkType)) {
74!
3030
      if (pInfo->pkType == TSDB_DATA_TYPE_JSON) {
12!
3031
        pInfo->pkBytes = getJsonValueLen(pkData);
×
3032
      } else {
3033
        pInfo->pkBytes = varDataTLen(pkData);
12✔
3034
      }
3035
    }
3036
    (void)memcpy(pInfo->buf + pInfo->bytes, pkData, pInfo->pkBytes);
74✔
3037
    pInfo->pkData = pInfo->buf + pInfo->bytes;
74✔
3038
  }
3039
  pInfo->ts = cts;
94,314,725✔
3040
  int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pInfo, false);
94,314,725✔
3041
  if (code != TSDB_CODE_SUCCESS) {
94,132,679!
3042
    return code;
×
3043
  }
3044

3045
  pInfo->hasResult = true;
94,132,679✔
3046

3047
  return TSDB_CODE_SUCCESS;
94,132,679✔
3048
}
3049

3050
int32_t lastRowFunction(SqlFunctionCtx* pCtx) {
95,166,222✔
3051
  int32_t numOfElems = 0;
95,166,222✔
3052

3053
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
95,166,222✔
3054
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
95,166,222✔
3055

3056
  SInputColumnInfoData* pInput = &pCtx->input;
95,166,222✔
3057
  SColumnInfoData*      pInputCol = pInput->pData[0];
95,166,222✔
3058

3059
  int32_t type = pInputCol->info.type;
95,166,222✔
3060
  int32_t bytes = pInputCol->info.bytes;
95,166,222✔
3061
  pInfo->bytes = bytes;
95,166,222✔
3062

3063
  if (IS_NULL_TYPE(type)) {
95,166,222✔
3064
    return TSDB_CODE_SUCCESS;
56✔
3065
  }
3066
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
95,166,166✔
3067
  pInfo->pkType = -1;
95,166,166✔
3068
  __compar_fn_t pkCompareFn = NULL;
95,166,166✔
3069
  if (pCtx->hasPrimaryKey) {
95,166,166✔
3070
    pInfo->pkType = pkCol->info.type;
57✔
3071
    pInfo->pkBytes = pkCol->info.bytes;
57✔
3072
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
57✔
3073
  }
3074
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
95,254,962!
3075
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
95,254,962!
3076

3077
  if (pCtx->order == TSDB_ORDER_ASC && !pCtx->hasPrimaryKey) {
95,254,962!
3078
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
102,410,642!
3079
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
51,209,244✔
3080
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
51,209,244!
3081
      TSKEY cts = getRowPTs(pInput->pPTS, i);
51,209,244!
3082
      numOfElems++;
51,209,244✔
3083

3084
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
51,209,244✔
3085
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
50,131,951✔
3086
        if (code != TSDB_CODE_SUCCESS) return code;
50,124,193!
3087
      }
3088

3089
      break;
51,201,486✔
3090
    }
3091
  } else if (!pCtx->hasPrimaryKey && pCtx->order == TSDB_ORDER_DESC) {
44,045,806!
3092
    // the optimized version only valid if all tuples in one block are monotonious increasing or descreasing.
3093
    // this assumption is NOT always works if project operator exists in downstream.
3094
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
88,195,381!
3095
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
44,209,094✔
3096
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
44,209,094!
3097
      TSKEY cts = getRowPTs(pInput->pPTS, i);
44,209,094!
3098
      numOfElems++;
44,209,094✔
3099

3100
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
44,209,094✔
3101
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
43,901,036✔
3102
        if (code != TSDB_CODE_SUCCESS) return code;
43,712,979!
3103
      }
3104
      break;
44,021,037✔
3105
    }
3106
  } else {
3107
    int64_t* pts = (int64_t*)pInput->pPTS->pData;
×
3108
    int      from = -1;
×
3109
    int32_t  i = -1;
×
3110
    while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
360,913✔
3111
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
489,412✔
3112
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
489,412!
3113
      TSKEY cts = pts[i];
489,412✔
3114

3115
      numOfElems++;
489,412✔
3116
      char* pkData = NULL;
489,412✔
3117
      if (pCtx->hasPrimaryKey) {
489,412✔
3118
        pkData = colDataGetData(pkCol, i);
171!
3119
      }
3120
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts ||
489,412✔
3121
          (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
191,468!
3122
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
297,950✔
3123
        if (code != TSDB_CODE_SUCCESS) {
297,989!
3124
          return code;
×
3125
        }
3126
        pResInfo->numOfRes = 1;
297,989✔
3127
      }
3128
    }
3129
  }
3130

3131
  SET_VAL(pResInfo, numOfElems, 1);
95,189,179!
3132
  return TSDB_CODE_SUCCESS;
95,189,179✔
3133
}
3134

3135
bool getDiffFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
28,827✔
3136
  pEnv->calcMemSize = sizeof(SDiffInfo);
28,827✔
3137
  return true;
28,827✔
3138
}
3139

3140
int32_t diffFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
1,896,450✔
3141
  if (pResInfo->initialized) {
1,896,450✔
3142
    return TSDB_CODE_SUCCESS;
1,815,494✔
3143
  }
3144
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
80,956!
3145
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
3146
  }
3147
  SDiffInfo* pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
80,960✔
3148
  pDiffInfo->hasPrev = false;
80,960✔
3149
  pDiffInfo->isFirstRow = true;
80,960✔
3150
  pDiffInfo->prev.i64 = 0;
80,960✔
3151
  pDiffInfo->prevTs = -1;
80,960✔
3152
  if (pCtx->numOfParams > 1) {
80,960!
3153
    pDiffInfo->ignoreOption = pCtx->param[1].param.i;  // TODO set correct param
80,960✔
3154
  } else {
3155
    pDiffInfo->ignoreOption = 0;
×
3156
  }
3157
  return TSDB_CODE_SUCCESS;
80,960✔
3158
}
3159

3160
static int32_t doSetPrevVal(SDiffInfo* pDiffInfo, int32_t type, const char* pv, int64_t ts) {
1,211,319✔
3161
  switch (type) {
1,211,319!
3162
    case TSDB_DATA_TYPE_BOOL:
28✔
3163
      pDiffInfo->prev.i64 = *(bool*)pv ? 1 : 0;
28✔
3164
      break;
28✔
3165
    case TSDB_DATA_TYPE_UTINYINT:
330✔
3166
    case TSDB_DATA_TYPE_TINYINT:
3167
      pDiffInfo->prev.i64 = *(int8_t*)pv;
330✔
3168
      break;
330✔
3169
    case TSDB_DATA_TYPE_UINT:
53,347✔
3170
    case TSDB_DATA_TYPE_INT:
3171
      pDiffInfo->prev.i64 = *(int32_t*)pv;
53,347✔
3172
      break;
53,347✔
3173
    case TSDB_DATA_TYPE_USMALLINT:
290✔
3174
    case TSDB_DATA_TYPE_SMALLINT:
3175
      pDiffInfo->prev.i64 = *(int16_t*)pv;
290✔
3176
      break;
290✔
3177
    case TSDB_DATA_TYPE_TIMESTAMP:
279✔
3178
    case TSDB_DATA_TYPE_UBIGINT:
3179
    case TSDB_DATA_TYPE_BIGINT:
3180
      pDiffInfo->prev.i64 = *(int64_t*)pv;
279✔
3181
      break;
279✔
3182
    case TSDB_DATA_TYPE_FLOAT:
1,156,595✔
3183
      pDiffInfo->prev.d64 = *(float*)pv;
1,156,595✔
3184
      break;
1,156,595✔
3185
    case TSDB_DATA_TYPE_DOUBLE:
450✔
3186
      pDiffInfo->prev.d64 = *(double*)pv;
450✔
3187
      break;
450✔
3188
    default:
×
3189
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3190
  }
3191
  pDiffInfo->prevTs = ts;
1,211,319✔
3192
  pDiffInfo->hasPrev = true;
1,211,319✔
3193
  return TSDB_CODE_SUCCESS;
1,211,319✔
3194
}
3195

3196
static bool diffIsNegtive(SDiffInfo* pDiffInfo, int32_t type, const char* pv) {
4,585,000✔
3197
  switch (type) {
4,585,000!
3198
    case TSDB_DATA_TYPE_UINT: {
×
3199
      int64_t v = *(uint32_t*)pv;
×
3200
      return v < pDiffInfo->prev.i64;
×
3201
    }
3202
    case TSDB_DATA_TYPE_INT: {
4,107✔
3203
      int64_t v = *(int32_t*)pv;
4,107✔
3204
      return v < pDiffInfo->prev.i64;
4,107✔
3205
    }
3206
    case TSDB_DATA_TYPE_BOOL: {
×
3207
      int64_t v = *(bool*)pv;
×
3208
      return v < pDiffInfo->prev.i64;
×
3209
    }
3210
    case TSDB_DATA_TYPE_UTINYINT: {
×
3211
      int64_t v = *(uint8_t*)pv;
×
3212
      return v < pDiffInfo->prev.i64;
×
3213
    }
3214
    case TSDB_DATA_TYPE_TINYINT: {
6,929✔
3215
      int64_t v = *(int8_t*)pv;
6,929✔
3216
      return v < pDiffInfo->prev.i64;
6,929✔
3217
    }
3218
    case TSDB_DATA_TYPE_USMALLINT: {
×
3219
      int64_t v = *(uint16_t*)pv;
×
3220
      return v < pDiffInfo->prev.i64;
×
3221
    }
3222
    case TSDB_DATA_TYPE_SMALLINT: {
6,537✔
3223
      int64_t v = *(int16_t*)pv;
6,537✔
3224
      return v < pDiffInfo->prev.i64;
6,537✔
3225
    }
3226
    case TSDB_DATA_TYPE_UBIGINT: {
24✔
3227
      uint64_t v = *(uint64_t*)pv;
24✔
3228
      return v < (uint64_t)pDiffInfo->prev.i64;
24✔
3229
    }
3230
    case TSDB_DATA_TYPE_TIMESTAMP:
3,929✔
3231
    case TSDB_DATA_TYPE_BIGINT: {
3232
      int64_t v = *(int64_t*)pv;
3,929✔
3233
      return v < pDiffInfo->prev.i64;
3,929✔
3234
    }
3235
    case TSDB_DATA_TYPE_FLOAT: {
4,557,334✔
3236
      float v = *(float*)pv;
4,557,334✔
3237
      return v < pDiffInfo->prev.d64;
4,557,334✔
3238
    }
3239
    case TSDB_DATA_TYPE_DOUBLE: {
6,140✔
3240
      double v = *(double*)pv;
6,140✔
3241
      return v < pDiffInfo->prev.d64;
6,140✔
3242
    }
3243
    default:
×
3244
      return false;
×
3245
  }
3246

3247
  return false;
3248
}
3249

3250
static void tryToSetInt64(SDiffInfo* pDiffInfo, int32_t type, SColumnInfoData* pOutput, int64_t v, int32_t pos) {
1,527,949,844✔
3251
  bool isNegative = v < pDiffInfo->prev.i64;
1,527,949,844✔
3252
  if (type == TSDB_DATA_TYPE_UBIGINT) {
1,527,949,844✔
3253
    isNegative = (uint64_t)v < (uint64_t)pDiffInfo->prev.i64;
453✔
3254
  }
3255
  int64_t delta = v - pDiffInfo->prev.i64;
1,527,949,844✔
3256
  if (isNegative && ignoreNegative(pDiffInfo->ignoreOption)) {
1,527,949,844✔
3257
    colDataSetNull_f_s(pOutput, pos);
10,588✔
3258
    pOutput->hasNull = true;
10,588✔
3259
  } else {
3260
    colDataSetInt64(pOutput, pos, &delta);
1,527,939,256✔
3261
  }
3262
  pDiffInfo->prev.i64 = v;
1,527,949,844✔
3263
}
1,527,949,844✔
3264

3265
static void tryToSetDouble(SDiffInfo* pDiffInfo, SColumnInfoData* pOutput, double v, int32_t pos) {
5,581,456✔
3266
  double delta = v - pDiffInfo->prev.d64;
5,581,456✔
3267
  if (delta < 0 && ignoreNegative(pDiffInfo->ignoreOption)) {
5,581,456✔
3268
    colDataSetNull_f_s(pOutput, pos);
1,057,913✔
3269
  } else {
3270
    colDataSetDouble(pOutput, pos, &delta);
4,523,543✔
3271
  }
3272
  pDiffInfo->prev.d64 = v;
5,581,456✔
3273
}
5,581,456✔
3274

3275
static int32_t doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, SColumnInfoData* pOutput, int32_t pos,
1,533,239,812✔
3276
                            int64_t ts) {
3277
  if (!pDiffInfo->hasPrev) {
1,533,239,812✔
3278
    colDataSetNull_f_s(pOutput, pos);
569✔
3279
    return doSetPrevVal(pDiffInfo, type, pv, ts);
569✔
3280
  }
3281
  pDiffInfo->prevTs = ts;
1,533,239,243✔
3282
  switch (type) {
1,533,239,243!
3283
    case TSDB_DATA_TYPE_UINT: {
411✔
3284
      int64_t v = *(uint32_t*)pv;
411✔
3285
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
411✔
3286
      break;
411✔
3287
    }
3288
    case TSDB_DATA_TYPE_INT: {
26,247,549✔
3289
      int64_t v = *(int32_t*)pv;
26,247,549✔
3290
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
26,247,549✔
3291
      break;
26,247,549✔
3292
    }
3293
    case TSDB_DATA_TYPE_BOOL: {
10,617✔
3294
      int64_t v = *(bool*)pv;
10,617✔
3295
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
10,617✔
3296
      break;
10,617✔
3297
    }
3298
    case TSDB_DATA_TYPE_UTINYINT: {
405✔
3299
      int64_t v = *(uint8_t*)pv;
405✔
3300
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
405✔
3301
      break;
405✔
3302
    }
3303
    case TSDB_DATA_TYPE_TINYINT: {
39,858✔
3304
      int64_t v = *(int8_t*)pv;
39,858✔
3305
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
39,858✔
3306
      break;
39,858✔
3307
    }
3308
    case TSDB_DATA_TYPE_USMALLINT: {
405✔
3309
      int64_t v = *(uint16_t*)pv;
405✔
3310
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
405✔
3311
      break;
405✔
3312
    }
3313
    case TSDB_DATA_TYPE_SMALLINT: {
32,790✔
3314
      int64_t v = *(int16_t*)pv;
32,790✔
3315
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
32,790✔
3316
      break;
32,790✔
3317
    }
3318
    case TSDB_DATA_TYPE_TIMESTAMP:
1,501,617,809✔
3319
    case TSDB_DATA_TYPE_UBIGINT:
3320
    case TSDB_DATA_TYPE_BIGINT: {
3321
      int64_t v = *(int64_t*)pv;
1,501,617,809✔
3322
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
1,501,617,809✔
3323
      break;
1,501,617,809✔
3324
    }
3325
    case TSDB_DATA_TYPE_FLOAT: {
5,530,059✔
3326
      double v = *(float*)pv;
5,530,059✔
3327
      tryToSetDouble(pDiffInfo, pOutput, v, pos);
5,530,059✔
3328
      break;
5,530,059✔
3329
    }
3330
    case TSDB_DATA_TYPE_DOUBLE: {
51,397✔
3331
      double v = *(double*)pv;
51,397✔
3332
      tryToSetDouble(pDiffInfo, pOutput, v, pos);
51,397✔
3333
      break;
51,397✔
3334
    }
3335
    default:
×
3336
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3337
  }
3338
  pDiffInfo->hasPrev = true;
1,533,531,300✔
3339
  return TSDB_CODE_SUCCESS;
1,533,531,300✔
3340
}
3341

3342
// TODO: the primary key compare can be skipped for ordered pk if knonwn before
3343
// TODO: for desc ordered, pk shall select the smallest one for one ts. if across block boundaries.
3344
bool funcInputGetNextRowIndex(SInputColumnInfoData* pInput, int32_t from, bool firstOccur, int32_t* pRowIndex,
303,627,294✔
3345
                              int32_t* nextFrom) {
3346
  if (pInput->pPrimaryKey == NULL) {
303,627,294✔
3347
    if (from == -1) {
203,683,024✔
3348
      from = pInput->startRowIndex;
65,767,353✔
3349
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
137,915,671✔
3350
      return false;
65,487,102✔
3351
    }
3352
    *pRowIndex = from;
138,195,922✔
3353
    *nextFrom = from + 1;
138,195,922✔
3354
    return true;
138,195,922✔
3355
  } else {
3356
    if (from == -1) {
99,944,270✔
3357
      from = pInput->startRowIndex;
30,175✔
3358
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
99,914,095✔
3359
      return false;
30,175✔
3360
    }
3361
    TSKEY*           tsList = (int64_t*)pInput->pPTS->pData;
99,914,095✔
3362
    SColumnInfoData* pkCol = pInput->pPrimaryKey;
99,914,095✔
3363
    int8_t           pkType = pkCol->info.type;
99,914,095✔
3364
    int32_t          order = (firstOccur) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
99,914,095✔
3365
    __compar_fn_t    compareFunc = getKeyComparFunc(pkType, order);
99,914,095✔
3366
    int32_t          select = from;
100,000,517✔
3367
    char*            val = colDataGetData(pkCol, select);
100,000,517!
3368
    while (from < pInput->numOfRows + pInput->startRowIndex - 1 && tsList[from + 1] == tsList[from]) {
100,001,072✔
3369
      char* val1 = colDataGetData(pkCol, from + 1);
555!
3370
      if (compareFunc(val1, val) < 0) {
555!
3371
        select = from + 1;
×
3372
        val = val1;
×
3373
      }
3374
      from = from + 1;
555✔
3375
    }
3376
    *pRowIndex = select;
100,000,517✔
3377
    *nextFrom = from + 1;
100,000,517✔
3378
    return true;
100,000,517✔
3379
  }
3380
}
3381

3382
bool getForecastConfEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
26✔
3383
  pEnv->calcMemSize = sizeof(float);
26✔
3384
  return true;
26✔
3385
}
3386

3387
int32_t diffResultIsNull(SqlFunctionCtx* pCtx, SFuncInputRow* pRow) {
1,534,557,653✔
3388
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,534,557,653✔
3389
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
1,534,557,653✔
3390

3391
  if (pRow->isDataNull || !pDiffInfo->hasPrev) {
1,534,557,653✔
3392
    return true;
163,976✔
3393
  } else if (ignoreNegative(pDiffInfo->ignoreOption)) {
1,534,393,677✔
3394
    return diffIsNegtive(pDiffInfo, pCtx->input.pData[0]->info.type, pRow->pData);
4,414,185✔
3395
  }
3396
  return false;
1,530,001,841✔
3397
}
3398

3399
bool isFirstRow(SqlFunctionCtx* pCtx, SFuncInputRow* pRow) {
1,533,321,892✔
3400
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,533,321,892✔
3401
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
1,533,321,892✔
3402
  return pDiffInfo->isFirstRow;
1,533,321,892✔
3403
}
3404

3405
int32_t trySetPreVal(SqlFunctionCtx* pCtx, SFuncInputRow* pRow) {
1,212,546✔
3406
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,212,546✔
3407
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
1,212,546✔
3408
  pDiffInfo->isFirstRow = false;
1,212,546✔
3409
  if (pRow->isDataNull) {
1,212,546✔
3410
    return TSDB_CODE_SUCCESS;
1,796✔
3411
  }
3412

3413
  SInputColumnInfoData* pInput = &pCtx->input;
1,210,750✔
3414
  SColumnInfoData*      pInputCol = pInput->pData[0];
1,210,750✔
3415
  int8_t                inputType = pInputCol->info.type;
1,210,750✔
3416

3417
  char* pv = pRow->pData;
1,210,750✔
3418
  return doSetPrevVal(pDiffInfo, inputType, pv, pRow->ts);
1,210,750✔
3419
}
3420

3421
int32_t setDoDiffResult(SqlFunctionCtx* pCtx, SFuncInputRow* pRow, int32_t pos) {
1,533,257,683✔
3422
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,533,257,683✔
3423
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
1,533,257,683✔
3424

3425
  SInputColumnInfoData* pInput = &pCtx->input;
1,533,257,683✔
3426
  SColumnInfoData*      pInputCol = pInput->pData[0];
1,533,257,683✔
3427
  int8_t                inputType = pInputCol->info.type;
1,533,257,683✔
3428
  SColumnInfoData*      pOutput = (SColumnInfoData*)pCtx->pOutput;
1,533,257,683✔
3429
  int32_t               code = TSDB_CODE_SUCCESS;
1,533,257,683✔
3430
  if (pRow->isDataNull) {
1,533,257,683✔
3431
    colDataSetNull_f_s(pOutput, pos);
91,671✔
3432
    pOutput->hasNull = true;
91,671✔
3433

3434
    // handle selectivity
3435
    if (pCtx->subsidiaries.num > 0) {
91,671✔
3436
      code = appendSelectivityCols(pCtx, pRow->block, pRow->rowIndex, pos);
149✔
3437
      if (code != TSDB_CODE_SUCCESS) {
149!
3438
        return code;
×
3439
      }
3440
    }
3441
    return TSDB_CODE_SUCCESS;
91,671✔
3442
  }
3443

3444
  char* pv = pRow->pData;
1,533,166,012✔
3445

3446
  if (pRow->ts == pDiffInfo->prevTs) {
1,533,166,012✔
3447
    return TSDB_CODE_FUNC_DUP_TIMESTAMP;
21✔
3448
  }
3449
  code = doHandleDiff(pDiffInfo, inputType, pv, pOutput, pos, pRow->ts);
1,533,165,991✔
3450
  if (code != TSDB_CODE_SUCCESS) {
1,533,253,895!
3451
    return code;
×
3452
  }
3453
  // handle selectivity
3454
  if (pCtx->subsidiaries.num > 0) {
1,533,253,895✔
3455
    code = appendSelectivityCols(pCtx, pRow->block, pRow->rowIndex, pos);
30,566,599✔
3456
    if (code != TSDB_CODE_SUCCESS) {
30,566,599!
3457
      return code;
×
3458
    }
3459
  }
3460

3461
  return TSDB_CODE_SUCCESS;
1,533,253,895✔
3462
}
3463

3464
int32_t diffFunction(SqlFunctionCtx* pCtx) { return TSDB_CODE_SUCCESS; }
1,867,625✔
3465

3466
int32_t diffFunctionByRow(SArray* pCtxArray) {
1,867,472✔
3467
  int32_t code = TSDB_CODE_SUCCESS;
1,867,472✔
3468
  int     diffColNum = pCtxArray->size;
1,867,472✔
3469
  if (diffColNum == 0) {
1,867,472!
3470
    return TSDB_CODE_SUCCESS;
×
3471
  }
3472
  int32_t numOfElems = 0;
1,867,472✔
3473

3474
  SArray* pRows = taosArrayInit_s(sizeof(SFuncInputRow), diffColNum);
1,867,472✔
3475
  if (NULL == pRows) {
1,867,475✔
3476
    return terrno;
1✔
3477
  }
3478

3479
  bool keepNull = false;
1,867,474✔
3480
  for (int i = 0; i < diffColNum; ++i) {
3,735,104✔
3481
    SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
1,867,629✔
3482
    if (NULL == pCtx) {
1,867,627!
3483
      code = terrno;
×
3484
      goto _exit;
×
3485
    }
3486
    funcInputUpdate(pCtx);
1,867,627✔
3487
    SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,867,630✔
3488
    SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
1,867,630✔
3489
    if (!ignoreNull(pDiffInfo->ignoreOption)) {
1,867,630✔
3490
      keepNull = true;
1,852,413✔
3491
    }
3492
  }
3493

3494
  SqlFunctionCtx* pCtx0 = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, 0);
1,867,475✔
3495
  SFuncInputRow*  pRow0 = (SFuncInputRow*)taosArrayGet(pRows, 0);
1,867,469✔
3496
  if (NULL == pCtx0 || NULL == pRow0) {
1,867,468!
3497
    code = terrno;
×
3498
    goto _exit;
×
3499
  }
3500
  int32_t startOffset = pCtx0->offset;
1,867,471✔
3501
  bool    result = false;
1,867,471✔
3502
  while (1) {
1,534,486,878✔
3503
    code = funcInputGetNextRow(pCtx0, pRow0, &result);
1,536,354,349✔
3504
    if (TSDB_CODE_SUCCESS != code) {
1,536,410,942!
3505
      goto _exit;
×
3506
    }
3507
    if (!result) {
1,536,410,942✔
3508
      break;
1,867,456✔
3509
    }
3510
    bool hasNotNullValue = !diffResultIsNull(pCtx0, pRow0);
1,534,543,486✔
3511
    for (int i = 1; i < diffColNum; ++i) {
1,534,562,476✔
3512
      SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
14,494✔
3513
      SFuncInputRow*  pRow = (SFuncInputRow*)taosArrayGet(pRows, i);
14,494✔
3514
      if (NULL == pCtx || NULL == pRow) {
14,494!
3515
        code = terrno;
×
3516
        goto _exit;
×
3517
      }
3518
      code = funcInputGetNextRow(pCtx, pRow, &result);
14,494✔
3519
      if (TSDB_CODE_SUCCESS != code) {
14,494!
3520
        goto _exit;
×
3521
      }
3522
      if (!result) {
14,494!
3523
        // rows are not equal
3524
        code = TSDB_CODE_QRY_EXECUTOR_INTERNAL_ERROR;
×
3525
        goto _exit;
×
3526
      }
3527
      if (!diffResultIsNull(pCtx, pRow)) {
14,494✔
3528
        hasNotNullValue = true;
14,052✔
3529
      }
3530
    }
3531
    int32_t pos = startOffset + numOfElems;
1,534,547,982✔
3532

3533
    bool newRow = false;
1,534,547,982✔
3534
    for (int i = 0; i < diffColNum; ++i) {
2,147,483,647✔
3535
      SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
1,534,558,068✔
3536
      SFuncInputRow*  pRow = (SFuncInputRow*)taosArrayGet(pRows, i);
1,534,477,084✔
3537
      if (NULL == pCtx || NULL == pRow) {
1,534,396,188!
3538
        code = terrno;
×
3539
        goto _exit;
×
3540
      }
3541
      if ((keepNull || hasNotNullValue) && !isFirstRow(pCtx, pRow)) {
1,534,405,719✔
3542
        code = setDoDiffResult(pCtx, pRow, pos);
1,533,250,330✔
3543
        if (code != TSDB_CODE_SUCCESS) {
1,533,284,439✔
3544
          goto _exit;
21✔
3545
        }
3546
        newRow = true;
1,533,284,418✔
3547
      } else {
3548
        code = trySetPreVal(pCtx, pRow);
1,209,531✔
3549
        if (code != TSDB_CODE_SUCCESS) {
1,212,546!
3550
          goto _exit;
×
3551
        }
3552
      }
3553
    }
3554
    if (newRow) ++numOfElems;
1,534,486,878✔
3555
  }
3556

3557
  for (int i = 0; i < diffColNum; ++i) {
3,735,064✔
3558
    SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
1,867,609✔
3559
    if (NULL == pCtx) {
1,867,608!
3560
      code = terrno;
×
3561
      goto _exit;
×
3562
    }
3563
    SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,867,608✔
3564
    pResInfo->numOfRes = numOfElems;
1,867,608✔
3565
  }
3566

3567
_exit:
1,867,455✔
3568
  if (pRows) {
1,867,476!
3569
    taosArrayDestroy(pRows);
1,867,476✔
3570
    pRows = NULL;
1,867,475✔
3571
  }
3572
  return code;
1,867,475✔
3573
}
3574

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

3577
bool getTopBotFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
81,844✔
3578
  SValueNode* pkNode = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
81,844✔
3579
  pEnv->calcMemSize = sizeof(STopBotRes) + pkNode->datum.i * sizeof(STopBotResItem);
81,891✔
3580
  return true;
81,891✔
3581
}
3582

3583
int32_t topBotFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
46,254,720✔
3584
  if (pResInfo->initialized) {
46,254,720!
3585
    return TSDB_CODE_SUCCESS;
×
3586
  }
3587
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
46,254,720!
3588
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
3589
  }
3590

3591
  STopBotRes*           pRes = GET_ROWCELL_INTERBUF(pResInfo);
46,289,813✔
3592
  SInputColumnInfoData* pInput = &pCtx->input;
46,289,813✔
3593

3594
  pRes->maxSize = pCtx->param[1].param.i;
46,289,813✔
3595

3596
  pRes->nullTupleSaved = false;
46,289,813✔
3597
  pRes->nullTuplePos.pageId = -1;
46,289,813✔
3598
  return TSDB_CODE_SUCCESS;
46,289,813✔
3599
}
3600

3601
static STopBotRes* getTopBotOutputInfo(SqlFunctionCtx* pCtx) {
219,415,710✔
3602
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
219,415,710✔
3603
  STopBotRes*          pRes = GET_ROWCELL_INTERBUF(pResInfo);
219,415,710✔
3604
  pRes->pItems = (STopBotResItem*)((char*)pRes + sizeof(STopBotRes));
219,415,710✔
3605

3606
  return pRes;
219,415,710✔
3607
}
3608

3609
static int32_t doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock,
3610
                               uint16_t type, uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery);
3611

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

3614
int32_t topFunction(SqlFunctionCtx* pCtx) {
34,877,040✔
3615
  int32_t              numOfElems = 0;
34,877,040✔
3616
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
34,877,040✔
3617

3618
  SInputColumnInfoData* pInput = &pCtx->input;
34,877,040✔
3619
  SColumnInfoData*      pCol = pInput->pData[0];
34,877,040✔
3620

3621
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
34,877,040✔
3622
  pRes->type = pInput->pData[0]->info.type;
34,877,943✔
3623

3624
  int32_t start = pInput->startRowIndex;
34,877,943✔
3625
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
117,614,479✔
3626
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
82,699,136✔
3627
      continue;
25,979✔
3628
    }
3629

3630
    numOfElems++;
82,673,157✔
3631
    char*   data = colDataGetData(pCol, i);
82,673,157!
3632
    int32_t code = doAddIntoResult(pCtx, data, i, pCtx->pSrcBlock, pRes->type, pInput->uid, pResInfo, true);
82,673,157✔
3633
    if (code != TSDB_CODE_SUCCESS) {
82,710,557!
3634
      return code;
×
3635
    }
3636
  }
3637

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

3648
int32_t bottomFunction(SqlFunctionCtx* pCtx) {
12,609,601✔
3649
  int32_t              numOfElems = 0;
12,609,601✔
3650
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
12,609,601✔
3651

3652
  SInputColumnInfoData* pInput = &pCtx->input;
12,609,601✔
3653
  SColumnInfoData*      pCol = pInput->pData[0];
12,609,601✔
3654

3655
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
12,609,601✔
3656
  pRes->type = pInput->pData[0]->info.type;
12,609,150✔
3657

3658
  int32_t start = pInput->startRowIndex;
12,609,150✔
3659
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
56,154,316✔
3660
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
43,526,037✔
3661
      continue;
20,618✔
3662
    }
3663

3664
    numOfElems++;
43,505,419✔
3665
    char*   data = colDataGetData(pCol, i);
43,505,419!
3666
    int32_t code = doAddIntoResult(pCtx, data, i, pCtx->pSrcBlock, pRes->type, pInput->uid, pResInfo, false);
43,505,419✔
3667
    if (code != TSDB_CODE_SUCCESS) {
43,524,548!
3668
      return code;
×
3669
    }
3670
  }
3671

3672
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pRes->nullTupleSaved) {
12,628,279✔
3673
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pRes->nullTuplePos);
109✔
3674
    if (code != TSDB_CODE_SUCCESS) {
109!
3675
      return code;
×
3676
    }
3677
    pRes->nullTupleSaved = true;
109✔
3678
  }
3679

3680
  return TSDB_CODE_SUCCESS;
12,628,279✔
3681
}
3682

3683
static int32_t topBotResComparFn(const void* p1, const void* p2, const void* param) {
555,507,930✔
3684
  uint16_t type = *(uint16_t*)param;
555,507,930✔
3685

3686
  STopBotResItem* val1 = (STopBotResItem*)p1;
555,507,930✔
3687
  STopBotResItem* val2 = (STopBotResItem*)p2;
555,507,930✔
3688

3689
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
555,507,930✔
3690
    if (val1->v.i == val2->v.i) {
200,788,310✔
3691
      return 0;
170,717✔
3692
    }
3693

3694
    return (val1->v.i > val2->v.i) ? 1 : -1;
200,617,593✔
3695
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
354,719,620!
3696
    if (val1->v.u == val2->v.u) {
461,893✔
3697
      return 0;
101,921✔
3698
    }
3699

3700
    return (val1->v.u > val2->v.u) ? 1 : -1;
359,972✔
3701
  } else if (TSDB_DATA_TYPE_FLOAT == type) {
354,257,727✔
3702
    if (val1->v.f == val2->v.f) {
100,943,630✔
3703
      return 0;
63✔
3704
    }
3705

3706
    return (val1->v.f > val2->v.f) ? 1 : -1;
100,943,567✔
3707
  }
3708

3709
  if (val1->v.d == val2->v.d) {
253,314,097✔
3710
    return 0;
11✔
3711
  }
3712

3713
  return (val1->v.d > val2->v.d) ? 1 : -1;
253,314,086✔
3714
}
3715

3716
int32_t doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, uint16_t type,
126,150,874✔
3717
                        uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery) {
3718
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
126,150,874✔
3719
  int32_t     code = TSDB_CODE_SUCCESS;
126,127,751✔
3720

3721
  SVariant val = {0};
126,127,751✔
3722
  TAOS_CHECK_RETURN(taosVariantCreateFromBinary(&val, pData, tDataTypes[type].bytes, type));
126,127,751!
3723

3724
  STopBotResItem* pItems = pRes->pItems;
126,195,375✔
3725

3726
  // not full yet
3727
  if (pEntryInfo->numOfRes < pRes->maxSize) {
126,195,375✔
3728
    STopBotResItem* pItem = &pItems[pEntryInfo->numOfRes];
83,681,004✔
3729
    pItem->v = val;
83,681,004✔
3730
    pItem->uid = uid;
83,681,004✔
3731

3732
    // save the data of this tuple
3733
    if (pCtx->subsidiaries.num > 0) {
83,681,004✔
3734
      code = saveTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
38,905,367✔
3735
      if (code != TSDB_CODE_SUCCESS) {
38,847,864!
3736
        return code;
×
3737
      }
3738
    }
3739
#ifdef BUF_PAGE_DEBUG
3740
    qDebug("page_saveTuple i:%d, item:%p,pageId:%d, offset:%d\n", pEntryInfo->numOfRes, pItem, pItem->tuplePos.pageId,
3741
           pItem->tuplePos.offset);
3742
#endif
3743
    // allocate the buffer and keep the data of this row into the new allocated buffer
3744
    pEntryInfo->numOfRes++;
83,623,501✔
3745
    code = taosheapsort((void*)pItems, sizeof(STopBotResItem), pEntryInfo->numOfRes, (const void*)&type,
83,623,501✔
3746
                        topBotResComparFn, !isTopQuery);
83,623,501✔
3747
    if (code != TSDB_CODE_SUCCESS) {
83,731,820!
3748
      return code;
×
3749
    }
3750
  } else {  // replace the minimum value in the result
3751
    if ((isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i > pItems[0].v.i) ||
42,514,371!
3752
                        (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u > pItems[0].v.u) ||
21,592,058✔
3753
                        (TSDB_DATA_TYPE_FLOAT == type && val.f > pItems[0].v.f) ||
21,537,532✔
3754
                        (TSDB_DATA_TYPE_DOUBLE == type && val.d > pItems[0].v.d))) ||
20,138,126✔
3755
        (!isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i < pItems[0].v.i) ||
36,105,696!
3756
                         (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u < pItems[0].v.u) ||
15,924,251!
3757
                         (TSDB_DATA_TYPE_FLOAT == type && val.f < pItems[0].v.f) ||
15,923,253✔
3758
                         (TSDB_DATA_TYPE_DOUBLE == type && val.d < pItems[0].v.d)))) {
15,413,778✔
3759
      // replace the old data and the coresponding tuple data
3760
      STopBotResItem* pItem = &pItems[0];
10,788,026✔
3761
      pItem->v = val;
10,788,026✔
3762
      pItem->uid = uid;
10,788,026✔
3763

3764
      // save the data of this tuple by over writing the old data
3765
      if (pCtx->subsidiaries.num > 0) {
10,788,026✔
3766
        code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
5,892,979✔
3767
        if (code != TSDB_CODE_SUCCESS) {
5,887,333!
3768
          return code;
×
3769
        }
3770
      }
3771
#ifdef BUF_PAGE_DEBUG
3772
      qDebug("page_copyTuple pageId:%d, offset:%d", pItem->tuplePos.pageId, pItem->tuplePos.offset);
3773
#endif
3774
      code = taosheapadjust((void*)pItems, sizeof(STopBotResItem), 0, pEntryInfo->numOfRes - 1, (const void*)&type,
10,782,380✔
3775
                            topBotResComparFn, NULL, !isTopQuery);
10,782,380✔
3776
      if (code != TSDB_CODE_SUCCESS) {
10,743,294!
3777
        return code;
×
3778
      }
3779
    }
3780
  }
3781

3782
  return TSDB_CODE_SUCCESS;
126,201,459✔
3783
}
3784

3785
/*
3786
 * +------------------------------------+--------------+--------------+
3787
 * |            null bitmap             |              |              |
3788
 * |(n columns, one bit for each column)| src column #1| src column #2|
3789
 * +------------------------------------+--------------+--------------+
3790
 */
3791
int32_t serializeTupleData(const SSDataBlock* pSrcBlock, int32_t rowIndex, SSubsidiaryResInfo* pSubsidiaryies,
267,288,323✔
3792
                           char* buf, char** res) {
3793
  char* nullList = buf;
267,288,323✔
3794
  char* pStart = (char*)(nullList + sizeof(bool) * pSubsidiaryies->num);
267,288,323✔
3795

3796
  int32_t offset = 0;
267,288,323✔
3797
  for (int32_t i = 0; i < pSubsidiaryies->num; ++i) {
534,123,650✔
3798
    SqlFunctionCtx* pc = pSubsidiaryies->pCtx[i];
267,301,945✔
3799

3800
    // group_key function has its own process function
3801
    // do not process there
3802
    if (fmIsGroupKeyFunc(pc->functionId)) {
267,301,945!
3803
      continue;
×
3804
    }
3805

3806
    SFunctParam* pFuncParam = &pc->pExpr->base.pParam[0];
267,255,401✔
3807
    int32_t      srcSlotId = pFuncParam->pCol->slotId;
267,255,401✔
3808

3809
    SColumnInfoData* pCol = taosArrayGet(pSrcBlock->pDataBlock, srcSlotId);
267,255,401✔
3810
    if (NULL == pCol) {
266,835,327!
3811
      return TSDB_CODE_OUT_OF_RANGE;
×
3812
    }
3813
    if ((nullList[i] = colDataIsNull_s(pCol, rowIndex)) == true) {
533,670,654✔
3814
      offset += pCol->info.bytes;
653✔
3815
      continue;
653✔
3816
    }
3817

3818
    char* p = colDataGetData(pCol, rowIndex);
266,834,674!
3819
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
266,834,674!
3820
      (void)memcpy(pStart + offset, p, (pCol->info.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(p) : varDataTLen(p));
×
3821
    } else {
3822
      (void)memcpy(pStart + offset, p, pCol->info.bytes);
266,838,141✔
3823
    }
3824

3825
    offset += pCol->info.bytes;
266,834,674✔
3826
  }
3827

3828
  *res = buf;
266,821,705✔
3829
  return TSDB_CODE_SUCCESS;
266,821,705✔
3830
}
3831

3832
static int32_t doSaveTupleData(SSerializeDataHandle* pHandle, const void* pBuf, size_t length, SWinKey* key,
328,380,285✔
3833
                               STuplePos* pPos, SFunctionStateStore* pStore) {
3834
  STuplePos p = {0};
328,380,285✔
3835
  if (pHandle->pBuf != NULL) {
328,380,285✔
3836
    SFilePage* pPage = NULL;
328,347,672✔
3837

3838
    if (pHandle->currentPage == -1) {
328,347,672✔
3839
      pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
670,322✔
3840
      if (pPage == NULL) {
670,332✔
3841
        return terrno;
1✔
3842
      }
3843
      pPage->num = sizeof(SFilePage);
670,331✔
3844
    } else {
3845
      pPage = getBufPage(pHandle->pBuf, pHandle->currentPage);
327,677,350✔
3846
      if (pPage == NULL) {
327,638,095!
3847
        return terrno;
×
3848
      }
3849
      if (pPage->num + length > getBufPageSize(pHandle->pBuf)) {
327,638,095✔
3850
        // current page is all used, let's prepare a new buffer page
3851
        releaseBufPage(pHandle->pBuf, pPage);
6,438,110✔
3852
        pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
6,438,108✔
3853
        if (pPage == NULL) {
6,438,115!
3854
          return terrno;
×
3855
        }
3856
        pPage->num = sizeof(SFilePage);
6,438,115✔
3857
      }
3858
    }
3859

3860
    p = (STuplePos){.pageId = pHandle->currentPage, .offset = pPage->num};
328,275,817✔
3861
    (void)memcpy(pPage->data + pPage->num, pBuf, length);
328,275,817✔
3862

3863
    pPage->num += length;
328,275,817✔
3864
    setBufPageDirty(pPage, true);
328,275,817✔
3865
    releaseBufPage(pHandle->pBuf, pPage);
328,114,947✔
3866
  } else {  // other tuple save policy
3867
    if (pStore->streamStateFuncPut(pHandle->pState, key, pBuf, length) >= 0) {
32,613!
3868
      p.streamTupleKey = *key;
59,771✔
3869
    }
3870
  }
3871

3872
  *pPos = p;
328,009,627✔
3873
  return TSDB_CODE_SUCCESS;
328,009,627✔
3874
}
3875

3876
int32_t saveTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
225,465,617✔
3877
  int32_t code = prepareBuf(pCtx);
225,465,617✔
3878
  if (TSDB_CODE_SUCCESS != code) {
225,421,143!
3879
    return code;
×
3880
  }
3881

3882
  SWinKey key = {0};
225,421,143✔
3883
  if (pCtx->saveHandle.pBuf == NULL) {
225,421,143✔
3884
    SColumnInfoData* pColInfo = taosArrayGet(pSrcBlock->pDataBlock, pCtx->saveHandle.pState->tsIndex);
59,771✔
3885
    if (NULL == pColInfo) {
59,771!
3886
      return TSDB_CODE_OUT_OF_RANGE;
×
3887
    }
3888
    if (pColInfo->info.type != TSDB_DATA_TYPE_TIMESTAMP) {
59,771!
3889
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3890
    }
3891
    key.groupId = pSrcBlock->info.id.groupId;
59,771✔
3892
    key.ts = *(int64_t*)colDataGetData(pColInfo, rowIndex);
59,771!
3893
  }
3894

3895
  char* buf = NULL;
225,421,143✔
3896
  code = serializeTupleData(pSrcBlock, rowIndex, &pCtx->subsidiaries, pCtx->subsidiaries.buf, &buf);
225,421,143✔
3897
  if (TSDB_CODE_SUCCESS != code) {
225,183,700!
3898
    return code;
×
3899
  }
3900
  return doSaveTupleData(&pCtx->saveHandle, buf, pCtx->subsidiaries.rowLen, &key, pPos, pCtx->pStore);
225,183,700✔
3901
}
3902

3903
static int32_t doUpdateTupleData(SSerializeDataHandle* pHandle, const void* pBuf, size_t length, STuplePos* pPos,
41,920,966✔
3904
                                 SFunctionStateStore* pStore) {
3905
  if (pHandle->pBuf != NULL) {
41,920,966✔
3906
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
41,819,680✔
3907
    if (pPage == NULL) {
41,819,836!
3908
      return terrno;
×
3909
    }
3910
    (void)memcpy(pPage->data + pPos->offset, pBuf, length);
41,819,836✔
3911
    setBufPageDirty(pPage, true);
41,819,836✔
3912
    releaseBufPage(pHandle->pBuf, pPage);
41,815,861✔
3913
  } else {
3914
    int32_t code = pStore->streamStateFuncPut(pHandle->pState, &pPos->streamTupleKey, pBuf, length);
101,286✔
3915
    if (TSDB_CODE_SUCCESS != code) {
101,517!
3916
      return code;
×
3917
    }
3918
  }
3919

3920
  return TSDB_CODE_SUCCESS;
41,912,986✔
3921
}
3922

3923
int32_t updateTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
41,927,205✔
3924
  int32_t code = prepareBuf(pCtx);
41,927,205✔
3925
  if (TSDB_CODE_SUCCESS != code) {
41,926,134!
3926
    return code;
×
3927
  }
3928

3929
  char* buf = NULL;
41,926,134✔
3930
  code = serializeTupleData(pSrcBlock, rowIndex, &pCtx->subsidiaries, pCtx->subsidiaries.buf, &buf);
41,926,134✔
3931
  if (TSDB_CODE_SUCCESS != code) {
41,921,012!
3932
    return code;
×
3933
  }
3934
  return doUpdateTupleData(&pCtx->saveHandle, buf, pCtx->subsidiaries.rowLen, pPos, pCtx->pStore);
41,921,012✔
3935
}
3936

3937
static int32_t doLoadTupleData(SSerializeDataHandle* pHandle, const STuplePos* pPos, SFunctionStateStore* pStore,
163,515,788✔
3938
                               char** value) {
3939
  if (pHandle->pBuf != NULL) {
163,515,788✔
3940
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
163,463,691✔
3941
    if (pPage == NULL) {
163,794,021!
3942
      *value = NULL;
×
3943
      return terrno;
×
3944
    }
3945
    *value = pPage->data + pPos->offset;
163,794,021✔
3946
    releaseBufPage(pHandle->pBuf, pPage);
163,794,021✔
3947
    return TSDB_CODE_SUCCESS;
163,685,303✔
3948
  } else {
3949
    *value = NULL;
52,097✔
3950
    int32_t vLen;
3951
    int32_t code = pStore->streamStateFuncGet(pHandle->pState, &pPos->streamTupleKey, (void**)(value), &vLen);
52,097✔
3952
    if (TSDB_CODE_SUCCESS != code) {
59,748!
3953
      return code;
×
3954
    }
3955
    return TSDB_CODE_SUCCESS;
59,748✔
3956
  }
3957
}
3958

3959
int32_t loadTupleData(SqlFunctionCtx* pCtx, const STuplePos* pPos, char** value) {
163,256,416✔
3960
  return doLoadTupleData(&pCtx->saveHandle, pPos, pCtx->pStore, value);
163,256,416✔
3961
}
3962

3963
int32_t topBotFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
46,018,267✔
3964
  int32_t code = TSDB_CODE_SUCCESS;
46,018,267✔
3965

3966
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
46,018,267✔
3967
  STopBotRes*          pRes = getTopBotOutputInfo(pCtx);
46,018,267✔
3968

3969
  int16_t type = pCtx->pExpr->base.resSchema.type;
46,016,981✔
3970
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
46,016,981✔
3971

3972
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
46,016,981✔
3973
  if (NULL == pCol) {
46,001,625!
3974
    return TSDB_CODE_OUT_OF_RANGE;
×
3975
  }
3976

3977
  // todo assign the tag value and the corresponding row data
3978
  int32_t currentRow = pBlock->info.rows;
46,001,625✔
3979
  if (pEntryInfo->numOfRes <= 0) {
46,001,625✔
3980
    colDataSetNULL(pCol, currentRow);
489!
3981
    code = setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, currentRow);
489✔
3982
    return code;
489✔
3983
  }
3984
  for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
128,781,657✔
3985
    STopBotResItem* pItem = &pRes->pItems[i];
82,866,469✔
3986
    code = colDataSetVal(pCol, currentRow, (const char*)&pItem->v.i, false);
82,866,469✔
3987
    if (TSDB_CODE_SUCCESS != code) {
82,802,703!
3988
      return code;
×
3989
    }
3990
#ifdef BUF_PAGE_DEBUG
3991
    qDebug("page_finalize i:%d,item:%p,pageId:%d, offset:%d\n", i, pItem, pItem->tuplePos.pageId,
3992
           pItem->tuplePos.offset);
3993
#endif
3994
    code = setSelectivityValue(pCtx, pBlock, &pRes->pItems[i].tuplePos, currentRow);
82,802,703✔
3995
    if (TSDB_CODE_SUCCESS != code) {
82,780,521!
3996
      return code;
×
3997
    }
3998
    currentRow += 1;
82,780,521✔
3999
  }
4000

4001
  return code;
45,915,188✔
4002
}
4003

4004
int32_t addResult(SqlFunctionCtx* pCtx, STopBotResItem* pSourceItem, int16_t type, bool isTopQuery) {
×
4005
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
×
4006
  STopBotRes*          pRes = getTopBotOutputInfo(pCtx);
×
4007
  STopBotResItem*      pItems = pRes->pItems;
×
4008
  int32_t              code = TSDB_CODE_SUCCESS;
×
4009

4010
  // not full yet
4011
  if (pEntryInfo->numOfRes < pRes->maxSize) {
×
4012
    STopBotResItem* pItem = &pItems[pEntryInfo->numOfRes];
×
4013
    pItem->v = pSourceItem->v;
×
4014
    pItem->uid = pSourceItem->uid;
×
4015
    pItem->tuplePos.pageId = -1;
×
4016
    replaceTupleData(&pItem->tuplePos, &pSourceItem->tuplePos);
×
4017
    pEntryInfo->numOfRes++;
×
4018
    code = taosheapsort((void*)pItems, sizeof(STopBotResItem), pEntryInfo->numOfRes, (const void*)&type,
×
4019
                        topBotResComparFn, !isTopQuery);
×
4020
    if (TSDB_CODE_SUCCESS != code) {
×
4021
      return code;
×
4022
    }
4023
  } else {  // replace the minimum value in the result
4024
    if ((isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && pSourceItem->v.i > pItems[0].v.i) ||
×
4025
                        (IS_UNSIGNED_NUMERIC_TYPE(type) && pSourceItem->v.u > pItems[0].v.u) ||
×
4026
                        (TSDB_DATA_TYPE_FLOAT == type && pSourceItem->v.f > pItems[0].v.f) ||
×
4027
                        (TSDB_DATA_TYPE_DOUBLE == type && pSourceItem->v.d > pItems[0].v.d))) ||
×
4028
        (!isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && pSourceItem->v.i < pItems[0].v.i) ||
×
4029
                         (IS_UNSIGNED_NUMERIC_TYPE(type) && pSourceItem->v.u < pItems[0].v.u) ||
×
4030
                         (TSDB_DATA_TYPE_FLOAT == type && pSourceItem->v.f < pItems[0].v.f) ||
×
4031
                         (TSDB_DATA_TYPE_DOUBLE == type && pSourceItem->v.d < pItems[0].v.d)))) {
×
4032
      // replace the old data and the coresponding tuple data
4033
      STopBotResItem* pItem = &pItems[0];
×
4034
      pItem->v = pSourceItem->v;
×
4035
      pItem->uid = pSourceItem->uid;
×
4036

4037
      // save the data of this tuple by over writing the old data
4038
      replaceTupleData(&pItem->tuplePos, &pSourceItem->tuplePos);
×
4039
      code = taosheapadjust((void*)pItems, sizeof(STopBotResItem), 0, pEntryInfo->numOfRes - 1, (const void*)&type,
×
4040
                            topBotResComparFn, NULL, !isTopQuery);
×
4041
      if (TSDB_CODE_SUCCESS != code) {
×
4042
        return code;
×
4043
      }
4044
    }
4045
  }
4046
  return code;
×
4047
}
4048

4049
int32_t topCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4050
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4051
  STopBotRes*          pSBuf = getTopBotOutputInfo(pSourceCtx);
×
4052
  int16_t              type = pSBuf->type;
×
4053
  int32_t              code = TSDB_CODE_SUCCESS;
×
4054
  for (int32_t i = 0; i < pSResInfo->numOfRes; i++) {
×
4055
    code = addResult(pDestCtx, pSBuf->pItems + i, type, true);
×
4056
    if (TSDB_CODE_SUCCESS != code) {
×
4057
      return code;
×
4058
    }
4059
  }
4060
  return TSDB_CODE_SUCCESS;
×
4061
}
4062

4063
int32_t bottomCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4064
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4065
  STopBotRes*          pSBuf = getTopBotOutputInfo(pSourceCtx);
×
4066
  int16_t              type = pSBuf->type;
×
4067
  int32_t              code = TSDB_CODE_SUCCESS;
×
4068
  for (int32_t i = 0; i < pSResInfo->numOfRes; i++) {
×
4069
    code = addResult(pDestCtx, pSBuf->pItems + i, type, false);
×
4070
    if (TSDB_CODE_SUCCESS != code) {
×
4071
      return code;
×
4072
    }
4073
  }
4074
  return TSDB_CODE_SUCCESS;
×
4075
}
4076

4077
int32_t getSpreadInfoSize() { return (int32_t)sizeof(SSpreadInfo); }
753,394✔
4078

4079
bool getSpreadFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
102,138✔
4080
  pEnv->calcMemSize = sizeof(SSpreadInfo);
102,138✔
4081
  return true;
102,138✔
4082
}
4083

4084
int32_t spreadFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
2,800,556✔
4085
  if (pResultInfo->initialized) {
2,800,556!
4086
    return TSDB_CODE_SUCCESS;
×
4087
  }
4088
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
2,800,556!
4089
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
4090
  }
4091

4092
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
2,800,525✔
4093
  SET_DOUBLE_VAL(&pInfo->min, DBL_MAX);
2,800,525✔
4094
  SET_DOUBLE_VAL(&pInfo->max, -DBL_MAX);
2,800,525✔
4095
  pInfo->hasResult = false;
2,800,525✔
4096
  return TSDB_CODE_SUCCESS;
2,800,525✔
4097
}
4098

4099
int32_t spreadFunction(SqlFunctionCtx* pCtx) {
2,100,903✔
4100
  int32_t numOfElems = 0;
2,100,903✔
4101

4102
  // Only the pre-computing information loaded and actual data does not loaded
4103
  SInputColumnInfoData* pInput = &pCtx->input;
2,100,903✔
4104
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
2,100,903✔
4105
  int32_t               type = pInput->pData[0]->info.type;
2,100,903✔
4106

4107
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,100,903✔
4108

4109
  if (pInput->colDataSMAIsSet) {
2,100,903!
4110
    numOfElems = pInput->numOfRows - pAgg->numOfNull;
×
4111
    if (numOfElems == 0) {
×
4112
      goto _spread_over;
×
4113
    }
4114
    double tmin = 0.0, tmax = 0.0;
×
4115
    if (IS_SIGNED_NUMERIC_TYPE(type) || IS_TIMESTAMP_TYPE(type)) {
×
4116
      tmin = (double)GET_INT64_VAL(&pAgg->min);
×
4117
      tmax = (double)GET_INT64_VAL(&pAgg->max);
×
4118
    } else if (IS_FLOAT_TYPE(type)) {
×
4119
      tmin = GET_DOUBLE_VAL(&pAgg->min);
×
4120
      tmax = GET_DOUBLE_VAL(&pAgg->max);
×
4121
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
4122
      tmin = (double)GET_UINT64_VAL(&pAgg->min);
×
4123
      tmax = (double)GET_UINT64_VAL(&pAgg->max);
×
4124
    }
4125

4126
    if (GET_DOUBLE_VAL(&pInfo->min) > tmin) {
×
4127
      SET_DOUBLE_VAL(&pInfo->min, tmin);
×
4128
    }
4129

4130
    if (GET_DOUBLE_VAL(&pInfo->max) < tmax) {
×
4131
      SET_DOUBLE_VAL(&pInfo->max, tmax);
×
4132
    }
4133

4134
  } else {  // computing based on the true data block
4135
    SColumnInfoData* pCol = pInput->pData[0];
2,100,903✔
4136

4137
    int32_t start = pInput->startRowIndex;
2,100,903✔
4138
    // check the valid data one by one
4139
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
11,359,706✔
4140
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
9,258,803✔
4141
        continue;
1,594,883✔
4142
      }
4143

4144
      char* data = colDataGetData(pCol, i);
7,663,920!
4145

4146
      double v = 0;
7,663,920✔
4147
      GET_TYPED_DATA(v, double, type, data);
7,663,920!
4148
      if (v < GET_DOUBLE_VAL(&pInfo->min)) {
7,663,920✔
4149
        SET_DOUBLE_VAL(&pInfo->min, v);
2,268,547✔
4150
      }
4151

4152
      if (v > GET_DOUBLE_VAL(&pInfo->max)) {
7,663,920✔
4153
        SET_DOUBLE_VAL(&pInfo->max, v);
2,848,270✔
4154
      }
4155

4156
      numOfElems += 1;
7,663,920✔
4157
    }
4158
  }
4159

4160
_spread_over:
2,100,903✔
4161
  // data in the check operation are all null, not output
4162
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
2,100,903✔
4163
  if (numOfElems > 0) {
2,100,903✔
4164
    pInfo->hasResult = true;
2,068,672✔
4165
  }
4166

4167
  return TSDB_CODE_SUCCESS;
2,100,903✔
4168
}
4169

4170
static void spreadTransferInfo(SSpreadInfo* pInput, SSpreadInfo* pOutput) {
751,855✔
4171
  pOutput->hasResult = pInput->hasResult;
751,855✔
4172
  if (pInput->max > pOutput->max) {
751,855✔
4173
    pOutput->max = pInput->max;
747,335✔
4174
  }
4175

4176
  if (pInput->min < pOutput->min) {
751,855✔
4177
    pOutput->min = pInput->min;
747,298✔
4178
  }
4179
}
751,855✔
4180

4181
int32_t spreadFunctionMerge(SqlFunctionCtx* pCtx) {
747,927✔
4182
  SInputColumnInfoData* pInput = &pCtx->input;
747,927✔
4183
  SColumnInfoData*      pCol = pInput->pData[0];
747,927✔
4184

4185
  if (IS_NULL_TYPE(pCol->info.type)) {
747,927!
4186
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
4187
    return TSDB_CODE_SUCCESS;
×
4188
  }
4189

4190
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
747,927!
4191
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
4192
  }
4193

4194
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
747,927✔
4195

4196
  int32_t start = pInput->startRowIndex;
747,927✔
4197
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
1,500,046✔
4198
    if (colDataIsNull_s(pCol, i)) continue;
1,504,238!
4199
    char*        data = colDataGetData(pCol, i);
752,119!
4200
    SSpreadInfo* pInputInfo = (SSpreadInfo*)varDataVal(data);
752,119✔
4201
    if (pInputInfo->hasResult) {
752,119✔
4202
      spreadTransferInfo(pInputInfo, pInfo);
751,854✔
4203
    }
4204
  }
4205

4206
  if (pInfo->hasResult) {
747,927✔
4207
    GET_RES_INFO(pCtx)->numOfRes = 1;
747,728✔
4208
  }
4209

4210
  return TSDB_CODE_SUCCESS;
747,927✔
4211
}
4212

4213
int32_t spreadFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
2,038,417✔
4214
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,038,417✔
4215
  if (pInfo->hasResult == true) {
2,038,417✔
4216
    SET_DOUBLE_VAL(&pInfo->result, pInfo->max - pInfo->min);
2,006,778✔
4217
  } else {
4218
    GET_RES_INFO(pCtx)->isNullRes = 1;
31,639✔
4219
  }
4220
  return functionFinalize(pCtx, pBlock);
2,038,417✔
4221
}
4222

4223
int32_t spreadPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
751,905✔
4224
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
751,905✔
4225
  SSpreadInfo*         pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
751,905✔
4226
  int32_t              resultBytes = getSpreadInfoSize();
751,905✔
4227
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
751,905!
4228

4229
  if (NULL == res) {
751,906!
4230
    return terrno;
×
4231
  }
4232
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
751,906✔
4233
  varDataSetLen(res, resultBytes);
751,906✔
4234

4235
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
751,906✔
4236
  int32_t          code = TSDB_CODE_SUCCESS;
751,906✔
4237
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
751,906✔
4238
  if (NULL == pCol) {
751,906!
4239
    code = terrno;
×
4240
    goto _exit;
×
4241
  }
4242

4243
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
751,906✔
4244
  if (TSDB_CODE_SUCCESS != code) {
751,905!
4245
    goto _exit;
×
4246
  }
4247

4248
_exit:
751,905✔
4249
  taosMemoryFree(res);
751,905!
4250
  return code;
751,905✔
4251
}
4252

4253
int32_t spreadCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
1✔
4254
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
1✔
4255
  SSpreadInfo*         pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
1✔
4256

4257
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
1✔
4258
  SSpreadInfo*         pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
1✔
4259
  spreadTransferInfo(pSBuf, pDBuf);
1✔
4260
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
1✔
4261
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
1✔
4262
  return TSDB_CODE_SUCCESS;
1✔
4263
}
4264

4265
int32_t getElapsedInfoSize() { return (int32_t)sizeof(SElapsedInfo); }
×
4266

4267
bool getElapsedFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
103,733✔
4268
  pEnv->calcMemSize = sizeof(SElapsedInfo);
103,733✔
4269
  return true;
103,733✔
4270
}
4271

4272
int32_t elapsedFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
8,059,637✔
4273
  if (pResultInfo->initialized) {
8,059,637!
4274
    return TSDB_CODE_SUCCESS;
×
4275
  }
4276
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
8,059,637!
4277
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
4278
  }
4279

4280
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
8,059,644✔
4281
  pInfo->result = 0;
8,059,644✔
4282
  pInfo->min = TSKEY_MAX;
8,059,644✔
4283
  pInfo->max = 0;
8,059,644✔
4284

4285
  if (pCtx->numOfParams > 1) {
8,059,644✔
4286
    pInfo->timeUnit = pCtx->param[1].param.i;
24,485✔
4287
  } else {
4288
    pInfo->timeUnit = 1;
8,035,159✔
4289
  }
4290

4291
  return TSDB_CODE_SUCCESS;
8,059,644✔
4292
}
4293

4294
int32_t elapsedFunction(SqlFunctionCtx* pCtx) {
8,059,796✔
4295
  int32_t numOfElems = 0;
8,059,796✔
4296

4297
  // Only the pre-computing information loaded and actual data does not loaded
4298
  SInputColumnInfoData* pInput = &pCtx->input;
8,059,796✔
4299
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
8,059,796✔
4300

4301
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
8,059,796✔
4302

4303
  numOfElems = pInput->numOfRows;  // since this is the primary timestamp, no need to exclude NULL values
8,059,796✔
4304
  if (numOfElems == 0) {
8,059,796✔
4305
    // for stream
4306
    if (pCtx->end.key != INT64_MIN) {
52!
4307
      pInfo->max = pCtx->end.key + 1;
52✔
4308
    }
4309
    goto _elapsed_over;
52✔
4310
  }
4311

4312
  if (pInput->colDataSMAIsSet) {
8,059,744!
4313
    if (pInfo->min == TSKEY_MAX) {
×
4314
      pInfo->min = GET_INT64_VAL(&pAgg->min);
×
4315
      pInfo->max = GET_INT64_VAL(&pAgg->max);
×
4316
    } else {
4317
      if (pCtx->order == TSDB_ORDER_ASC) {
×
4318
        pInfo->max = GET_INT64_VAL(&pAgg->max);
×
4319
      } else {
4320
        pInfo->min = GET_INT64_VAL(&pAgg->min);
×
4321
      }
4322
    }
4323
  } else {  // computing based on the true data block
4324
    if (0 == pInput->numOfRows) {
8,059,744!
4325
      if (pCtx->order == TSDB_ORDER_DESC) {
×
4326
        if (pCtx->end.key != INT64_MIN) {
×
4327
          pInfo->min = pCtx->end.key;
×
4328
        }
4329
      } else {
4330
        if (pCtx->end.key != INT64_MIN) {
×
4331
          pInfo->max = pCtx->end.key + 1;
×
4332
        }
4333
      }
4334
      goto _elapsed_over;
×
4335
    }
4336

4337
    SColumnInfoData* pCol = pInput->pData[0];
8,059,744✔
4338

4339
    int32_t start = pInput->startRowIndex;
8,059,744✔
4340
    TSKEY*  ptsList = (int64_t*)colDataGetData(pCol, 0);
8,059,744!
4341
    if (pCtx->order == TSDB_ORDER_DESC) {
8,059,744✔
4342
      if (pCtx->start.key == INT64_MIN) {
674!
4343
        pInfo->max = (pInfo->max < ptsList[start]) ? ptsList[start] : pInfo->max;
674✔
4344
      } else {
4345
        pInfo->max = pCtx->start.key + 1;
×
4346
      }
4347

4348
      if (pCtx->end.key == INT64_MIN) {
674!
4349
        pInfo->min =
674✔
4350
            (pInfo->min > ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->min;
674✔
4351
      } else {
4352
        pInfo->min = pCtx->end.key;
×
4353
      }
4354
    } else {
4355
      if (pCtx->start.key == INT64_MIN) {
8,059,070✔
4356
        pInfo->min = (pInfo->min > ptsList[start]) ? ptsList[start] : pInfo->min;
4,141,193✔
4357
      } else {
4358
        pInfo->min = pCtx->start.key;
3,917,877✔
4359
      }
4360

4361
      if (pCtx->end.key == INT64_MIN) {
8,059,070✔
4362
        pInfo->max =
3,879,790✔
4363
            (pInfo->max < ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->max;
3,879,790✔
4364
      } else {
4365
        pInfo->max = pCtx->end.key + 1;
4,179,280✔
4366
      }
4367
    }
4368
  }
4369

4370
_elapsed_over:
8,059,796✔
4371
  // data in the check operation are all null, not output
4372
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
8,059,796✔
4373

4374
  return TSDB_CODE_SUCCESS;
8,059,796✔
4375
}
4376

4377
static void elapsedTransferInfo(SElapsedInfo* pInput, SElapsedInfo* pOutput) {
×
4378
  pOutput->timeUnit = pInput->timeUnit;
×
4379
  if (pOutput->min > pInput->min) {
×
4380
    pOutput->min = pInput->min;
×
4381
  }
4382

4383
  if (pOutput->max < pInput->max) {
×
4384
    pOutput->max = pInput->max;
×
4385
  }
4386
}
×
4387

4388
int32_t elapsedFunctionMerge(SqlFunctionCtx* pCtx) {
×
4389
  SInputColumnInfoData* pInput = &pCtx->input;
×
4390
  SColumnInfoData*      pCol = pInput->pData[0];
×
4391
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
×
4392
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
4393
  }
4394

4395
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
×
4396

4397
  int32_t start = pInput->startRowIndex;
×
4398

4399
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
×
4400
    char*         data = colDataGetData(pCol, i);
×
4401
    SElapsedInfo* pInputInfo = (SElapsedInfo*)varDataVal(data);
×
4402
    elapsedTransferInfo(pInputInfo, pInfo);
×
4403
  }
4404

4405
  SET_VAL(GET_RES_INFO(pCtx), 1, 1);
×
4406
  return TSDB_CODE_SUCCESS;
×
4407
}
4408

4409
int32_t elapsedFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
8,056,942✔
4410
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
8,056,942✔
4411
  double        result = (double)pInfo->max - (double)pInfo->min;
8,056,942✔
4412
  result = (result >= 0) ? result : -result;
8,056,942✔
4413
  pInfo->result = result / pInfo->timeUnit;
8,056,942✔
4414
  return functionFinalize(pCtx, pBlock);
8,056,942✔
4415
}
4416

4417
int32_t elapsedPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
×
4418
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
×
4419
  SElapsedInfo*        pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
×
4420
  int32_t              resultBytes = getElapsedInfoSize();
×
4421
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
×
4422

4423
  if (NULL == res) {
×
4424
    return terrno;
×
4425
  }
4426
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
×
4427
  varDataSetLen(res, resultBytes);
×
4428

4429
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
×
4430
  int32_t          code = TSDB_CODE_SUCCESS;
×
4431
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
×
4432
  if (NULL == pCol) {
×
4433
    code = terrno;
×
4434
    goto _exit;
×
4435
  }
4436

4437
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
×
4438
  if (TSDB_CODE_SUCCESS != code) {
×
4439
    goto _exit;
×
4440
  }
4441
_exit:
×
4442
  taosMemoryFree(res);
×
4443
  return code;
×
4444
}
4445

4446
int32_t elapsedCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4447
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
4448
  SElapsedInfo*        pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
4449

4450
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4451
  SElapsedInfo*        pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
4452

4453
  elapsedTransferInfo(pSBuf, pDBuf);
×
4454
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
4455
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
4456
  return TSDB_CODE_SUCCESS;
×
4457
}
4458

4459
int32_t getHistogramInfoSize() {
2,154,780✔
4460
  return (int32_t)sizeof(SHistoFuncInfo) + HISTOGRAM_MAX_BINS_NUM * sizeof(SHistoFuncBin);
2,154,780✔
4461
}
4462

4463
bool getHistogramFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
112,250✔
4464
  pEnv->calcMemSize = sizeof(SHistoFuncInfo) + HISTOGRAM_MAX_BINS_NUM * sizeof(SHistoFuncBin);
112,250✔
4465
  return true;
112,250✔
4466
}
4467

4468
static int8_t getHistogramBinType(char* binTypeStr) {
13,543,106✔
4469
  int8_t binType;
4470
  if (strcasecmp(binTypeStr, "user_input") == 0) {
13,543,106✔
4471
    binType = USER_INPUT_BIN;
2,366✔
4472
  } else if (strcasecmp(binTypeStr, "linear_bin") == 0) {
13,540,740✔
4473
    binType = LINEAR_BIN;
3,362✔
4474
  } else if (strcasecmp(binTypeStr, "log_bin") == 0) {
13,537,378!
4475
    binType = LOG_BIN;
13,537,661✔
4476
  } else {
4477
    binType = UNKNOWN_BIN;
×
4478
  }
4479

4480
  return binType;
13,543,106✔
4481
}
4482

4483
static int32_t getHistogramBinDesc(SHistoFuncInfo* pInfo, char* binDescStr, int8_t binType, bool normalized) {
13,543,254✔
4484
  cJSON*  binDesc = cJSON_Parse(binDescStr);
13,543,254✔
4485
  int32_t numOfBins;
4486
  double* intervals;
4487
  if (cJSON_IsObject(binDesc)) { /* linaer/log bins */
13,543,385✔
4488
    int32_t numOfParams = cJSON_GetArraySize(binDesc);
13,540,986✔
4489
    int32_t startIndex;
4490
    if (numOfParams != 4) {
13,540,888!
4491
      cJSON_Delete(binDesc);
×
4492
      return TSDB_CODE_FAILED;
×
4493
    }
4494

4495
    cJSON* start = cJSON_GetObjectItem(binDesc, "start");
13,540,888✔
4496
    cJSON* factor = cJSON_GetObjectItem(binDesc, "factor");
13,541,068✔
4497
    cJSON* width = cJSON_GetObjectItem(binDesc, "width");
13,540,800✔
4498
    cJSON* count = cJSON_GetObjectItem(binDesc, "count");
13,538,818✔
4499
    cJSON* infinity = cJSON_GetObjectItem(binDesc, "infinity");
13,540,354✔
4500

4501
    if (!cJSON_IsNumber(start) || !cJSON_IsNumber(count) || !cJSON_IsBool(infinity)) {
13,541,026!
4502
      cJSON_Delete(binDesc);
×
4503
      return TSDB_CODE_FAILED;
×
4504
    }
4505

4506
    if (count->valueint <= 0 || count->valueint > 1000) {  // limit count to 1000
13,540,841!
4507
      cJSON_Delete(binDesc);
×
4508
      return TSDB_CODE_FAILED;
×
4509
    }
4510

4511
    if (isinf(start->valuedouble) || (width != NULL && isinf(width->valuedouble)) ||
13,540,841!
4512
        (factor != NULL && isinf(factor->valuedouble)) || (count != NULL && isinf(count->valuedouble))) {
13,540,841!
4513
      cJSON_Delete(binDesc);
×
4514
      return TSDB_CODE_FAILED;
×
4515
    }
4516

4517
    int32_t counter = (int32_t)count->valueint;
13,540,841✔
4518
    if (infinity->valueint == false) {
13,540,841✔
4519
      startIndex = 0;
9,582✔
4520
      numOfBins = counter + 1;
9,582✔
4521
    } else {
4522
      startIndex = 1;
13,531,259✔
4523
      numOfBins = counter + 3;
13,531,259✔
4524
    }
4525

4526
    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
13,540,841!
4527
    if (NULL == intervals) {
13,541,212!
4528
      cJSON_Delete(binDesc);
×
4529
      qError("histogram function out of memory");
×
4530
      return terrno;
×
4531
    }
4532
    if (cJSON_IsNumber(width) && factor == NULL && binType == LINEAR_BIN) {
13,541,212!
4533
      // linear bin process
4534
      if (width->valuedouble == 0) {
3,362!
4535
        taosMemoryFree(intervals);
×
4536
        cJSON_Delete(binDesc);
×
4537
        return TSDB_CODE_FAILED;
×
4538
      }
4539
      for (int i = 0; i < counter + 1; ++i) {
21,230✔
4540
        intervals[startIndex] = start->valuedouble + i * width->valuedouble;
17,868✔
4541
        if (isinf(intervals[startIndex])) {
17,868!
4542
          taosMemoryFree(intervals);
×
4543
          cJSON_Delete(binDesc);
×
4544
          return TSDB_CODE_FAILED;
×
4545
        }
4546
        startIndex++;
17,868✔
4547
      }
4548
    } else if (cJSON_IsNumber(factor) && width == NULL && binType == LOG_BIN) {
13,537,825!
4549
      // log bin process
4550
      if (start->valuedouble == 0) {
13,537,775!
4551
        taosMemoryFree(intervals);
×
4552
        cJSON_Delete(binDesc);
×
4553
        return TSDB_CODE_FAILED;
×
4554
      }
4555
      if (factor->valuedouble < 0 || factor->valuedouble == 0 || factor->valuedouble == 1) {
13,537,775!
4556
        taosMemoryFree(intervals);
×
4557
        cJSON_Delete(binDesc);
×
4558
        return TSDB_CODE_FAILED;
×
4559
      }
4560
      for (int i = 0; i < counter + 1; ++i) {
94,751,990✔
4561
        intervals[startIndex] = start->valuedouble * pow(factor->valuedouble, i * 1.0);
81,214,209✔
4562
        if (isinf(intervals[startIndex])) {
81,214,209!
4563
          taosMemoryFree(intervals);
×
4564
          cJSON_Delete(binDesc);
×
4565
          return TSDB_CODE_FAILED;
×
4566
        }
4567
        startIndex++;
81,214,209✔
4568
      }
4569
    } else {
4570
      taosMemoryFree(intervals);
×
4571
      cJSON_Delete(binDesc);
×
4572
      return TSDB_CODE_FAILED;
×
4573
    }
4574

4575
    if (infinity->valueint == true) {
13,541,143✔
4576
      intervals[0] = -INFINITY;
13,531,380✔
4577
      intervals[numOfBins - 1] = INFINITY;
13,531,380✔
4578
      // in case of desc bin orders, -inf/inf should be swapped
4579
      if (numOfBins < 4) {
13,531,380!
4580
        return TSDB_CODE_FAILED;
×
4581
      }
4582
      if (intervals[1] > intervals[numOfBins - 2]) {
13,531,380✔
4583
        TSWAP(intervals[0], intervals[numOfBins - 1]);
13,531,286✔
4584
      }
4585
    }
4586
  } else if (cJSON_IsArray(binDesc)) { /* user input bins */
2,366!
4587
    if (binType != USER_INPUT_BIN) {
2,366!
4588
      cJSON_Delete(binDesc);
×
4589
      return TSDB_CODE_FAILED;
×
4590
    }
4591
    numOfBins = cJSON_GetArraySize(binDesc);
2,366✔
4592
    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
2,366!
4593
    if (NULL == intervals) {
2,365!
4594
      cJSON_Delete(binDesc);
×
4595
      qError("histogram function out of memory");
×
4596
      return terrno;
×
4597
    }
4598
    cJSON* bin = binDesc->child;
2,365✔
4599
    if (bin == NULL) {
2,365!
4600
      taosMemoryFree(intervals);
×
4601
      cJSON_Delete(binDesc);
×
4602
      return TSDB_CODE_FAILED;
×
4603
    }
4604
    int i = 0;
2,365✔
4605
    while (bin) {
9,521✔
4606
      intervals[i] = bin->valuedouble;
7,156✔
4607
      if (!cJSON_IsNumber(bin)) {
7,156!
4608
        taosMemoryFree(intervals);
×
4609
        cJSON_Delete(binDesc);
×
4610
        return TSDB_CODE_FAILED;
×
4611
      }
4612
      if (i != 0 && intervals[i] <= intervals[i - 1]) {
7,156!
4613
        taosMemoryFree(intervals);
×
4614
        cJSON_Delete(binDesc);
×
4615
        return TSDB_CODE_FAILED;
×
4616
      }
4617
      bin = bin->next;
7,156✔
4618
      i++;
7,156✔
4619
    }
4620
  } else {
4621
    cJSON_Delete(binDesc);
×
4622
    return TSDB_CODE_FAILED;
×
4623
  }
4624

4625
  pInfo->numOfBins = numOfBins - 1;
13,543,508✔
4626
  pInfo->normalized = normalized;
13,543,508✔
4627
  for (int32_t i = 0; i < pInfo->numOfBins; ++i) {
108,307,069✔
4628
    pInfo->bins[i].lower = intervals[i] < intervals[i + 1] ? intervals[i] : intervals[i + 1];
94,763,561✔
4629
    pInfo->bins[i].upper = intervals[i + 1] > intervals[i] ? intervals[i + 1] : intervals[i];
94,763,561✔
4630
    pInfo->bins[i].count = 0;
94,763,561✔
4631
  }
4632

4633
  taosMemoryFree(intervals);
13,543,508✔
4634
  cJSON_Delete(binDesc);
13,543,173✔
4635

4636
  return TSDB_CODE_SUCCESS;
13,543,490✔
4637
}
4638

4639
int32_t histogramFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
13,543,382✔
4640
  if (pResultInfo->initialized) {
13,543,382!
4641
    return TSDB_CODE_SUCCESS;
×
4642
  }
4643
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
13,543,382!
4644
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
4645
  }
4646

4647
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
13,543,230✔
4648
  pInfo->numOfBins = 0;
13,543,230✔
4649
  pInfo->totalCount = 0;
13,543,230✔
4650
  pInfo->normalized = 0;
13,543,230✔
4651

4652
  char* binTypeStr = taosStrndup(varDataVal(pCtx->param[1].param.pz), varDataLen(pCtx->param[1].param.pz));
13,543,230!
4653
  if (binTypeStr == NULL) {
13,543,143!
4654
    return terrno;
×
4655
  }
4656
  int8_t binType = getHistogramBinType(binTypeStr);
13,543,143✔
4657
  taosMemoryFree(binTypeStr);
13,543,298!
4658

4659
  if (binType == UNKNOWN_BIN) {
13,543,037!
4660
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
4661
  }
4662
  char* binDesc = taosStrndup(varDataVal(pCtx->param[2].param.pz), varDataLen(pCtx->param[2].param.pz));
13,543,037!
4663
  if (binDesc == NULL) {
13,543,215!
4664
    return terrno;
×
4665
  }
4666
  int64_t normalized = pCtx->param[3].param.i;
13,543,215✔
4667
  if (normalized != 0 && normalized != 1) {
13,543,215!
4668
    taosMemoryFree(binDesc);
×
4669
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
4670
  }
4671
  int32_t code = getHistogramBinDesc(pInfo, binDesc, binType, (bool)normalized);
13,543,215✔
4672
  if (TSDB_CODE_SUCCESS != code) {
13,543,485!
4673
    taosMemoryFree(binDesc);
×
4674
    return code;
×
4675
  }
4676
  taosMemoryFree(binDesc);
13,543,485✔
4677

4678
  return TSDB_CODE_SUCCESS;
13,543,599✔
4679
}
4680

4681
static int32_t histogramFunctionImpl(SqlFunctionCtx* pCtx, bool isPartial) {
15,586,858✔
4682
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
15,586,858✔
4683

4684
  SInputColumnInfoData* pInput = &pCtx->input;
15,586,858✔
4685
  SColumnInfoData*      pCol = pInput->pData[0];
15,586,858✔
4686

4687
  int32_t type = pInput->pData[0]->info.type;
15,586,858✔
4688

4689
  int32_t start = pInput->startRowIndex;
15,586,858✔
4690
  int32_t numOfRows = pInput->numOfRows;
15,586,858✔
4691

4692
  int32_t numOfElems = 0;
15,586,858✔
4693
  for (int32_t i = start; i < numOfRows + start; ++i) {
59,211,509✔
4694
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
43,624,651✔
4695
      continue;
641,883✔
4696
    }
4697

4698
    numOfElems++;
42,982,768✔
4699

4700
    char*  data = colDataGetData(pCol, i);
42,982,768!
4701
    double v;
4702
    GET_TYPED_DATA(v, double, type, data);
42,982,768!
4703

4704
    for (int32_t k = 0; k < pInfo->numOfBins; ++k) {
92,146,919✔
4705
      if (v > pInfo->bins[k].lower && v <= pInfo->bins[k].upper) {
89,115,413✔
4706
        pInfo->bins[k].count++;
39,951,262✔
4707
        pInfo->totalCount++;
39,951,262✔
4708
        break;
39,951,262✔
4709
      }
4710
    }
4711
  }
4712

4713
  if (!isPartial) {
15,586,858✔
4714
    GET_RES_INFO(pCtx)->numOfRes = pInfo->numOfBins;
11,395,331✔
4715
  } else {
4716
    GET_RES_INFO(pCtx)->numOfRes = 1;
4,191,527✔
4717
  }
4718
  return TSDB_CODE_SUCCESS;
15,586,858✔
4719
}
4720

4721
int32_t histogramFunction(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, false); }
11,395,263✔
4722

4723
int32_t histogramFunctionPartial(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, true); }
4,192,238✔
4724

4725
static void histogramTransferInfo(SHistoFuncInfo* pInput, SHistoFuncInfo* pOutput) {
2,120,713✔
4726
  pOutput->normalized = pInput->normalized;
2,120,713✔
4727
  pOutput->numOfBins = pInput->numOfBins;
2,120,713✔
4728
  pOutput->totalCount += pInput->totalCount;
2,120,713✔
4729
  for (int32_t k = 0; k < pOutput->numOfBins; ++k) {
16,959,123✔
4730
    pOutput->bins[k].lower = pInput->bins[k].lower;
14,838,410✔
4731
    pOutput->bins[k].upper = pInput->bins[k].upper;
14,838,410✔
4732
    pOutput->bins[k].count += pInput->bins[k].count;
14,838,410✔
4733
  }
4734
}
2,120,713✔
4735

4736
int32_t histogramFunctionMerge(SqlFunctionCtx* pCtx) {
2,120,713✔
4737
  SInputColumnInfoData* pInput = &pCtx->input;
2,120,713✔
4738
  SColumnInfoData*      pCol = pInput->pData[0];
2,120,713✔
4739
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
2,120,713!
4740
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
4741
  }
4742

4743
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,120,713✔
4744

4745
  int32_t start = pInput->startRowIndex;
2,120,713✔
4746

4747
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
4,241,426✔
4748
    char*           data = colDataGetData(pCol, i);
2,120,713!
4749
    SHistoFuncInfo* pInputInfo = (SHistoFuncInfo*)varDataVal(data);
2,120,713✔
4750
    histogramTransferInfo(pInputInfo, pInfo);
2,120,713✔
4751
  }
4752

4753
  SET_VAL(GET_RES_INFO(pCtx), pInfo->numOfBins, pInfo->numOfBins);
2,120,713!
4754
  return TSDB_CODE_SUCCESS;
2,120,713✔
4755
}
4756

4757
int32_t histogramFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
13,445,610✔
4758
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
13,445,610✔
4759
  SHistoFuncInfo*      pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
13,445,610✔
4760
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
13,445,610✔
4761
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
13,445,610✔
4762
  int32_t              code = TSDB_CODE_SUCCESS;
13,445,297✔
4763

4764
  int32_t currentRow = pBlock->info.rows;
13,445,297✔
4765
  if (NULL == pCol) {
13,445,297!
4766
    return TSDB_CODE_OUT_OF_RANGE;
×
4767
  }
4768

4769
  if (pInfo->normalized) {
13,445,297✔
4770
    for (int32_t k = 0; k < pResInfo->numOfRes; ++k) {
55,918✔
4771
      if (pInfo->totalCount != 0) {
46,168✔
4772
        pInfo->bins[k].percentage = pInfo->bins[k].count / (double)pInfo->totalCount;
16,755✔
4773
      } else {
4774
        pInfo->bins[k].percentage = 0;
29,413✔
4775
      }
4776
    }
4777
  }
4778

4779
  for (int32_t i = 0; i < pResInfo->numOfRes; ++i) {
107,460,966✔
4780
    int32_t len;
4781
    char    buf[512] = {0};
94,076,702✔
4782
    if (!pInfo->normalized) {
94,076,702✔
4783
      len = tsnprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE,
94,030,534✔
4784
                      "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%" PRId64 "}", pInfo->bins[i].lower,
4785
                      pInfo->bins[i].upper, pInfo->bins[i].count);
4786
    } else {
4787
      len = tsnprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE,
46,168✔
4788
                      "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%lf}", pInfo->bins[i].lower, pInfo->bins[i].upper,
4789
                      pInfo->bins[i].percentage);
4790
    }
4791
    varDataSetLen(buf, len);
94,077,249✔
4792
    code = colDataSetVal(pCol, currentRow, buf, false);
94,077,249✔
4793
    if (TSDB_CODE_SUCCESS != code) {
94,015,669!
4794
      return code;
×
4795
    }
4796
    currentRow++;
94,015,669✔
4797
  }
4798

4799
  return code;
13,384,264✔
4800
}
4801

4802
int32_t histogramPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
2,148,655✔
4803
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,148,655✔
4804
  SHistoFuncInfo*      pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,148,655✔
4805
  int32_t              resultBytes = getHistogramInfoSize();
2,148,655✔
4806
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
2,148,655!
4807

4808
  if (NULL == res) {
2,148,655!
4809
    return terrno;
×
4810
  }
4811
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
2,148,655✔
4812
  varDataSetLen(res, resultBytes);
2,148,655✔
4813

4814
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
2,148,655✔
4815
  int32_t          code = TSDB_CODE_SUCCESS;
2,148,655✔
4816
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
2,148,655✔
4817
  if (NULL == pCol) {
2,148,655!
4818
    code = terrno;
×
4819
    goto _exit;
×
4820
  }
4821
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
2,148,655✔
4822

4823
_exit:
2,148,655✔
4824
  taosMemoryFree(res);
2,148,655!
4825
  return code;
2,148,655✔
4826
}
4827

4828
int32_t histogramCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4829
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
4830
  SHistoFuncInfo*      pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
4831

4832
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4833
  SHistoFuncInfo*      pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
4834

4835
  histogramTransferInfo(pSBuf, pDBuf);
×
4836
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
4837
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
4838
  return TSDB_CODE_SUCCESS;
×
4839
}
4840

4841
int32_t getHLLInfoSize() { return (int32_t)sizeof(SHLLInfo); }
10,223✔
4842

4843
bool getHLLFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
66,719✔
4844
  pEnv->calcMemSize = sizeof(SHLLInfo);
66,719✔
4845
  return true;
66,719✔
4846
}
4847

4848
static uint8_t hllCountNum(void* data, int32_t bytes, int32_t* buk) {
3,750,130✔
4849
  uint64_t hash = MurmurHash3_64(data, bytes);
3,750,130✔
4850
  int32_t  index = hash & HLL_BUCKET_MASK;
3,748,151✔
4851
  hash >>= HLL_BUCKET_BITS;
3,748,151✔
4852
  hash |= ((uint64_t)1 << HLL_DATA_BITS);
3,748,151✔
4853
  uint64_t bit = 1;
3,748,151✔
4854
  uint8_t  count = 1;
3,748,151✔
4855
  while ((hash & bit) == 0) {
7,118,149✔
4856
    count++;
3,369,998✔
4857
    bit <<= 1;
3,369,998✔
4858
  }
4859
  *buk = index;
3,748,151✔
4860
  return count;
3,748,151✔
4861
}
4862

4863
static void hllBucketHisto(uint8_t* buckets, int32_t* bucketHisto) {
251,067✔
4864
  uint64_t* word = (uint64_t*)buckets;
251,067✔
4865
  uint8_t*  bytes;
4866

4867
  for (int32_t j = 0; j < HLL_BUCKETS >> 3; j++) {
506,594,540✔
4868
    if (*word == 0) {
506,343,473✔
4869
      bucketHisto[0] += 8;
505,311,424✔
4870
    } else {
4871
      bytes = (uint8_t*)word;
1,032,049✔
4872
      bucketHisto[bytes[0]]++;
1,032,049✔
4873
      bucketHisto[bytes[1]]++;
1,032,049✔
4874
      bucketHisto[bytes[2]]++;
1,032,049✔
4875
      bucketHisto[bytes[3]]++;
1,032,049✔
4876
      bucketHisto[bytes[4]]++;
1,032,049✔
4877
      bucketHisto[bytes[5]]++;
1,032,049✔
4878
      bucketHisto[bytes[6]]++;
1,032,049✔
4879
      bucketHisto[bytes[7]]++;
1,032,049✔
4880
    }
4881
    word++;
506,343,473✔
4882
  }
4883
}
251,067✔
4884
static double hllTau(double x) {
251,075✔
4885
  if (x == 0. || x == 1.) return 0.;
251,075!
4886
  double zPrime;
4887
  double y = 1.0;
×
4888
  double z = 1 - x;
×
4889
  do {
4890
    x = sqrt(x);
×
4891
    zPrime = z;
×
4892
    y *= 0.5;
×
4893
    z -= pow(1 - x, 2) * y;
×
4894
  } while (zPrime != z);
×
4895
  return z / 3;
×
4896
}
4897

4898
static double hllSigma(double x) {
251,090✔
4899
  if (x == 1.0) return INFINITY;
251,090✔
4900
  double zPrime;
4901
  double y = 1;
225,562✔
4902
  double z = x;
225,562✔
4903
  do {
4904
    x *= x;
4,415,316✔
4905
    zPrime = z;
4,415,316✔
4906
    z += x * y;
4,415,316✔
4907
    y += y;
4,415,316✔
4908
  } while (zPrime != z);
4,415,316✔
4909
  return z;
225,562✔
4910
}
4911

4912
// estimate the cardinality, the algorithm refer this paper: "New cardinality estimation algorithms for HyperLogLog
4913
// sketches"
4914
static uint64_t hllCountCnt(uint8_t* buckets) {
251,037✔
4915
  double  m = HLL_BUCKETS;
251,037✔
4916
  int32_t buckethisto[64] = {0};
251,037✔
4917
  hllBucketHisto(buckets, buckethisto);
251,037✔
4918

4919
  double z = m * hllTau((m - buckethisto[HLL_DATA_BITS + 1]) / (double)m);
251,075✔
4920
  for (int j = HLL_DATA_BITS; j >= 1; --j) {
12,801,580✔
4921
    z += buckethisto[j];
12,550,492✔
4922
    z *= 0.5;
12,550,492✔
4923
  }
4924

4925
  z += m * hllSigma(buckethisto[0] / (double)m);
251,088✔
4926
  double E = (double)llroundl(HLL_ALPHA_INF * m * m / z);
251,090✔
4927

4928
  return (uint64_t)E;
251,090✔
4929
}
4930

4931
int32_t hllFunction(SqlFunctionCtx* pCtx) {
275,786✔
4932
  SHLLInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
275,786✔
4933

4934
  SInputColumnInfoData* pInput = &pCtx->input;
275,786✔
4935
  SColumnInfoData*      pCol = pInput->pData[0];
275,786✔
4936

4937
  int32_t type = pCol->info.type;
275,786✔
4938
  int32_t bytes = pCol->info.bytes;
275,786✔
4939

4940
  int32_t start = pInput->startRowIndex;
275,786✔
4941
  int32_t numOfRows = pInput->numOfRows;
275,786✔
4942

4943
  int32_t numOfElems = 0;
275,786✔
4944
  if (IS_NULL_TYPE(type)) {
275,786✔
4945
    goto _hll_over;
1,564✔
4946
  }
4947

4948
  for (int32_t i = start; i < numOfRows + start; ++i) {
4,869,387✔
4949
    if (pCol->hasNull && colDataIsNull_s(pCol, i)) {
6,071,594!
4950
      continue;
845,798✔
4951
    }
4952

4953
    numOfElems++;
3,751,817✔
4954

4955
    char* data = colDataGetData(pCol, i);
3,751,817!
4956
    if (IS_VAR_DATA_TYPE(type)) {
3,751,817!
4957
      bytes = varDataLen(data);
1,225,620✔
4958
      data = varDataVal(data);
1,225,620✔
4959
    }
4960

4961
    int32_t index = 0;
3,751,817✔
4962
    uint8_t count = hllCountNum(data, bytes, &index);
3,751,817✔
4963
    uint8_t oldcount = pInfo->buckets[index];
3,749,367✔
4964
    if (count > oldcount) {
3,749,367✔
4965
      pInfo->buckets[index] = count;
1,063,040✔
4966
    }
4967
  }
4968

4969
_hll_over:
271,772✔
4970
  pInfo->totalCount += numOfElems;
273,336✔
4971

4972
  if (pInfo->totalCount == 0 && !tsCountAlwaysReturnValue) {
273,336✔
4973
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
1,851✔
4974
  } else {
4975
    SET_VAL(GET_RES_INFO(pCtx), 1, 1);
271,485✔
4976
  }
4977

4978
  return TSDB_CODE_SUCCESS;
273,336✔
4979
}
4980

4981
static void hllTransferInfo(SHLLInfo* pInput, SHLLInfo* pOutput) {
10,507✔
4982
  for (int32_t k = 0; k < HLL_BUCKETS; ++k) {
168,070,515✔
4983
    if (pOutput->buckets[k] < pInput->buckets[k]) {
168,060,008✔
4984
      pOutput->buckets[k] = pInput->buckets[k];
293,387✔
4985
    }
4986
  }
4987
  pOutput->totalCount += pInput->totalCount;
10,507✔
4988
}
10,507✔
4989

4990
int32_t hllFunctionMerge(SqlFunctionCtx* pCtx) {
10,436✔
4991
  SInputColumnInfoData* pInput = &pCtx->input;
10,436✔
4992
  SColumnInfoData*      pCol = pInput->pData[0];
10,436✔
4993

4994
  if (IS_NULL_TYPE(pCol->info.type)) {
10,436!
4995
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
4996
    return TSDB_CODE_SUCCESS;
×
4997
  }
4998

4999
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
10,436!
5000
    return TSDB_CODE_SUCCESS;
×
5001
  }
5002

5003
  SHLLInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
10,436✔
5004

5005
  int32_t start = pInput->startRowIndex;
10,436✔
5006

5007
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
20,942✔
5008
    if (colDataIsNull_s(pCol, i)) continue;
21,012!
5009
    char*     data = colDataGetData(pCol, i);
10,506!
5010
    SHLLInfo* pInputInfo = (SHLLInfo*)varDataVal(data);
10,506✔
5011
    hllTransferInfo(pInputInfo, pInfo);
10,506✔
5012
  }
5013

5014
  if (pInfo->totalCount == 0 && !tsCountAlwaysReturnValue) {
10,436✔
5015
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
3✔
5016
  } else {
5017
    SET_VAL(GET_RES_INFO(pCtx), 1, 1);
10,433✔
5018
  }
5019

5020
  return TSDB_CODE_SUCCESS;
10,436✔
5021
}
5022

5023
int32_t hllFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
251,039✔
5024
  SResultRowEntryInfo* pInfo = GET_RES_INFO(pCtx);
251,039✔
5025

5026
  SHLLInfo* pHllInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
251,039✔
5027
  pHllInfo->result = hllCountCnt(pHllInfo->buckets);
251,039✔
5028
  if (tsCountAlwaysReturnValue && pHllInfo->result == 0) {
251,092✔
5029
    pInfo->numOfRes = 1;
23,698✔
5030
  }
5031

5032
  return functionFinalize(pCtx, pBlock);
251,092✔
5033
}
5034

5035
int32_t hllPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
10,223✔
5036
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
10,223✔
5037
  SHLLInfo*            pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
10,223✔
5038
  int32_t              resultBytes = getHLLInfoSize();
10,223✔
5039
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
10,223!
5040

5041
  if (NULL == res) {
10,224!
5042
    return terrno;
×
5043
  }
5044
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
10,224✔
5045
  varDataSetLen(res, resultBytes);
10,224✔
5046

5047
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
10,224✔
5048
  int32_t          code = TSDB_CODE_SUCCESS;
10,224✔
5049
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
10,224✔
5050
  if (NULL == pCol) {
10,224!
5051
    code = terrno;
×
5052
    goto _exit;
×
5053
  }
5054

5055
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
10,224✔
5056

5057
_exit:
10,224✔
5058
  taosMemoryFree(res);
10,224!
5059
  return code;
10,224✔
5060
}
5061

5062
int32_t hllCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
1✔
5063
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
1✔
5064
  SHLLInfo*            pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
1✔
5065

5066
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
1✔
5067
  SHLLInfo*            pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
1✔
5068

5069
  hllTransferInfo(pSBuf, pDBuf);
1✔
5070
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
1✔
5071
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
1✔
5072
  return TSDB_CODE_SUCCESS;
1✔
5073
}
5074

5075
bool getStateFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
19,251✔
5076
  pEnv->calcMemSize = sizeof(SStateInfo);
19,251✔
5077
  return true;
19,251✔
5078
}
5079

5080
static int8_t getStateOpType(char* opStr) {
37,623✔
5081
  int8_t opType;
5082
  if (strncasecmp(opStr, "LT", 2) == 0) {
37,623✔
5083
    opType = STATE_OPER_LT;
1,522✔
5084
  } else if (strncasecmp(opStr, "GT", 2) == 0) {
36,101✔
5085
    opType = STATE_OPER_GT;
3,421✔
5086
  } else if (strncasecmp(opStr, "LE", 2) == 0) {
32,680✔
5087
    opType = STATE_OPER_LE;
496✔
5088
  } else if (strncasecmp(opStr, "GE", 2) == 0) {
32,184✔
5089
    opType = STATE_OPER_GE;
504✔
5090
  } else if (strncasecmp(opStr, "NE", 2) == 0) {
31,680✔
5091
    opType = STATE_OPER_NE;
6,592✔
5092
  } else if (strncasecmp(opStr, "EQ", 2) == 0) {
25,088!
5093
    opType = STATE_OPER_EQ;
25,088✔
5094
  } else {
5095
    opType = STATE_OPER_INVALID;
×
5096
  }
5097

5098
  return opType;
37,623✔
5099
}
5100

5101
static bool checkStateOp(int8_t op, SColumnInfoData* pCol, int32_t index, SVariant param) {
34,988,810✔
5102
  char* data = colDataGetData(pCol, index);
34,988,810!
5103
  switch (pCol->info.type) {
34,988,810!
5104
    case TSDB_DATA_TYPE_TINYINT: {
10,948✔
5105
      int8_t v = *(int8_t*)data;
10,948✔
5106
      STATE_COMP(op, v, param);
10,948!
5107
      break;
×
5108
    }
5109
    case TSDB_DATA_TYPE_UTINYINT: {
2,880✔
5110
      uint8_t v = *(uint8_t*)data;
2,880✔
5111
      STATE_COMP(op, v, param);
2,880!
5112
      break;
×
5113
    }
5114
    case TSDB_DATA_TYPE_SMALLINT: {
61,556✔
5115
      int16_t v = *(int16_t*)data;
61,556✔
5116
      STATE_COMP(op, v, param);
61,556!
5117
      break;
×
5118
    }
5119
    case TSDB_DATA_TYPE_USMALLINT: {
2,880✔
5120
      uint16_t v = *(uint16_t*)data;
2,880✔
5121
      STATE_COMP(op, v, param);
2,880!
5122
      break;
×
5123
    }
5124
    case TSDB_DATA_TYPE_INT: {
149,648✔
5125
      int32_t v = *(int32_t*)data;
149,648✔
5126
      STATE_COMP(op, v, param);
149,648!
5127
      break;
12✔
5128
    }
5129
    case TSDB_DATA_TYPE_UINT: {
2,880✔
5130
      uint32_t v = *(uint32_t*)data;
2,880✔
5131
      STATE_COMP(op, v, param);
2,880!
5132
      break;
×
5133
    }
5134
    case TSDB_DATA_TYPE_BIGINT: {
7,105,030✔
5135
      int64_t v = *(int64_t*)data;
7,105,030✔
5136
      STATE_COMP(op, v, param);
7,105,030!
5137
      break;
×
5138
    }
5139
    case TSDB_DATA_TYPE_UBIGINT: {
2,880✔
5140
      uint64_t v = *(uint64_t*)data;
2,880✔
5141
      STATE_COMP(op, v, param);
2,880!
5142
      break;
×
5143
    }
5144
    case TSDB_DATA_TYPE_FLOAT: {
5,263,299✔
5145
      float v = *(float*)data;
5,263,299✔
5146
      STATE_COMP(op, v, param);
5,263,299!
5147
      break;
×
5148
    }
5149
    case TSDB_DATA_TYPE_DOUBLE: {
22,388,977✔
5150
      double v = *(double*)data;
22,388,977✔
5151
      STATE_COMP(op, v, param);
22,388,977!
5152
      break;
×
5153
    }
5154
    default: {
×
5155
      return false;
×
5156
    }
5157
  }
5158
  return false;
12✔
5159
}
5160

5161
int32_t stateCountFunction(SqlFunctionCtx* pCtx) {
2,457✔
5162
  int32_t              code = TSDB_CODE_SUCCESS;
2,457✔
5163
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,457✔
5164
  SStateInfo*          pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,457✔
5165

5166
  SInputColumnInfoData* pInput = &pCtx->input;
2,457✔
5167
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
2,457✔
5168

5169
  SColumnInfoData* pInputCol = pInput->pData[0];
2,457✔
5170

5171
  int32_t          numOfElems = 0;
2,457✔
5172
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
2,457✔
5173

5174
  int8_t op = getStateOpType(varDataVal(pCtx->param[1].param.pz));
2,457✔
5175
  if (STATE_OPER_INVALID == op) {
2,457!
5176
    return 0;
×
5177
  }
5178

5179
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
382,581✔
5180
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
380,121!
5181
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5182
    } else {
5183
      pInfo->prevTs = tsList[i];
380,121✔
5184
    }
5185

5186
    pInfo->isPrevTsSet = true;
380,121✔
5187
    numOfElems++;
380,121✔
5188

5189
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
380,121✔
5190
      colDataSetNULL(pOutput, i);
142,512!
5191
      // handle selectivity
5192
      if (pCtx->subsidiaries.num > 0) {
142,512✔
5193
        code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
18✔
5194
        if (TSDB_CODE_SUCCESS != code) {
18!
5195
          return code;
×
5196
        }
5197
      }
5198
      continue;
142,512✔
5199
    }
5200

5201
    bool ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
237,609✔
5202

5203
    int64_t output = -1;
237,702✔
5204
    if (ret) {
237,702✔
5205
      output = ++pInfo->count;
148,747✔
5206
    } else {
5207
      pInfo->count = 0;
88,955✔
5208
    }
5209
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
237,702✔
5210
    if (TSDB_CODE_SUCCESS != code) {
237,612!
5211
      return code;
×
5212
    }
5213

5214
    // handle selectivity
5215
    if (pCtx->subsidiaries.num > 0) {
237,612✔
5216
      code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
216✔
5217
      if (TSDB_CODE_SUCCESS != code) {
216!
5218
        return code;
×
5219
      }
5220
    }
5221
  }
5222

5223
  pResInfo->numOfRes = numOfElems;
2,460✔
5224
  return TSDB_CODE_SUCCESS;
2,460✔
5225
}
5226

5227
int32_t stateDurationFunction(SqlFunctionCtx* pCtx) {
35,166✔
5228
  int32_t              code = TSDB_CODE_SUCCESS;
35,166✔
5229
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
35,166✔
5230
  SStateInfo*          pInfo = GET_ROWCELL_INTERBUF(pResInfo);
35,166✔
5231

5232
  SInputColumnInfoData* pInput = &pCtx->input;
35,166✔
5233
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
35,166✔
5234

5235
  SColumnInfoData* pInputCol = pInput->pData[0];
35,166✔
5236

5237
  int32_t          numOfElems = 0;
35,166✔
5238
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
35,166✔
5239

5240
  // TODO: process timeUnit for different db precisions
5241
  int32_t timeUnit = 1;
35,166✔
5242
  if (pCtx->numOfParams == 5) {  // TODO: param number incorrect
35,166✔
5243
    timeUnit = pCtx->param[3].param.i;
34,184✔
5244
  }
5245

5246
  int8_t op = getStateOpType(varDataVal(pCtx->param[1].param.pz));
35,166✔
5247
  if (STATE_OPER_INVALID == op) {
35,166!
5248
    return TSDB_CODE_INVALID_PARA;
×
5249
  }
5250

5251
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
35,031,244✔
5252
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
34,996,255!
5253
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5254
    } else {
5255
      pInfo->prevTs = tsList[i];
34,996,255✔
5256
    }
5257

5258
    pInfo->isPrevTsSet = true;
34,996,255✔
5259
    numOfElems++;
34,996,255✔
5260

5261
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
34,996,255✔
5262
      colDataSetNULL(pOutput, i);
244,792!
5263
      // handle selectivity
5264
      if (pCtx->subsidiaries.num > 0) {
244,792✔
5265
        code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
26✔
5266
        if (TSDB_CODE_SUCCESS != code) {
26!
5267
          return code;
×
5268
        }
5269
      }
5270
      continue;
244,792✔
5271
    }
5272

5273
    bool    ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
34,751,463✔
5274
    int64_t output = -1;
34,751,406✔
5275
    if (ret) {
34,751,406✔
5276
      if (pInfo->durationStart == 0) {
5,274,594✔
5277
        output = 0;
81,039✔
5278
        pInfo->durationStart = tsList[i];
81,039✔
5279
      } else {
5280
        output = (tsList[i] - pInfo->durationStart) / timeUnit;
5,193,555✔
5281
      }
5282
    } else {
5283
      pInfo->durationStart = 0;
29,476,812✔
5284
    }
5285
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
34,751,406✔
5286
    if (TSDB_CODE_SUCCESS != code) {
34,751,286!
5287
      return code;
×
5288
    }
5289

5290
    // handle selectivity
5291
    if (pCtx->subsidiaries.num > 0) {
34,751,286✔
5292
      code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
20,032,260✔
5293
      if (TSDB_CODE_SUCCESS != code) {
20,032,260!
5294
        return code;
×
5295
      }
5296
    }
5297
  }
5298

5299
  pResInfo->numOfRes = numOfElems;
34,989✔
5300
  return TSDB_CODE_SUCCESS;
34,989✔
5301
}
5302

5303
bool getCsumFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
15,645✔
5304
  pEnv->calcMemSize = sizeof(SSumRes);
15,645✔
5305
  return true;
15,645✔
5306
}
5307

5308
int32_t csumFunction(SqlFunctionCtx* pCtx) {
25,899✔
5309
  int32_t              code = TSDB_CODE_SUCCESS;
25,899✔
5310
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
25,899✔
5311
  SSumRes*             pSumRes = GET_ROWCELL_INTERBUF(pResInfo);
25,899✔
5312

5313
  SInputColumnInfoData* pInput = &pCtx->input;
25,899✔
5314
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
25,899✔
5315

5316
  SColumnInfoData* pInputCol = pInput->pData[0];
25,899✔
5317
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
25,899✔
5318

5319
  int32_t numOfElems = 0;
25,899✔
5320
  int32_t type = pInputCol->info.type;
25,899✔
5321
  int32_t startOffset = pCtx->offset;
25,899✔
5322
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
3,999,060✔
5323
    if (pSumRes->isPrevTsSet == true && tsList[i] == pSumRes->prevTs) {
3,972,986✔
5324
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
18✔
5325
    } else {
5326
      pSumRes->prevTs = tsList[i];
3,972,968✔
5327
    }
5328
    pSumRes->isPrevTsSet = true;
3,972,968✔
5329

5330
    int32_t pos = startOffset + numOfElems;
3,972,968✔
5331
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
3,972,968✔
5332
      // colDataSetNULL(pOutput, i);
5333
      continue;
287,316✔
5334
    }
5335

5336
    char* data = colDataGetData(pInputCol, i);
3,685,652!
5337
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
4,507,103✔
5338
      int64_t v;
5339
      GET_TYPED_DATA(v, int64_t, type, data);
821,258!
5340
      pSumRes->isum += v;
821,258✔
5341
      code = colDataSetVal(pOutput, pos, (char*)&pSumRes->isum, false);
821,258✔
5342
      if (TSDB_CODE_SUCCESS != code) {
821,451!
5343
        return code;
×
5344
      }
5345
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
2,865,074!
5346
      uint64_t v;
5347
      GET_TYPED_DATA(v, uint64_t, type, data);
680!
5348
      pSumRes->usum += v;
680✔
5349
      code = colDataSetVal(pOutput, pos, (char*)&pSumRes->usum, false);
680✔
5350
      if (TSDB_CODE_SUCCESS != code) {
680!
5351
        return code;
×
5352
      }
5353
    } else if (IS_FLOAT_TYPE(type)) {
2,863,714!
5354
      double v;
5355
      GET_TYPED_DATA(v, double, type, data);
2,864,464!
5356
      pSumRes->dsum += v;
2,864,464✔
5357
      // check for overflow
5358
      if (isinf(pSumRes->dsum) || isnan(pSumRes->dsum)) {
2,864,464!
5359
        colDataSetNULL(pOutput, pos);
8!
5360
      } else {
5361
        code = colDataSetVal(pOutput, pos, (char*)&pSumRes->dsum, false);
2,864,456✔
5362
        if (TSDB_CODE_SUCCESS != code) {
2,864,456!
5363
          return code;
×
5364
        }
5365
      }
5366
    }
5367

5368
    // handle selectivity
5369
    if (pCtx->subsidiaries.num > 0) {
3,685,845✔
5370
      code = appendSelectivityValue(pCtx, i, pos);
2,009,474✔
5371
      if (TSDB_CODE_SUCCESS != code) {
2,009,474!
5372
        return code;
×
5373
      }
5374
    }
5375

5376
    numOfElems++;
3,685,845✔
5377
  }
5378

5379
  pResInfo->numOfRes = numOfElems;
26,074✔
5380
  return TSDB_CODE_SUCCESS;
26,074✔
5381
}
5382

5383
bool getMavgFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
13,627✔
5384
  pEnv->calcMemSize = sizeof(SMavgInfo) + MAVG_MAX_POINTS_NUM * sizeof(double);
13,627✔
5385
  return true;
13,627✔
5386
}
5387

5388
int32_t mavgFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
251,258✔
5389
  if (pResultInfo->initialized) {
251,258✔
5390
    return TSDB_CODE_SUCCESS;
236,941✔
5391
  }
5392
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
14,317!
5393
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5394
  }
5395

5396
  SMavgInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
14,318✔
5397
  pInfo->pos = 0;
14,318✔
5398
  pInfo->sum = 0;
14,318✔
5399
  pInfo->prevTs = -1;
14,318✔
5400
  pInfo->isPrevTsSet = false;
14,318✔
5401
  pInfo->numOfPoints = pCtx->param[1].param.i;
14,318✔
5402
  if (pInfo->numOfPoints < 1 || pInfo->numOfPoints > MAVG_MAX_POINTS_NUM) {
14,318!
5403
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
5404
  }
5405
  pInfo->pointsMeet = false;
14,319✔
5406

5407
  return TSDB_CODE_SUCCESS;
14,319✔
5408
}
5409

5410
int32_t mavgFunction(SqlFunctionCtx* pCtx) {
237,630✔
5411
  int32_t              code = TSDB_CODE_SUCCESS;
237,630✔
5412
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
237,630✔
5413
  SMavgInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
237,630✔
5414

5415
  SInputColumnInfoData* pInput = &pCtx->input;
237,630✔
5416
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
237,630✔
5417

5418
  SColumnInfoData* pInputCol = pInput->pData[0];
237,630✔
5419
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
237,630✔
5420
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
237,630✔
5421

5422
  int32_t numOfElems = 0;
237,630✔
5423
  int32_t type = pInputCol->info.type;
237,630✔
5424
  int32_t startOffset = pCtx->offset;
237,630✔
5425
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
57,464,151✔
5426
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
57,226,508!
5427
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5428
    } else {
5429
      pInfo->prevTs = tsList[i];
57,226,508✔
5430
    }
5431
    pInfo->isPrevTsSet = true;
57,226,508✔
5432

5433
    int32_t pos = startOffset + numOfElems;
57,226,508✔
5434
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
57,226,508✔
5435
      // colDataSetNULL(pOutput, i);
5436
      continue;
370,057✔
5437
    }
5438

5439
    char*  data = colDataGetData(pInputCol, i);
56,856,451!
5440
    double v;
5441
    GET_TYPED_DATA(v, double, type, data);
56,856,451!
5442

5443
    if (!pInfo->pointsMeet && (pInfo->pos < pInfo->numOfPoints - 1)) {
56,856,451✔
5444
      pInfo->points[pInfo->pos] = v;
4,568,000✔
5445
      pInfo->sum += v;
4,568,000✔
5446
    } else {
5447
      if (!pInfo->pointsMeet && (pInfo->pos == pInfo->numOfPoints - 1)) {
52,288,451!
5448
        pInfo->sum += v;
11,065✔
5449
        pInfo->pointsMeet = true;
11,065✔
5450
      } else {
5451
        pInfo->sum = pInfo->sum + v - pInfo->points[pInfo->pos];
52,277,386✔
5452
      }
5453

5454
      pInfo->points[pInfo->pos] = v;
52,288,451✔
5455
      double result = pInfo->sum / pInfo->numOfPoints;
52,288,451✔
5456
      // check for overflow
5457
      if (isinf(result) || isnan(result)) {
52,288,451!
5458
        colDataSetNULL(pOutput, pos);
×
5459
      } else {
5460
        code = colDataSetVal(pOutput, pos, (char*)&result, false);
52,288,612✔
5461
        if (TSDB_CODE_SUCCESS != code) {
52,288,625!
5462
          return code;
×
5463
        }
5464
      }
5465

5466
      // handle selectivity
5467
      if (pCtx->subsidiaries.num > 0) {
52,288,464✔
5468
        code = appendSelectivityValue(pCtx, i, pos);
33,048,301✔
5469
        if (TSDB_CODE_SUCCESS != code) {
33,048,301!
5470
          return code;
×
5471
        }
5472
      }
5473

5474
      numOfElems++;
52,288,464✔
5475
    }
5476

5477
    pInfo->pos++;
56,856,464✔
5478
    if (pInfo->pos == pInfo->numOfPoints) {
56,856,464✔
5479
      pInfo->pos = 0;
139,457✔
5480
    }
5481
  }
5482

5483
  pResInfo->numOfRes = numOfElems;
237,643✔
5484
  return TSDB_CODE_SUCCESS;
237,643✔
5485
}
5486

5487
static SSampleInfo* getSampleOutputInfo(SqlFunctionCtx* pCtx) {
13,476,993✔
5488
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
13,476,993✔
5489
  SSampleInfo*         pInfo = GET_ROWCELL_INTERBUF(pResInfo);
13,476,993✔
5490

5491
  pInfo->data = (char*)pInfo + sizeof(SSampleInfo);
13,476,993✔
5492
  pInfo->tuplePos = (STuplePos*)((char*)pInfo + sizeof(SSampleInfo) + pInfo->samples * pInfo->colBytes);
13,476,993✔
5493

5494
  return pInfo;
13,476,993✔
5495
}
5496

5497
bool getSampleFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
29,922✔
5498
  SColumnNode* pCol = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
29,922✔
5499
  SValueNode*  pVal = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
29,927✔
5500
  int32_t      numOfSamples = pVal->datum.i;
29,929✔
5501
  pEnv->calcMemSize = sizeof(SSampleInfo) + numOfSamples * (pCol->node.resType.bytes + sizeof(STuplePos));
29,929✔
5502
  return true;
29,929✔
5503
}
5504

5505
int32_t sampleFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
6,780,673✔
5506
  if (pResultInfo->initialized) {
6,780,673!
5507
    return TSDB_CODE_SUCCESS;
×
5508
  }
5509
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
6,780,673!
5510
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5511
  }
5512

5513
  taosSeedRand(taosSafeRand());
6,780,677✔
5514

5515
  SSampleInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
6,780,677✔
5516
  pInfo->samples = pCtx->param[1].param.i;
6,780,677✔
5517
  pInfo->totalPoints = 0;
6,780,677✔
5518
  pInfo->numSampled = 0;
6,780,677✔
5519
  pInfo->colType = pCtx->resDataInfo.type;
6,780,677✔
5520
  pInfo->colBytes = pCtx->resDataInfo.bytes;
6,780,677✔
5521
  pInfo->nullTuplePos.pageId = -1;
6,780,677✔
5522
  pInfo->nullTupleSaved = false;
6,780,677✔
5523
  pInfo->data = (char*)pInfo + sizeof(SSampleInfo);
6,780,677✔
5524
  pInfo->tuplePos = (STuplePos*)((char*)pInfo + sizeof(SSampleInfo) + pInfo->samples * pInfo->colBytes);
6,780,677✔
5525

5526
  return TSDB_CODE_SUCCESS;
6,780,677✔
5527
}
5528

5529
static void sampleAssignResult(SSampleInfo* pInfo, char* data, int32_t index) {
14,050,286✔
5530
  assignVal(pInfo->data + index * pInfo->colBytes, data, pInfo->colBytes, pInfo->colType);
14,050,286✔
5531
}
14,050,448✔
5532

5533
static int32_t doReservoirSample(SqlFunctionCtx* pCtx, SSampleInfo* pInfo, char* data, int32_t index) {
14,695,568✔
5534
  pInfo->totalPoints++;
14,695,568✔
5535
  if (pInfo->numSampled < pInfo->samples) {
14,695,568✔
5536
    sampleAssignResult(pInfo, data, pInfo->numSampled);
13,331,592✔
5537
    if (pCtx->subsidiaries.num > 0) {
13,331,562✔
5538
      int32_t code = saveTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[pInfo->numSampled]);
782,030✔
5539
      if (code != TSDB_CODE_SUCCESS) {
781,888!
5540
        return code;
×
5541
      }
5542
    }
5543
    pInfo->numSampled++;
13,331,420✔
5544
  } else {
5545
    int32_t j = taosRand() % (pInfo->totalPoints);
1,363,976✔
5546
    if (j < pInfo->samples) {
1,364,092✔
5547
      sampleAssignResult(pInfo, data, j);
718,870✔
5548
      if (pCtx->subsidiaries.num > 0) {
718,870✔
5549
        int32_t code = updateTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[j]);
420,901✔
5550
        if (code != TSDB_CODE_SUCCESS) {
420,812!
5551
          return code;
×
5552
        }
5553
      }
5554
    }
5555
  }
5556

5557
  return TSDB_CODE_SUCCESS;
14,695,423✔
5558
}
5559

5560
int32_t sampleFunction(SqlFunctionCtx* pCtx) {
6,782,166✔
5561
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
6,782,166✔
5562
  SSampleInfo*         pInfo = getSampleOutputInfo(pCtx);
6,782,166✔
5563

5564
  SInputColumnInfoData* pInput = &pCtx->input;
6,782,166✔
5565

5566
  SColumnInfoData* pInputCol = pInput->pData[0];
6,782,166✔
5567
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
21,863,712✔
5568
    if (colDataIsNull_s(pInputCol, i)) {
30,160,724✔
5569
      continue;
386,253✔
5570
    }
5571

5572
    char*   data = colDataGetData(pInputCol, i);
14,694,109!
5573
    int32_t code = doReservoirSample(pCtx, pInfo, data, i);
14,694,109✔
5574
    if (code != TSDB_CODE_SUCCESS) {
14,695,293!
5575
      return code;
×
5576
    }
5577
  }
5578

5579
  if (pInfo->numSampled == 0 && pCtx->subsidiaries.num > 0 && !pInfo->nullTupleSaved) {
6,783,350✔
5580
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pInfo->nullTuplePos);
12✔
5581
    if (code != TSDB_CODE_SUCCESS) {
12!
5582
      return code;
×
5583
    }
5584
    pInfo->nullTupleSaved = true;
12✔
5585
  }
5586

5587
  SET_VAL(pResInfo, pInfo->numSampled, pInfo->numSampled);
6,783,350✔
5588
  return TSDB_CODE_SUCCESS;
6,783,350✔
5589
}
5590

5591
int32_t sampleFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
6,694,831✔
5592
  int32_t              code = TSDB_CODE_SUCCESS;
6,694,831✔
5593
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
6,694,831✔
5594

5595
  SSampleInfo* pInfo = getSampleOutputInfo(pCtx);
6,694,831✔
5596
  pEntryInfo->complete = true;
6,694,832✔
5597

5598
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
6,694,832✔
5599
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
6,694,832✔
5600
  if (NULL == pCol) {
6,694,830!
5601
    return TSDB_CODE_OUT_OF_RANGE;
×
5602
  }
5603

5604
  int32_t currentRow = pBlock->info.rows;
6,694,830✔
5605
  if (pInfo->numSampled == 0) {
6,694,830✔
5606
    colDataSetNULL(pCol, currentRow);
2,271✔
5607
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
2,271✔
5608
    return code;
2,271✔
5609
  }
5610
  for (int32_t i = 0; i < pInfo->numSampled; ++i) {
19,851,136✔
5611
    code = colDataSetVal(pCol, currentRow + i, pInfo->data + i * pInfo->colBytes, false);
13,158,959✔
5612
    if (TSDB_CODE_SUCCESS != code) {
13,158,591!
5613
      return code;
×
5614
    }
5615
    code = setSelectivityValue(pCtx, pBlock, &pInfo->tuplePos[i], currentRow + i);
13,158,591✔
5616
    if (TSDB_CODE_SUCCESS != code) {
13,158,577!
5617
      return code;
×
5618
    }
5619
  }
5620

5621
  return code;
6,692,177✔
5622
}
5623

5624
bool getTailFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
×
5625
#if 0
5626
  SColumnNode* pCol = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
5627
  SValueNode*  pVal = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
5628
  int32_t      numOfPoints = pVal->datum.i;
5629
  pEnv->calcMemSize = sizeof(STailInfo) + numOfPoints * (POINTER_BYTES + sizeof(STailItem) + pCol->node.resType.bytes);
5630
#endif
5631
  return true;
×
5632
}
5633

5634
int32_t tailFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
×
5635
#if 0
5636
  if (!functionSetup(pCtx, pResultInfo)) {
5637
    return false;
5638
  }
5639

5640
  STailInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
5641
  pInfo->numAdded = 0;
5642
  pInfo->numOfPoints = pCtx->param[1].param.i;
5643
  if (pCtx->numOfParams == 4) {
5644
    pInfo->offset = pCtx->param[2].param.i;
5645
  } else {
5646
    pInfo->offset = 0;
5647
  }
5648
  pInfo->colType = pCtx->resDataInfo.type;
5649
  pInfo->colBytes = pCtx->resDataInfo.bytes;
5650
  if ((pInfo->numOfPoints < 1 || pInfo->numOfPoints > TAIL_MAX_POINTS_NUM) ||
5651
      (pInfo->numOfPoints < 0 || pInfo->numOfPoints > TAIL_MAX_OFFSET)) {
5652
    return false;
5653
  }
5654

5655
  pInfo->pItems = (STailItem**)((char*)pInfo + sizeof(STailInfo));
5656
  char* pItem = (char*)pInfo->pItems + pInfo->numOfPoints * POINTER_BYTES;
5657

5658
  size_t unitSize = sizeof(STailItem) + pInfo->colBytes;
5659
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
5660
    pInfo->pItems[i] = (STailItem*)(pItem + i * unitSize);
5661
    pInfo->pItems[i]->isNull = false;
5662
  }
5663
#endif
5664

5665
  return TSDB_CODE_SUCCESS;
×
5666
}
5667

5668
static void tailAssignResult(STailItem* pItem, char* data, int32_t colBytes, TSKEY ts, bool isNull) {
×
5669
#if 0
5670
  pItem->timestamp = ts;
5671
  if (isNull) {
5672
    pItem->isNull = true;
5673
  } else {
5674
    pItem->isNull = false;
5675
    memcpy(pItem->data, data, colBytes);
5676
  }
5677
#endif
5678
}
×
5679

5680
#if 0
5681
static int32_t tailCompFn(const void* p1, const void* p2, const void* param) {
5682
  STailItem* d1 = *(STailItem**)p1;
5683
  STailItem* d2 = *(STailItem**)p2;
5684
  return compareInt64Val(&d1->timestamp, &d2->timestamp);
5685
}
5686

5687
static void doTailAdd(STailInfo* pInfo, char* data, TSKEY ts, bool isNull) {
5688
  STailItem** pList = pInfo->pItems;
5689
  if (pInfo->numAdded < pInfo->numOfPoints) {
5690
    tailAssignResult(pList[pInfo->numAdded], data, pInfo->colBytes, ts, isNull);
5691
    taosheapsort((void*)pList, sizeof(STailItem**), pInfo->numAdded + 1, NULL, tailCompFn, 0);
5692
    pInfo->numAdded++;
5693
  } else if (pList[0]->timestamp < ts) {
5694
    tailAssignResult(pList[0], data, pInfo->colBytes, ts, isNull);
5695
    taosheapadjust((void*)pList, sizeof(STailItem**), 0, pInfo->numOfPoints - 1, NULL, tailCompFn, NULL, 0);
5696
  }
5697
}
5698
#endif
5699

5700
int32_t tailFunction(SqlFunctionCtx* pCtx) {
×
5701
#if 0
5702
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5703
  STailInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5704

5705
  SInputColumnInfoData* pInput = &pCtx->input;
5706
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
5707

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

5711
  int32_t startOffset = pCtx->offset;
5712
  if (pInfo->offset >= pInput->numOfRows) {
5713
    return 0;
5714
  } else {
5715
    pInfo->numOfPoints = TMIN(pInfo->numOfPoints, pInput->numOfRows - pInfo->offset);
5716
  }
5717
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex - pInfo->offset; i += 1) {
5718
    char* data = colDataGetData(pInputCol, i);
5719
    doTailAdd(pInfo, data, tsList[i], colDataIsNull_s(pInputCol, i));
5720
  }
5721

5722
  taosqsort(pInfo->pItems, pInfo->numOfPoints, POINTER_BYTES, NULL, tailCompFn);
5723

5724
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
5725
    int32_t    pos = startOffset + i;
5726
    STailItem* pItem = pInfo->pItems[i];
5727
    if (pItem->isNull) {
5728
      colDataSetNULL(pOutput, pos);
5729
    } else {
5730
      colDataSetVal(pOutput, pos, pItem->data, false);
5731
    }
5732
  }
5733

5734
  return pInfo->numOfPoints;
5735
#endif
5736
  return 0;
×
5737
}
5738

5739
int32_t tailFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
×
5740
#if 0
5741
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
5742
  STailInfo*           pInfo = GET_ROWCELL_INTERBUF(pEntryInfo);
5743
  pEntryInfo->complete = true;
5744

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

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

5750
  // todo assign the tag value and the corresponding row data
5751
  int32_t currentRow = pBlock->info.rows;
5752
  for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
5753
    STailItem* pItem = pInfo->pItems[i];
5754
    colDataSetVal(pCol, currentRow, pItem->data, false);
5755
    currentRow += 1;
5756
  }
5757

5758
  return pEntryInfo->numOfRes;
5759
#endif
5760
  return 0;
×
5761
}
5762

5763
bool getUniqueFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
×
5764
#if 0
5765
  pEnv->calcMemSize = sizeof(SUniqueInfo) + UNIQUE_MAX_RESULT_SIZE;
5766
#endif
5767
  return true;
×
5768
}
5769

5770
int32_t uniqueFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
×
5771
#if 0
5772
  if (!functionSetup(pCtx, pResInfo)) {
5773
    return false;
5774
  }
5775

5776
  SUniqueInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5777
  pInfo->numOfPoints = 0;
5778
  pInfo->colType = pCtx->resDataInfo.type;
5779
  pInfo->colBytes = pCtx->resDataInfo.bytes;
5780
  if (pInfo->pHash != NULL) {
5781
    taosHashClear(pInfo->pHash);
5782
  } else {
5783
    pInfo->pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
5784
  }
5785
#endif
5786
  return TSDB_CODE_SUCCESS;
×
5787
}
5788

5789
#if 0
5790
static void doUniqueAdd(SUniqueInfo* pInfo, char* data, TSKEY ts, bool isNull) {
5791
  // handle null elements
5792
  if (isNull == true) {
5793
    int32_t      size = sizeof(SUniqueItem) + pInfo->colBytes;
5794
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + pInfo->numOfPoints * size);
5795
    if (pInfo->hasNull == false && pItem->isNull == false) {
5796
      pItem->timestamp = ts;
5797
      pItem->isNull = true;
5798
      pInfo->numOfPoints++;
5799
      pInfo->hasNull = true;
5800
    } else if (pItem->timestamp > ts && pItem->isNull == true) {
5801
      pItem->timestamp = ts;
5802
    }
5803
    return;
5804
  }
5805

5806
  int32_t      hashKeyBytes = IS_VAR_DATA_TYPE(pInfo->colType) ? varDataTLen(data) : pInfo->colBytes;
5807
  SUniqueItem* pHashItem = taosHashGet(pInfo->pHash, data, hashKeyBytes);
5808
  if (pHashItem == NULL) {
5809
    int32_t      size = sizeof(SUniqueItem) + pInfo->colBytes;
5810
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + pInfo->numOfPoints * size);
5811
    pItem->timestamp = ts;
5812
    memcpy(pItem->data, data, pInfo->colBytes);
5813

5814
    taosHashPut(pInfo->pHash, data, hashKeyBytes, (char*)pItem, sizeof(SUniqueItem*));
5815
    pInfo->numOfPoints++;
5816
  } else if (pHashItem->timestamp > ts) {
5817
    pHashItem->timestamp = ts;
5818
  }
5819
}
5820
#endif
5821

5822
int32_t uniqueFunction(SqlFunctionCtx* pCtx) {
×
5823
#if 0
5824
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5825
  SUniqueInfo*         pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5826

5827
  SInputColumnInfoData* pInput = &pCtx->input;
5828
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
5829

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

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

5839
    if (sizeof(SUniqueInfo) + pInfo->numOfPoints * (sizeof(SUniqueItem) + pInfo->colBytes) >= UNIQUE_MAX_RESULT_SIZE) {
5840
      taosHashCleanup(pInfo->pHash);
5841
      return 0;
5842
    }
5843
  }
5844

5845
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
5846
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + i * (sizeof(SUniqueItem) + pInfo->colBytes));
5847
    if (pItem->isNull == true) {
5848
      colDataSetNULL(pOutput, i);
5849
    } else {
5850
      colDataSetVal(pOutput, i, pItem->data, false);
5851
    }
5852
    if (pTsOutput != NULL) {
5853
      colDataSetInt64(pTsOutput, i, &pItem->timestamp);
5854
    }
5855
  }
5856

5857
  return pInfo->numOfPoints;
5858
#endif
5859
  return 0;
×
5860
}
5861

5862
bool getModeFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
24,856✔
5863
  pEnv->calcMemSize = sizeof(SModeInfo);
24,856✔
5864
  return true;
24,856✔
5865
}
5866

5867
int32_t modeFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
25,680✔
5868
  if (pResInfo->initialized) {
25,680!
5869
    return TSDB_CODE_SUCCESS;
×
5870
  }
5871
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
25,680!
5872
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5873
  }
5874

5875
  SModeInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
25,680✔
5876
  pInfo->colType = pCtx->resDataInfo.type;
25,680✔
5877
  pInfo->colBytes = pCtx->resDataInfo.bytes;
25,680✔
5878
  if (pInfo->pHash != NULL) {
25,680!
5879
    taosHashClear(pInfo->pHash);
×
5880
  } else {
5881
    pInfo->pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
25,680✔
5882
    if (NULL == pInfo->pHash) {
25,679!
5883
      return terrno;
×
5884
    }
5885
  }
5886
  pInfo->nullTupleSaved = false;
25,679✔
5887
  pInfo->nullTuplePos.pageId = -1;
25,679✔
5888

5889
  pInfo->buf = taosMemoryMalloc(pInfo->colBytes);
25,679!
5890
  if (NULL == pInfo->buf) {
25,680!
5891
    taosHashCleanup(pInfo->pHash);
×
5892
    pInfo->pHash = NULL;
×
5893
    return terrno;
×
5894
  }
5895
  pCtx->needCleanup = true;
25,680✔
5896
  return TSDB_CODE_SUCCESS;
25,680✔
5897
}
5898

5899
static void modeFunctionCleanup(SModeInfo* pInfo) {
25,680✔
5900
  taosHashCleanup(pInfo->pHash);
25,680✔
5901
  pInfo->pHash = NULL;
25,680✔
5902
  taosMemoryFreeClear(pInfo->buf);
25,680!
5903
}
25,680✔
5904

5905
void modeFunctionCleanupExt(SqlFunctionCtx* pCtx) {
×
5906
  if (pCtx == NULL || GET_RES_INFO(pCtx) == NULL || GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)) == NULL) {
×
5907
    return;
×
5908
  }
5909
  modeFunctionCleanup(GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)));
×
5910
}
5911

5912
static int32_t saveModeTupleData(SqlFunctionCtx* pCtx, char* data, SModeInfo* pInfo, STuplePos* pPos) {
103,131,146✔
5913
  if (IS_VAR_DATA_TYPE(pInfo->colType)) {
103,131,146!
5914
    if (pInfo->colType == TSDB_DATA_TYPE_JSON) {
78,744,863!
5915
      (void)memcpy(pInfo->buf, data, getJsonValueLen(data));
×
5916
    } else {
5917
      (void)memcpy(pInfo->buf, data, varDataTLen(data));
78,744,863✔
5918
    }
5919
  } else {
5920
    (void)memcpy(pInfo->buf, data, pInfo->colBytes);
24,386,283✔
5921
  }
5922

5923
  return doSaveTupleData(&pCtx->saveHandle, pInfo->buf, pInfo->colBytes, NULL, pPos, pCtx->pStore);
103,131,146✔
5924
}
5925

5926
static int32_t doModeAdd(SModeInfo* pInfo, int32_t rowIndex, SqlFunctionCtx* pCtx, char* data) {
123,482,727✔
5927
  int32_t code = TSDB_CODE_SUCCESS;
123,482,727✔
5928
  int32_t hashKeyBytes;
5929
  if (IS_VAR_DATA_TYPE(pInfo->colType)) {
123,482,727!
5930
    if (pInfo->colType == TSDB_DATA_TYPE_JSON) {
78,744,965!
5931
      hashKeyBytes = getJsonValueLen(data);
×
5932
    } else {
5933
      hashKeyBytes = varDataTLen(data);
78,744,965✔
5934
    }
5935
  } else {
5936
    hashKeyBytes = pInfo->colBytes;
44,737,762✔
5937
  }
5938

5939
  SModeItem* pHashItem = (SModeItem*)taosHashGet(pInfo->pHash, data, hashKeyBytes);
123,482,720✔
5940
  if (pHashItem == NULL) {
123,482,535✔
5941
    int32_t   size = sizeof(SModeItem);
103,131,187✔
5942
    SModeItem item = {0};
103,131,187✔
5943

5944
    item.count += 1;
103,131,187✔
5945
    code = saveModeTupleData(pCtx, data, pInfo, &item.dataPos);
103,131,187✔
5946
    if (code != TSDB_CODE_SUCCESS) {
103,129,872!
5947
      return code;
×
5948
    }
5949

5950
    if (pCtx->subsidiaries.num > 0) {
103,129,872✔
5951
      code = saveTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &item.tuplePos);
61,249,356✔
5952
      if (code != TSDB_CODE_SUCCESS) {
61,249,356!
5953
        return code;
×
5954
      }
5955
    }
5956

5957
    code = taosHashPut(pInfo->pHash, data, hashKeyBytes, &item, sizeof(SModeItem));
103,129,872✔
5958
    if (code != TSDB_CODE_SUCCESS) {
103,131,861!
5959
      return code;
×
5960
    }
5961
  } else {
5962
    pHashItem->count += 1;
20,351,348✔
5963
    if (pCtx->subsidiaries.num > 0) {
20,351,348✔
5964
      code = updateTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &pHashItem->tuplePos);
11,074,830✔
5965
      if (code != TSDB_CODE_SUCCESS) {
11,074,830!
5966
        return code;
×
5967
      }
5968
    }
5969
  }
5970

5971
  return code;
123,483,209✔
5972
}
5973

5974
int32_t modeFunction(SqlFunctionCtx* pCtx) {
2,181,931✔
5975
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,181,931✔
5976
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,181,931✔
5977

5978
  SInputColumnInfoData* pInput = &pCtx->input;
2,181,931✔
5979

5980
  SColumnInfoData* pInputCol = pInput->pData[0];
2,181,931✔
5981
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
2,181,931✔
5982

5983
  int32_t numOfElems = 0;
2,181,931✔
5984
  int32_t startOffset = pCtx->offset;
2,181,931✔
5985
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
126,110,781✔
5986
    if (colDataIsNull_s(pInputCol, i)) {
247,857,948✔
5987
      continue;
446,322✔
5988
    }
5989
    numOfElems++;
123,482,652✔
5990

5991
    char*   data = colDataGetData(pInputCol, i);
123,482,652!
5992
    int32_t code = doModeAdd(pInfo, i, pCtx, data);
123,482,652✔
5993
    if (code != TSDB_CODE_SUCCESS) {
123,483,198✔
5994
      modeFunctionCleanup(pInfo);
670✔
5995
      return code;
×
5996
    }
5997
  }
5998

5999
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pInfo->nullTupleSaved) {
2,181,807!
6000
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pInfo->nullTuplePos);
30✔
6001
    if (code != TSDB_CODE_SUCCESS) {
30!
6002
      modeFunctionCleanup(pInfo);
×
6003
      return code;
×
6004
    }
6005
    pInfo->nullTupleSaved = true;
30✔
6006
  }
6007

6008
  SET_VAL(pResInfo, numOfElems, 1);
2,181,807✔
6009

6010
  return TSDB_CODE_SUCCESS;
2,181,807✔
6011
}
6012

6013
int32_t modeFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
25,680✔
6014
  int32_t              code = TSDB_CODE_SUCCESS;
25,680✔
6015
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
25,680✔
6016
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
25,680✔
6017
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
25,680✔
6018
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
25,680✔
6019
  int32_t              currentRow = pBlock->info.rows;
25,680✔
6020
  if (NULL == pCol) {
25,680!
6021
    modeFunctionCleanup(pInfo);
×
6022
    return TSDB_CODE_OUT_OF_RANGE;
×
6023
  }
6024

6025
  STuplePos resDataPos, resTuplePos;
6026
  int32_t   maxCount = 0;
25,680✔
6027

6028
  void* pIter = taosHashIterate(pInfo->pHash, NULL);
25,680✔
6029
  while (pIter != NULL) {
103,157,892✔
6030
    SModeItem* pItem = (SModeItem*)pIter;
103,132,212✔
6031
    if (pItem->count >= maxCount) {
103,132,212✔
6032
      maxCount = pItem->count;
81,138,266✔
6033
      resDataPos = pItem->dataPos;
81,138,266✔
6034
      resTuplePos = pItem->tuplePos;
81,138,266✔
6035
    }
6036

6037
    pIter = taosHashIterate(pInfo->pHash, pIter);
103,132,212✔
6038
  }
6039

6040
  if (maxCount != 0) {
25,680✔
6041
    char* pData = NULL;
23,251✔
6042
    code = loadTupleData(pCtx, &resDataPos, &pData);
23,251✔
6043
    if (pData == NULL || TSDB_CODE_SUCCESS != code) {
23,251!
6044
      code = terrno = TSDB_CODE_NOT_FOUND;
×
6045
      qError("Load tuple data failed since %s, groupId:%" PRIu64 ", ts:%" PRId64, terrstr(),
×
6046
             resDataPos.streamTupleKey.groupId, resDataPos.streamTupleKey.ts);
6047
      modeFunctionCleanup(pInfo);
×
6048
      return code;
×
6049
    }
6050

6051
    code = colDataSetVal(pCol, currentRow, pData, false);
23,251✔
6052
    if (TSDB_CODE_SUCCESS != code) {
23,251!
6053
      modeFunctionCleanup(pInfo);
×
6054
      return code;
×
6055
    }
6056
    code = setSelectivityValue(pCtx, pBlock, &resTuplePos, currentRow);
23,251✔
6057
  } else {
6058
    colDataSetNULL(pCol, currentRow);
2,429✔
6059
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
2,429✔
6060
  }
6061

6062
  modeFunctionCleanup(pInfo);
25,680✔
6063

6064
  return code;
25,680✔
6065
}
6066

6067
bool getTwaFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
78,044✔
6068
  pEnv->calcMemSize = sizeof(STwaInfo);
78,044✔
6069
  return true;
78,044✔
6070
}
6071

6072
int32_t twaFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
7,644,005✔
6073
  if (pResultInfo->initialized) {
7,644,005!
6074
    return TSDB_CODE_SUCCESS;
×
6075
  }
6076
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
7,644,005!
6077
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6078
  }
6079

6080
  STwaInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
7,644,006✔
6081
  pInfo->numOfElems = 0;
7,644,006✔
6082
  pInfo->p.key = INT64_MIN;
7,644,006✔
6083
  pInfo->win = TSWINDOW_INITIALIZER;
7,644,006✔
6084
  return TSDB_CODE_SUCCESS;
7,644,006✔
6085
}
6086

6087
static double twa_get_area(SPoint1 s, SPoint1 e) {
16,519,107✔
6088
  if (e.key == INT64_MAX || s.key == INT64_MIN) {
16,519,107!
6089
    return 0;
×
6090
  }
6091

6092
  if ((s.val >= 0 && e.val >= 0) || (s.val <= 0 && e.val <= 0)) {
16,519,410✔
6093
    return (s.val + e.val) * (e.key - s.key) / 2;
11,753,660✔
6094
  }
6095

6096
  double x = (s.key * e.val - e.key * s.val) / (e.val - s.val);
4,765,750✔
6097
  double val = (s.val * (x - s.key) + e.val * (e.key - x)) / 2;
4,765,750✔
6098
  return val;
4,765,750✔
6099
}
6100

6101
int32_t twaFunction(SqlFunctionCtx* pCtx) {
7,648,293✔
6102
  int32_t               code = TSDB_CODE_SUCCESS;
7,648,293✔
6103
  SInputColumnInfoData* pInput = &pCtx->input;
7,648,293✔
6104
  SColumnInfoData*      pInputCol = pInput->pData[0];
7,648,293✔
6105

6106
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
7,648,293✔
6107
  STwaInfo*            pInfo = GET_ROWCELL_INTERBUF(pResInfo);
7,648,293✔
6108
  SPoint1*             last = &pInfo->p;
7,648,293✔
6109

6110
  if (IS_NULL_TYPE(pInputCol->info.type)) {
7,648,293!
6111
    pInfo->numOfElems = 0;
×
6112
    goto _twa_over;
×
6113
  }
6114

6115
  funcInputUpdate(pCtx);
7,648,293✔
6116
  SFuncInputRow row = {0};
7,648,352✔
6117
  bool          result = false;
7,648,352✔
6118
  if (pCtx->start.key != INT64_MIN && last->key == INT64_MIN) {
7,648,352✔
6119
    while (1) {
6120
      code = funcInputGetNextRow(pCtx, &row, &result);
4,182,985✔
6121
      if (TSDB_CODE_SUCCESS != code) {
4,183,000!
6122
        return code;
×
6123
      }
6124
      if (!result) {
4,183,000✔
6125
        break;
2✔
6126
      }
6127
      if (row.isDataNull) {
4,182,998✔
6128
        continue;
2✔
6129
      }
6130

6131
      last->key = row.ts;
4,182,996✔
6132

6133
      GET_TYPED_DATA(last->val, double, pInputCol->info.type, row.pData);
4,182,996!
6134

6135
      pInfo->dOutput += twa_get_area(pCtx->start, *last);
4,182,996✔
6136
      pInfo->win.skey = pCtx->start.key;
4,182,976✔
6137
      pInfo->numOfElems++;
4,182,976✔
6138
      break;
4,182,976✔
6139
    }
6140
  } else if (pInfo->p.key == INT64_MIN) {
3,465,369✔
6141
    while (1) {
6142
      code = funcInputGetNextRow(pCtx, &row, &result);
3,592,835✔
6143
      if (TSDB_CODE_SUCCESS != code) {
3,592,750!
6144
        return code;
×
6145
      }
6146
      if (!result) {
3,592,750✔
6147
        break;
15,273✔
6148
      }
6149
      if (row.isDataNull) {
3,577,477✔
6150
        continue;
131,264✔
6151
      }
6152

6153
      last->key = row.ts;
3,446,213✔
6154

6155
      GET_TYPED_DATA(last->val, double, pInputCol->info.type, row.pData);
3,446,213!
6156

6157
      pInfo->win.skey = last->key;
3,446,213✔
6158
      pInfo->numOfElems++;
3,446,213✔
6159
      break;
3,446,213✔
6160
    }
6161
  }
6162

6163
  SPoint1 st = {0};
7,648,262✔
6164

6165
  // calculate the value of
6166
  while (1) {
6167
    code = funcInputGetNextRow(pCtx, &row, &result);
15,565,456✔
6168
    if (TSDB_CODE_SUCCESS != code) {
15,564,807!
6169
      return code;
×
6170
    }
6171
    if (!result) {
15,564,807✔
6172
      break;
7,648,280✔
6173
    }
6174
    if (row.isDataNull) {
7,916,527✔
6175
      continue;
630✔
6176
    }
6177
    pInfo->numOfElems++;
7,915,897✔
6178
    switch (pInputCol->info.type) {
7,915,897!
6179
      case TSDB_DATA_TYPE_TINYINT: {
2,933,804✔
6180
        INIT_INTP_POINT(st, row.ts, *(int8_t*)row.pData);
2,933,804✔
6181
        break;
2,933,804✔
6182
      }
6183
      case TSDB_DATA_TYPE_SMALLINT: {
61,313✔
6184
        INIT_INTP_POINT(st, row.ts, *(int16_t*)row.pData);
61,313✔
6185
        break;
61,313✔
6186
      }
6187
      case TSDB_DATA_TYPE_INT: {
92,343✔
6188
        INIT_INTP_POINT(st, row.ts, *(int32_t*)row.pData);
92,343✔
6189
        break;
92,343✔
6190
      }
6191
      case TSDB_DATA_TYPE_BIGINT: {
349,148✔
6192
        INIT_INTP_POINT(st, row.ts, *(int64_t*)row.pData);
349,148✔
6193
        break;
349,148✔
6194
      }
6195
      case TSDB_DATA_TYPE_FLOAT: {
326,938✔
6196
        INIT_INTP_POINT(st, row.ts, *(float_t*)row.pData);
326,938✔
6197
        break;
326,938✔
6198
      }
6199
      case TSDB_DATA_TYPE_DOUBLE: {
3,965,240✔
6200
        INIT_INTP_POINT(st, row.ts, *(double*)row.pData);
3,965,240✔
6201
        break;
3,965,240✔
6202
      }
6203
      case TSDB_DATA_TYPE_UTINYINT: {
48,955✔
6204
        INIT_INTP_POINT(st, row.ts, *(uint8_t*)row.pData);
48,955✔
6205
        break;
48,955✔
6206
      }
6207
      case TSDB_DATA_TYPE_USMALLINT: {
48,534✔
6208
        INIT_INTP_POINT(st, row.ts, *(uint16_t*)row.pData);
48,534✔
6209
        break;
48,534✔
6210
      }
6211
      case TSDB_DATA_TYPE_UINT: {
51,098✔
6212
        INIT_INTP_POINT(st, row.ts, *(uint32_t*)row.pData);
51,098✔
6213
        break;
51,098✔
6214
      }
6215
      case TSDB_DATA_TYPE_UBIGINT: {
38,822✔
6216
        INIT_INTP_POINT(st, row.ts, *(uint64_t*)row.pData);
38,822✔
6217
        break;
38,822✔
6218
      }
6219
      default: {
×
6220
        return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
6221
      }
6222
    }
6223
    if (pInfo->p.key == st.key) {
7,916,195!
6224
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6225
    }
6226

6227
    pInfo->dOutput += twa_get_area(pInfo->p, st);
7,916,195✔
6228
    pInfo->p = st;
7,916,564✔
6229
  }
6230

6231
  // the last interpolated time window value
6232
  if (pCtx->end.key != INT64_MIN) {
7,648,280✔
6233
    pInfo->dOutput += twa_get_area(pInfo->p, pCtx->end);
4,420,507✔
6234
    pInfo->p = pCtx->end;
4,420,495✔
6235
    pInfo->numOfElems += 1;
4,420,495✔
6236
  }
6237

6238
  pInfo->win.ekey = pInfo->p.key;
7,648,268✔
6239

6240
_twa_over:
7,648,268✔
6241
  SET_VAL(pResInfo, 1, 1);
7,648,268✔
6242
  return TSDB_CODE_SUCCESS;
7,648,268✔
6243
}
6244

6245
/*
6246
 * To copy the input to interResBuf to avoid the input buffer space be over writen
6247
 * by next input data. The TWA function only applies to each table, so no merge procedure
6248
 * is required, we simply copy to the resut ot interResBuffer.
6249
 */
6250
// void twa_function_copy(SQLFunctionCtx *pCtx) {
6251
//   SResultRowEntryInfo *pResInfo = GET_RES_INFO(pCtx);
6252
//
6253
//   memcpy(GET_ROWCELL_INTERBUF(pResInfo), pCtx->pInput, (size_t)pCtx->inputBytes);
6254
//   pResInfo->hasResult = ((STwaInfo *)pCtx->pInput)->hasResult;
6255
// }
6256

6257
int32_t twaFinalize(struct SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
7,628,933✔
6258
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
7,628,933✔
6259

6260
  STwaInfo* pInfo = (STwaInfo*)GET_ROWCELL_INTERBUF(pResInfo);
7,628,933✔
6261
  if (pInfo->numOfElems == 0) {
7,628,933✔
6262
    pResInfo->numOfRes = 0;
14,925✔
6263
  } else {
6264
    if (pInfo->win.ekey == pInfo->win.skey) {
7,614,008✔
6265
      pInfo->dTwaRes = pInfo->p.val;
2,769,909✔
6266
    } else if (pInfo->win.ekey == INT64_MAX || pInfo->win.skey == INT64_MIN) {  // no data in timewindow
4,844,099!
6267
      pInfo->dTwaRes = 0;
×
6268
    } else {
6269
      pInfo->dTwaRes = pInfo->dOutput / (pInfo->win.ekey - pInfo->win.skey);
4,844,425✔
6270
    }
6271

6272
    pResInfo->numOfRes = 1;
7,614,008✔
6273
  }
6274

6275
  return functionFinalize(pCtx, pBlock);
7,628,933✔
6276
}
6277

6278
int32_t blockDistSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
1,628✔
6279
  if (pResultInfo->initialized) {
1,628!
6280
    return TSDB_CODE_SUCCESS;
×
6281
  }
6282
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
1,628!
6283
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6284
  }
6285

6286
  STableBlockDistInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,628✔
6287
  pInfo->minRows = INT32_MAX;
1,628✔
6288
  return TSDB_CODE_SUCCESS;
1,628✔
6289
}
6290

6291
int32_t blockDistFunction(SqlFunctionCtx* pCtx) {
3,253✔
6292
  const int32_t BLOCK_DIST_RESULT_ROWS = 25;
3,253✔
6293

6294
  SInputColumnInfoData* pInput = &pCtx->input;
3,253✔
6295
  SColumnInfoData*      pInputCol = pInput->pData[0];
3,253✔
6296
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
3,253✔
6297
  STableBlockDistInfo*  pDistInfo = GET_ROWCELL_INTERBUF(pResInfo);
3,253✔
6298

6299
  STableBlockDistInfo p1 = {0};
3,253✔
6300
  if (tDeserializeBlockDistInfo(varDataVal(pInputCol->pData), varDataLen(pInputCol->pData), &p1) < 0) {
3,253!
6301
    qError("failed to deserialize block dist info");
×
6302
    return TSDB_CODE_FAILED;
×
6303
  }
6304

6305
  pDistInfo->numOfBlocks += p1.numOfBlocks;
3,253✔
6306
  pDistInfo->numOfTables += p1.numOfTables;
3,253✔
6307
  pDistInfo->numOfInmemRows += p1.numOfInmemRows;
3,253✔
6308
  pDistInfo->numOfSttRows += p1.numOfSttRows;
3,253✔
6309
  pDistInfo->totalSize += p1.totalSize;
3,253✔
6310
  pDistInfo->totalRows += p1.totalRows;
3,253✔
6311
  pDistInfo->numOfFiles += p1.numOfFiles;
3,253✔
6312

6313
  pDistInfo->defMinRows = p1.defMinRows;
3,253✔
6314
  pDistInfo->defMaxRows = p1.defMaxRows;
3,253✔
6315
  pDistInfo->rowSize = p1.rowSize;
3,253✔
6316

6317
  if (pDistInfo->minRows > p1.minRows) {
3,253✔
6318
    pDistInfo->minRows = p1.minRows;
2✔
6319
  }
6320
  if (pDistInfo->maxRows < p1.maxRows) {
3,253✔
6321
    pDistInfo->maxRows = p1.maxRows;
2✔
6322
  }
6323
  pDistInfo->numOfVgroups += (p1.numOfTables != 0 ? 1 : 0);
3,253✔
6324
  for (int32_t i = 0; i < tListLen(pDistInfo->blockRowsHisto); ++i) {
68,313✔
6325
    pDistInfo->blockRowsHisto[i] += p1.blockRowsHisto[i];
65,060✔
6326
  }
6327

6328
  pResInfo->numOfRes = BLOCK_DIST_RESULT_ROWS;  // default output rows
3,253✔
6329
  return TSDB_CODE_SUCCESS;
3,253✔
6330
}
6331

6332
int32_t tSerializeBlockDistInfo(void* buf, int32_t bufLen, const STableBlockDistInfo* pInfo) {
6,498✔
6333
  SEncoder encoder = {0};
6,498✔
6334
  int32_t  code = 0;
6,498✔
6335
  int32_t  lino;
6336
  int32_t  tlen;
6337
  tEncoderInit(&encoder, buf, bufLen);
6,498✔
6338

6339
  TAOS_CHECK_EXIT(tStartEncode(&encoder));
6,501!
6340
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->rowSize));
13,006!
6341

6342
  TAOS_CHECK_EXIT(tEncodeU16(&encoder, pInfo->numOfFiles));
13,006!
6343
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfBlocks));
13,006!
6344
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfTables));
13,006!
6345

6346
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalSize));
13,006!
6347
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalRows));
13,006!
6348
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->maxRows));
13,006!
6349
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->minRows));
13,006!
6350
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMaxRows));
13,006!
6351
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMinRows));
13,006!
6352
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfInmemRows));
13,006!
6353
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfSttRows));
13,006!
6354
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfVgroups));
13,006!
6355

6356
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
136,407✔
6357
    TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->blockRowsHisto[i]));
259,808!
6358
  }
6359

6360
  tEndEncode(&encoder);
6,503✔
6361

6362
_exit:
6,500✔
6363
  if (code) {
6,500!
6364
    tlen = code;
×
6365
  } else {
6366
    tlen = encoder.pos;
6,500✔
6367
  }
6368
  tEncoderClear(&encoder);
6,500✔
6369
  return tlen;
6,500✔
6370
}
6371

6372
int32_t tDeserializeBlockDistInfo(void* buf, int32_t bufLen, STableBlockDistInfo* pInfo) {
3,253✔
6373
  SDecoder decoder = {0};
3,253✔
6374
  int32_t  code = 0;
3,253✔
6375
  int32_t  lino;
6376
  tDecoderInit(&decoder, buf, bufLen);
3,253✔
6377

6378
  TAOS_CHECK_EXIT(tStartDecode(&decoder));
3,253!
6379
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->rowSize));
6,506!
6380

6381
  TAOS_CHECK_EXIT(tDecodeU16(&decoder, &pInfo->numOfFiles));
6,506!
6382
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfBlocks));
6,506!
6383
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfTables));
6,506!
6384

6385
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->totalSize));
6,506!
6386
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->totalRows));
6,506!
6387
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->maxRows));
6,506!
6388
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->minRows));
6,506!
6389
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->defMaxRows));
6,506!
6390
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->defMinRows));
6,506!
6391
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfInmemRows));
6,506!
6392
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfSttRows));
6,506!
6393
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfVgroups));
6,506!
6394

6395
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
68,313✔
6396
    TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->blockRowsHisto[i]));
130,120!
6397
  }
6398

6399
_exit:
3,253✔
6400
  tDecoderClear(&decoder);
3,253✔
6401
  return code;
3,253✔
6402
}
6403

6404
int32_t blockDistFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1,628✔
6405
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,628✔
6406
  STableBlockDistInfo* pData = GET_ROWCELL_INTERBUF(pResInfo);
1,628✔
6407

6408
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);
1,628✔
6409
  if (NULL == pColInfo) {
1,628!
6410
    return TSDB_CODE_OUT_OF_RANGE;
×
6411
  }
6412

6413
  if (pData->totalRows == 0) {
1,628✔
6414
    pData->minRows = 0;
1,626✔
6415
  }
6416

6417
  int32_t row = 0;
1,628✔
6418
  char    st[256] = {0};
1,628✔
6419
  double  averageSize = 0;
1,628✔
6420
  if (pData->numOfBlocks != 0) {
1,628✔
6421
    averageSize = ((double)pData->totalSize) / pData->numOfBlocks;
2✔
6422
  }
6423
  uint64_t totalRawSize = pData->totalRows * pData->rowSize;
1,628✔
6424
  double   compRatio = 0;
1,628✔
6425
  if (totalRawSize != 0) {
1,628✔
6426
    compRatio = pData->totalSize * 100 / (double)totalRawSize;
2✔
6427
  }
6428

6429
  int32_t len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
3,256✔
6430
                          "Total_Blocks=[%d] Total_Size=[%.2f KiB] Average_size=[%.2f KiB] Compression_Ratio=[%.2f %c]",
6431
                          pData->numOfBlocks, pData->totalSize / 1024.0, averageSize / 1024.0, compRatio, '%');
1,628✔
6432

6433
  varDataSetLen(st, len);
1,628✔
6434
  int32_t code = colDataSetVal(pColInfo, row++, st, false);
1,628✔
6435
  if (TSDB_CODE_SUCCESS != code) {
1,628!
6436
    return code;
×
6437
  }
6438

6439
  int64_t avgRows = 0;
1,628✔
6440
  if (pData->numOfBlocks > 0) {
1,628✔
6441
    avgRows = pData->totalRows / pData->numOfBlocks;
2✔
6442
  }
6443

6444
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
1,628✔
6445
                  "Block_Rows=[%" PRId64 "] MinRows=[%d] MaxRows=[%d] AvgRows=[%" PRId64 "]", pData->totalRows,
6446
                  pData->minRows, pData->maxRows, avgRows);
6447
  varDataSetLen(st, len);
1,628✔
6448
  code = colDataSetVal(pColInfo, row++, st, false);
1,628✔
6449
  if (TSDB_CODE_SUCCESS != code) {
1,628!
6450
    return code;
×
6451
  }
6452

6453
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Inmem_Rows=[%u] Stt_Rows=[%u] ",
1,628✔
6454
                  pData->numOfInmemRows, pData->numOfSttRows);
6455
  varDataSetLen(st, len);
1,628✔
6456
  code = colDataSetVal(pColInfo, row++, st, false);
1,628✔
6457
  if (TSDB_CODE_SUCCESS != code) {
1,628!
6458
    return code;
×
6459
  }
6460

6461
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
3,256✔
6462
                  "Total_Tables=[%d] Total_Filesets=[%d] Total_Vgroups=[%d]", pData->numOfTables, pData->numOfFiles,
1,628✔
6463
                  pData->numOfVgroups);
6464

6465
  varDataSetLen(st, len);
1,628✔
6466
  code = colDataSetVal(pColInfo, row++, st, false);
1,628✔
6467
  if (TSDB_CODE_SUCCESS != code) {
1,628!
6468
    return code;
×
6469
  }
6470

6471
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
1,628✔
6472
                  "--------------------------------------------------------------------------------");
6473
  varDataSetLen(st, len);
1,628✔
6474
  code = colDataSetVal(pColInfo, row++, st, false);
1,628✔
6475
  if (TSDB_CODE_SUCCESS != code) {
1,628!
6476
    return code;
×
6477
  }
6478

6479
  int32_t maxVal = 0;
1,628✔
6480
  int32_t minVal = INT32_MAX;
1,628✔
6481
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
34,188✔
6482
    if (maxVal < pData->blockRowsHisto[i]) {
32,560✔
6483
      maxVal = pData->blockRowsHisto[i];
4✔
6484
    }
6485

6486
    if (minVal > pData->blockRowsHisto[i]) {
32,560✔
6487
      minVal = pData->blockRowsHisto[i];
1,629✔
6488
    }
6489
  }
6490

6491
  // maximum number of step is 80
6492
  double factor = pData->numOfBlocks / 80.0;
1,628✔
6493

6494
  int32_t numOfBuckets = sizeof(pData->blockRowsHisto) / sizeof(pData->blockRowsHisto[0]);
1,628✔
6495
  int32_t bucketRange = ceil(((double)(pData->defMaxRows - pData->defMinRows)) / numOfBuckets);
1,628✔
6496

6497
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
34,188✔
6498
    len =
32,560✔
6499
        tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "%04d |", pData->defMinRows + bucketRange * (i + 1));
32,560✔
6500

6501
    int32_t num = 0;
32,560✔
6502
    if (pData->blockRowsHisto[i] > 0) {
32,560✔
6503
      num = (pData->blockRowsHisto[i]) / factor;
4✔
6504
    }
6505

6506
    for (int32_t j = 0; j < num; ++j) {
32,719✔
6507
      int32_t x = tsnprintf(varDataVal(st) + len, sizeof(st) - VARSTR_HEADER_SIZE - len, "%c", '|');
159✔
6508
      len += x;
159✔
6509
    }
6510

6511
    if (pData->blockRowsHisto[i] > 0) {
32,560✔
6512
      double v = pData->blockRowsHisto[i] * 100.0 / pData->numOfBlocks;
4✔
6513
      len += tsnprintf(varDataVal(st) + len, sizeof(st) - VARSTR_HEADER_SIZE - len, "  %d (%.2f%c)",
4✔
6514
                       pData->blockRowsHisto[i], v, '%');
6515
    }
6516

6517
    varDataSetLen(st, len);
32,560✔
6518
    code = colDataSetVal(pColInfo, row++, st, false);
32,560✔
6519
    if (TSDB_CODE_SUCCESS != code) {
32,560!
6520
      return code;
×
6521
    }
6522
  }
6523

6524
  return TSDB_CODE_SUCCESS;
1,628✔
6525
}
6526
int32_t blockDBUsageSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
1✔
6527
  if (pResultInfo->initialized) {
1!
6528
    return TSDB_CODE_SUCCESS;
×
6529
  }
6530
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
1!
6531
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6532
  }
6533

6534
  SDBBlockUsageInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1✔
6535
  return TSDB_CODE_SUCCESS;
1✔
6536
}
6537
int32_t blockDBUsageFunction(SqlFunctionCtx* pCtx) {
2✔
6538
  const int32_t BLOCK_DISK_USAGE_RESULT_ROWS = 2;
2✔
6539

6540
  SInputColumnInfoData* pInput = &pCtx->input;
2✔
6541
  SColumnInfoData*      pInputCol = pInput->pData[0];
2✔
6542
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
2✔
6543
  SDBBlockUsageInfo*    pDistInfo = GET_ROWCELL_INTERBUF(pResInfo);
2✔
6544

6545
  SDBBlockUsageInfo p1 = {0};
2✔
6546
  if (tDeserializeBlockDbUsage(varDataVal(pInputCol->pData), varDataLen(pInputCol->pData), &p1) < 0) {
2!
6547
    qError("failed to deserialize block dist info");
×
6548
    return TSDB_CODE_FAILED;
×
6549
  }
6550

6551
  pDistInfo->dataInDiskSize += p1.dataInDiskSize;
2✔
6552
  pDistInfo->walInDiskSize += p1.walInDiskSize;
2✔
6553
  pDistInfo->rawDataSize += p1.rawDataSize;
2✔
6554
  pResInfo->numOfRes = BLOCK_DISK_USAGE_RESULT_ROWS;  // default output rows
2✔
6555
  return TSDB_CODE_SUCCESS;
2✔
6556
}
6557

6558
int32_t tSerializeBlockDbUsage(void* buf, int32_t bufLen, const SDBBlockUsageInfo* pInfo) {
4✔
6559
  SEncoder encoder = {0};
4✔
6560
  int32_t  code = 0;
4✔
6561
  int32_t  lino;
6562
  int32_t  tlen;
6563
  tEncoderInit(&encoder, buf, bufLen);
4✔
6564

6565
  TAOS_CHECK_EXIT(tStartEncode(&encoder));
4!
6566

6567
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->dataInDiskSize));
8!
6568
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->walInDiskSize));
8!
6569
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->rawDataSize));
8!
6570

6571
  tEndEncode(&encoder);
4✔
6572

6573
_exit:
4✔
6574
  if (code) {
4!
6575
    tlen = code;
×
6576
  } else {
6577
    tlen = encoder.pos;
4✔
6578
  }
6579
  tEncoderClear(&encoder);
4✔
6580
  return tlen;
4✔
6581
}
6582
int32_t tDeserializeBlockDbUsage(void* buf, int32_t bufLen, SDBBlockUsageInfo* pInfo) {
2✔
6583
  SDecoder decoder = {0};
2✔
6584
  int32_t  code = 0;
2✔
6585
  int32_t  lino;
6586
  tDecoderInit(&decoder, buf, bufLen);
2✔
6587

6588
  TAOS_CHECK_EXIT(tStartDecode(&decoder));
2!
6589
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->dataInDiskSize));
4!
6590
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->walInDiskSize));
4!
6591
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->rawDataSize));
4!
6592

6593
_exit:
2✔
6594
  tDecoderClear(&decoder);
2✔
6595
  return code;
2✔
6596
}
6597
int32_t blockDBUsageFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1✔
6598
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1✔
6599
  SDBBlockUsageInfo*   pData = GET_ROWCELL_INTERBUF(pResInfo);
1✔
6600

6601
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);
1✔
6602
  if (NULL == pColInfo) {
1!
6603
    return TSDB_CODE_OUT_OF_RANGE;
×
6604
  }
6605
  int32_t len = 0;
1✔
6606
  int32_t row = 0;
1✔
6607
  char    st[256] = {0};
1✔
6608

6609
  uint64_t totalDiskSize = pData->dataInDiskSize;
1✔
6610
  uint64_t rawDataSize = pData->rawDataSize;
1✔
6611
  double   compressRadio = 0;
1✔
6612
  if (rawDataSize != 0) {
1!
6613
    compressRadio = totalDiskSize * 100 / (double)rawDataSize;
1✔
6614
    len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Compress_radio=[%.2f]", compressRadio);
1✔
6615
  } else {
6616
    len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Compress_radio=[NULL]");
×
6617
  }
6618

6619
  varDataSetLen(st, len);
1✔
6620
  int32_t code = colDataSetVal(pColInfo, row++, st, false);
1✔
6621
  if (TSDB_CODE_SUCCESS != code) {
1!
6622
    return code;
×
6623
  }
6624

6625
  len =
1✔
6626
      tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Disk_occupied=[%" PRId64 "k]", pData->dataInDiskSize);
1✔
6627
  varDataSetLen(st, len);
1✔
6628
  code = colDataSetVal(pColInfo, row++, st, false);
1✔
6629
  if (TSDB_CODE_SUCCESS != code) {
1!
6630
    return code;
×
6631
  }
6632
  return code;
1✔
6633
}
6634

6635
bool getDerivativeFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
30,697✔
6636
  pEnv->calcMemSize = sizeof(SDerivInfo);
30,697✔
6637
  return true;
30,697✔
6638
}
6639

6640
int32_t derivativeFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
84,485✔
6641
  if (pResInfo->initialized) {
84,485✔
6642
    return TSDB_CODE_SUCCESS;
53,665✔
6643
  }
6644
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
30,820!
6645
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6646
  }
6647

6648
  SDerivInfo* pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
30,820✔
6649

6650
  pDerivInfo->ignoreNegative = pCtx->param[2].param.i;
30,820✔
6651
  pDerivInfo->prevTs = -1;
30,820✔
6652
  pDerivInfo->tsWindow = pCtx->param[1].param.i;
30,820✔
6653
  pDerivInfo->valueSet = false;
30,820✔
6654
  return TSDB_CODE_SUCCESS;
30,820✔
6655
}
6656

6657
int32_t derivativeFunction(SqlFunctionCtx* pCtx) {
53,788✔
6658
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
53,788✔
6659
  SDerivInfo*          pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
53,788✔
6660

6661
  SInputColumnInfoData* pInput = &pCtx->input;
53,788✔
6662
  SColumnInfoData*      pInputCol = pInput->pData[0];
53,788✔
6663

6664
  int32_t          numOfElems = 0;
53,788✔
6665
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
53,788✔
6666
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
53,788✔
6667
  int32_t          code = TSDB_CODE_SUCCESS;
53,788✔
6668

6669
  funcInputUpdate(pCtx);
53,788✔
6670

6671
  double v = 0;
53,788✔
6672
  if (pCtx->order == TSDB_ORDER_ASC) {
53,788✔
6673
    SFuncInputRow row = {0};
50,420✔
6674
    bool          result = false;
50,420✔
6675
    while (1) {
2,740,762✔
6676
      code = funcInputGetNextRow(pCtx, &row, &result);
2,791,182✔
6677
      if (TSDB_CODE_SUCCESS != code) {
2,791,182!
6678
        return code;
×
6679
      }
6680
      if (!result) {
2,791,182✔
6681
        break;
50,420✔
6682
      }
6683
      if (row.isDataNull) {
2,740,762✔
6684
        continue;
39,876✔
6685
      }
6686

6687
      char* d = row.pData;
2,700,886✔
6688
      GET_TYPED_DATA(v, double, pInputCol->info.type, d);
2,700,886!
6689

6690
      int32_t pos = pCtx->offset + numOfElems;
2,700,886✔
6691
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
2,700,886✔
6692
        pDerivInfo->valueSet = true;
27,032✔
6693
      } else {
6694
        if (row.ts == pDerivInfo->prevTs) {
2,673,854!
6695
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6696
        }
6697
        double r = ((v - pDerivInfo->prevValue) * pDerivInfo->tsWindow) / (row.ts - pDerivInfo->prevTs);
2,673,854✔
6698
        if (pDerivInfo->ignoreNegative && r < 0) {
2,673,854✔
6699
        } else {
6700
          if (isinf(r) || isnan(r)) {
1,560,132!
6701
            colDataSetNULL(pOutput, pos);
×
6702
          } else {
6703
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
1,560,132✔
6704
            if (code != TSDB_CODE_SUCCESS) {
1,560,132!
6705
              return code;
×
6706
            }
6707
          }
6708

6709
          if (pTsOutput != NULL) {
1,560,132!
6710
            colDataSetInt64(pTsOutput, pos, &row.ts);
×
6711
          }
6712

6713
          // handle selectivity
6714
          if (pCtx->subsidiaries.num > 0) {
1,560,132✔
6715
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
1,054,253✔
6716
            if (code != TSDB_CODE_SUCCESS) {
1,054,253!
6717
              return code;
×
6718
            }
6719
          }
6720

6721
          numOfElems++;
1,560,132✔
6722
        }
6723
      }
6724

6725
      pDerivInfo->prevValue = v;
2,700,886✔
6726
      pDerivInfo->prevTs = row.ts;
2,700,886✔
6727
    }
6728
  } else {
6729
    SFuncInputRow row = {0};
3,368✔
6730
    bool          result = false;
3,368✔
6731
    while (1) {
333,076✔
6732
      code = funcInputGetNextRow(pCtx, &row, &result);
336,444✔
6733
      if (TSDB_CODE_SUCCESS != code) {
336,444!
6734
        return code;
×
6735
      }
6736
      if (!result) {
336,444✔
6737
        break;
3,368✔
6738
      }
6739
      if (row.isDataNull) {
333,076✔
6740
        continue;
46✔
6741
      }
6742

6743
      char* d = row.pData;
333,030✔
6744
      GET_TYPED_DATA(v, double, pInputCol->info.type, d);
333,030!
6745

6746
      int32_t pos = pCtx->offset + numOfElems;
333,030✔
6747
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
333,030✔
6748
        pDerivInfo->valueSet = true;
3,345✔
6749
      } else {
6750
        if (row.ts == pDerivInfo->prevTs) {
329,685!
6751
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6752
        }
6753
        double r = ((pDerivInfo->prevValue - v) * pDerivInfo->tsWindow) / (pDerivInfo->prevTs - row.ts);
329,685✔
6754
        if (pDerivInfo->ignoreNegative && r < 0) {
329,685✔
6755
        } else {
6756
          if (isinf(r) || isnan(r)) {
252,872!
6757
            colDataSetNULL(pOutput, pos);
×
6758
          } else {
6759
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
252,872✔
6760
            if (code != TSDB_CODE_SUCCESS) {
252,872!
6761
              return code;
×
6762
            }
6763
          }
6764

6765
          if (pTsOutput != NULL) {
252,872!
6766
            colDataSetInt64(pTsOutput, pos, &pDerivInfo->prevTs);
×
6767
          }
6768

6769
          // handle selectivity
6770
          if (pCtx->subsidiaries.num > 0) {
252,872✔
6771
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
75,594✔
6772
            if (code != TSDB_CODE_SUCCESS) {
75,594!
6773
              return code;
×
6774
            }
6775
          }
6776
          numOfElems++;
252,872✔
6777
        }
6778
      }
6779

6780
      pDerivInfo->prevValue = v;
333,030✔
6781
      pDerivInfo->prevTs = row.ts;
333,030✔
6782
    }
6783
  }
6784

6785
  pResInfo->numOfRes = numOfElems;
53,788✔
6786

6787
  return TSDB_CODE_SUCCESS;
53,788✔
6788
}
6789

6790
int32_t getIrateInfoSize(int32_t pkBytes) { return (int32_t)sizeof(SRateInfo) + 2 * pkBytes; }
32,072✔
6791

6792
bool getIrateFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
31,691✔
6793
  int32_t pkBytes = (pFunc->hasPk) ? pFunc->pkBytes : 0;
31,691✔
6794
  pEnv->calcMemSize = getIrateInfoSize(pkBytes);
31,691✔
6795
  return true;
31,705✔
6796
}
6797

6798
int32_t irateFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
2,994,174✔
6799
  if (pResInfo->initialized) {
2,994,174!
6800
    return TSDB_CODE_SUCCESS;
×
6801
  }
6802
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
2,994,174!
6803
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6804
  }
6805

6806
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,994,174✔
6807

6808
  pInfo->firstKey = INT64_MIN;
2,994,174✔
6809
  pInfo->lastKey = INT64_MIN;
2,994,174✔
6810
  pInfo->firstValue = (double)INT64_MIN;
2,994,174✔
6811
  pInfo->lastValue = (double)INT64_MIN;
2,994,174✔
6812

6813
  pInfo->hasResult = 0;
2,994,174✔
6814
  return TSDB_CODE_SUCCESS;
2,994,174✔
6815
}
6816

6817
static void doSaveRateInfo(SRateInfo* pRateInfo, bool isFirst, int64_t ts, char* pk, double v) {
10,800,756✔
6818
  if (isFirst) {
10,800,756✔
6819
    pRateInfo->firstValue = v;
3,910,096✔
6820
    pRateInfo->firstKey = ts;
3,910,096✔
6821
    if (pRateInfo->firstPk) {
3,910,096✔
6822
      int32_t pkBytes;
6823
      if (IS_VAR_DATA_TYPE(pRateInfo->pkType)) {
35!
6824
        if (pRateInfo->pkType == TSDB_DATA_TYPE_JSON) {
8!
6825
          pkBytes = getJsonValueLen(pk);
×
6826
        } else {
6827
          pkBytes = varDataTLen(pk);
8✔
6828
        }
6829
      } else {
6830
        pkBytes = pRateInfo->pkBytes;
27✔
6831
      }
6832
      (void)memcpy(pRateInfo->firstPk, pk, pkBytes);
35✔
6833
    }
6834
  } else {
6835
    pRateInfo->lastValue = v;
6,890,660✔
6836
    pRateInfo->lastKey = ts;
6,890,660✔
6837
    if (pRateInfo->lastPk) {
6,890,660✔
6838
      int32_t pkBytes;
6839
      if (IS_VAR_DATA_TYPE(pRateInfo->pkType)) {
52!
6840
        if (pRateInfo->pkType == TSDB_DATA_TYPE_JSON) {
12!
6841
          pkBytes = getJsonValueLen(pk);
×
6842
        } else {
6843
          pkBytes = varDataTLen(pk);
12✔
6844
        }
6845
      } else {
6846
        pkBytes = pRateInfo->pkBytes;
40✔
6847
      }
6848
      (void)memcpy(pRateInfo->lastPk, pk, pkBytes);
52✔
6849
    }
6850
  }
6851
}
10,800,756✔
6852

6853
static void initializeRateInfo(SqlFunctionCtx* pCtx, SRateInfo* pRateInfo, bool isMerge) {
3,009,837✔
6854
  if (pCtx->hasPrimaryKey) {
3,009,837✔
6855
    if (!isMerge) {
19✔
6856
      pRateInfo->pkType = pCtx->input.pPrimaryKey->info.type;
17✔
6857
      pRateInfo->pkBytes = pCtx->input.pPrimaryKey->info.bytes;
17✔
6858
      pRateInfo->firstPk = pRateInfo->pkData;
17✔
6859
      pRateInfo->lastPk = pRateInfo->pkData + pRateInfo->pkBytes;
17✔
6860
    } else {
6861
      pRateInfo->firstPk = pRateInfo->pkData;
2✔
6862
      pRateInfo->lastPk = pRateInfo->pkData + pRateInfo->pkBytes;
2✔
6863
    }
6864
  } else {
6865
    pRateInfo->firstPk = NULL;
3,009,818✔
6866
    pRateInfo->lastPk = NULL;
3,009,818✔
6867
  }
6868
}
3,009,837✔
6869

6870
int32_t irateFunction(SqlFunctionCtx* pCtx) {
3,009,228✔
6871
  int32_t              code = TSDB_CODE_SUCCESS;
3,009,228✔
6872
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
3,009,228✔
6873
  SRateInfo*           pRateInfo = GET_ROWCELL_INTERBUF(pResInfo);
3,009,228✔
6874

6875
  SInputColumnInfoData* pInput = &pCtx->input;
3,009,228✔
6876
  SColumnInfoData*      pInputCol = pInput->pData[0];
3,009,228✔
6877

6878
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
3,009,228✔
6879

6880
  funcInputUpdate(pCtx);
3,009,228✔
6881

6882
  initializeRateInfo(pCtx, pRateInfo, false);
3,009,231✔
6883

6884
  int32_t       numOfElems = 0;
3,009,231✔
6885
  int32_t       type = pInputCol->info.type;
3,009,231✔
6886
  SFuncInputRow row = {0};
3,009,231✔
6887
  bool          result = false;
3,009,231✔
6888
  while (1) {
7,163,343✔
6889
    code = funcInputGetNextRow(pCtx, &row, &result);
10,172,574✔
6890
    if (TSDB_CODE_SUCCESS != code) {
10,172,615!
6891
      return code;
×
6892
    }
6893
    if (!result) {
10,172,615✔
6894
      break;
3,009,234✔
6895
    }
6896
    if (row.isDataNull) {
7,163,381✔
6897
      continue;
129,542✔
6898
    }
6899

6900
    char*  data = row.pData;
7,033,839✔
6901
    double v = 0;
7,033,839✔
6902
    GET_TYPED_DATA(v, double, type, data);
7,033,839!
6903

6904
    if (INT64_MIN == pRateInfo->lastKey) {
7,033,839✔
6905
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
2,981,237✔
6906
      pRateInfo->hasResult = 1;
2,981,237✔
6907
      continue;
2,981,237✔
6908
    }
6909

6910
    if (row.ts > pRateInfo->lastKey) {
4,052,602✔
6911
      if ((INT64_MIN == pRateInfo->firstKey) || pRateInfo->lastKey > pRateInfo->firstKey) {
3,909,268!
6912
        doSaveRateInfo(pRateInfo, true, pRateInfo->lastKey, pRateInfo->lastPk, pRateInfo->lastValue);
3,909,269✔
6913
      }
6914
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
3,909,271✔
6915
      continue;
3,909,228✔
6916
    } else if (row.ts == pRateInfo->lastKey) {
143,334!
6917
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6918
    }
6919

6920
    if ((INT64_MIN == pRateInfo->firstKey) || row.ts > pRateInfo->firstKey) {
143,334!
6921
      doSaveRateInfo(pRateInfo, true, row.ts, row.pPk, v);
493✔
6922
    } else if (row.ts == pRateInfo->firstKey) {
142,841!
6923
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6924
    }
6925
  }
6926

6927
  numOfElems++;
3,009,234✔
6928

6929
  SET_VAL(pResInfo, numOfElems, 1);
3,009,234!
6930
  return TSDB_CODE_SUCCESS;
3,009,234✔
6931
}
6932

6933
static double doCalcRate(const SRateInfo* pRateInfo, double tickPerSec) {
2,991,149✔
6934
  if ((INT64_MIN == pRateInfo->lastKey) || (INT64_MIN == pRateInfo->firstKey) ||
2,991,149✔
6935
      (pRateInfo->firstKey >= pRateInfo->lastKey)) {
255,290!
6936
    return 0.0;
2,735,859✔
6937
  }
6938

6939
  double diff = 0;
255,290✔
6940
  // If the previous value of the last is greater than the last value, only keep the last point instead of the delta
6941
  // value between two values.
6942
  diff = pRateInfo->lastValue;
255,290✔
6943
  if (diff >= pRateInfo->firstValue) {
255,290✔
6944
    diff -= pRateInfo->firstValue;
131,275✔
6945
  }
6946

6947
  int64_t duration = pRateInfo->lastKey - pRateInfo->firstKey;
255,290✔
6948
  if (duration == 0) {
255,290!
6949
    return 0;
×
6950
  }
6951

6952
  return (duration > 0) ? ((double)diff) / (duration / tickPerSec) : 0.0;
255,290!
6953
}
6954

6955
static void irateTransferInfoImpl(TSKEY inputKey, SRateInfo* pInput, SRateInfo* pOutput, bool isFirstKey) {
174✔
6956
  if (inputKey > pOutput->lastKey) {
174✔
6957
    doSaveRateInfo(pOutput, true, pOutput->lastKey, pOutput->lastPk, pOutput->lastValue);
105✔
6958
    if (isFirstKey) {
105✔
6959
      doSaveRateInfo(pOutput, false, pInput->firstKey, pInput->firstPk, pInput->firstValue);
47✔
6960
    } else {
6961
      doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
58✔
6962
    }
6963
  } else if ((inputKey < pOutput->lastKey) && (inputKey > pOutput->firstKey)) {
69!
6964
    if (isFirstKey) {
14✔
6965
      doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
7✔
6966
    } else {
6967
      doSaveRateInfo(pOutput, true, pInput->lastKey, pInput->lastPk, pInput->lastValue);
7✔
6968
    }
6969
  } else {
6970
    // inputKey < pOutput->firstKey
6971
  }
6972
}
174✔
6973

6974
static void irateCopyInfo(SRateInfo* pInput, SRateInfo* pOutput) {
208✔
6975
  doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
208✔
6976
  doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
208✔
6977
}
208✔
6978

6979
static int32_t irateTransferInfo(SRateInfo* pInput, SRateInfo* pOutput) {
295✔
6980
  if ((pInput->firstKey != INT64_MIN &&
295✔
6981
       (pInput->firstKey == pOutput->firstKey || pInput->firstKey == pOutput->lastKey)) ||
290!
6982
      (pInput->lastKey != INT64_MIN && (pInput->lastKey == pOutput->firstKey || pInput->lastKey == pOutput->lastKey))) {
295!
6983
    return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6984
  }
6985

6986
  if (pOutput->hasResult == 0) {
295✔
6987
    irateCopyInfo(pInput, pOutput);
208✔
6988
    pOutput->hasResult = pInput->hasResult;
208✔
6989
    return TSDB_CODE_SUCCESS;
208✔
6990
  }
6991

6992
  if (pInput->firstKey != INT64_MIN) {
87!
6993
    irateTransferInfoImpl(pInput->firstKey, pInput, pOutput, true);
87✔
6994
  }
6995

6996
  if (pInput->lastKey != INT64_MIN) {
87!
6997
    irateTransferInfoImpl(pInput->lastKey, pInput, pOutput, false);
87✔
6998
  }
6999

7000
  pOutput->hasResult = pInput->hasResult;
87✔
7001
  return TSDB_CODE_SUCCESS;
87✔
7002
}
7003

7004
int32_t irateFunctionMerge(SqlFunctionCtx* pCtx) {
303✔
7005
  SInputColumnInfoData* pInput = &pCtx->input;
303✔
7006
  SColumnInfoData*      pCol = pInput->pData[0];
303✔
7007
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
303!
7008
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
7009
  }
7010

7011
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
303✔
7012
  initializeRateInfo(pCtx, pInfo, true);
303✔
7013

7014
  int32_t start = pInput->startRowIndex;
303✔
7015
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
606✔
7016
    char*      data = colDataGetData(pCol, i);
303!
7017
    SRateInfo* pInputInfo = (SRateInfo*)varDataVal(data);
303✔
7018
    initializeRateInfo(pCtx, pInfo, true);
303✔
7019
    if (pInputInfo->hasResult) {
303✔
7020
      int32_t code = irateTransferInfo(pInputInfo, pInfo);
295✔
7021
      if (code != TSDB_CODE_SUCCESS) {
295!
7022
        return code;
×
7023
      }
7024
    }
7025
  }
7026

7027
  if (pInfo->hasResult) {
303✔
7028
    GET_RES_INFO(pCtx)->numOfRes = 1;
295✔
7029
  }
7030

7031
  return TSDB_CODE_SUCCESS;
303✔
7032
}
7033

7034
int32_t iratePartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
303✔
7035
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
303✔
7036
  SRateInfo*           pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
303✔
7037
  int32_t              resultBytes = getIrateInfoSize(pInfo->pkBytes);
303✔
7038
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
303!
7039

7040
  if (NULL == res) {
303!
7041
    return terrno;
×
7042
  }
7043
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
303✔
7044
  varDataSetLen(res, resultBytes);
303✔
7045

7046
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
303✔
7047
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
303✔
7048
  if (NULL == pCol) {
303!
7049
    taosMemoryFree(res);
×
7050
    return TSDB_CODE_OUT_OF_RANGE;
×
7051
  }
7052

7053
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
303✔
7054

7055
  taosMemoryFree(res);
303!
7056
  return code;
303✔
7057
}
7058

7059
int32_t irateFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
2,991,149✔
7060
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
2,991,149✔
7061
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
2,991,149✔
7062
  if (NULL == pCol) {
2,991,149!
7063
    return TSDB_CODE_OUT_OF_RANGE;
×
7064
  }
7065

7066
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,991,149✔
7067
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
2,991,149✔
7068

7069
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,991,149✔
7070
  double     result = doCalcRate(pInfo, (double)TSDB_TICK_PER_SECOND(pCtx->param[1].param.i));
2,991,149!
7071
  int32_t    code = colDataSetVal(pCol, pBlock->info.rows, (const char*)&result, pResInfo->isNullRes);
2,991,149✔
7072

7073
  return code;
2,991,149✔
7074
}
7075

7076
int32_t groupConstValueFunction(SqlFunctionCtx* pCtx) {
106,887,565✔
7077
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
106,887,565✔
7078
  SGroupKeyInfo*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
106,887,565✔
7079

7080
  SInputColumnInfoData* pInput = &pCtx->input;
106,887,565✔
7081
  SColumnInfoData*      pInputCol = pInput->pData[0];
106,887,565✔
7082

7083
  int32_t startIndex = pInput->startRowIndex;
106,887,565✔
7084

7085
  // escape rest of data blocks to avoid first entry to be overwritten.
7086
  if (pInfo->hasResult) {
106,887,565✔
7087
    goto _group_value_over;
10,635,205✔
7088
  }
7089

7090
  if (pInputCol->pData == NULL || colDataIsNull_s(pInputCol, startIndex)) {
192,124,893✔
7091
    pInfo->isNull = true;
2,506,121✔
7092
    pInfo->hasResult = true;
2,506,121✔
7093
    goto _group_value_over;
2,506,121✔
7094
  }
7095

7096
  char* data = colDataGetData(pInputCol, startIndex);
93,746,239!
7097
  if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
93,746,239!
7098
    (void)memcpy(pInfo->data, data,
72,554,545✔
7099
                 (pInputCol->info.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(data) : varDataTLen(data));
72,554,545✔
7100
  } else {
7101
    (void)memcpy(pInfo->data, data, pInputCol->info.bytes);
21,191,694✔
7102
  }
7103
  pInfo->hasResult = true;
93,746,239✔
7104

7105
_group_value_over:
106,887,565✔
7106

7107
  SET_VAL(pResInfo, 1, 1);
106,887,565✔
7108
  return TSDB_CODE_SUCCESS;
106,887,565✔
7109
}
7110

7111
int32_t groupKeyFunction(SqlFunctionCtx* pCtx) { return groupConstValueFunction(pCtx); }
106,879,991✔
7112

7113
int32_t groupConstValueFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
95,070,782✔
7114
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
95,070,782✔
7115
  int32_t          code = TSDB_CODE_SUCCESS;
95,070,782✔
7116
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
95,070,782✔
7117
  if (NULL == pCol) {
95,200,494!
7118
    return TSDB_CODE_OUT_OF_RANGE;
×
7119
  }
7120

7121
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
95,200,494✔
7122

7123
  SGroupKeyInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
95,200,494✔
7124

7125
  if (pInfo->hasResult) {
95,200,494!
7126
    int32_t currentRow = pBlock->info.rows;
95,256,668✔
7127
    for (; currentRow < pBlock->info.rows + pResInfo->numOfRes; ++currentRow) {
191,174,185✔
7128
      code = colDataSetVal(pCol, currentRow, pInfo->data, pInfo->isNull ? true : false);
95,284,487✔
7129
      if (TSDB_CODE_SUCCESS != code) {
95,917,517!
7130
        return code;
×
7131
      }
7132
    }
7133
  } else {
7134
    pResInfo->numOfRes = 0;
×
7135
  }
7136

7137
  return code;
95,833,524✔
7138
}
7139

7140
int32_t groupKeyFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { return groupConstValueFinalize(pCtx, pBlock); }
95,059,265✔
7141

7142
int32_t groupKeyCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
7143
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
7144
  SGroupKeyInfo*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
7145

7146
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
7147
  SGroupKeyInfo*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
7148

7149
  // escape rest of data blocks to avoid first entry to be overwritten.
7150
  if (pDBuf->hasResult) {
×
7151
    goto _group_key_over;
×
7152
  }
7153

7154
  if (pSBuf->isNull) {
×
7155
    pDBuf->isNull = true;
×
7156
    pDBuf->hasResult = true;
×
7157
    goto _group_key_over;
×
7158
  }
7159

7160
  if (IS_VAR_DATA_TYPE(pSourceCtx->resDataInfo.type)) {
×
7161
    (void)memcpy(pDBuf->data, pSBuf->data,
×
7162
                 (pSourceCtx->resDataInfo.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(pSBuf->data)
×
7163
                                                                       : varDataTLen(pSBuf->data));
×
7164
  } else {
7165
    (void)memcpy(pDBuf->data, pSBuf->data, pSourceCtx->resDataInfo.bytes);
×
7166
  }
7167

7168
  pDBuf->hasResult = true;
×
7169

7170
_group_key_over:
×
7171

7172
  SET_VAL(pDResInfo, 1, 1);
×
7173
  return TSDB_CODE_SUCCESS;
×
7174
}
7175

7176
int32_t cachedLastRowFunction(SqlFunctionCtx* pCtx) {
3,588✔
7177
  int32_t numOfElems = 0;
3,588✔
7178

7179
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
3,588✔
7180
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
3,588✔
7181

7182
  SInputColumnInfoData* pInput = &pCtx->input;
3,588✔
7183
  SColumnInfoData*      pInputCol = pInput->pData[0];
3,588✔
7184

7185
  int32_t bytes = pInputCol->info.bytes;
3,588✔
7186
  pInfo->bytes = bytes;
3,588✔
7187

7188
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
3,588✔
7189
  pInfo->pkType = -1;
3,588✔
7190
  __compar_fn_t pkCompareFn = NULL;
3,588✔
7191
  if (pCtx->hasPrimaryKey) {
3,588✔
7192
    pInfo->pkType = pkCol->info.type;
20✔
7193
    pInfo->pkBytes = pkCol->info.bytes;
20✔
7194
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
20✔
7195
  }
7196

7197
  // TODO it traverse the different way.
7198
  // last_row function does not ignore the null value
7199
  for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
7,188✔
7200
    numOfElems++;
3,599✔
7201

7202
    bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
3,599✔
7203
    char* data = isNull ? NULL : colDataGetData(pInputCol, i);
3,599!
7204

7205
    TSKEY cts = getRowPTs(pInput->pPTS, i);
3,599✔
7206
    if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
3,599✔
7207
      int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
3,227✔
7208
      if (code != TSDB_CODE_SUCCESS) {
3,228!
7209
        return code;
×
7210
      }
7211
      pResInfo->numOfRes = 1;
3,228✔
7212
    }
7213
  }
7214

7215
  SET_VAL(pResInfo, numOfElems, 1);
3,589!
7216
  return TSDB_CODE_SUCCESS;
3,589✔
7217
}
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