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

taosdata / TDengine / #3663

19 Mar 2025 09:21AM UTC coverage: 61.664% (-0.6%) from 62.28%
#3663

push

travis-ci

web-flow
docs: add defination of tmq_config_res_t & fix spell error (#30271)

153169 of 318241 branches covered (48.13%)

Branch coverage included in aggregate %.

239405 of 318390 relevant lines covered (75.19%)

5762846.6 hits per line

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

71.4
/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 "decimal.h"
19
#include "function.h"
20
#include "functionResInfoInt.h"
21
#include "query.h"
22
#include "querynodes.h"
23
#include "tanalytics.h"
24
#include "tcompare.h"
25
#include "tdatablock.h"
26
#include "tdigest.h"
27
#include "tfunctionInt.h"
28
#include "tglobal.h"
29
#include "thistogram.h"
30
#include "tpercentile.h"
31

32
bool ignoreNegative(int8_t ignoreOption) { return (ignoreOption & 0x1) == 0x1; }
33,741,156✔
33
bool ignoreNull(int8_t ignoreOption) { return (ignoreOption & 0x2) == 0x2; }
371,713✔
34

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

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

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

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

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

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

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

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

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

109
#define LIST_ADD_DECIMAL_N(_res, _col, _start, _rows, _t, numOfElem)                                  \
110
  do {                                                                                                \
111
    _t*                d = (_t*)(_col->pData);                                                        \
112
    const SDecimalOps* pOps = getDecimalOps(TSDB_DATA_TYPE_DECIMAL);                                  \
113
    for (int32_t i = (_start); i < (_rows) + (_start); ++i) {                                         \
114
      if (((_col)->hasNull) && colDataIsNull_f((_col)->nullbitmap, i)) {                              \
115
        continue;                                                                                     \
116
      };                                                                                              \
117
      overflow = overflow || decimal128AddCheckOverflow((Decimal*)_res, d + i, DECIMAL_WORD_NUM(_t)); \
118
      if (overflow) break;                                                                            \
119
      pOps->add(_res, d + i, DECIMAL_WORD_NUM(_t));                                                   \
120
      (numOfElem)++;                                                                                  \
121
    }                                                                                                 \
122
  } while (0)
123

124
#define LIST_SUB_N(_res, _col, _start, _rows, _t, numOfElem)             \
125
  do {                                                                   \
126
    _t* d = (_t*)(_col->pData);                                          \
127
    for (int32_t i = (_start); i < (_rows) + (_start); ++i) {            \
128
      if (((_col)->hasNull) && colDataIsNull_f((_col)->nullbitmap, i)) { \
129
        continue;                                                        \
130
      };                                                                 \
131
      (_res) -= (d)[i];                                                  \
132
      (numOfElem)++;                                                     \
133
    }                                                                    \
134
  } while (0)
135

136
//#define LIST_AVG_N(sumT, T)                                               \
137
//  do {                                                                    \
138
//    T* plist = (T*)pCol->pData;                                           \
139
//    for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) { \
140
//      if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {        \
141
//        continue;                                                         \
142
//      }                                                                   \
143
//                                                                          \
144
//      numOfElem += 1;                                                     \
145
//      pAvgRes->count -= 1;                                                \
146
//      sumT -= plist[i];                                                   \
147
//    }                                                                     \
148
//  } while (0)
149

150
#define LIST_STDDEV_SUB_N(sumT, T)                                 \
151
  do {                                                             \
152
    T* plist = (T*)pCol->pData;                                    \
153
    for (int32_t i = start; i < numOfRows + start; ++i) {          \
154
      if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) { \
155
        continue;                                                  \
156
      }                                                            \
157
      numOfElem += 1;                                              \
158
      pStddevRes->count -= 1;                                      \
159
      sumT -= plist[i];                                            \
160
      pStddevRes->quadraticISum -= (int64_t)(plist[i] * plist[i]); \
161
    }                                                              \
162
  } while (0)
163

164
#define LEASTSQR_CAL(p, x, y, index, step) \
165
  do {                                     \
166
    (p)[0][0] += (double)(x) * (x);        \
167
    (p)[0][1] += (double)(x);              \
168
    (p)[0][2] += (double)(x) * (y)[index]; \
169
    (p)[1][2] += (y)[index];               \
170
    (x) += step;                           \
171
  } while (0)
172

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

175
#define GET_STATE_VAL(param) ((param.nType == TSDB_DATA_TYPE_BIGINT) ? (param.i) : (param.d))
176

177
#define STATE_COMP_IMPL(_op, _lval, _rval) \
178
  do {                                     \
179
    switch (_op) {                         \
180
      case STATE_OPER_LT:                  \
181
        return ((_lval) < (_rval));        \
182
        break;                             \
183
      case STATE_OPER_GT:                  \
184
        return ((_lval) > (_rval));        \
185
        break;                             \
186
      case STATE_OPER_LE:                  \
187
        return ((_lval) <= (_rval));       \
188
        break;                             \
189
      case STATE_OPER_GE:                  \
190
        return ((_lval) >= (_rval));       \
191
        break;                             \
192
      case STATE_OPER_NE:                  \
193
        return ((_lval) != (_rval));       \
194
        break;                             \
195
      case STATE_OPER_EQ:                  \
196
        return ((_lval) == (_rval));       \
197
        break;                             \
198
      default:                             \
199
        break;                             \
200
    }                                      \
201
  } while (0)
202

203
#define INIT_INTP_POINT(_p, _k, _v) \
204
  do {                              \
205
    (_p).key = (_k);                \
206
    (_p).val = (_v);                \
207
  } while (0)
208

209
void funcInputUpdate(SqlFunctionCtx* pCtx) {
448,369✔
210
  SFuncInputRowIter* pIter = &pCtx->rowIter;
448,369✔
211

212
  if (!pCtx->bInputFinished) {
448,369!
213
    pIter->pInput = &pCtx->input;
448,376✔
214
    pIter->tsList = (TSKEY*)pIter->pInput->pPTS->pData;
448,376✔
215
    pIter->pDataCol = pIter->pInput->pData[0];
448,376✔
216
    pIter->pPkCol = pIter->pInput->pPrimaryKey;
448,376✔
217
    pIter->rowIndex = pIter->pInput->startRowIndex;
448,376✔
218
    pIter->inputEndIndex = pIter->rowIndex + pIter->pInput->numOfRows - 1;
448,376✔
219
    pIter->pSrcBlock = pCtx->pSrcBlock;
448,376✔
220
    if (!pIter->hasGroupId || pIter->groupId != pIter->pSrcBlock->info.id.groupId) {
448,376✔
221
      pIter->hasGroupId = true;
66,294✔
222
      pIter->groupId = pIter->pSrcBlock->info.id.groupId;
66,294✔
223
      pIter->hasPrev = false;
66,294✔
224
    }
225
  } else {
226
    pIter->finalRow = true;
×
227
  }
228
}
448,369✔
229

230
int32_t funcInputGetNextRowDescPk(SFuncInputRowIter* pIter, SFuncInputRow* pRow, bool* res) {
×
231
  if (pIter->finalRow) {
×
232
    if (pIter->hasPrev) {
×
233
      pRow->ts = pIter->prevBlockTsEnd;
×
234
      pRow->isDataNull = pIter->prevIsDataNull;
×
235
      pRow->pData = pIter->pPrevData;
×
236
      pRow->block = pIter->pPrevRowBlock;
×
237
      pRow->rowIndex = 0;
×
238

239
      pIter->hasPrev = false;
×
240
      *res = true;
×
241
      return TSDB_CODE_SUCCESS;
×
242
    } else {
243
      *res = false;
×
244
      return TSDB_CODE_SUCCESS;
×
245
    }
246
  }
247
  if (pIter->hasPrev) {
×
248
    if (pIter->prevBlockTsEnd == pIter->tsList[pIter->inputEndIndex]) {
×
249
      blockDataDestroy(pIter->pPrevRowBlock);
×
250
      int32_t code = blockDataExtractBlock(pIter->pSrcBlock, pIter->inputEndIndex, 1, &pIter->pPrevRowBlock);
×
251
      if (code) {
×
252
        return code;
×
253
      }
254

255
      pIter->prevIsDataNull = colDataIsNull_f(pIter->pDataCol->nullbitmap, pIter->inputEndIndex);
×
256

257
      pIter->pPrevData = taosMemoryMalloc(pIter->pDataCol->info.bytes);
×
258
      if (NULL == pIter->pPrevData) {
×
259
        qError("out of memory when function get input row.");
×
260
        return terrno;
×
261
      }
262
      char* srcData = colDataGetData(pIter->pDataCol, pIter->inputEndIndex);
×
263
      (void)memcpy(pIter->pPrevData, srcData, pIter->pDataCol->info.bytes);
×
264

265
      pIter->pPrevPk = taosMemoryMalloc(pIter->pPkCol->info.bytes);
×
266
      if (NULL == pIter->pPrevPk) {
×
267
        qError("out of memory when function get input row.");
×
268
        taosMemoryFree(pIter->pPrevData);
×
269
        return terrno;
×
270
      }
271
      char* pkData = colDataGetData(pIter->pPkCol, pIter->inputEndIndex);
×
272
      (void)memcpy(pIter->pPrevPk, pkData, pIter->pPkCol->info.bytes);
×
273

274
      code = blockDataExtractBlock(pIter->pSrcBlock, pIter->inputEndIndex, 1, &pIter->pPrevRowBlock);
×
275
      pIter->hasPrev = true;
×
276
      *res = false;
×
277
      return code;
×
278
    } else {
279
      int32_t idx = pIter->rowIndex;
×
280
      while (pIter->tsList[idx] == pIter->prevBlockTsEnd) {
×
281
        ++idx;
×
282
      }
283
      pRow->ts = pIter->prevBlockTsEnd;
×
284
      if (idx == pIter->pInput->startRowIndex) {
×
285
        pRow->isDataNull = pIter->prevIsDataNull;
×
286
        pRow->pData = pIter->pPrevData;
×
287
        pRow->block = pIter->pPrevRowBlock;
×
288
        pRow->rowIndex = 0;
×
289
      } else {
290
        pRow->ts = pIter->tsList[idx - 1];
×
291
        pRow->isDataNull = colDataIsNull_f(pIter->pDataCol->nullbitmap, idx - 1);
×
292
        pRow->pData = colDataGetData(pIter->pDataCol, idx - 1);
×
293
        pRow->pPk = colDataGetData(pIter->pPkCol, idx - 1);
×
294
        pRow->block = pIter->pSrcBlock;
×
295
        pRow->rowIndex = idx - 1;
×
296
      }
297
      pIter->hasPrev = false;
×
298
      pIter->rowIndex = idx;
×
299
      *res = true;
×
300
      return TSDB_CODE_SUCCESS;
×
301
    }
302
  } else {
303
    TSKEY tsEnd = pIter->tsList[pIter->inputEndIndex];
×
304
    if (pIter->tsList[pIter->rowIndex] != tsEnd) {
×
305
      int32_t idx = pIter->rowIndex;
×
306
      while (pIter->tsList[idx + 1] == pIter->tsList[pIter->rowIndex]) {
×
307
        ++idx;
×
308
      }
309
      pRow->ts = pIter->tsList[idx];
×
310
      pRow->isDataNull = colDataIsNull_f(pIter->pDataCol->nullbitmap, idx);
×
311
      pRow->pData = colDataGetData(pIter->pDataCol, idx);
×
312
      pRow->pPk = colDataGetData(pIter->pPkCol, idx);
×
313
      pRow->block = pIter->pSrcBlock;
×
314

315
      pIter->rowIndex = idx + 1;
×
316
      *res = true;
×
317
      return TSDB_CODE_SUCCESS;
×
318
    } else {
319
      pIter->hasPrev = true;
×
320
      pIter->prevBlockTsEnd = tsEnd;
×
321
      pIter->prevIsDataNull = colDataIsNull_f(pIter->pDataCol->nullbitmap, pIter->inputEndIndex);
×
322
      pIter->pPrevData = taosMemoryMalloc(pIter->pDataCol->info.bytes);
×
323
      if (NULL == pIter->pPrevData) {
×
324
        qError("out of memory when function get input row.");
×
325
        return terrno;
×
326
      }
327
      (void)memcpy(pIter->pPrevData, colDataGetData(pIter->pDataCol, pIter->inputEndIndex),
×
328
                   pIter->pDataCol->info.bytes);
×
329
      pIter->pPrevPk = taosMemoryMalloc(pIter->pPkCol->info.bytes);
×
330
      if (NULL == pIter->pPrevPk) {
×
331
        qError("out of memory when function get input row.");
×
332
        taosMemoryFree(pIter->pPrevData);
×
333
        return terrno;
×
334
      }
335
      (void)memcpy(pIter->pPrevPk, colDataGetData(pIter->pPkCol, pIter->inputEndIndex), pIter->pPkCol->info.bytes);
×
336

337
      int32_t code = blockDataExtractBlock(pIter->pSrcBlock, pIter->inputEndIndex, 1, &pIter->pPrevRowBlock);
×
338
      *res = false;
×
339
      return code;
×
340
    }
341
  }
342
}
343

344
static void forwardToNextDiffTsRow(SFuncInputRowIter* pIter, int32_t rowIndex) {
160✔
345
  int32_t idx = rowIndex + 1;
160✔
346
  while (idx <= pIter->inputEndIndex && pIter->tsList[idx] == pIter->tsList[rowIndex]) {
362!
347
    ++idx;
202✔
348
  }
349
  pIter->rowIndex = idx;
160✔
350
}
160✔
351

352
static void setInputRowInfo(SFuncInputRow* pRow, SFuncInputRowIter* pIter, int32_t rowIndex, bool setPk) {
28,818,818✔
353
  pRow->ts = pIter->tsList[rowIndex];
28,818,818✔
354
  pRow->ts = pIter->tsList[rowIndex];
28,818,818✔
355
  pRow->isDataNull = colDataIsNull_f(pIter->pDataCol->nullbitmap, rowIndex);
28,818,818✔
356
  pRow->pData = colDataGetData(pIter->pDataCol, rowIndex);
28,818,818!
357
  pRow->pPk = setPk ? colDataGetData(pIter->pPkCol, rowIndex) : NULL;
28,818,818!
358
  pRow->block = pIter->pSrcBlock;
28,818,818✔
359
  pRow->rowIndex = rowIndex;
28,818,818✔
360
}
28,818,818✔
361

362
bool funcInputGetNextRowAscPk(SFuncInputRowIter* pIter, SFuncInputRow* pRow) {
330✔
363
  if (pIter->hasPrev) {
330!
364
    if (pIter->prevBlockTsEnd == pIter->tsList[pIter->inputEndIndex]) {
×
365
      pIter->hasPrev = true;
×
366
      return false;
×
367
    } else {
368
      int32_t idx = pIter->rowIndex;
×
369
      while (pIter->tsList[idx] == pIter->prevBlockTsEnd) {
×
370
        ++idx;
×
371
      }
372

373
      pIter->hasPrev = false;
×
374
      setInputRowInfo(pRow, pIter, idx, true);
×
375
      forwardToNextDiffTsRow(pIter, idx);
×
376
      return true;
×
377
    }
378
  } else {
379
    if (pIter->rowIndex <= pIter->inputEndIndex) {
330✔
380
      setInputRowInfo(pRow, pIter, pIter->rowIndex, true);
248✔
381

382
      TSKEY tsEnd = pIter->tsList[pIter->inputEndIndex];
248✔
383
      if (pIter->tsList[pIter->rowIndex] != tsEnd) {
248✔
384
        forwardToNextDiffTsRow(pIter, pIter->rowIndex);
160✔
385
      } else {
386
        pIter->rowIndex = pIter->inputEndIndex + 1;
88✔
387
      }
388
      return true;
248✔
389
    } else {
390
      TSKEY tsEnd = pIter->tsList[pIter->inputEndIndex];
82✔
391
      pIter->hasPrev = true;
82✔
392
      pIter->prevBlockTsEnd = tsEnd;
82✔
393
      return false;
82✔
394
    }
395
  }
396
}
397

398
bool funcInputGetNextRowNoPk(SFuncInputRowIter* pIter, SFuncInputRow* pRow) {
29,283,057✔
399
  if (pIter->rowIndex <= pIter->inputEndIndex) {
29,283,057✔
400
    setInputRowInfo(pRow, pIter, pIter->rowIndex, false);
28,818,860✔
401
    ++pIter->rowIndex;
28,821,403✔
402
    return true;
28,821,403✔
403
  } else {
404
    return false;
464,197✔
405
  }
406
}
407

408
int32_t funcInputGetNextRow(SqlFunctionCtx* pCtx, SFuncInputRow* pRow, bool* res) {
29,282,997✔
409
  SFuncInputRowIter* pIter = &pCtx->rowIter;
29,282,997✔
410
  if (pCtx->hasPrimaryKey) {
29,282,997✔
411
    if (pCtx->order == TSDB_ORDER_ASC) {
330!
412
      *res = funcInputGetNextRowAscPk(pIter, pRow);
330✔
413
      return TSDB_CODE_SUCCESS;
330✔
414
    } else {
415
      return funcInputGetNextRowDescPk(pIter, pRow, res);
×
416
    }
417
  } else {
418
    *res = funcInputGetNextRowNoPk(pIter, pRow);
29,282,667✔
419
    return TSDB_CODE_SUCCESS;
29,285,222✔
420
  }
421
  return TSDB_CODE_SUCCESS;
422
}
423

424
// This function append the selectivity to subsidiaries function context directly, without fetching data
425
// from intermediate disk based buf page
426
int32_t appendSelectivityCols(SqlFunctionCtx* pCtx, SSDataBlock* pSrcBlock, int32_t rowIndex, int32_t pos) {
26,702,162✔
427
  if (pCtx->subsidiaries.num <= 0) {
26,702,162!
428
    return TSDB_CODE_SUCCESS;
×
429
  }
430

431
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
53,404,324✔
432
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
26,702,162✔
433

434
    // get data from source col
435
    SFunctParam* pFuncParam = &pc->pExpr->base.pParam[0];
26,702,162✔
436
    int32_t      srcSlotId = pFuncParam->pCol->slotId;
26,702,162✔
437

438
    SColumnInfoData* pSrcCol = taosArrayGet(pSrcBlock->pDataBlock, srcSlotId);
26,702,162✔
439
    if (NULL == pSrcCol) {
26,702,162!
440
      return TSDB_CODE_OUT_OF_RANGE;
×
441
    }
442

443
    char* pData = colDataGetData(pSrcCol, rowIndex);
26,702,162!
444

445
    // append to dest col
446
    int32_t dstSlotId = pc->pExpr->base.resSchema.slotId;
26,702,162✔
447

448
    SColumnInfoData* pDstCol = taosArrayGet(pCtx->pDstBlock->pDataBlock, dstSlotId);
26,702,162✔
449
    if (NULL == pDstCol) {
26,702,162!
450
      return TSDB_CODE_OUT_OF_RANGE;
×
451
    }
452
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
53,404,324✔
453
      colDataSetNULL(pDstCol, pos);
20!
454
    } else {
455
      int32_t code = colDataSetVal(pDstCol, pos, pData, false);
26,702,142✔
456
      if (TSDB_CODE_SUCCESS != code) {
26,702,142!
457
        return code;
×
458
      }
459
    }
460
  }
461
  return TSDB_CODE_SUCCESS;
26,702,162✔
462
}
463

464
bool funcInputGetNextRowIndex(SInputColumnInfoData* pInput, int32_t from, bool firstOccur, int32_t* pRowIndex,
465
                              int32_t* nextFrom);
466

467
static bool firstLastTransferInfoImpl(SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst);
468

469
int32_t functionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
320,701,021✔
470
  if (pResultInfo->initialized) {
320,701,021✔
471
    return TSDB_CODE_SUCCESS;  // already initialized
12,753✔
472
  }
473

474
  if (pCtx->pOutput != NULL) {
320,688,268!
475
    (void)memset(pCtx->pOutput, 0, (size_t)pCtx->resDataInfo.bytes);
×
476
  }
477

478
  initResultRowEntry(pResultInfo, pCtx->resDataInfo.interBufSize);
320,688,268✔
479
  return TSDB_CODE_SUCCESS;
320,688,268✔
480
}
481

482
int32_t functionFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
144,944,181✔
483
  int32_t          code = TSDB_CODE_SUCCESS;
144,944,181✔
484
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
144,944,181✔
485
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
144,944,181✔
486
  if (NULL == pCol) {
144,456,251!
487
    return TSDB_CODE_OUT_OF_RANGE;
×
488
  }
489
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
144,456,251✔
490
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
144,456,251✔
491

492
  char* in = GET_ROWCELL_INTERBUF(pResInfo);
144,456,251✔
493
  code = colDataSetVal(pCol, pBlock->info.rows, in, pResInfo->isNullRes);
144,456,251✔
494

495
  return code;
145,533,299✔
496
}
497

498
int32_t firstCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
3✔
499
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
3✔
500
  SFirstLastRes*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
3✔
501
  int32_t              bytes = pDBuf->bytes;
3✔
502

503
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
3✔
504
  SFirstLastRes*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
3✔
505

506
  pDBuf->hasResult = firstLastTransferInfoImpl(pSBuf, pDBuf, true);
3✔
507

508
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
3✔
509
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
3✔
510
  return TSDB_CODE_SUCCESS;
3✔
511
}
512

513
int32_t functionFinalizeWithResultBuf(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, char* finalResult) {
39✔
514
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
39✔
515
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
39✔
516
  if (NULL == pCol) {
39!
517
    return TSDB_CODE_OUT_OF_RANGE;
×
518
  }
519
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
39✔
520
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
39✔
521

522
  char*   in = finalResult;
39✔
523
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, in, pResInfo->isNullRes);
39✔
524

525
  return code;
39✔
526
}
527

528
EFuncDataRequired countDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
94,338✔
529
  SNode* pParam = nodesListGetNode(pFunc->pParameterList, 0);
94,338✔
530
  if (QUERY_NODE_COLUMN == nodeType(pParam) && PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)pParam)->colId) {
94,337✔
531
    return FUNC_DATA_REQUIRED_NOT_LOAD;
48,774✔
532
  }
533
  return FUNC_DATA_REQUIRED_SMA_LOAD;
45,563✔
534
}
535

536
bool getCountFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
379,977✔
537
  pEnv->calcMemSize = sizeof(int64_t);
379,977✔
538
  return true;
379,977✔
539
}
540

541
static int64_t getNumOfElems(SqlFunctionCtx* pCtx) {
107,717,722✔
542
  int64_t numOfElem = 0;
107,717,722✔
543

544
  /*
545
   * 1. column data missing (schema modified) causes pInputCol->hasNull == true. pInput->colDataSMAIsSet == true;
546
   * 2. for general non-primary key columns, pInputCol->hasNull may be true or false, pInput->colDataSMAIsSet == true;
547
   * 3. for primary key column, pInputCol->hasNull always be false, pInput->colDataSMAIsSet == false;
548
   */
549
  SInputColumnInfoData* pInput = &pCtx->input;
107,717,722✔
550
  SColumnInfoData*      pInputCol = pInput->pData[0];
107,717,722✔
551
  if (1 == pInput->numOfRows && pInput->blankFill) {
107,717,722✔
552
    return 0;
396,208✔
553
  }
554
  if (pInput->colDataSMAIsSet && pInput->totalRows == pInput->numOfRows) {
107,321,514!
555
    numOfElem = pInput->numOfRows - pInput->pColumnDataAgg[0]->numOfNull;
3,504✔
556
  } else {
557
    if (pInputCol->hasNull) {
107,318,010✔
558
      for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
284,743,393✔
559
        if (colDataIsNull(pInputCol, pInput->totalRows, i, NULL)) {
518,715,698!
560
          continue;
1,934,850✔
561
        }
562
        numOfElem += 1;
257,422,999✔
563
      }
564
    } else {
565
      // when counting on the primary time stamp column and no statistics data is presented, use the size value
566
      // directly.
567
      numOfElem = pInput->numOfRows;
81,932,466✔
568
    }
569
  }
570
  return numOfElem;
107,321,514✔
571
}
572

573
/*
574
 * count function does need the finalize, if data is missing, the default value, which is 0, is used
575
 * count function does not use the pCtx->interResBuf to keep the intermediate buffer
576
 */
577
int32_t countFunction(SqlFunctionCtx* pCtx) {
107,687,362✔
578
  int64_t numOfElem = 0;
107,687,362✔
579

580
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
107,687,362✔
581
  SInputColumnInfoData* pInput = &pCtx->input;
107,687,362✔
582

583
  int32_t type = pInput->pData[0]->info.type;
107,687,362✔
584

585
  char*   buf = GET_ROWCELL_INTERBUF(pResInfo);
107,687,362✔
586
  int64_t val = *((int64_t*)buf);
107,687,362✔
587
  if (IS_NULL_TYPE(type)) {
107,687,362✔
588
    // select count(NULL) returns 0
589
    numOfElem = 1;
13,120✔
590
    val += 0;
13,120✔
591
  } else {
592
    numOfElem = getNumOfElems(pCtx);
107,674,242✔
593
    val += numOfElem;
107,416,789✔
594
  }
595
  taosSetInt64Aligned((int64_t*)buf, val);
596

597
  if (tsCountAlwaysReturnValue) {
107,429,909!
598
    pResInfo->numOfRes = 1;
107,724,603✔
599
  } else {
600
    SET_VAL(pResInfo, val, 1);
×
601
  }
602

603
  return TSDB_CODE_SUCCESS;
107,429,909✔
604
}
605

606
#ifdef BUILD_NO_CALL
607
int32_t countInvertFunction(SqlFunctionCtx* pCtx) {
608
  int64_t numOfElem = getNumOfElems(pCtx);
609

610
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
611
  char*                buf = GET_ROWCELL_INTERBUF(pResInfo);
612
  *((int64_t*)buf) -= numOfElem;
613

614
  SET_VAL(pResInfo, *((int64_t*)buf), 1);
615
  return TSDB_CODE_SUCCESS;
616
}
617
#endif
618

619
int32_t combineFunction(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
23✔
620
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
23✔
621
  char*                pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
23✔
622

623
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
23✔
624
  char*                pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
23✔
625
  *((int64_t*)pDBuf) += *((int64_t*)pSBuf);
23✔
626

627
  SET_VAL(pDResInfo, *((int64_t*)pDBuf), 1);
23!
628
  return TSDB_CODE_SUCCESS;
23✔
629
}
630

631
int32_t sumFunction(SqlFunctionCtx* pCtx) {
85,400,440✔
632
  int32_t numOfElem = 0;
85,400,440✔
633

634
  // Only the pre-computing information loaded and actual data does not loaded
635
  SInputColumnInfoData* pInput = &pCtx->input;
85,400,440✔
636
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
85,400,440✔
637
  int32_t               type = pInput->pData[0]->info.type;
85,400,440✔
638
  pCtx->inputType = type;
85,400,440✔
639

640
  void* pSumRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
85,400,440✔
641
  SUM_RES_SET_TYPE(pSumRes, pCtx->inputType, type);
85,400,440!
642

643
  if (IS_NULL_TYPE(type)) {
85,400,440✔
644
    numOfElem = 0;
209✔
645
    goto _sum_over;
209✔
646
  }
647

648
  if (pInput->colDataSMAIsSet) {
85,400,231✔
649
    numOfElem = pInput->numOfRows - pAgg->numOfNull;
685✔
650

651
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
685!
652
      SUM_RES_INC_ISUM(pSumRes, pAgg->sum);
630✔
653
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
55!
654
      SUM_RES_INC_USUM(pSumRes, pAgg->sum);
×
655
    } else if (IS_FLOAT_TYPE(type)) {
55!
656
      SUM_RES_INC_DSUM(pSumRes, GET_DOUBLE_VAL((const char*)&(pAgg->sum)));
×
657
    } else if (IS_DECIMAL_TYPE(type)) {
55!
658
      SUM_RES_SET_TYPE(pSumRes, pCtx->inputType, TSDB_DATA_TYPE_DECIMAL);
55!
659
      const SDecimalOps* pOps = getDecimalOps(TSDB_DATA_TYPE_DECIMAL);
55✔
660
      if (pAgg->overflow || decimal128AddCheckOverflow((Decimal*)&SUM_RES_GET_DECIMAL_SUM(pSumRes),
100!
661
                                                       &pAgg->decimal128Sum, DECIMAL_WORD_NUM(Decimal))) {
45✔
662
        return TSDB_CODE_DECIMAL_OVERFLOW;
10✔
663
      }
664
      pOps->add(&SUM_RES_GET_DECIMAL_SUM(pSumRes), &pAgg->decimal128Sum, DECIMAL_WORD_NUM(Decimal));
45✔
665
    }
666
  } else {  // computing based on the true data block
667
    SColumnInfoData* pCol = pInput->pData[0];
85,399,546✔
668

669
    int32_t start = pInput->startRowIndex;
85,399,546✔
670
    int32_t numOfRows = pInput->numOfRows;
85,399,546✔
671

672
    if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
85,399,546!
673
      if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
84,552,720!
674
        LIST_ADD_N(SUM_RES_GET_ISUM(pSumRes), pCol, start, numOfRows, int8_t, numOfElem);
1,391,736✔
675
      } else if (type == TSDB_DATA_TYPE_SMALLINT) {
84,222,093✔
676
        LIST_ADD_N(SUM_RES_GET_ISUM(pSumRes), pCol, start, numOfRows, int16_t, numOfElem);
408,894✔
677
      } else if (type == TSDB_DATA_TYPE_INT) {
84,174,462✔
678
        LIST_ADD_N(SUM_RES_GET_ISUM(pSumRes), pCol, start, numOfRows, int32_t, numOfElem);
385,473,124✔
679
      } else if (type == TSDB_DATA_TYPE_BIGINT) {
18,502,906✔
680
        LIST_ADD_N(SUM_RES_GET_ISUM(pSumRes), pCol, start, numOfRows, int64_t, numOfElem);
70,152,621✔
681
      }
682
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
846,826✔
683
      if (type == TSDB_DATA_TYPE_UTINYINT) {
106✔
684
        LIST_ADD_N(SUM_RES_GET_USUM(pSumRes), pCol, start, numOfRows, uint8_t, numOfElem);
50,015!
685
      } else if (type == TSDB_DATA_TYPE_USMALLINT) {
91✔
686
        LIST_ADD_N(SUM_RES_GET_USUM(pSumRes), pCol, start, numOfRows, uint16_t, numOfElem);
50,023✔
687
      } else if (type == TSDB_DATA_TYPE_UINT) {
75✔
688
        LIST_ADD_N(SUM_RES_GET_USUM(pSumRes), pCol, start, numOfRows, uint32_t, numOfElem);
50,015!
689
      } else if (type == TSDB_DATA_TYPE_UBIGINT) {
60!
690
        LIST_ADD_N(SUM_RES_GET_USUM(pSumRes), pCol, start, numOfRows, uint64_t, numOfElem);
50,600✔
691
      }
692
    } else if (type == TSDB_DATA_TYPE_DOUBLE) {
846,720✔
693
      LIST_ADD_N(SUM_RES_GET_DSUM(pSumRes), pCol, start, numOfRows, double, numOfElem);
2,152,698✔
694
    } else if (type == TSDB_DATA_TYPE_FLOAT) {
761,682✔
695
      LIST_ADD_N(SUM_RES_GET_DSUM(pSumRes), pCol, start, numOfRows, float, numOfElem);
1,702,193✔
696
    } else if (IS_DECIMAL_TYPE(type)) {
3,181✔
697
      SUM_RES_SET_TYPE(pSumRes, pCtx->inputType, TSDB_DATA_TYPE_DECIMAL);
3,165!
698
      int32_t overflow = false;
3,165✔
699
      if (TSDB_DATA_TYPE_DECIMAL64 == type) {
3,165✔
700
        LIST_ADD_DECIMAL_N(&SUM_RES_GET_DECIMAL_SUM(pSumRes), pCol, start, numOfRows, Decimal64, numOfElem);
40,040!
701
      } else if (TSDB_DATA_TYPE_DECIMAL == type) {
3,125!
702
        LIST_ADD_DECIMAL_N(&SUM_RES_GET_DECIMAL_SUM(pSumRes), pCol, start, numOfRows, Decimal128, numOfElem);
133,670!
703
      }
704
      if (overflow) return TSDB_CODE_DECIMAL_OVERFLOW;
3,165!
705
    }
706
  }
707

708
  // check for overflow
709
  if (IS_FLOAT_TYPE(type) && (isinf(SUM_RES_GET_DSUM(pSumRes)) || isnan(SUM_RES_GET_DSUM(pSumRes)))) {
85,400,221!
710
    numOfElem = 0;
×
711
  }
712

713
_sum_over:
85,874,192✔
714
  if (numOfElem == 0) {
85,400,430✔
715
    if (tsCountAlwaysReturnValue && pCtx->pExpr->pExpr->_function.pFunctNode->hasOriginalFunc &&
97,885✔
716
        fmIsCountLikeFunc(pCtx->pExpr->pExpr->_function.pFunctNode->originalFuncId)) {
11,460✔
717
      numOfElem = 1;
19✔
718
    }
719
  }
720
  // data in the check operation are all null, not output
721
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
85,400,430✔
722
  return TSDB_CODE_SUCCESS;
85,400,430✔
723
}
724

725
#ifdef BUILD_NO_CALL
726
int32_t sumInvertFunction(SqlFunctionCtx* pCtx) {
727
  int32_t numOfElem = 0;
728

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

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

736
  if (pInput->colDataSMAIsSet) {
737
    numOfElem = pInput->numOfRows - pAgg->numOfNull;
738

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

749
    int32_t start = pInput->startRowIndex;
750
    int32_t numOfRows = pInput->numOfRows;
751

752
    if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
753
      if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
754
        LIST_SUB_N(pSumRes->isum, pCol, start, numOfRows, int8_t, numOfElem);
755
      } else if (type == TSDB_DATA_TYPE_SMALLINT) {
756
        LIST_SUB_N(pSumRes->isum, pCol, start, numOfRows, int16_t, numOfElem);
757
      } else if (type == TSDB_DATA_TYPE_INT) {
758
        LIST_SUB_N(pSumRes->isum, pCol, start, numOfRows, int32_t, numOfElem);
759
      } else if (type == TSDB_DATA_TYPE_BIGINT) {
760
        LIST_SUB_N(pSumRes->isum, pCol, start, numOfRows, int64_t, numOfElem);
761
      }
762
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
763
      if (type == TSDB_DATA_TYPE_UTINYINT) {
764
        LIST_SUB_N(pSumRes->usum, pCol, start, numOfRows, uint8_t, numOfElem);
765
      } else if (type == TSDB_DATA_TYPE_USMALLINT) {
766
        LIST_SUB_N(pSumRes->usum, pCol, start, numOfRows, uint16_t, numOfElem);
767
      } else if (type == TSDB_DATA_TYPE_UINT) {
768
        LIST_SUB_N(pSumRes->usum, pCol, start, numOfRows, uint32_t, numOfElem);
769
      } else if (type == TSDB_DATA_TYPE_UBIGINT) {
770
        LIST_SUB_N(pSumRes->usum, pCol, start, numOfRows, uint64_t, numOfElem);
771
      }
772
    } else if (type == TSDB_DATA_TYPE_DOUBLE) {
773
      LIST_SUB_N(pSumRes->dsum, pCol, start, numOfRows, double, numOfElem);
774
    } else if (type == TSDB_DATA_TYPE_FLOAT) {
775
      LIST_SUB_N(pSumRes->dsum, pCol, start, numOfRows, float, numOfElem);
776
    }
777
  }
778

779
  // data in the check operation are all null, not output
780
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
781
  return TSDB_CODE_SUCCESS;
782
}
783
#endif
784

785
int32_t sumCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
40✔
786
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
40✔
787
  void*                pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
40✔
788
  int16_t              type = SUM_RES_GET_TYPE(pDBuf, pDestCtx->inputType);
40!
789

790
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
40✔
791
  void*                pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
40✔
792
  type = (type == TSDB_DATA_TYPE_NULL) ? SUM_RES_GET_TYPE(pSBuf, pDestCtx->inputType) : type;
40!
793

794
  if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
40!
795
    SUM_RES_INC_ISUM(pDBuf, SUM_RES_GET_ISUM(pSBuf));
35✔
796
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
5!
797
    SUM_RES_INC_USUM(pDBuf, SUM_RES_GET_USUM(pSBuf));
×
798
  } else if (IS_DECIMAL_TYPE(type)) {
10!
799
    bool overflow = false;
5✔
800
    SUM_RES_INC_DECIMAL_SUM(pDBuf, &SUM_RES_GET_DECIMAL_SUM(pSBuf), type);
5!
801
  } else if (type == TSDB_DATA_TYPE_DOUBLE || type == TSDB_DATA_TYPE_FLOAT) {
×
802
    SUM_RES_INC_DSUM(pDBuf, SUM_RES_GET_DSUM(pSBuf));
×
803
  }
804
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
40✔
805
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
40✔
806
  return TSDB_CODE_SUCCESS;
40✔
807
}
808

809
bool getSumFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
158,298✔
810
  pEnv->calcMemSize = SUM_RES_GET_SIZE(pFunc->node.resType.type);
158,298!
811
  return true;
158,298✔
812
}
813

814
static bool funcNotSupportStringSma(SFunctionNode* pFunc) {
148,224✔
815
  SNode* pParam;
816
  switch (pFunc->funcType) {
148,224!
817
    case FUNCTION_TYPE_MAX:
148,224✔
818
    case FUNCTION_TYPE_MIN:
819
    case FUNCTION_TYPE_SUM:
820
    case FUNCTION_TYPE_AVG:
821
    case FUNCTION_TYPE_AVG_PARTIAL:
822
    case FUNCTION_TYPE_PERCENTILE:
823
    case FUNCTION_TYPE_SPREAD:
824
    case FUNCTION_TYPE_SPREAD_PARTIAL:
825
    case FUNCTION_TYPE_SPREAD_MERGE:
826
    case FUNCTION_TYPE_TWA:
827
    case FUNCTION_TYPE_ELAPSED:
828
      pParam = nodesListGetNode(pFunc->pParameterList, 0);
148,224✔
829
      if (pParam && nodesIsExprNode(pParam) && (IS_VAR_DATA_TYPE(((SExprNode*)pParam)->resType.type))) {
148,224!
830
        return true;
86✔
831
      }
832
      break;
148,138✔
833
    default:
×
834
      break;
×
835
  }
836
  return false;
148,138✔
837
}
838

839
EFuncDataRequired statisDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
148,224✔
840
  if (funcNotSupportStringSma(pFunc)) {
148,224✔
841
    return FUNC_DATA_REQUIRED_DATA_LOAD;
86✔
842
  }
843
  return FUNC_DATA_REQUIRED_SMA_LOAD;
148,138✔
844
}
845

846
int32_t minmaxFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
32,149,389✔
847
  if (pResultInfo->initialized) {
32,149,389!
848
    return TSDB_CODE_SUCCESS;
×
849
  }
850
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
32,149,389!
851
    return TSDB_CODE_FUNC_SETUP_ERROR;  // not initialized since it has been initialized
×
852
  }
853

854
  SMinmaxResInfo* buf = GET_ROWCELL_INTERBUF(pResultInfo);
32,153,318✔
855
  buf->assign = false;
32,153,318✔
856
  buf->tuplePos.pageId = -1;
32,153,318✔
857

858
  buf->nullTupleSaved = false;
32,153,318✔
859
  buf->nullTuplePos.pageId = -1;
32,153,318✔
860
  buf->str = NULL;
32,153,318✔
861
  return TSDB_CODE_SUCCESS;
32,153,318✔
862
}
863

864
bool getMinmaxFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
198,298✔
865
  COMPILE_TIME_ASSERT(sizeof(SMinmaxResInfo) == sizeof(SOldMinMaxResInfo));
866
  pEnv->calcMemSize = sizeof(SMinmaxResInfo);
198,298✔
867
  return true;
198,298✔
868
}
869

870
int32_t minFunction(SqlFunctionCtx* pCtx) {
17,547,724✔
871
  int32_t numOfElems = 0;
17,547,724✔
872
  int32_t code = doMinMaxHelper(pCtx, 1, &numOfElems);
17,547,724✔
873
  if (code != TSDB_CODE_SUCCESS) {
17,642,641!
874
    return code;
×
875
  }
876
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
17,642,641✔
877
  return TSDB_CODE_SUCCESS;
17,642,641✔
878
}
879

880
int32_t maxFunction(SqlFunctionCtx* pCtx) {
17,482,445✔
881
  int32_t numOfElems = 0;
17,482,445✔
882
  int32_t code = doMinMaxHelper(pCtx, 0, &numOfElems);
17,482,445✔
883
  if (code != TSDB_CODE_SUCCESS) {
17,566,885!
884
    return code;
×
885
  }
886
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
17,566,885✔
887
  return TSDB_CODE_SUCCESS;
17,566,885✔
888
}
889

890
static int32_t setNullSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t rowIndex);
891
static int32_t setSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, const STuplePos* pTuplePos,
892
                                   int32_t rowIndex);
893

894
int32_t minmaxFunctionFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
30,910,638✔
895
  int32_t code = TSDB_CODE_SUCCESS;
30,910,638✔
896

897
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
30,910,638✔
898
  SMinmaxResInfo*      pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
30,910,638✔
899

900
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
30,910,638✔
901
  int32_t currentRow = pBlock->info.rows;
30,910,638✔
902

903
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
30,910,638✔
904
  if (NULL == pCol) {
30,922,781!
905
    return TSDB_CODE_OUT_OF_RANGE;
×
906
  }
907
  pEntryInfo->isNullRes = (pEntryInfo->numOfRes == 0) ? 1 : 0;
30,922,781✔
908

909
  // NOTE: do nothing change it, for performance issue
910
  if (!pEntryInfo->isNullRes) {
30,922,781✔
911
    switch (pCol->info.type) {
23,546,716!
912
      case TSDB_DATA_TYPE_UBIGINT:
7,856,976✔
913
      case TSDB_DATA_TYPE_BIGINT:
914
        ((int64_t*)pCol->pData)[currentRow] = pRes->v;
7,856,976✔
915
        break;
7,856,976✔
916
      case TSDB_DATA_TYPE_UINT:
15,292,374✔
917
      case TSDB_DATA_TYPE_INT:
918
        colDataSetInt32(pCol, currentRow, (int32_t*)&pRes->v);
15,292,374✔
919
        break;
15,292,374✔
920
      case TSDB_DATA_TYPE_USMALLINT:
209,500✔
921
      case TSDB_DATA_TYPE_SMALLINT:
922
        colDataSetInt16(pCol, currentRow, (int16_t*)&pRes->v);
209,500✔
923
        break;
209,500✔
924
      case TSDB_DATA_TYPE_BOOL:
196,908✔
925
      case TSDB_DATA_TYPE_UTINYINT:
926
      case TSDB_DATA_TYPE_TINYINT:
927
        colDataSetInt8(pCol, currentRow, (int8_t*)&pRes->v);
196,908✔
928
        break;
196,908✔
929
      case TSDB_DATA_TYPE_DOUBLE:
4,884✔
930
        colDataSetDouble(pCol, currentRow, (double*)&pRes->v);
4,884✔
931
        break;
4,884✔
932
      case TSDB_DATA_TYPE_FLOAT: {
2,608✔
933
        float v = GET_FLOAT_VAL(&pRes->v);
2,608✔
934
        colDataSetFloat(pCol, currentRow, &v);
2,608✔
935
        break;
2,608✔
936
      }
937
      case TSDB_DATA_TYPE_VARBINARY:
703✔
938
      case TSDB_DATA_TYPE_VARCHAR:
939
      case TSDB_DATA_TYPE_NCHAR: {
940
        code = colDataSetVal(pCol, currentRow, pRes->str, false);
703✔
941
        if (TSDB_CODE_SUCCESS != code) {
704!
942
          return code;
×
943
        }
944
        break;
704✔
945
      }
946
      case TSDB_DATA_TYPE_DECIMAL64:
70✔
947
        code = colDataSetVal(pCol, currentRow, (const char*)&pRes->v, false);
70✔
948
        break;
70✔
949
      case TSDB_DATA_TYPE_DECIMAL:
1,050✔
950
        code = colDataSetVal(pCol, currentRow, (void*)pRes->dec, false);
1,050✔
951
        break;
1,050✔
952
    }
953
  } else {
954
    colDataSetNULL(pCol, currentRow);
7,376,065!
955
  }
956

957
  if (IS_VAR_DATA_TYPE(pCol->info.type)) taosMemoryFreeClear(pRes->str);
30,922,782!
958
  if (pCtx->subsidiaries.num > 0) {
30,922,782✔
959
    if (pEntryInfo->numOfRes > 0) {
31,414✔
960
      code = setSelectivityValue(pCtx, pBlock, &pRes->tuplePos, currentRow);
28,721✔
961
    } else {
962
      code = setNullSelectivityValue(pCtx, pBlock, currentRow);
2,693✔
963
    }
964
  }
965

966
  return code;
30,927,937✔
967
}
968

969
int32_t setNullSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t rowIndex) {
2,419,749✔
970
  if (pCtx->subsidiaries.num <= 0) {
2,419,749✔
971
    return TSDB_CODE_SUCCESS;
2,417,085✔
972
  }
973

974
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
7,275✔
975
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
4,611✔
976
    int32_t         dstSlotId = pc->pExpr->base.resSchema.slotId;
4,611✔
977

978
    SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId);
4,611✔
979
    if (NULL == pDstCol) {
4,611!
980
      return terrno;
×
981
    }
982
    colDataSetNULL(pDstCol, rowIndex);
4,611✔
983
  }
984

985
  return TSDB_CODE_SUCCESS;
2,664✔
986
}
987

988
int32_t setSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, const STuplePos* pTuplePos, int32_t rowIndex) {
29,716,532✔
989
  if (pCtx->subsidiaries.num <= 0) {
29,716,532✔
990
    return TSDB_CODE_SUCCESS;
29,624,817✔
991
  }
992

993
  if ((pCtx->saveHandle.pBuf != NULL && pTuplePos->pageId != -1) ||
91,715!
994
      (pCtx->saveHandle.pState && pTuplePos->streamTupleKey.ts > 0)) {
22,190!
995
    int32_t numOfCols = pCtx->subsidiaries.num;
91,710✔
996
    char*   p = NULL;
91,710✔
997
    int32_t code = loadTupleData(pCtx, pTuplePos, &p);
91,710✔
998
    if (p == NULL || TSDB_CODE_SUCCESS != code) {
93,223!
999
      qError("Load tuple data failed since %s, groupId:%" PRIu64 ", ts:%" PRId64, terrstr(),
×
1000
             pTuplePos->streamTupleKey.groupId, pTuplePos->streamTupleKey.ts);
1001
      return TSDB_CODE_NOT_FOUND;
×
1002
    }
1003

1004
    bool* nullList = (bool*)p;
93,232✔
1005
    char* pStart = (char*)(nullList + numOfCols * sizeof(bool));
93,232✔
1006

1007
    // todo set the offset value to optimize the performance.
1008
    for (int32_t j = 0; j < numOfCols; ++j) {
201,381✔
1009
      SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
108,157✔
1010
      int32_t         dstSlotId = pc->pExpr->base.resSchema.slotId;
108,157✔
1011

1012
      SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId);
108,157✔
1013
      if (NULL == pDstCol) {
108,153!
1014
        return terrno;
×
1015
      }
1016
      if (nullList[j]) {
108,155✔
1017
        colDataSetNULL(pDstCol, rowIndex);
176!
1018
      } else {
1019
        code = colDataSetValOrCover(pDstCol, rowIndex, pStart, false);
107,979✔
1020
        if (TSDB_CODE_SUCCESS != code) {
107,973!
1021
          return code;
×
1022
        }
1023
      }
1024
      pStart += pDstCol->info.bytes;
108,149✔
1025
    }
1026
  }
1027

1028
  return TSDB_CODE_SUCCESS;
93,229✔
1029
}
1030

1031
// This function append the selectivity to subsidiaries function context directly, without fetching data
1032
// from intermediate disk based buf page
1033
int32_t appendSelectivityValue(SqlFunctionCtx* pCtx, int32_t rowIndex, int32_t pos) {
976✔
1034
  if (pCtx->subsidiaries.num <= 0) {
976!
1035
    return TSDB_CODE_SUCCESS;
×
1036
  }
1037

1038
  int32_t code = TSDB_CODE_SUCCESS;
976✔
1039
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
3,542✔
1040
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
2,566✔
1041

1042
    // get data from source col
1043
    SFunctParam* pFuncParam = &pc->pExpr->base.pParam[0];
2,566✔
1044
    int32_t      srcSlotId = pFuncParam->pCol->slotId;
2,566✔
1045

1046
    SColumnInfoData* pSrcCol = taosArrayGet(pCtx->pSrcBlock->pDataBlock, srcSlotId);
2,566✔
1047
    if (NULL == pSrcCol) {
2,566!
1048
      return TSDB_CODE_OUT_OF_RANGE;
×
1049
    }
1050

1051
    char* pData = colDataGetData(pSrcCol, rowIndex);
2,566!
1052

1053
    // append to dest col
1054
    int32_t dstSlotId = pc->pExpr->base.resSchema.slotId;
2,566✔
1055

1056
    SColumnInfoData* pDstCol = taosArrayGet(pCtx->pDstBlock->pDataBlock, dstSlotId);
2,566✔
1057
    if (NULL == pDstCol) {
2,566!
1058
      return TSDB_CODE_OUT_OF_RANGE;
×
1059
    }
1060

1061
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
5,132✔
1062
      colDataSetNULL(pDstCol, pos);
392✔
1063
    } else {
1064
      code = colDataSetVal(pDstCol, pos, pData, false);
2,174✔
1065
      if (TSDB_CODE_SUCCESS != code) {
2,174!
1066
        return code;
×
1067
      }
1068
    }
1069
  }
1070
  return code;
976✔
1071
}
1072

1073
void replaceTupleData(STuplePos* pDestPos, STuplePos* pSourcePos) { *pDestPos = *pSourcePos; }
32✔
1074

1075
#define COMPARE_MINMAX_DATA(type) (((*(type*)&pDBuf->v) < (*(type*)&pSBuf->v)) ^ isMinFunc)
1076
int32_t minMaxCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx, int32_t isMinFunc) {
71✔
1077
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
71✔
1078
  SMinmaxResInfo*      pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
71✔
1079

1080
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
71✔
1081
  SMinmaxResInfo*      pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
71✔
1082
  int16_t              type = pDBuf->type == TSDB_DATA_TYPE_NULL ? pSBuf->type : pDBuf->type;
71✔
1083

1084
  switch (type) {
71!
1085
    case TSDB_DATA_TYPE_UBIGINT:
×
1086
    case TSDB_DATA_TYPE_BIGINT:
1087
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(int64_t) || !pDBuf->assign)) {
×
1088
        pDBuf->v = pSBuf->v;
×
1089
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1090
        pDBuf->assign = true;
×
1091
      }
1092
      break;
×
1093
    case TSDB_DATA_TYPE_UINT:
48✔
1094
    case TSDB_DATA_TYPE_INT:
1095
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(int32_t) || !pDBuf->assign)) {
48!
1096
        pDBuf->v = pSBuf->v;
26✔
1097
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
26✔
1098
        pDBuf->assign = true;
26✔
1099
      }
1100
      break;
48✔
1101
    case TSDB_DATA_TYPE_USMALLINT:
×
1102
    case TSDB_DATA_TYPE_SMALLINT:
1103
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(int16_t) || !pDBuf->assign)) {
×
1104
        pDBuf->v = pSBuf->v;
×
1105
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1106
        pDBuf->assign = true;
×
1107
      }
1108
      break;
×
1109
    case TSDB_DATA_TYPE_BOOL:
×
1110
    case TSDB_DATA_TYPE_UTINYINT:
1111
    case TSDB_DATA_TYPE_TINYINT:
1112
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(int8_t) || !pDBuf->assign)) {
×
1113
        pDBuf->v = pSBuf->v;
×
1114
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1115
        pDBuf->assign = true;
×
1116
      }
1117
      break;
×
1118
    case TSDB_DATA_TYPE_DOUBLE:
3✔
1119
    case TSDB_DATA_TYPE_FLOAT: {
1120
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(double) || !pDBuf->assign)) {
3!
1121
        pDBuf->v = pSBuf->v;
1✔
1122
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
1✔
1123
        pDBuf->assign = true;
1✔
1124
      }
1125
      break;
3✔
1126
    }
1127
    case TSDB_DATA_TYPE_DECIMAL64: {
10✔
1128
      const SDecimalOps* pOps = getDecimalOps(type);
10✔
1129
      if (pSBuf->assign && ((pOps->lt(&pDBuf->v, &pSBuf->v, DECIMAL_WORD_NUM(Decimal64)) ^ isMinFunc) || !pDBuf->assign)) {
10!
1130
        pDBuf->v = pSBuf->v;
3✔
1131
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
3✔
1132
        pDBuf->assign = true;
3✔
1133
      }
1134
    } break;
10✔
1135
    case TSDB_DATA_TYPE_DECIMAL: {
10✔
1136
      const SDecimalOps* pOps = getDecimalOps(type);
10✔
1137
      if (pSBuf->assign && (pOps->lt(pDBuf->dec, pSBuf->dec, DECIMAL_WORD_NUM(Decimal)) ^ isMinFunc) || !pDBuf->assign) {
10!
1138
        memcpy(pDBuf->dec, pSBuf->dec, DECIMAL128_BYTES);
2✔
1139
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
2✔
1140
        pDBuf->assign = true;
2✔
1141
      }
1142
    } break;
10✔
1143
    default:
×
1144
      if (pSBuf->assign && (strcmp(pDBuf->str, pSBuf->str) || !pDBuf->assign)) {
×
1145
        memcpy(pDBuf->str, pSBuf->str, varDataLen(pSBuf->str));
×
1146
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1147
        pDBuf->assign = true;
×
1148
      }
1149
      break;
×
1150
  }
1151
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
71✔
1152
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
71✔
1153
  return TSDB_CODE_SUCCESS;
71✔
1154
}
1155

1156
int32_t minCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
21✔
1157
  return minMaxCombine(pDestCtx, pSourceCtx, 1);
21✔
1158
}
1159
int32_t maxCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
50✔
1160
  return minMaxCombine(pDestCtx, pSourceCtx, 0);
50✔
1161
}
1162

1163
int32_t getStdInfoSize() { return (int32_t)sizeof(SStdRes); }
9,520✔
1164

1165
bool getStdFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
56,364✔
1166
  pEnv->calcMemSize = sizeof(SStdRes);
56,364✔
1167
  return true;
56,364✔
1168
}
1169

1170
int32_t stdFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
330,232✔
1171
  if (pResultInfo->initialized) {
330,232!
1172
    return TSDB_CODE_SUCCESS;
×
1173
  }
1174
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
330,232!
1175
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1176
  }
1177

1178
  SStdRes* pRes = GET_ROWCELL_INTERBUF(pResultInfo);
330,257✔
1179
  (void)memset(pRes, 0, sizeof(SStdRes));
330,257✔
1180
  return TSDB_CODE_SUCCESS;
330,257✔
1181
}
1182

1183
int32_t stdFunction(SqlFunctionCtx* pCtx) {
335,833✔
1184
  int32_t numOfElem = 0;
335,833✔
1185

1186
  // Only the pre-computing information loaded and actual data does not loaded
1187
  SInputColumnInfoData* pInput = &pCtx->input;
335,833✔
1188
  int32_t               type = pInput->pData[0]->info.type;
335,833✔
1189

1190
  SStdRes* pStdRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
335,833✔
1191
  pStdRes->type = type;
335,833✔
1192

1193
  // computing based on the true data block
1194
  SColumnInfoData* pCol = pInput->pData[0];
335,833✔
1195

1196
  int32_t start = pInput->startRowIndex;
335,833✔
1197
  int32_t numOfRows = pInput->numOfRows;
335,833✔
1198

1199
  if (IS_NULL_TYPE(type)) {
335,833✔
1200
    numOfElem = 0;
109✔
1201
    goto _stddev_over;
109✔
1202
  }
1203

1204
  switch (type) {
335,724!
1205
    case TSDB_DATA_TYPE_TINYINT: {
19,732✔
1206
      int8_t* plist = (int8_t*)pCol->pData;
19,732✔
1207
      for (int32_t i = start; i < numOfRows + start; ++i) {
150,229✔
1208
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
130,497✔
1209
          continue;
25,411✔
1210
        }
1211

1212
        numOfElem += 1;
105,086✔
1213
        pStdRes->count += 1;
105,086✔
1214
        pStdRes->isum += plist[i];
105,086✔
1215
        pStdRes->quadraticISum += plist[i] * plist[i];
105,086✔
1216
      }
1217

1218
      break;
19,732✔
1219
    }
1220

1221
    case TSDB_DATA_TYPE_SMALLINT: {
208,897✔
1222
      int16_t* plist = (int16_t*)pCol->pData;
208,897✔
1223
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
795,663✔
1224
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
586,766✔
1225
          continue;
114,924✔
1226
        }
1227

1228
        numOfElem += 1;
471,842✔
1229
        pStdRes->count += 1;
471,842✔
1230
        pStdRes->isum += plist[i];
471,842✔
1231
        pStdRes->quadraticISum += plist[i] * plist[i];
471,842✔
1232
      }
1233
      break;
208,897✔
1234
    }
1235

1236
    case TSDB_DATA_TYPE_INT: {
15,135✔
1237
      int32_t* plist = (int32_t*)pCol->pData;
15,135✔
1238
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
156,292✔
1239
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
141,157✔
1240
          continue;
89,939✔
1241
        }
1242

1243
        numOfElem += 1;
51,218✔
1244
        pStdRes->count += 1;
51,218✔
1245
        pStdRes->isum += plist[i];
51,218✔
1246
        pStdRes->quadraticISum += plist[i] * plist[i];
51,218✔
1247
      }
1248

1249
      break;
15,135✔
1250
    }
1251

1252
    case TSDB_DATA_TYPE_BIGINT: {
24,310✔
1253
      int64_t* plist = (int64_t*)pCol->pData;
24,310✔
1254
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
739,621✔
1255
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
715,311✔
1256
          continue;
31,492✔
1257
        }
1258

1259
        numOfElem += 1;
683,819✔
1260
        pStdRes->count += 1;
683,819✔
1261
        pStdRes->isum += plist[i];
683,819✔
1262
        pStdRes->quadraticISum += plist[i] * plist[i];
683,819✔
1263
      }
1264
      break;
24,310✔
1265
    }
1266

1267
    case TSDB_DATA_TYPE_UTINYINT: {
1✔
1268
      uint8_t* plist = (uint8_t*)pCol->pData;
1✔
1269
      for (int32_t i = start; i < numOfRows + start; ++i) {
8✔
1270
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
7!
1271
          continue;
4✔
1272
        }
1273

1274
        numOfElem += 1;
3✔
1275
        pStdRes->count += 1;
3✔
1276
        pStdRes->usum += plist[i];
3✔
1277
        pStdRes->quadraticUSum += plist[i] * plist[i];
3✔
1278
      }
1279

1280
      break;
1✔
1281
    }
1282

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

1290
        numOfElem += 1;
×
1291
        pStdRes->count += 1;
×
1292
        pStdRes->usum += plist[i];
×
1293
        pStdRes->quadraticUSum += plist[i] * plist[i];
×
1294
      }
1295
      break;
×
1296
    }
1297

1298
    case TSDB_DATA_TYPE_UINT: {
1✔
1299
      uint32_t* plist = (uint32_t*)pCol->pData;
1✔
1300
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
6✔
1301
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
5!
1302
          continue;
×
1303
        }
1304

1305
        numOfElem += 1;
5✔
1306
        pStdRes->count += 1;
5✔
1307
        pStdRes->usum += plist[i];
5✔
1308
        pStdRes->quadraticUSum += plist[i] * plist[i];
5✔
1309
      }
1310

1311
      break;
1✔
1312
    }
1313

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

1321
        numOfElem += 1;
×
1322
        pStdRes->count += 1;
×
1323
        pStdRes->usum += plist[i];
×
1324
        pStdRes->quadraticUSum += plist[i] * plist[i];
×
1325
      }
1326
      break;
×
1327
    }
1328

1329
    case TSDB_DATA_TYPE_FLOAT: {
16,992✔
1330
      float* plist = (float*)pCol->pData;
16,992✔
1331
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
688,176✔
1332
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
671,184✔
1333
          continue;
101,067✔
1334
        }
1335

1336
        numOfElem += 1;
570,117✔
1337
        pStdRes->count += 1;
570,117✔
1338
        pStdRes->dsum += plist[i];
570,117✔
1339
        pStdRes->quadraticDSum += plist[i] * plist[i];
570,117✔
1340
      }
1341
      break;
16,992✔
1342
    }
1343

1344
    case TSDB_DATA_TYPE_DOUBLE: {
50,629✔
1345
      double* plist = (double*)pCol->pData;
50,629✔
1346
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
1,956,089✔
1347
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
1,905,460✔
1348
          continue;
892,887✔
1349
        }
1350

1351
        numOfElem += 1;
1,012,573✔
1352
        pStdRes->count += 1;
1,012,573✔
1353
        pStdRes->dsum += plist[i];
1,012,573✔
1354
        pStdRes->quadraticDSum += plist[i] * plist[i];
1,012,573✔
1355
      }
1356
      break;
50,629✔
1357
    }
1358

1359
    default:
27✔
1360
      break;
27✔
1361
  }
1362

1363
_stddev_over:
335,833✔
1364
  // data in the check operation are all null, not output
1365
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
335,833✔
1366
  return TSDB_CODE_SUCCESS;
335,833✔
1367
}
1368

1369
static void stdTransferInfo(SStdRes* pInput, SStdRes* pOutput) {
7,998✔
1370
  if (IS_NULL_TYPE(pInput->type)) {
7,998✔
1371
    return;
80✔
1372
  }
1373
  pOutput->type = pInput->type;
7,918✔
1374
  if (IS_SIGNED_NUMERIC_TYPE(pOutput->type)) {
7,918!
1375
    pOutput->quadraticISum += pInput->quadraticISum;
7,843✔
1376
    pOutput->isum += pInput->isum;
7,843✔
1377
  } else if (IS_UNSIGNED_NUMERIC_TYPE(pOutput->type)) {
75!
1378
    pOutput->quadraticUSum += pInput->quadraticUSum;
1✔
1379
    pOutput->usum += pInput->usum;
1✔
1380
  } else {
1381
    pOutput->quadraticDSum += pInput->quadraticDSum;
74✔
1382
    pOutput->dsum += pInput->dsum;
74✔
1383
  }
1384

1385
  pOutput->count += pInput->count;
7,918✔
1386
}
1387

1388
int32_t stdFunctionMerge(SqlFunctionCtx* pCtx) {
7,939✔
1389
  SInputColumnInfoData* pInput = &pCtx->input;
7,939✔
1390
  SColumnInfoData*      pCol = pInput->pData[0];
7,939✔
1391

1392
  if (IS_NULL_TYPE(pCol->info.type)) {
7,939!
1393
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
1394
    return TSDB_CODE_SUCCESS;
×
1395
  }
1396

1397
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
7,939!
1398
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
1399
  }
1400

1401
  SStdRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
7,939✔
1402

1403
  for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
15,934✔
1404
    if (colDataIsNull_s(pCol, i)) continue;
15,990!
1405
    char*    data = colDataGetData(pCol, i);
7,995!
1406
    SStdRes* pInputInfo = (SStdRes*)varDataVal(data);
7,995✔
1407
    stdTransferInfo(pInputInfo, pInfo);
7,995✔
1408
  }
1409

1410
  SET_VAL(GET_RES_INFO(pCtx), 1, 1);
7,939✔
1411
  return TSDB_CODE_SUCCESS;
7,939✔
1412
}
1413

1414
#ifdef BUILD_NO_CALL
1415
int32_t stdInvertFunction(SqlFunctionCtx* pCtx) {
1416
  int32_t numOfElem = 0;
1417

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

1422
  SStdRes* pStdRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1423

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

1427
  int32_t start = pInput->startRowIndex;
1428
  int32_t numOfRows = pInput->numOfRows;
1429

1430
  switch (type) {
1431
    case TSDB_DATA_TYPE_TINYINT: {
1432
      LIST_STDDEV_SUB_N(pStdRes->isum, int8_t);
1433
      break;
1434
    }
1435
    case TSDB_DATA_TYPE_SMALLINT: {
1436
      LIST_STDDEV_SUB_N(pStdRes->isum, int16_t);
1437
      break;
1438
    }
1439
    case TSDB_DATA_TYPE_INT: {
1440
      LIST_STDDEV_SUB_N(pStdRes->isum, int32_t);
1441
      break;
1442
    }
1443
    case TSDB_DATA_TYPE_BIGINT: {
1444
      LIST_STDDEV_SUB_N(pStdRes->isum, int64_t);
1445
      break;
1446
    }
1447
    case TSDB_DATA_TYPE_UTINYINT: {
1448
      LIST_STDDEV_SUB_N(pStdRes->isum, uint8_t);
1449
      break;
1450
    }
1451
    case TSDB_DATA_TYPE_USMALLINT: {
1452
      LIST_STDDEV_SUB_N(pStdRes->isum, uint16_t);
1453
      break;
1454
    }
1455
    case TSDB_DATA_TYPE_UINT: {
1456
      LIST_STDDEV_SUB_N(pStdRes->isum, uint32_t);
1457
      break;
1458
    }
1459
    case TSDB_DATA_TYPE_UBIGINT: {
1460
      LIST_STDDEV_SUB_N(pStdRes->isum, uint64_t);
1461
      break;
1462
    }
1463
    case TSDB_DATA_TYPE_FLOAT: {
1464
      LIST_STDDEV_SUB_N(pStdRes->dsum, float);
1465
      break;
1466
    }
1467
    case TSDB_DATA_TYPE_DOUBLE: {
1468
      LIST_STDDEV_SUB_N(pStdRes->dsum, double);
1469
      break;
1470
    }
1471
    default:
1472
      break;
1473
  }
1474

1475
  // data in the check operation are all null, not output
1476
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
1477
  return TSDB_CODE_SUCCESS;
1478
}
1479
#endif
1480

1481
int32_t stddevFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
287,999✔
1482
  SInputColumnInfoData* pInput = &pCtx->input;
287,999✔
1483
  SStdRes*              pStddevRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
287,999✔
1484
  int32_t               type = pStddevRes->type;
287,999✔
1485
  double                avg;
1486

1487
  if (pStddevRes->count == 0) {
287,999✔
1488
    GET_RES_INFO(pCtx)->numOfRes = 0;
66,379✔
1489
    return functionFinalize(pCtx, pBlock);
66,379✔
1490
  }
1491

1492
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
221,620!
1493
    avg = pStddevRes->isum / ((double)pStddevRes->count);
195,030✔
1494
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticISum / ((double)pStddevRes->count) - avg * avg));
195,030✔
1495
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
26,590!
1496
    avg = pStddevRes->usum / ((double)pStddevRes->count);
2✔
1497
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticUSum / ((double)pStddevRes->count) - avg * avg));
2✔
1498
  } else {
1499
    avg = pStddevRes->dsum / ((double)pStddevRes->count);
26,588✔
1500
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticDSum / ((double)pStddevRes->count) - avg * avg));
26,588✔
1501
  }
1502

1503
  // check for overflow
1504
  if (isinf(pStddevRes->result) || isnan(pStddevRes->result)) {
221,620!
1505
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1506
  }
1507

1508
  return functionFinalize(pCtx, pBlock);
221,620✔
1509
}
1510

1511
int32_t stdvarFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
×
1512
  SInputColumnInfoData* pInput = &pCtx->input;
×
1513
  SStdRes*              pStdvarRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
×
1514
  int32_t               type = pStdvarRes->type;
×
1515
  double                avg;
1516

1517
  if (pStdvarRes->count == 0) {
×
1518
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1519
    return functionFinalize(pCtx, pBlock);
×
1520
  }
1521

1522
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
×
1523
    avg = pStdvarRes->isum / ((double)pStdvarRes->count);
×
1524
    pStdvarRes->result = fabs(pStdvarRes->quadraticISum / ((double)pStdvarRes->count) - avg * avg);
×
1525
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
1526
    avg = pStdvarRes->usum / ((double)pStdvarRes->count);
×
1527
    pStdvarRes->result = fabs(pStdvarRes->quadraticUSum / ((double)pStdvarRes->count) - avg * avg);
×
1528
  } else {
1529
    avg = pStdvarRes->dsum / ((double)pStdvarRes->count);
×
1530
    pStdvarRes->result = fabs(pStdvarRes->quadraticDSum / ((double)pStdvarRes->count) - avg * avg);
×
1531
  }
1532

1533
  // check for overflow
1534
  if (isinf(pStdvarRes->result) || isnan(pStdvarRes->result)) {
×
1535
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1536
  }
1537

1538
  return functionFinalize(pCtx, pBlock);
×
1539
}
1540

1541
int32_t stdPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
7,914✔
1542
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
7,914✔
1543
  SStdRes*             pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
7,914✔
1544
  int32_t              resultBytes = getStdInfoSize();
7,914✔
1545
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
7,914!
1546

1547
  if (NULL == res) {
7,915!
1548
    return terrno;
×
1549
  }
1550
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
7,915✔
1551
  varDataSetLen(res, resultBytes);
7,915✔
1552

1553
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
7,915✔
1554
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
7,915✔
1555
  if (NULL == pCol) {
7,915!
1556
    taosMemoryFree(res);
×
1557
    return TSDB_CODE_OUT_OF_RANGE;
×
1558
  }
1559

1560
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
7,915✔
1561

1562
  taosMemoryFree(res);
7,915!
1563
  return code;
7,915✔
1564
}
1565

1566
int32_t stdCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
3✔
1567
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
3✔
1568
  SStdRes*             pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
3✔
1569

1570
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
3✔
1571
  SStdRes*             pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
3✔
1572
  int16_t              type = pDBuf->type == TSDB_DATA_TYPE_NULL ? pSBuf->type : pDBuf->type;
3!
1573

1574
  stdTransferInfo(pSBuf, pDBuf);
3✔
1575

1576
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
3✔
1577
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
3✔
1578
  return TSDB_CODE_SUCCESS;
3✔
1579
}
1580

1581
bool getLeastSQRFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
8,152✔
1582
  pEnv->calcMemSize = sizeof(SLeastSQRInfo);
8,152✔
1583
  return true;
8,152✔
1584
}
1585

1586
int32_t leastSQRFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
48,898✔
1587
  if (pResultInfo->initialized) {
48,898!
1588
    return TSDB_CODE_SUCCESS;
×
1589
  }
1590
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
48,898!
1591
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1592
  }
1593

1594
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
48,901✔
1595

1596
  GET_TYPED_DATA(pInfo->startVal, double, pCtx->param[1].param.nType, &pCtx->param[1].param.i,
48,901!
1597
                 typeGetTypeModFromCol(pCtx->param[1].pCol));
1598
  GET_TYPED_DATA(pInfo->stepVal, double, pCtx->param[2].param.nType, &pCtx->param[2].param.i,
48,895!
1599
                 typeGetTypeModFromCol(pCtx->param[2].pCol));
1600
  return TSDB_CODE_SUCCESS;
48,895✔
1601
}
1602

1603
int32_t leastSQRFunction(SqlFunctionCtx* pCtx) {
51,959✔
1604
  int32_t numOfElem = 0;
51,959✔
1605

1606
  SInputColumnInfoData* pInput = &pCtx->input;
51,959✔
1607
  int32_t               type = pInput->pData[0]->info.type;
51,959✔
1608

1609
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
51,959✔
1610

1611
  SColumnInfoData* pCol = pInput->pData[0];
51,959✔
1612

1613
  double(*param)[3] = pInfo->matrix;
51,959✔
1614
  double x = pInfo->startVal;
51,959✔
1615

1616
  int32_t start = pInput->startRowIndex;
51,959✔
1617
  int32_t numOfRows = pInput->numOfRows;
51,959✔
1618

1619
  switch (type) {
51,959!
1620
    case TSDB_DATA_TYPE_TINYINT: {
8,105✔
1621
      int8_t* plist = (int8_t*)pCol->pData;
8,105✔
1622
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
159,999✔
1623
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
151,894✔
1624
          continue;
2,636✔
1625
        }
1626
        numOfElem++;
149,258✔
1627
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
149,258✔
1628
      }
1629
      break;
8,105✔
1630
    }
1631
    case TSDB_DATA_TYPE_SMALLINT: {
6,499✔
1632
      int16_t* plist = (int16_t*)pCol->pData;
6,499✔
1633
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
284,756✔
1634
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
278,257✔
1635
          continue;
138,436✔
1636
        }
1637

1638
        numOfElem++;
139,821✔
1639
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
139,821✔
1640
      }
1641
      break;
6,499✔
1642
    }
1643

1644
    case TSDB_DATA_TYPE_INT: {
7,226✔
1645
      int32_t* plist = (int32_t*)pCol->pData;
7,226✔
1646
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
162,696✔
1647
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
155,470✔
1648
          continue;
139,901✔
1649
        }
1650

1651
        numOfElem++;
15,569✔
1652
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
15,569✔
1653
      }
1654
      break;
7,226✔
1655
    }
1656

1657
    case TSDB_DATA_TYPE_BIGINT: {
6,198✔
1658
      int64_t* plist = (int64_t*)pCol->pData;
6,198✔
1659
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
149,007✔
1660
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
142,809✔
1661
          continue;
3,636✔
1662
        }
1663

1664
        numOfElem++;
139,173✔
1665
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
139,173✔
1666
      }
1667
      break;
6,198✔
1668
    }
1669

1670
    case TSDB_DATA_TYPE_UTINYINT: {
78✔
1671
      uint8_t* plist = (uint8_t*)pCol->pData;
78✔
1672
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
330✔
1673
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
252!
1674
          continue;
66✔
1675
        }
1676
        numOfElem++;
186✔
1677
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
186✔
1678
      }
1679
      break;
78✔
1680
    }
1681
    case TSDB_DATA_TYPE_USMALLINT: {
78✔
1682
      uint16_t* plist = (uint16_t*)pCol->pData;
78✔
1683
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
330✔
1684
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
252!
1685
          continue;
60✔
1686
        }
1687

1688
        numOfElem++;
192✔
1689
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
192✔
1690
      }
1691
      break;
78✔
1692
    }
1693

1694
    case TSDB_DATA_TYPE_UINT: {
78✔
1695
      uint32_t* plist = (uint32_t*)pCol->pData;
78✔
1696
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
330✔
1697
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
252!
1698
          continue;
60✔
1699
        }
1700

1701
        numOfElem++;
192✔
1702
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
192✔
1703
      }
1704
      break;
78✔
1705
    }
1706

1707
    case TSDB_DATA_TYPE_UBIGINT: {
78✔
1708
      uint64_t* plist = (uint64_t*)pCol->pData;
78✔
1709
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
330✔
1710
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
252!
1711
          continue;
60✔
1712
        }
1713

1714
        numOfElem++;
192✔
1715
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
192✔
1716
      }
1717
      break;
78✔
1718
    }
1719

1720
    case TSDB_DATA_TYPE_FLOAT: {
9,704✔
1721
      float* plist = (float*)pCol->pData;
9,704✔
1722
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
163,071✔
1723
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
153,367✔
1724
          continue;
149,751✔
1725
        }
1726

1727
        numOfElem++;
3,616✔
1728
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
3,616✔
1729
      }
1730
      break;
9,704✔
1731
    }
1732

1733
    case TSDB_DATA_TYPE_DOUBLE: {
13,916✔
1734
      double* plist = (double*)pCol->pData;
13,916✔
1735
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
317,088✔
1736
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
303,172✔
1737
          continue;
296,592✔
1738
        }
1739

1740
        numOfElem++;
6,580✔
1741
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
6,580✔
1742
      }
1743
      break;
13,916✔
1744
    }
1745
    case TSDB_DATA_TYPE_NULL: {
×
1746
      GET_RES_INFO(pCtx)->isNullRes = 1;
×
1747
      numOfElem = 1;
×
1748
      break;
×
1749
    }
1750

1751
    default:
×
1752
      break;
×
1753
  }
1754

1755
  pInfo->startVal = x;
51,959✔
1756
  pInfo->num += numOfElem;
51,959✔
1757

1758
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
51,959✔
1759

1760
  return TSDB_CODE_SUCCESS;
51,959✔
1761
}
1762

1763
int32_t leastSQRFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
48,913✔
1764
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
48,913✔
1765
  SLeastSQRInfo*       pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
48,913✔
1766
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
48,913✔
1767
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
48,913✔
1768

1769
  if (NULL == pCol) {
48,913!
1770
    return TSDB_CODE_OUT_OF_RANGE;
×
1771
  }
1772
  int32_t currentRow = pBlock->info.rows;
48,913✔
1773

1774
  if (0 == pInfo->num) {
48,913✔
1775
    colDataSetNULL(pCol, currentRow);
27,792!
1776
    return TSDB_CODE_SUCCESS;
27,792✔
1777
  }
1778

1779
  double(*param)[3] = pInfo->matrix;
21,121✔
1780

1781
  param[1][1] = (double)pInfo->num;
21,121✔
1782
  param[1][0] = param[0][1];
21,121✔
1783

1784
  double param00 = param[0][0] - param[1][0] * (param[0][1] / param[1][1]);
21,121✔
1785
  double param02 = param[0][2] - param[1][2] * (param[0][1] / param[1][1]);
21,121✔
1786

1787
  if (0 == param00) {
21,121✔
1788
    colDataSetNULL(pCol, currentRow);
17,705!
1789
    return TSDB_CODE_SUCCESS;
17,705✔
1790
  }
1791

1792
  // param[0][1] = 0;
1793
  double param12 = param[1][2] - param02 * (param[1][0] / param00);
3,416✔
1794
  // param[1][0] = 0;
1795
  param02 /= param00;
3,416✔
1796

1797
  param12 /= param[1][1];
3,416✔
1798

1799
  char buf[LEASTSQUARES_BUFF_LENGTH] = {0};
3,416✔
1800
  char slopBuf[64] = {0};
3,416✔
1801
  char interceptBuf[64] = {0};
3,416✔
1802
  int  n = tsnprintf(slopBuf, 64, "%.6lf", param02);
3,416✔
1803
  if (n > LEASTSQUARES_DOUBLE_ITEM_LENGTH) {
3,419✔
1804
    (void)snprintf(slopBuf, 64, "%." DOUBLE_PRECISION_DIGITS, param02);
6✔
1805
  }
1806
  n = tsnprintf(interceptBuf, 64, "%.6lf", param12);
3,419✔
1807
  if (n > LEASTSQUARES_DOUBLE_ITEM_LENGTH) {
3,419✔
1808
    (void)snprintf(interceptBuf, 64, "%." DOUBLE_PRECISION_DIGITS, param12);
928✔
1809
  }
1810
  size_t len =
3,419✔
1811
      snprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE, "{slop:%s, intercept:%s}", slopBuf, interceptBuf);
3,419✔
1812
  varDataSetLen(buf, len);
3,419✔
1813

1814
  int32_t code = colDataSetVal(pCol, currentRow, buf, pResInfo->isNullRes);
3,419✔
1815

1816
  return code;
3,418✔
1817
}
1818

1819
int32_t leastSQRCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
1820
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
1821
  SLeastSQRInfo*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
1822
  int32_t              type = pDestCtx->input.pData[0]->info.type;
×
1823
  double(*pDparam)[3] = pDBuf->matrix;
×
1824

1825
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
1826
  SLeastSQRInfo*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
1827
  double(*pSparam)[3] = pSBuf->matrix;
×
1828
  for (int32_t i = 0; i < pSBuf->num; i++) {
×
1829
    pDparam[0][0] += pDBuf->startVal * pDBuf->startVal;
×
1830
    pDparam[0][1] += pDBuf->startVal;
×
1831
    pDBuf->startVal += pDBuf->stepVal;
×
1832
  }
1833
  pDparam[0][2] += pSparam[0][2] + pDBuf->num * pDBuf->stepVal * pSparam[1][2];
×
1834
  pDparam[1][2] += pSparam[1][2];
×
1835
  pDBuf->num += pSBuf->num;
×
1836
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
1837
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
1838
  return TSDB_CODE_SUCCESS;
×
1839
}
1840

1841
bool getPercentileFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
607✔
1842
  pEnv->calcMemSize = sizeof(SPercentileInfo);
607✔
1843
  return true;
607✔
1844
}
1845

1846
int32_t percentileFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
4,443✔
1847
  if (pResultInfo->initialized) {
4,443!
1848
    return TSDB_CODE_SUCCESS;
×
1849
  }
1850
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
4,443!
1851
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1852
  }
1853

1854
  // in the first round, get the min-max value of all involved data
1855
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
4,443✔
1856
  SET_DOUBLE_VAL(&pInfo->minval, DBL_MAX);
4,443✔
1857
  SET_DOUBLE_VAL(&pInfo->maxval, -DBL_MAX);
4,443✔
1858
  pInfo->numOfElems = 0;
4,443✔
1859

1860
  return TSDB_CODE_SUCCESS;
4,443✔
1861
}
1862

1863
void percentileFunctionCleanupExt(SqlFunctionCtx* pCtx) {
×
1864
  if (pCtx == NULL || GET_RES_INFO(pCtx) == NULL || GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)) == NULL) {
×
1865
    return;
×
1866
  }
1867
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
×
1868
  if (pInfo->pMemBucket != NULL) {
×
1869
    tMemBucketDestroy(&(pInfo->pMemBucket));
×
1870
    pInfo->pMemBucket = NULL;
×
1871
  }
1872
}
1873

1874
int32_t percentileFunction(SqlFunctionCtx* pCtx) {
10,914✔
1875
  int32_t              code = TSDB_CODE_SUCCESS;
10,914✔
1876
  int32_t              numOfElems = 0;
10,914✔
1877
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
10,914✔
1878

1879
  SInputColumnInfoData* pInput = &pCtx->input;
10,914✔
1880
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
10,914✔
1881

1882
  SColumnInfoData* pCol = pInput->pData[0];
10,914✔
1883
  int32_t          type = pCol->info.type;
10,914✔
1884

1885
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
10,914✔
1886
  if (pCtx->scanFlag == MAIN_SCAN && pInfo->stage == 0) {
10,914✔
1887
    pInfo->stage += 1;
4,443✔
1888

1889
    // all data are null, set it completed
1890
    if (pInfo->numOfElems == 0) {
4,443✔
1891
      pResInfo->complete = true;
2,578✔
1892
      return TSDB_CODE_SUCCESS;
2,578✔
1893
    } else {
1894
      code = tMemBucketCreate(pCol->info.bytes, type, typeGetTypeModFromColInfo(&pCol->info), pInfo->minval, pInfo->maxval, pCtx->hasWindowOrGroup,
1,865✔
1895
                              &pInfo->pMemBucket, pInfo->numOfElems);
1,865✔
1896
      if (TSDB_CODE_SUCCESS != code) {
1,865!
1897
        return code;
×
1898
      }
1899
    }
1900
  }
1901

1902
  // the first stage, only acquire the min/max value
1903
  if (pInfo->stage == 0) {
8,336✔
1904
    if (pCtx->input.colDataSMAIsSet) {
5,471!
1905
      double tmin = 0.0, tmax = 0.0;
×
1906
      if (IS_SIGNED_NUMERIC_TYPE(type)) {
×
1907
        tmin = (double)GET_INT64_VAL(&pAgg->min);
×
1908
        tmax = (double)GET_INT64_VAL(&pAgg->max);
×
1909
      } else if (IS_FLOAT_TYPE(type)) {
×
1910
        tmin = GET_DOUBLE_VAL(&pAgg->min);
×
1911
        tmax = GET_DOUBLE_VAL(&pAgg->max);
×
1912
      } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
1913
        tmin = (double)GET_UINT64_VAL(&pAgg->min);
×
1914
        tmax = (double)GET_UINT64_VAL(&pAgg->max);
×
1915
      }
1916

1917
      if (GET_DOUBLE_VAL(&pInfo->minval) > tmin) {
×
1918
        SET_DOUBLE_VAL(&pInfo->minval, tmin);
×
1919
      }
1920

1921
      if (GET_DOUBLE_VAL(&pInfo->maxval) < tmax) {
×
1922
        SET_DOUBLE_VAL(&pInfo->maxval, tmax);
×
1923
      }
1924

1925
      pInfo->numOfElems += (pInput->numOfRows - pAgg->numOfNull);
×
1926
    } else {
1927
      // check the valid data one by one
1928
      int32_t start = pInput->startRowIndex;
5,471✔
1929
      for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
516,774✔
1930
        if (colDataIsNull_f(pCol->nullbitmap, i)) {
511,303✔
1931
          continue;
3,200✔
1932
        }
1933

1934
        char* data = colDataGetData(pCol, i);
508,103!
1935

1936
        double v = 0;
508,103✔
1937
        GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pCol->info));
508,103!
1938
        if (v < GET_DOUBLE_VAL(&pInfo->minval)) {
508,103✔
1939
          SET_DOUBLE_VAL(&pInfo->minval, v);
2,131✔
1940
        }
1941

1942
        if (v > GET_DOUBLE_VAL(&pInfo->maxval)) {
508,103✔
1943
          SET_DOUBLE_VAL(&pInfo->maxval, v);
407,409✔
1944
        }
1945

1946
        pInfo->numOfElems += 1;
508,103✔
1947
      }
1948
    }
1949
  } else {
1950
    // the second stage, calculate the true percentile value
1951
    int32_t start = pInput->startRowIndex;
2,865✔
1952
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
510,968✔
1953
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
508,103!
1954
        continue;
×
1955
      }
1956

1957
      char* data = colDataGetData(pCol, i);
508,103!
1958
      numOfElems += 1;
508,103✔
1959
      code = tMemBucketPut(pInfo->pMemBucket, data, 1);
508,103✔
1960
      if (code != TSDB_CODE_SUCCESS) {
508,103!
1961
        tMemBucketDestroy(&(pInfo->pMemBucket));
×
1962
        return code;
×
1963
      }
1964
    }
1965

1966
    SET_VAL(pResInfo, numOfElems, 1);
2,865!
1967
  }
1968

1969
  pCtx->needCleanup = true;
8,336✔
1970
  return TSDB_CODE_SUCCESS;
8,336✔
1971
}
1972

1973
int32_t percentileFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
4,443✔
1974
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
4,443✔
1975
  SPercentileInfo*     ppInfo = (SPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
4,443✔
1976

1977
  int32_t code = 0;
4,443✔
1978
  double  v = 0;
4,443✔
1979

1980
  tMemBucket** pMemBucket = &ppInfo->pMemBucket;
4,443✔
1981
  if ((*pMemBucket) != NULL && (*pMemBucket)->total > 0) {  // check for null
4,443!
1982
    if (pCtx->numOfParams > 2) {
1,865✔
1983
      char buf[3200] = {0};
18✔
1984
      // max length of double num is 317, e.g. use %.6lf to print -1.0e+308, consider the comma and bracket, 3200 is
1985
      // enough.
1986
      size_t len = 1;
18✔
1987

1988
      varDataVal(buf)[0] = '[';
18✔
1989
      for (int32_t i = 1; i < pCtx->numOfParams; ++i) {
198✔
1990
        SVariant* pVal = &pCtx->param[i].param;
180✔
1991

1992
        GET_TYPED_DATA(v, double, pVal->nType, &pVal->i, typeGetTypeModFromCol(pCtx->param[i].pCol));
180!
1993

1994
        code = getPercentile((*pMemBucket), v, &ppInfo->result);
180✔
1995
        if (code != TSDB_CODE_SUCCESS) {
180!
1996
          goto _fin_error;
×
1997
        }
1998

1999
        if (i == pCtx->numOfParams - 1) {
180✔
2000
          len += tsnprintf(varDataVal(buf) + len, sizeof(buf) - VARSTR_HEADER_SIZE - len, "%.6lf]", ppInfo->result);
18✔
2001
        } else {
2002
          len += tsnprintf(varDataVal(buf) + len, sizeof(buf) - VARSTR_HEADER_SIZE - len, "%.6lf, ", ppInfo->result);
162✔
2003
        }
2004
      }
2005

2006
      int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
18✔
2007
      SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
18✔
2008
      if (NULL == pCol) {
18!
2009
        code = terrno;
×
2010
        goto _fin_error;
×
2011
      }
2012

2013
      varDataSetLen(buf, len);
18✔
2014
      code = colDataSetVal(pCol, pBlock->info.rows, buf, false);
18✔
2015
      if (code != TSDB_CODE_SUCCESS) {
18!
2016
        goto _fin_error;
×
2017
      }
2018

2019
      tMemBucketDestroy(pMemBucket);
18✔
2020
      return TSDB_CODE_SUCCESS;
18✔
2021
    } else {
2022
      SVariant* pVal = &pCtx->param[1].param;
1,847✔
2023

2024
      GET_TYPED_DATA(v, double, pVal->nType, &pVal->i, typeGetTypeModFromCol(pCtx->param[1].pCol));
1,847!
2025

2026
      code = getPercentile((*pMemBucket), v, &ppInfo->result);
1,847✔
2027
      if (code != TSDB_CODE_SUCCESS) {
1,847!
2028
        goto _fin_error;
×
2029
      }
2030

2031
      tMemBucketDestroy(pMemBucket);
1,847✔
2032
      return functionFinalize(pCtx, pBlock);
1,847✔
2033
    }
2034
  } else {
2035
    return functionFinalize(pCtx, pBlock);
2,578✔
2036
  }
2037

2038
_fin_error:
×
2039

2040
  tMemBucketDestroy(pMemBucket);
×
2041
  return code;
×
2042
}
2043

2044
bool getApercentileFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
63,071✔
2045
  int32_t bytesHist =
63,071✔
2046
      (int32_t)(sizeof(SAPercentileInfo) + sizeof(SHistogramInfo) + sizeof(SHistBin) * (MAX_HISTOGRAM_BIN + 1));
2047
  int32_t bytesDigest = (int32_t)(sizeof(SAPercentileInfo) + TDIGEST_SIZE(COMPRESSION));
63,071✔
2048
  pEnv->calcMemSize = TMAX(bytesHist, bytesDigest);
63,071✔
2049
  return true;
63,071✔
2050
}
2051

2052
int32_t getApercentileMaxSize() {
8,891✔
2053
  int32_t bytesHist =
8,891✔
2054
      (int32_t)(sizeof(SAPercentileInfo) + sizeof(SHistogramInfo) + sizeof(SHistBin) * (MAX_HISTOGRAM_BIN + 1));
2055
  int32_t bytesDigest = (int32_t)(sizeof(SAPercentileInfo) + TDIGEST_SIZE(COMPRESSION));
8,891✔
2056
  return TMAX(bytesHist, bytesDigest);
8,891✔
2057
}
2058

2059
static int8_t getApercentileAlgo(char* algoStr) {
22,312✔
2060
  int8_t algoType;
2061
  if (strcasecmp(algoStr, "default") == 0) {
22,312✔
2062
    algoType = APERCT_ALGO_DEFAULT;
11,138✔
2063
  } else if (strcasecmp(algoStr, "t-digest") == 0) {
11,174✔
2064
    algoType = APERCT_ALGO_TDIGEST;
11,160✔
2065
  } else {
2066
    algoType = APERCT_ALGO_UNKNOWN;
14✔
2067
  }
2068

2069
  return algoType;
22,312✔
2070
}
2071

2072
static void buildHistogramInfo(SAPercentileInfo* pInfo) {
867,004✔
2073
  pInfo->pHisto = (SHistogramInfo*)((char*)pInfo + sizeof(SAPercentileInfo));
867,004✔
2074
  pInfo->pHisto->elems = (SHistBin*)((char*)pInfo->pHisto + sizeof(SHistogramInfo));
867,004✔
2075
}
867,004✔
2076

2077
static void buildTDigestInfo(SAPercentileInfo* pInfo) {
22,391✔
2078
  pInfo->pTDigest = (TDigest*)((char*)pInfo + sizeof(SAPercentileInfo));
22,391✔
2079
}
22,391✔
2080

2081
int32_t apercentileFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
302,454✔
2082
  if (pResultInfo->initialized) {
302,454!
2083
    return TSDB_CODE_SUCCESS;
×
2084
  }
2085
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
302,454!
2086
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
2087
  }
2088

2089
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
302,485✔
2090

2091
  SVariant* pVal = &pCtx->param[1].param;
302,485✔
2092
  pInfo->percent = 0;
302,485✔
2093
  GET_TYPED_DATA(pInfo->percent, double, pVal->nType, &pVal->i, typeGetTypeModFromCol(pCtx->param[1].pCol));
302,485!
2094

2095
  if (pCtx->numOfParams == 2) {
302,483✔
2096
    pInfo->algo = APERCT_ALGO_DEFAULT;
280,182✔
2097
  } else if (pCtx->numOfParams == 3) {
22,301!
2098
    pInfo->algo = getApercentileAlgo(varDataVal(pCtx->param[2].param.pz));
22,311✔
2099
    if (pInfo->algo == APERCT_ALGO_UNKNOWN) {
22,297!
2100
      return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
2101
    }
2102
  }
2103

2104
  char* tmp = (char*)pInfo + sizeof(SAPercentileInfo);
302,469✔
2105
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
302,469✔
2106
    pInfo->pTDigest = tdigestNewFrom(tmp, COMPRESSION);
11,163✔
2107
  } else {
2108
    buildHistogramInfo(pInfo);
291,306✔
2109
    pInfo->pHisto = tHistogramCreateFrom(tmp, MAX_HISTOGRAM_BIN);
291,325✔
2110
    qDebug("%s set up histogram, numOfElems:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
291,329✔
2111
           pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2112
  }
2113

2114
  return TSDB_CODE_SUCCESS;
302,493✔
2115
}
2116

2117
int32_t apercentileFunction(SqlFunctionCtx* pCtx) {
306,573✔
2118
  int32_t               numOfElems = 0;
306,573✔
2119
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
306,573✔
2120
  SInputColumnInfoData* pInput = &pCtx->input;
306,573✔
2121

2122
  SColumnInfoData* pCol = pInput->pData[0];
306,573✔
2123
  int32_t          type = pCol->info.type;
306,573✔
2124

2125
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
306,573✔
2126

2127
  int32_t start = pInput->startRowIndex;
306,573✔
2128
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
306,573✔
2129
    buildTDigestInfo(pInfo);
11,157✔
2130
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
11,157✔
2131
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
582,568✔
2132
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
571,410✔
2133
        continue;
357,370✔
2134
      }
2135
      numOfElems += 1;
214,040✔
2136
      char* data = colDataGetData(pCol, i);
214,040!
2137

2138
      double  v = 0;  // value
214,040✔
2139
      int64_t w = 1;  // weigth
214,040✔
2140
      GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pCol->info));
214,040!
2141
      int32_t code = tdigestAdd(pInfo->pTDigest, v, w);
214,040✔
2142
      if (code != TSDB_CODE_SUCCESS) {
214,042!
2143
        return code;
×
2144
      }
2145
    }
2146
  } else {
2147
    // might be a race condition here that pHisto can be overwritten or setup function
2148
    // has not been called, need to relink the buffer pHisto points to.
2149
    buildHistogramInfo(pInfo);
295,416✔
2150
    qDebug("%s before add %d elements into histogram, total:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems: %p",
295,396✔
2151
           __FUNCTION__, numOfElems, pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto,
2152
           pInfo->pHisto->elems);
2153
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
2,473,517✔
2154
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
2,178,155✔
2155
        continue;
993,947✔
2156
      }
2157
      numOfElems += 1;
1,184,208✔
2158
      char* data = colDataGetData(pCol, i);
1,184,208!
2159

2160
      double v = 0;
1,184,208✔
2161
      GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pCol->info));
1,184,208!
2162
      int32_t code = tHistogramAdd(&pInfo->pHisto, v);
1,184,208✔
2163
      if (code != TSDB_CODE_SUCCESS) {
1,184,167!
2164
        return code;
×
2165
      }
2166
    }
2167

2168
    qDebug("%s after add %d elements into histogram, total:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems: %p",
295,362✔
2169
           __FUNCTION__, numOfElems, pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto,
2170
           pInfo->pHisto->elems);
2171
  }
2172

2173
  SET_VAL(pResInfo, numOfElems, 1);
306,587✔
2174
  return TSDB_CODE_SUCCESS;
306,587✔
2175
}
2176

2177
static int32_t apercentileTransferInfo(SAPercentileInfo* pInput, SAPercentileInfo* pOutput, bool* hasRes) {
7,525✔
2178
  pOutput->percent = pInput->percent;
7,525✔
2179
  pOutput->algo = pInput->algo;
7,525✔
2180
  if (pOutput->algo == APERCT_ALGO_TDIGEST) {
7,525✔
2181
    buildTDigestInfo(pInput);
93✔
2182
    tdigestAutoFill(pInput->pTDigest, COMPRESSION);
93✔
2183

2184
    if (pInput->pTDigest->num_centroids == 0 && pInput->pTDigest->num_buffered_pts == 0) {
93✔
2185
      return TSDB_CODE_SUCCESS;
1✔
2186
    }
2187

2188
    if (hasRes) {
92✔
2189
      *hasRes = true;
90✔
2190
    }
2191

2192
    buildTDigestInfo(pOutput);
92✔
2193
    TDigest* pTDigest = pOutput->pTDigest;
92✔
2194
    tdigestAutoFill(pTDigest, COMPRESSION);
92✔
2195

2196
    if (pTDigest->num_centroids <= 0 && pTDigest->num_buffered_pts == 0) {
92!
2197
      (void)memcpy(pTDigest, pInput->pTDigest, (size_t)TDIGEST_SIZE(COMPRESSION));
90✔
2198
      tdigestAutoFill(pTDigest, COMPRESSION);
90✔
2199
    } else {
2200
      int32_t code = tdigestMerge(pTDigest, pInput->pTDigest);
2✔
2201
      if (TSDB_CODE_SUCCESS != code) {
2!
2202
        return code;
×
2203
      }
2204
    }
2205
  } else {
2206
    buildHistogramInfo(pInput);
7,432✔
2207
    if (pInput->pHisto->numOfElems <= 0) {
7,432✔
2208
      return TSDB_CODE_SUCCESS;
202✔
2209
    }
2210

2211
    if (hasRes) {
7,230✔
2212
      *hasRes = true;
7,228✔
2213
    }
2214

2215
    buildHistogramInfo(pOutput);
7,230✔
2216
    SHistogramInfo* pHisto = pOutput->pHisto;
7,230✔
2217

2218
    if (pHisto->numOfElems <= 0) {
7,230✔
2219
      (void)memcpy(pHisto, pInput->pHisto, sizeof(SHistogramInfo) + sizeof(SHistBin) * (MAX_HISTOGRAM_BIN + 1));
6,908✔
2220
      pHisto->elems = (SHistBin*)((char*)pHisto + sizeof(SHistogramInfo));
6,908✔
2221

2222
      qDebug("%s merge histo, total:%" PRId64 ", entry:%d, %p", __FUNCTION__, pHisto->numOfElems, pHisto->numOfEntries,
6,908✔
2223
             pHisto);
2224
    } else {
2225
      pHisto->elems = (SHistBin*)((char*)pHisto + sizeof(SHistogramInfo));
322✔
2226
      qDebug("%s input histogram, elem:%" PRId64 ", entry:%d, %p", __FUNCTION__, pHisto->numOfElems,
322✔
2227
             pHisto->numOfEntries, pInput->pHisto);
2228

2229
      SHistogramInfo* pRes = NULL;
322✔
2230
      int32_t         code = tHistogramMerge(pHisto, pInput->pHisto, MAX_HISTOGRAM_BIN, &pRes);
322✔
2231
      if (TSDB_CODE_SUCCESS != code) {
322!
2232
        tHistogramDestroy(&pRes);
×
2233
        return code;
×
2234
      }
2235
      (void)memcpy(pHisto, pRes, sizeof(SHistogramInfo) + sizeof(SHistBin) * MAX_HISTOGRAM_BIN);
322✔
2236
      pHisto->elems = (SHistBin*)((char*)pHisto + sizeof(SHistogramInfo));
322✔
2237

2238
      qDebug("%s merge histo, total:%" PRId64 ", entry:%d, %p", __FUNCTION__, pHisto->numOfElems, pHisto->numOfEntries,
322✔
2239
             pHisto);
2240
      tHistogramDestroy(&pRes);
322✔
2241
    }
2242
  }
2243
  return TSDB_CODE_SUCCESS;
7,322✔
2244
}
2245

2246
int32_t apercentileFunctionMerge(SqlFunctionCtx* pCtx) {
7,467✔
2247
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
7,467✔
2248

2249
  SInputColumnInfoData* pInput = &pCtx->input;
7,467✔
2250

2251
  SColumnInfoData* pCol = pInput->pData[0];
7,467✔
2252
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
7,467!
2253
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
2254
  }
2255

2256
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
7,467✔
2257

2258
  qDebug("%s total %" PRId64 " rows will merge, %p", __FUNCTION__, pInput->numOfRows, pInfo->pHisto);
7,467✔
2259

2260
  bool    hasRes = false;
7,467✔
2261
  int32_t start = pInput->startRowIndex;
7,467✔
2262
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
14,988✔
2263
    char* data = colDataGetData(pCol, i);
7,521!
2264

2265
    SAPercentileInfo* pInputInfo = (SAPercentileInfo*)varDataVal(data);
7,521✔
2266
    int32_t           code = apercentileTransferInfo(pInputInfo, pInfo, &hasRes);
7,521✔
2267
    if (TSDB_CODE_SUCCESS != code) {
7,521!
2268
      return code;
×
2269
    }
2270
  }
2271

2272
  if (pInfo->algo != APERCT_ALGO_TDIGEST) {
7,467✔
2273
    buildHistogramInfo(pInfo);
7,376✔
2274
    qDebug("%s after merge, total:%" PRId64 ", numOfEntry:%d, %p", __FUNCTION__, pInfo->pHisto->numOfElems,
7,376✔
2275
           pInfo->pHisto->numOfEntries, pInfo->pHisto);
2276
  }
2277

2278
  SET_VAL(pResInfo, hasRes ? 1 : 0, 1);
7,467✔
2279
  return TSDB_CODE_SUCCESS;
7,467✔
2280
}
2281

2282
int32_t apercentileFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
269,337✔
2283
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
269,337✔
2284
  SAPercentileInfo*    pInfo = (SAPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
269,337✔
2285

2286
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
269,337✔
2287
    buildTDigestInfo(pInfo);
11,056✔
2288
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
11,056✔
2289
    if (pInfo->pTDigest->size > 0) {
11,057!
2290
      pInfo->result = tdigestQuantile(pInfo->pTDigest, pInfo->percent / 100);
11,057✔
2291
    } else {  // no need to free
2292
      // setNull(pCtx->pOutput, pCtx->outputType, pCtx->outputBytes);
2293
      return TSDB_CODE_SUCCESS;
×
2294
    }
2295
  } else {
2296
    buildHistogramInfo(pInfo);
258,281✔
2297
    if (pInfo->pHisto->numOfElems > 0) {
258,285✔
2298
      qDebug("%s get the final res, elements:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
202,273✔
2299
             pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2300

2301
      double  ratio[] = {pInfo->percent};
202,273✔
2302
      double* res = NULL;
202,273✔
2303
      int32_t code = tHistogramUniform(pInfo->pHisto, ratio, 1, &res);
202,273✔
2304
      if (TSDB_CODE_SUCCESS != code) {
202,270!
2305
        taosMemoryFree(res);
×
2306
        return code;
×
2307
      }
2308
      pInfo->result = *res;
202,270✔
2309
      // memcpy(pCtx->pOutput, res, sizeof(double));
2310
      taosMemoryFree(res);
202,270✔
2311
    } else {  // no need to free
2312
      // setNull(pCtx->pOutput, pCtx->outputType, pCtx->outputBytes);
2313
      // return TSDB_CODE_SUCCESS;
2314
      qDebug("%s get the final res, elements:%" PRId64 ", numOfEntry:%d. result is null", __FUNCTION__,
56,012✔
2315
             pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries);
2316
    }
2317
  }
2318

2319
  return functionFinalize(pCtx, pBlock);
269,335✔
2320
}
2321

2322
int32_t apercentilePartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
7,201✔
2323
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
7,201✔
2324
  SAPercentileInfo*    pInfo = (SAPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
7,201✔
2325

2326
  int32_t resultBytes = getApercentileMaxSize();
7,201✔
2327
  char*   res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
7,201!
2328
  if (NULL == res) {
7,201!
2329
    return terrno;
×
2330
  }
2331

2332
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
7,201✔
2333
    (void)memcpy(varDataVal(res), pInfo, resultBytes);
91✔
2334
    varDataSetLen(res, resultBytes);
91✔
2335
  } else {
2336
    (void)memcpy(varDataVal(res), pInfo, resultBytes);
7,110✔
2337
    varDataSetLen(res, resultBytes);
7,110✔
2338
  }
2339

2340
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
7,201✔
2341
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
7,201✔
2342
  if (NULL == pCol) {
7,200!
2343
    taosMemoryFree(res);
×
2344
    return TSDB_CODE_OUT_OF_RANGE;
×
2345
  }
2346

2347
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
7,200✔
2348

2349
  taosMemoryFree(res);
7,201!
2350
  return code;
7,201✔
2351
}
2352

2353
int32_t apercentileCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
4✔
2354
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
4✔
2355
  SAPercentileInfo*    pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
4✔
2356

2357
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
4✔
2358
  SAPercentileInfo*    pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
4✔
2359

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

2362
  int32_t code = apercentileTransferInfo(pSBuf, pDBuf, NULL);
4✔
2363
  if (TSDB_CODE_SUCCESS != code) {
4!
2364
    return code;
×
2365
  }
2366
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
4✔
2367
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
4✔
2368
  return TSDB_CODE_SUCCESS;
4✔
2369
}
2370

2371
// TODO: change this function when block data info pks changed
2372
static int32_t comparePkDataWithSValue(int8_t pkType, char* pkData, SValue* pVal, int32_t order) {
11✔
2373
  char numVal[8] = {0};
11✔
2374
  switch (pkType) {
11!
2375
    case TSDB_DATA_TYPE_INT:
11✔
2376
      *(int32_t*)numVal = (int32_t)VALUE_GET_TRIVIAL_DATUM(pVal);
11✔
2377
      break;
11✔
2378
    case TSDB_DATA_TYPE_UINT:
×
2379
      *(uint32_t*)numVal = (uint32_t)VALUE_GET_TRIVIAL_DATUM(pVal);
×
2380
      break;
×
2381
    case TSDB_DATA_TYPE_BIGINT:
×
2382
      *(int64_t*)numVal = (int64_t)VALUE_GET_TRIVIAL_DATUM(pVal);
×
2383
      break;
×
2384
    case TSDB_DATA_TYPE_UBIGINT:
×
2385
      *(uint64_t*)numVal = (uint64_t)VALUE_GET_TRIVIAL_DATUM(pVal);
×
2386
      break;
×
2387
    default:
×
2388
      break;
×
2389
  }
2390
  char*         blockData = (IS_NUMERIC_TYPE(pkType)) ? (char*)numVal : (char*)pVal->pData;
11!
2391
  __compar_fn_t fn = getKeyComparFunc(pkType, order);
11✔
2392
  return fn(pkData, blockData);
11✔
2393
}
2394

2395
EFuncDataRequired firstDynDataReq(void* pRes, SDataBlockInfo* pBlockInfo) {
1,231✔
2396
  SResultRowEntryInfo* pEntry = (SResultRowEntryInfo*)pRes;
1,231✔
2397

2398
  // not initialized yet, data is required
2399
  if (pEntry == NULL) {
1,231!
2400
    return FUNC_DATA_REQUIRED_DATA_LOAD;
×
2401
  }
2402

2403
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
1,231✔
2404
  if (pResult->hasResult) {
1,231✔
2405
    if (pResult->pkBytes > 0) {
1,162✔
2406
      pResult->pkData = pResult->buf + pResult->bytes;
6✔
2407
    } else {
2408
      pResult->pkData = NULL;
1,156✔
2409
    }
2410
    if (pResult->ts < pBlockInfo->window.skey) {
1,162✔
2411
      return FUNC_DATA_REQUIRED_NOT_LOAD;
207✔
2412
    } else if (pResult->ts == pBlockInfo->window.skey) {
955✔
2413
      if (NULL == pResult->pkData) {
436✔
2414
        return FUNC_DATA_REQUIRED_NOT_LOAD;
430✔
2415
      }
2416
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 0, TSDB_ORDER_ASC) < 0) {
6!
2417
        return FUNC_DATA_REQUIRED_NOT_LOAD;
6✔
2418
      }
2419
    }
2420
    return FUNC_DATA_REQUIRED_DATA_LOAD;
519✔
2421
  } else {
2422
    return FUNC_DATA_REQUIRED_DATA_LOAD;
69✔
2423
  }
2424
}
2425

2426
EFuncDataRequired lastDynDataReq(void* pRes, SDataBlockInfo* pBlockInfo) {
1,601✔
2427
  SResultRowEntryInfo* pEntry = (SResultRowEntryInfo*)pRes;
1,601✔
2428

2429
  // not initialized yet, data is required
2430
  if (pEntry == NULL) {
1,601!
2431
    return FUNC_DATA_REQUIRED_DATA_LOAD;
×
2432
  }
2433

2434
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
1,601✔
2435
  if (pResult->hasResult) {
1,601✔
2436
    if (pResult->pkBytes > 0) {
1,515✔
2437
      pResult->pkData = pResult->buf + pResult->bytes;
5✔
2438
    } else {
2439
      pResult->pkData = NULL;
1,510✔
2440
    }
2441
    if (pResult->ts > pBlockInfo->window.ekey) {
1,515✔
2442
      return FUNC_DATA_REQUIRED_NOT_LOAD;
499✔
2443
    } else if (pResult->ts == pBlockInfo->window.ekey && pResult->pkData) {
1,016✔
2444
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 1, TSDB_ORDER_DESC) < 0) {
5!
2445
        return FUNC_DATA_REQUIRED_NOT_LOAD;
×
2446
      }
2447
    }
2448
    return FUNC_DATA_REQUIRED_DATA_LOAD;
1,016✔
2449
  } else {
2450
    return FUNC_DATA_REQUIRED_DATA_LOAD;
86✔
2451
  }
2452
}
2453

2454
// TODO modify it to include primary key bytes
2455
int32_t getFirstLastInfoSize(int32_t resBytes, int32_t pkBytes) { return sizeof(SFirstLastRes) + resBytes + pkBytes; }
22,783,742✔
2456

2457
bool getFirstLastFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
148,013✔
2458
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
148,013✔
2459
  // TODO: change SFunctionNode to add pk info
2460
  int32_t pkBytes = (pFunc->hasPk) ? pFunc->pkBytes : 0;
148,086✔
2461
  pEnv->calcMemSize = getFirstLastInfoSize(pNode->node.resType.bytes, pkBytes);
148,086✔
2462
  return true;
148,091✔
2463
}
2464

2465
bool getSelectivityFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
54,135✔
2466
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
54,135✔
2467
  pEnv->calcMemSize = pNode->node.resType.bytes;
54,145✔
2468
  return true;
54,145✔
2469
}
2470

2471
bool getGroupKeyFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
233,565✔
2472
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
233,565✔
2473
  pEnv->calcMemSize = sizeof(SGroupKeyInfo) + pNode->node.resType.bytes;
233,919✔
2474
  return true;
233,919✔
2475
}
2476

2477
static FORCE_INLINE TSKEY getRowPTs(SColumnInfoData* pTsColInfo, int32_t rowIndex) {
2478
  if (pTsColInfo == NULL || pTsColInfo->pData == NULL) {
100,675,243!
2479
    return 0;
×
2480
  }
2481

2482
  return *(TSKEY*)colDataGetData(pTsColInfo, rowIndex);
100,719,643!
2483
}
2484

2485
int32_t firstLastFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
4,029,103✔
2486
  if (pResInfo->initialized) {
4,029,103!
2487
    return TSDB_CODE_SUCCESS;
×
2488
  }
2489
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
4,029,103!
2490
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
2491
  }
2492

2493
  SFirstLastRes*        pRes = GET_ROWCELL_INTERBUF(pResInfo);
4,029,108✔
2494
  pRes->nullTupleSaved = false;
4,029,108✔
2495
  pRes->nullTuplePos.pageId = -1;
4,029,108✔
2496
  return TSDB_CODE_SUCCESS;
4,029,108✔
2497
}
2498

2499
static int32_t prepareBuf(SqlFunctionCtx* pCtx) {
270,384✔
2500
  if (pCtx->subsidiaries.rowLen == 0) {
270,384✔
2501
    int32_t rowLen = 0;
18,505✔
2502
    for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
42,928✔
2503
      SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
24,423✔
2504
      rowLen += pc->pExpr->base.resSchema.bytes;
24,423✔
2505
    }
2506

2507
    pCtx->subsidiaries.rowLen = rowLen + pCtx->subsidiaries.num * sizeof(bool);
18,505✔
2508
    pCtx->subsidiaries.buf = taosMemoryMalloc(pCtx->subsidiaries.rowLen);
18,505!
2509
    if (NULL == pCtx->subsidiaries.buf) {
18,490!
2510
      return terrno;
×
2511
    }
2512
  }
2513
  return TSDB_CODE_SUCCESS;
270,369✔
2514
}
2515

2516
static int32_t firstlastSaveTupleData(const SSDataBlock* pSrcBlock, int32_t rowIndex, SqlFunctionCtx* pCtx,
54,745,335✔
2517
                                      SFirstLastRes* pInfo, bool noElements) {
2518
  int32_t code = TSDB_CODE_SUCCESS;
54,745,335✔
2519

2520
  if (pCtx->subsidiaries.num <= 0) {
54,745,335!
2521
    return TSDB_CODE_SUCCESS;
54,748,499✔
2522
  }
2523

2524
  if (!pInfo->hasResult) {
×
2525
    code = saveTupleData(pCtx, rowIndex, pSrcBlock, &pInfo->pos);
13,231✔
2526
  } else if (!noElements) {
×
2527
    code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pInfo->pos);
2,689✔
2528
  } else { } // dothing
2529

2530
  return code;
15,958✔
2531
}
2532

2533
static int32_t doSaveCurrentVal(SqlFunctionCtx* pCtx, int32_t rowIndex, int64_t currentTs, char* pkData, int32_t type,
32,241,503✔
2534
                                char* pData) {
2535
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
32,241,503✔
2536
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
32,241,503✔
2537

2538
  if (IS_VAR_DATA_TYPE(type)) {
32,241,503!
2539
    if (type == TSDB_DATA_TYPE_JSON) {
177,546!
2540
      pInfo->bytes = getJsonValueLen(pData);
×
2541
    } else {
2542
      pInfo->bytes = varDataTLen(pData);
177,546✔
2543
    }
2544
  }
2545

2546
  (void)memcpy(pInfo->buf, pData, pInfo->bytes);
32,241,503✔
2547
  if (pkData != NULL) {
32,241,503✔
2548
    if (IS_VAR_DATA_TYPE(pInfo->pkType)) {
118!
2549
      if (pInfo->pkType == TSDB_DATA_TYPE_JSON) {
24!
2550
        pInfo->pkBytes = getJsonValueLen(pkData);
×
2551
      } else {
2552
        pInfo->pkBytes = varDataTLen(pkData);
24✔
2553
      }
2554
    }
2555
    (void)memcpy(pInfo->buf + pInfo->bytes, pkData, pInfo->pkBytes);
118✔
2556
    pInfo->pkData = pInfo->buf + pInfo->bytes;
118✔
2557
  }
2558

2559
  pInfo->ts = currentTs;
32,241,503✔
2560
  int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pInfo, false);
32,241,503✔
2561
  if (code != TSDB_CODE_SUCCESS) {
32,302,807!
2562
    return code;
×
2563
  }
2564

2565
  pInfo->hasResult = true;
32,302,807✔
2566
  return TSDB_CODE_SUCCESS;
32,302,807✔
2567
}
2568

2569
// This ordinary first function does not care if current scan is ascending order or descending order scan
2570
// the OPTIMIZED version of first function will only handle the ascending order scan
2571
int32_t firstFunction(SqlFunctionCtx* pCtx) {
29,710,788✔
2572
  int32_t numOfElems = 0;
29,710,788✔
2573

2574
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
29,710,788✔
2575
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
29,710,788✔
2576

2577
  SInputColumnInfoData* pInput = &pCtx->input;
29,710,788✔
2578
  SColumnInfoData*      pInputCol = pInput->pData[0];
29,710,788✔
2579

2580
  pInfo->bytes = pInputCol->info.bytes;
29,710,788✔
2581

2582
  if (IS_NULL_TYPE(pInputCol->info.type)) {
29,710,788✔
2583
    return TSDB_CODE_SUCCESS;
2,913✔
2584
  }
2585

2586
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
29,707,875✔
2587
  pInfo->pkType = -1;
29,707,875✔
2588
  __compar_fn_t pkCompareFn = NULL;
29,707,875✔
2589
  if (pCtx->hasPrimaryKey) {
29,707,875✔
2590
    pInfo->pkType = pkCol->info.type;
51✔
2591
    pInfo->pkBytes = pkCol->info.bytes;
51✔
2592
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_ASC);
51✔
2593
  }
2594

2595
  // All null data column, return directly.
2596
  if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) &&
29,796,283!
2597
      pInputCol->hasNull == true) {
×
2598
    // save selectivity value for column consisted of all null values
2599
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
×
2600
    if (code != TSDB_CODE_SUCCESS) {
×
2601
      return code;
×
2602
    }
2603
    pInfo->nullTupleSaved = true;
×
2604
    return TSDB_CODE_SUCCESS;
×
2605
  }
2606

2607
  SColumnDataAgg* pColAgg = (pInput->colDataSMAIsSet) ? pInput->pColumnDataAgg[0] : NULL;
29,796,283!
2608

2609
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
29,796,283!
2610
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
29,796,283!
2611

2612
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
29,796,283✔
2613

2614
  //  please ref. to the comment in lastRowFunction for the reason why disabling the opt version of last/first
2615
  //  function. we will use this opt implementation in an new version that is only available in scan subplan
2616
#if 0
2617
  if (blockDataOrder == TSDB_ORDER_ASC) {
2618
    // filter according to current result firstly
2619
    if (pResInfo->numOfRes > 0) {
2620
      if (pInfo->ts < startKey) {
2621
        return TSDB_CODE_SUCCESS;
2622
      }
2623
    }
2624

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

2630
      numOfElems++;
2631

2632
      char* data = colDataGetData(pInputCol, i);
2633
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2634
      if (pResInfo->numOfRes == 0 || pInfo->ts > cts) {
2635
        doSaveCurrentVal(pCtx, i, cts, pInputCol->info.type, data);
2636
        break;
2637
      }
2638
    }
2639
  } else {
2640
    // in case of descending order time stamp serial, which usually happens as the results of the nest query,
2641
    // all data needs to be check.
2642
    if (pResInfo->numOfRes > 0) {
2643
      if (pInfo->ts < endKey) {
2644
        return TSDB_CODE_SUCCESS;
2645
      }
2646
    }
2647

2648
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
2649
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2650
        continue;
2651
      }
2652

2653
      numOfElems++;
2654

2655
      char* data = colDataGetData(pInputCol, i);
2656
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2657

2658
      if (pResInfo->numOfRes == 0 || pInfo->ts > cts) {
2659
        doSaveCurrentVal(pCtx, i, cts, pInputCol->info.type, data);
2660
        break;
2661
      }
2662
    }
2663
  }
2664
#else
2665
  int64_t* pts = (int64_t*)pInput->pPTS->pData;
29,796,283✔
2666

2667
  int     from = -1;
29,796,283✔
2668
  int32_t i = -1;
29,796,283✔
2669
  while (funcInputGetNextRowIndex(pInput, from, true, &i, &from)) {
78,088,261✔
2670
    if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
62,916,747!
2671
      continue;
75,217✔
2672
    }
2673

2674
    numOfElems++;
48,261,380✔
2675
    char* data = colDataGetData(pInputCol, i);
48,261,380!
2676
    char* pkData = NULL;
48,261,380✔
2677
    if (pCtx->hasPrimaryKey) {
48,261,380✔
2678
      pkData = colDataGetData(pkCol, i);
153!
2679
    }
2680
    TSKEY cts = pts[i];
48,261,380✔
2681
    if (pResInfo->numOfRes == 0 || pInfo->ts > cts ||
48,261,380✔
2682
        (pInfo->ts == cts && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
30,133,218!
2683
      int32_t code = doSaveCurrentVal(pCtx, i, cts, pkData, pInputCol->info.type, data);
18,128,162✔
2684
      if (code != TSDB_CODE_SUCCESS) {
18,083,543!
2685
        return code;
×
2686
      }
2687
      pResInfo->numOfRes = 1;
18,083,543✔
2688
    }
2689
  }
2690
#endif
2691

2692
  if (numOfElems == 0) {
29,376,088✔
2693
    // save selectivity value for column consisted of all null values
2694
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
25,108✔
2695
    if (code != TSDB_CODE_SUCCESS) {
25,108!
2696
      return code;
×
2697
    }
2698
    pInfo->nullTupleSaved = true;
25,108✔
2699
  }
2700
  SET_VAL(pResInfo, numOfElems, 1);
29,376,088✔
2701
  return TSDB_CODE_SUCCESS;
29,376,088✔
2702
}
2703

2704
int32_t lastFunction(SqlFunctionCtx* pCtx) {
20,231,331✔
2705
  int32_t numOfElems = 0;
20,231,331✔
2706

2707
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
20,231,331✔
2708
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
20,231,331✔
2709

2710
  SInputColumnInfoData* pInput = &pCtx->input;
20,231,331✔
2711
  SColumnInfoData*      pInputCol = pInput->pData[0];
20,231,331✔
2712

2713
  int32_t type = pInputCol->info.type;
20,231,331✔
2714
  int32_t bytes = pInputCol->info.bytes;
20,231,331✔
2715

2716
  if (IS_NULL_TYPE(type)) {
20,231,331✔
2717
    return TSDB_CODE_SUCCESS;
2,917✔
2718
  }
2719
  pInfo->bytes = bytes;
20,228,414✔
2720

2721
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
20,228,414✔
2722
  pInfo->pkType = -1;
20,228,414✔
2723
  __compar_fn_t pkCompareFn = NULL;
20,228,414✔
2724
  if (pCtx->hasPrimaryKey) {
20,228,414✔
2725
    pInfo->pkType = pkCol->info.type;
67✔
2726
    pInfo->pkBytes = pkCol->info.bytes;
67✔
2727
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
67✔
2728
  }
2729

2730
  // All null data column, return directly.
2731
  if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) &&
20,295,329!
2732
      pInputCol->hasNull == true) {
×
2733
    // save selectivity value for column consisted of all null values
2734
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
×
2735
    if (code != TSDB_CODE_SUCCESS) {
×
2736
      return code;
×
2737
    }
2738
    pInfo->nullTupleSaved = true;
×
2739
    return TSDB_CODE_SUCCESS;
×
2740
  }
2741

2742
  SColumnDataAgg* pColAgg = (pInput->colDataSMAIsSet) ? pInput->pColumnDataAgg[0] : NULL;
20,295,329!
2743

2744
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
20,295,329!
2745
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
20,295,329!
2746

2747
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
20,295,329✔
2748

2749
  //  please ref. to the comment in lastRowFunction for the reason why disabling the opt version of last/first function.
2750
#if 0
2751
  if (blockDataOrder == TSDB_ORDER_ASC) {
2752
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
2753
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2754
        continue;
2755
      }
2756

2757
      numOfElems++;
2758

2759
      char* data = colDataGetData(pInputCol, i);
2760
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2761
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
2762
        doSaveCurrentVal(pCtx, i, cts, type, data);
2763
      }
2764

2765
      break;
2766
    }
2767
  } else {  // descending order
2768
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
2769
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2770
        continue;
2771
      }
2772

2773
      numOfElems++;
2774

2775
      char* data = colDataGetData(pInputCol, i);
2776
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2777
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
2778
        doSaveCurrentVal(pCtx, i, cts, type, data);
2779
      }
2780
      break;
2781
    }
2782
  }
2783
#else
2784
  int64_t* pts = (int64_t*)pInput->pPTS->pData;
20,295,329✔
2785

2786
#if 0
2787
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
2788
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2789
        continue;
2790
      }
2791

2792
      numOfElems++;
2793
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i]) {
2794
        char* data = colDataGetData(pInputCol, i);
2795
        doSaveCurrentVal(pCtx, i, pts[i], type, data);
2796
        pResInfo->numOfRes = 1;
2797
      }
2798
    }
2799
#else
2800

2801
  // todo refactor
2802
  if (!pInputCol->hasNull && !pCtx->hasPrimaryKey) {
34,234,894!
2803
    numOfElems = 1;
13,930,441✔
2804

2805
    int32_t round = pInput->numOfRows >> 2;
13,930,441✔
2806
    int32_t reminder = pInput->numOfRows & 0x03;
13,930,441✔
2807

2808
    for (int32_t i = pInput->startRowIndex, tick = 0; tick < round; i += 4, tick += 1) {
21,277,767✔
2809
      int64_t cts = pts[i];
7,340,129✔
2810
      int32_t chosen = i;
7,340,129✔
2811

2812
      if (cts < pts[i + 1]) {
7,340,129✔
2813
        cts = pts[i + 1];
4,896,250✔
2814
        chosen = i + 1;
4,896,250✔
2815
      }
2816

2817
      if (cts < pts[i + 2]) {
7,340,129✔
2818
        cts = pts[i + 2];
4,896,482✔
2819
        chosen = i + 2;
4,896,482✔
2820
      }
2821

2822
      if (cts < pts[i + 3]) {
7,340,129✔
2823
        cts = pts[i + 3];
4,895,493✔
2824
        chosen = i + 3;
4,895,493✔
2825
      }
2826

2827
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
7,340,129✔
2828
        char*   data = colDataGetData(pInputCol, chosen);
3,356,650!
2829
        int32_t code = doSaveCurrentVal(pCtx, chosen, cts, NULL, type, data);
3,356,650✔
2830
        if (code != TSDB_CODE_SUCCESS) {
3,363,847!
2831
          return code;
×
2832
        }
2833
        pResInfo->numOfRes = 1;
3,363,847✔
2834
      }
2835
    }
2836

2837
    for (int32_t i = pInput->startRowIndex + round * 4; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
28,944,759✔
2838
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i]) {
15,005,194✔
2839
        char*   data = colDataGetData(pInputCol, i);
7,281,274!
2840
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], NULL, type, data);
7,281,274✔
2841
        if (code != TSDB_CODE_SUCCESS) {
7,283,201!
2842
          return code;
×
2843
        }
2844
        pResInfo->numOfRes = 1;
7,283,201✔
2845
      }
2846
    }
2847
  } else {
2848
    int     from = -1;
6,364,888✔
2849
    int32_t i = -1;
6,364,888✔
2850
    while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
24,237,751✔
2851
      if (colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
35,748,894✔
2852
        continue;
5,562,824✔
2853
      }
2854

2855
      numOfElems++;
12,311,623✔
2856
      char* pkData = NULL;
12,311,623✔
2857
      if (pCtx->hasPrimaryKey) {
12,311,623✔
2858
        pkData = colDataGetData(pkCol, i);
193!
2859
      }
2860
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i] ||
12,311,623✔
2861
          (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
8,934,381!
2862
        char*   data = colDataGetData(pInputCol, i);
3,441,463!
2863
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], pkData, type, data);
3,441,463✔
2864
        if (code != TSDB_CODE_SUCCESS) {
3,439,879!
2865
          return code;
×
2866
        }
2867
        pResInfo->numOfRes = 1;
3,439,879✔
2868
      }
2869
    }
2870
  }
2871
#endif
2872

2873
#endif
2874

2875
  // save selectivity value for column consisted of all null values
2876
  if (numOfElems == 0) {
20,492,420✔
2877
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
4,078,832✔
2878
    if (code != TSDB_CODE_SUCCESS) {
4,075,233!
2879
      return code;
×
2880
    }
2881
    pInfo->nullTupleSaved = true;
4,075,233✔
2882
  }
2883

2884
  return TSDB_CODE_SUCCESS;
20,488,821✔
2885
}
2886

2887
static bool firstLastTransferInfoImpl(SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst) {
18,512,409✔
2888
  if (!pInput->hasResult) {
18,512,409✔
2889
    return false;
2✔
2890
  }
2891
  __compar_fn_t pkCompareFn = NULL;
18,512,407✔
2892
  if (pInput->pkData) {
18,512,407✔
2893
    pkCompareFn = getKeyComparFunc(pInput->pkType, (isFirst) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC);
49✔
2894
  }
2895
  if (pOutput->hasResult) {
18,512,407✔
2896
    if (isFirst) {
11,206,282✔
2897
      if (pInput->ts > pOutput->ts ||
8,571,677✔
2898
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
8,571,226!
2899
        return false;
451✔
2900
      }
2901
    } else {
2902
      if (pInput->ts < pOutput->ts ||
2,634,605✔
2903
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
2,630,622!
2904
        return false;
3,983✔
2905
      }
2906
    }
2907
  }
2908

2909
  pOutput->isNull = pInput->isNull;
18,507,973✔
2910
  pOutput->ts = pInput->ts;
18,507,973✔
2911
  pOutput->bytes = pInput->bytes;
18,507,973✔
2912
  pOutput->pkType = pInput->pkType;
18,507,973✔
2913

2914
  (void)memcpy(pOutput->buf, pInput->buf, pOutput->bytes);
18,507,973✔
2915
  if (pInput->pkData) {
18,507,973✔
2916
    pOutput->pkBytes = pInput->pkBytes;
42✔
2917
    (void)memcpy(pOutput->buf + pOutput->bytes, pInput->pkData, pOutput->pkBytes);
42✔
2918
    pOutput->pkData = pOutput->buf + pOutput->bytes;
42✔
2919
  }
2920
  return true;
18,507,973✔
2921
}
2922

2923
static int32_t firstLastTransferInfo(SqlFunctionCtx* pCtx, SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst,
18,512,393✔
2924
                                     int32_t rowIndex) {
2925
  if (firstLastTransferInfoImpl(pInput, pOutput, isFirst)) {
18,512,393✔
2926
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pOutput, false);
18,507,960✔
2927
    if (TSDB_CODE_SUCCESS != code) {
18,507,960!
2928
      return code;
×
2929
    }
2930
    pOutput->hasResult = true;
18,507,960✔
2931
  }
2932
  return TSDB_CODE_SUCCESS;
18,512,393✔
2933
}
2934

2935
static int32_t firstLastFunctionMergeImpl(SqlFunctionCtx* pCtx, bool isFirstQuery) {
7,320,628✔
2936
  SInputColumnInfoData* pInput = &pCtx->input;
7,320,628✔
2937
  SColumnInfoData*      pCol = pInput->pData[0];
7,320,628✔
2938

2939
  if (IS_NULL_TYPE(pCol->info.type)) {
7,320,628!
2940
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
2941
    return TSDB_CODE_SUCCESS;
×
2942
  }
2943

2944
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
7,320,628!
2945
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
2946
  }
2947

2948
  SFirstLastRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
7,320,628✔
2949

2950
  int32_t start = pInput->startRowIndex;
7,320,628✔
2951
  int32_t numOfElems = 0;
7,320,628✔
2952

2953
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
28,118,316✔
2954
    if (colDataIsNull_s(pCol, i)) {
41,595,376✔
2955
      continue;
2,285,295✔
2956
    }
2957
    char*          data = colDataGetData(pCol, i);
18,512,393!
2958
    SFirstLastRes* pInputInfo = (SFirstLastRes*)varDataVal(data);
18,512,393✔
2959
    if (pCtx->hasPrimaryKey) {
18,512,393✔
2960
      pInputInfo->pkData = pInputInfo->buf + pInputInfo->bytes;
49✔
2961
    } else {
2962
      pInputInfo->pkData = NULL;
18,512,344✔
2963
    }
2964

2965
    int32_t code = firstLastTransferInfo(pCtx, pInputInfo, pInfo, isFirstQuery, i);
18,512,393✔
2966
    if (code != TSDB_CODE_SUCCESS) {
18,512,393!
2967
      return code;
×
2968
    }
2969
    if (!numOfElems) {
18,512,393✔
2970
      numOfElems = pInputInfo->hasResult ? 1 : 0;
7,312,525✔
2971
    }
2972
  }
2973

2974
  if (numOfElems == 0) {
7,320,628✔
2975
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
8,103✔
2976
    if (code != TSDB_CODE_SUCCESS) {
8,103!
2977
      return code;
×
2978
    }
2979
    pInfo->nullTupleSaved = true;
8,103✔
2980
  }
2981

2982
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
7,320,628✔
2983
  return TSDB_CODE_SUCCESS;
7,320,628✔
2984
}
2985

2986
int32_t firstFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, true); }
4,267,268✔
2987

2988
int32_t lastFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, false); }
3,053,360✔
2989

2990
int32_t firstLastFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
8,876,500✔
2991
  int32_t          code = TSDB_CODE_SUCCESS;
8,876,500✔
2992
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
8,876,500✔
2993
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
8,876,500✔
2994
  if (NULL == pCol) {
8,876,502!
2995
    return TSDB_CODE_OUT_OF_RANGE;
×
2996
  }
2997

2998
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
8,876,502✔
2999
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
8,876,502✔
3000

3001
  SFirstLastRes* pRes = GET_ROWCELL_INTERBUF(pResInfo);
8,876,502✔
3002

3003
  if (pResInfo->isNullRes) {
8,876,502✔
3004
    colDataSetNULL(pCol, pBlock->info.rows);
36,796✔
3005
    return setNullSelectivityValue(pCtx, pBlock, pBlock->info.rows);
36,796✔
3006
  }
3007
  code = colDataSetVal(pCol, pBlock->info.rows, pRes->buf, pRes->isNull || pResInfo->isNullRes);
8,839,706!
3008
  if (TSDB_CODE_SUCCESS != code) {
8,839,706!
3009
    return code;
×
3010
  }
3011

3012
  // handle selectivity
3013
  code = setSelectivityValue(pCtx, pBlock, &pRes->pos, pBlock->info.rows);
8,839,706✔
3014

3015
  return code;
8,839,705✔
3016
}
3017

3018
int32_t firstLastPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
22,628,985✔
3019
  int32_t code = TSDB_CODE_SUCCESS;
22,628,985✔
3020

3021
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
22,628,985✔
3022
  SFirstLastRes*       pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
22,628,985✔
3023

3024
  int32_t resultBytes = getFirstLastInfoSize(pRes->bytes, pRes->pkBytes);
22,628,985✔
3025

3026
  // todo check for failure
3027
  char* res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
22,580,579!
3028
  if (NULL == res) {
23,024,164!
3029
    return terrno;
×
3030
  }
3031
  (void)memcpy(varDataVal(res), pRes, resultBytes);
23,024,164✔
3032

3033
  varDataSetLen(res, resultBytes);
23,024,164✔
3034

3035
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
23,024,164✔
3036
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
23,024,164✔
3037
  if (NULL == pCol) {
22,959,094!
3038
    taosMemoryFree(res);
×
3039
    return TSDB_CODE_OUT_OF_RANGE;
×
3040
  }
3041

3042
  if (pEntryInfo->numOfRes == 0) {
22,968,338✔
3043
    colDataSetNULL(pCol, pBlock->info.rows);
2,385,059!
3044
    code = setNullSelectivityValue(pCtx, pBlock, pBlock->info.rows);
2,385,059✔
3045
  } else {
3046
    code = colDataSetVal(pCol, pBlock->info.rows, res, false);
20,583,279✔
3047
    if (TSDB_CODE_SUCCESS != code) {
20,352,514!
3048
      taosMemoryFree(res);
×
3049
      return code;
×
3050
    }
3051
    code = setSelectivityValue(pCtx, pBlock, &pRes->pos, pBlock->info.rows);
20,352,514✔
3052
  }
3053
  taosMemoryFree(res);
22,720,616✔
3054
  return code;
22,839,792✔
3055
}
3056

3057
int32_t lastCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
13✔
3058
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
13✔
3059
  SFirstLastRes*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
13✔
3060
  int32_t              bytes = pDBuf->bytes;
13✔
3061

3062
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
13✔
3063
  SFirstLastRes*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
13✔
3064

3065
  pDBuf->hasResult = firstLastTransferInfoImpl(pSBuf, pDBuf, false);
13✔
3066
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
13✔
3067
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
13✔
3068
  return TSDB_CODE_SUCCESS;
13✔
3069
}
3070

3071
static int32_t doSaveLastrow(SqlFunctionCtx* pCtx, char* pData, int32_t rowIndex, int64_t cts, SFirstLastRes* pInfo) {
13,369✔
3072
  SInputColumnInfoData* pInput = &pCtx->input;
13,369✔
3073
  SColumnInfoData*      pInputCol = pInput->pData[0];
13,369✔
3074
  SColumnInfoData*      pkCol = pInput->pPrimaryKey;
13,369✔
3075

3076
  if (colDataIsNull_s(pInputCol, rowIndex)) {
26,738✔
3077
    pInfo->isNull = true;
2,138✔
3078
  } else {
3079
    pInfo->isNull = false;
11,231✔
3080

3081
    if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
11,231!
3082
      if (pInputCol->info.type == TSDB_DATA_TYPE_JSON) {
397!
3083
        pInfo->bytes = getJsonValueLen(pData);
×
3084
      } else {
3085
        pInfo->bytes = varDataTLen(pData);
397✔
3086
      }
3087
    }
3088

3089
    (void)memcpy(pInfo->buf, pData, pInfo->bytes);
11,231✔
3090
  }
3091

3092
  if (pCtx->hasPrimaryKey && !colDataIsNull_s(pkCol, rowIndex)) {
13,440!
3093
    char* pkData = colDataGetData(pkCol, rowIndex);
71!
3094
    if (IS_VAR_DATA_TYPE(pInfo->pkType)) {
71!
3095
      if (pInfo->pkType == TSDB_DATA_TYPE_JSON) {
12!
3096
        pInfo->pkBytes = getJsonValueLen(pkData);
×
3097
      } else {
3098
        pInfo->pkBytes = varDataTLen(pkData);
12✔
3099
      }
3100
    }
3101
    (void)memcpy(pInfo->buf + pInfo->bytes, pkData, pInfo->pkBytes);
71✔
3102
    pInfo->pkData = pInfo->buf + pInfo->bytes;
71✔
3103
  }
3104
  pInfo->ts = cts;
13,369✔
3105
  int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pInfo, false);
13,369✔
3106
  if (code != TSDB_CODE_SUCCESS) {
13,402!
3107
    return code;
×
3108
  }
3109

3110
  pInfo->hasResult = true;
13,402✔
3111

3112
  return TSDB_CODE_SUCCESS;
13,402✔
3113
}
3114

3115
int32_t lastRowFunction(SqlFunctionCtx* pCtx) {
27,153✔
3116
  int32_t numOfElems = 0;
27,153✔
3117

3118
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
27,153✔
3119
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
27,153✔
3120

3121
  SInputColumnInfoData* pInput = &pCtx->input;
27,153✔
3122
  SColumnInfoData*      pInputCol = pInput->pData[0];
27,153✔
3123

3124
  int32_t type = pInputCol->info.type;
27,153✔
3125
  int32_t bytes = pInputCol->info.bytes;
27,153✔
3126
  pInfo->bytes = bytes;
27,153✔
3127

3128
  if (IS_NULL_TYPE(type)) {
27,153✔
3129
    return TSDB_CODE_SUCCESS;
56✔
3130
  }
3131
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
27,097✔
3132
  pInfo->pkType = -1;
27,097✔
3133
  __compar_fn_t pkCompareFn = NULL;
27,097✔
3134
  if (pCtx->hasPrimaryKey) {
27,097✔
3135
    pInfo->pkType = pkCol->info.type;
57✔
3136
    pInfo->pkBytes = pkCol->info.bytes;
57✔
3137
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
57✔
3138
  }
3139
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
27,082✔
3140
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
27,082✔
3141

3142
  if (pCtx->order == TSDB_ORDER_ASC && !pCtx->hasPrimaryKey) {
27,082!
3143
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
45,589!
3144
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
22,760✔
3145
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
22,760!
3146
      TSKEY cts = getRowPTs(pInput->pPTS, i);
22,760!
3147
      numOfElems++;
22,760✔
3148

3149
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
22,760✔
3150
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
5,549✔
3151
        if (code != TSDB_CODE_SUCCESS) return code;
5,661!
3152
      }
3153

3154
      break;
22,872✔
3155
    }
3156
  } else if (!pCtx->hasPrimaryKey && pCtx->order == TSDB_ORDER_DESC) {
4,365✔
3157
    // the optimized version only valid if all tuples in one block are monotonious increasing or descreasing.
3158
    // this assumption is NOT always works if project operator exists in downstream.
3159
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
7,918!
3160
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
3,967✔
3161
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
3,967!
3162
      TSKEY cts = getRowPTs(pInput->pPTS, i);
3,967✔
3163
      numOfElems++;
3,967✔
3164

3165
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
3,967✔
3166
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
3,751✔
3167
        if (code != TSDB_CODE_SUCCESS) return code;
3,745!
3168
      }
3169
      break;
3,961✔
3170
    }
3171
  } else {
3172
    int64_t* pts = (int64_t*)pInput->pPTS->pData;
408✔
3173
    int      from = -1;
408✔
3174
    int32_t  i = -1;
408✔
3175
    while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
12,095✔
3176
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
11,687✔
3177
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
11,687!
3178
      TSKEY cts = pts[i];
11,687✔
3179

3180
      numOfElems++;
11,687✔
3181
      char* pkData = NULL;
11,687✔
3182
      if (pCtx->hasPrimaryKey) {
11,687✔
3183
        pkData = colDataGetData(pkCol, i);
171!
3184
      }
3185
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts ||
11,687✔
3186
          (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
9,792!
3187
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
1,901✔
3188
        if (code != TSDB_CODE_SUCCESS) {
1,901!
3189
          return code;
×
3190
        }
3191
        pResInfo->numOfRes = 1;
1,901✔
3192
      }
3193
    }
3194
  }
3195

3196
  SET_VAL(pResInfo, numOfElems, 1);
27,163!
3197
  return TSDB_CODE_SUCCESS;
27,163✔
3198
}
3199

3200
bool getDiffFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
4,005✔
3201
  pEnv->calcMemSize = sizeof(SDiffInfo);
4,005✔
3202
  return true;
4,005✔
3203
}
3204

3205
int32_t diffFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
375,718✔
3206
  if (pResInfo->initialized) {
375,718✔
3207
    return TSDB_CODE_SUCCESS;
319,559✔
3208
  }
3209
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
56,159!
3210
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
3211
  }
3212
  SDiffInfo* pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
56,159✔
3213
  pDiffInfo->hasPrev = false;
56,159✔
3214
  pDiffInfo->isFirstRow = true;
56,159✔
3215
  pDiffInfo->prev.i64 = 0;
56,159✔
3216
  pDiffInfo->prevTs = -1;
56,159✔
3217
  if (pCtx->numOfParams > 1) {
56,159!
3218
    pDiffInfo->ignoreOption = pCtx->param[1].param.i;  // TODO set correct param
56,159✔
3219
  } else {
3220
    pDiffInfo->ignoreOption = 0;
×
3221
  }
3222
  return TSDB_CODE_SUCCESS;
56,159✔
3223
}
3224

3225
static int32_t doSetPrevVal(SDiffInfo* pDiffInfo, int32_t type, const char* pv, int64_t ts) {
54,962✔
3226
  switch (type) {
54,962!
3227
    case TSDB_DATA_TYPE_BOOL:
28✔
3228
      pDiffInfo->prev.i64 = *(bool*)pv ? 1 : 0;
28✔
3229
      break;
28✔
3230
    case TSDB_DATA_TYPE_UTINYINT:
347✔
3231
    case TSDB_DATA_TYPE_TINYINT:
3232
      pDiffInfo->prev.i64 = *(int8_t*)pv;
347✔
3233
      break;
347✔
3234
    case TSDB_DATA_TYPE_UINT:
53,336✔
3235
    case TSDB_DATA_TYPE_INT:
3236
      pDiffInfo->prev.i64 = *(int32_t*)pv;
53,336✔
3237
      break;
53,336✔
3238
    case TSDB_DATA_TYPE_USMALLINT:
341✔
3239
    case TSDB_DATA_TYPE_SMALLINT:
3240
      pDiffInfo->prev.i64 = *(int16_t*)pv;
341✔
3241
      break;
341✔
3242
    case TSDB_DATA_TYPE_TIMESTAMP:
286✔
3243
    case TSDB_DATA_TYPE_UBIGINT:
3244
    case TSDB_DATA_TYPE_BIGINT:
3245
      pDiffInfo->prev.i64 = *(int64_t*)pv;
286✔
3246
      break;
286✔
3247
    case TSDB_DATA_TYPE_FLOAT:
196✔
3248
      pDiffInfo->prev.d64 = *(float*)pv;
196✔
3249
      break;
196✔
3250
    case TSDB_DATA_TYPE_DOUBLE:
428✔
3251
      pDiffInfo->prev.d64 = *(double*)pv;
428✔
3252
      break;
428✔
3253
    default:
×
3254
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3255
  }
3256
  pDiffInfo->prevTs = ts;
54,962✔
3257
  pDiffInfo->hasPrev = true;
54,962✔
3258
  return TSDB_CODE_SUCCESS;
54,962✔
3259
}
3260

3261
static bool diffIsNegtive(SDiffInfo* pDiffInfo, int32_t type, const char* pv) {
32,175✔
3262
  switch (type) {
32,175!
3263
    case TSDB_DATA_TYPE_UINT: {
×
3264
      int64_t v = *(uint32_t*)pv;
×
3265
      return v < pDiffInfo->prev.i64;
×
3266
    }
3267
    case TSDB_DATA_TYPE_INT: {
4,299✔
3268
      int64_t v = *(int32_t*)pv;
4,299✔
3269
      return v < pDiffInfo->prev.i64;
4,299✔
3270
    }
3271
    case TSDB_DATA_TYPE_BOOL: {
×
3272
      int64_t v = *(bool*)pv;
×
3273
      return v < pDiffInfo->prev.i64;
×
3274
    }
3275
    case TSDB_DATA_TYPE_UTINYINT: {
×
3276
      int64_t v = *(uint8_t*)pv;
×
3277
      return v < pDiffInfo->prev.i64;
×
3278
    }
3279
    case TSDB_DATA_TYPE_TINYINT: {
5,737✔
3280
      int64_t v = *(int8_t*)pv;
5,737✔
3281
      return v < pDiffInfo->prev.i64;
5,737✔
3282
    }
3283
    case TSDB_DATA_TYPE_USMALLINT: {
×
3284
      int64_t v = *(uint16_t*)pv;
×
3285
      return v < pDiffInfo->prev.i64;
×
3286
    }
3287
    case TSDB_DATA_TYPE_SMALLINT: {
6,177✔
3288
      int64_t v = *(int16_t*)pv;
6,177✔
3289
      return v < pDiffInfo->prev.i64;
6,177✔
3290
    }
3291
    case TSDB_DATA_TYPE_UBIGINT: {
24✔
3292
      uint64_t v = *(uint64_t*)pv;
24✔
3293
      return v < (uint64_t)pDiffInfo->prev.i64;
24✔
3294
    }
3295
    case TSDB_DATA_TYPE_TIMESTAMP:
6,080✔
3296
    case TSDB_DATA_TYPE_BIGINT: {
3297
      int64_t v = *(int64_t*)pv;
6,080✔
3298
      return v < pDiffInfo->prev.i64;
6,080✔
3299
    }
3300
    case TSDB_DATA_TYPE_FLOAT: {
3,097✔
3301
      float v = *(float*)pv;
3,097✔
3302
      return v < pDiffInfo->prev.d64;
3,097✔
3303
    }
3304
    case TSDB_DATA_TYPE_DOUBLE: {
6,761✔
3305
      double v = *(double*)pv;
6,761✔
3306
      return v < pDiffInfo->prev.d64;
6,761✔
3307
    }
3308
    default:
×
3309
      return false;
×
3310
  }
3311

3312
  return false;
3313
}
3314

3315
static void tryToSetInt64(SDiffInfo* pDiffInfo, int32_t type, SColumnInfoData* pOutput, int64_t v, int32_t pos) {
27,474,258✔
3316
  bool isNegative = v < pDiffInfo->prev.i64;
27,474,258✔
3317
  if (type == TSDB_DATA_TYPE_UBIGINT) {
27,474,258✔
3318
    isNegative = (uint64_t)v < (uint64_t)pDiffInfo->prev.i64;
453✔
3319
  }
3320
  int64_t delta = v - pDiffInfo->prev.i64;
27,474,258✔
3321
  if (isNegative && ignoreNegative(pDiffInfo->ignoreOption)) {
27,474,258✔
3322
    colDataSetNull_f_s(pOutput, pos);
10,995✔
3323
    pOutput->hasNull = true;
10,995✔
3324
  } else {
3325
    colDataSetInt64(pOutput, pos, &delta);
27,463,263✔
3326
  }
3327
  pDiffInfo->prev.i64 = v;
27,474,258✔
3328
}
27,474,258✔
3329

3330
static void tryToSetDouble(SDiffInfo* pDiffInfo, SColumnInfoData* pOutput, double v, int32_t pos) {
91,495✔
3331
  double delta = v - pDiffInfo->prev.d64;
91,495✔
3332
  if (delta < 0 && ignoreNegative(pDiffInfo->ignoreOption)) {
91,495✔
3333
    colDataSetNull_f_s(pOutput, pos);
4,951✔
3334
  } else {
3335
    colDataSetDouble(pOutput, pos, &delta);
86,544✔
3336
  }
3337
  pDiffInfo->prev.d64 = v;
91,495✔
3338
}
91,495✔
3339

3340
static int32_t doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, SColumnInfoData* pOutput, int32_t pos,
27,566,322✔
3341
                            int64_t ts) {
3342
  if (!pDiffInfo->hasPrev) {
27,566,322✔
3343
    colDataSetNull_f_s(pOutput, pos);
569✔
3344
    return doSetPrevVal(pDiffInfo, type, pv, ts);
569✔
3345
  }
3346
  pDiffInfo->prevTs = ts;
27,565,753✔
3347
  switch (type) {
27,565,753!
3348
    case TSDB_DATA_TYPE_UINT: {
411✔
3349
      int64_t v = *(uint32_t*)pv;
411✔
3350
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
411✔
3351
      break;
411✔
3352
    }
3353
    case TSDB_DATA_TYPE_INT: {
26,246,725✔
3354
      int64_t v = *(int32_t*)pv;
26,246,725✔
3355
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
26,246,725✔
3356
      break;
26,246,725✔
3357
    }
3358
    case TSDB_DATA_TYPE_BOOL: {
10,617✔
3359
      int64_t v = *(bool*)pv;
10,617✔
3360
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
10,617✔
3361
      break;
10,617✔
3362
    }
3363
    case TSDB_DATA_TYPE_UTINYINT: {
405✔
3364
      int64_t v = *(uint8_t*)pv;
405✔
3365
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
405✔
3366
      break;
405✔
3367
    }
3368
    case TSDB_DATA_TYPE_TINYINT: {
36,743✔
3369
      int64_t v = *(int8_t*)pv;
36,743✔
3370
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
36,743✔
3371
      break;
36,743✔
3372
    }
3373
    case TSDB_DATA_TYPE_USMALLINT: {
405✔
3374
      int64_t v = *(uint16_t*)pv;
405✔
3375
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
405✔
3376
      break;
405✔
3377
    }
3378
    case TSDB_DATA_TYPE_SMALLINT: {
39,571✔
3379
      int64_t v = *(int16_t*)pv;
39,571✔
3380
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
39,571✔
3381
      break;
39,571✔
3382
    }
3383
    case TSDB_DATA_TYPE_TIMESTAMP:
1,139,381✔
3384
    case TSDB_DATA_TYPE_UBIGINT:
3385
    case TSDB_DATA_TYPE_BIGINT: {
3386
      int64_t v = *(int64_t*)pv;
1,139,381✔
3387
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
1,139,381✔
3388
      break;
1,139,381✔
3389
    }
3390
    case TSDB_DATA_TYPE_FLOAT: {
43,654✔
3391
      double v = *(float*)pv;
43,654✔
3392
      tryToSetDouble(pDiffInfo, pOutput, v, pos);
43,654✔
3393
      break;
43,654✔
3394
    }
3395
    case TSDB_DATA_TYPE_DOUBLE: {
47,841✔
3396
      double v = *(double*)pv;
47,841✔
3397
      tryToSetDouble(pDiffInfo, pOutput, v, pos);
47,841✔
3398
      break;
47,841✔
3399
    }
3400
    default:
×
3401
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3402
  }
3403
  pDiffInfo->hasPrev = true;
27,565,753✔
3404
  return TSDB_CODE_SUCCESS;
27,565,753✔
3405
}
3406

3407
// TODO: the primary key compare can be skipped for ordered pk if knonwn before
3408
// TODO: for desc ordered, pk shall select the smallest one for one ts. if across block boundaries.
3409
bool funcInputGetNextRowIndex(SInputColumnInfoData* pInput, int32_t from, bool firstOccur, int32_t* pRowIndex,
101,848,744✔
3410
                              int32_t* nextFrom) {
3411
  if (pInput->pPrimaryKey == NULL) {
101,848,744!
3412
    if (from == -1) {
101,921,555✔
3413
      from = pInput->startRowIndex;
37,304,674✔
3414
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
64,616,881✔
3415
      return false;
37,074,620✔
3416
    }
3417
    *pRowIndex = from;
64,846,935✔
3418
    *nextFrom = from + 1;
64,846,935✔
3419
    return true;
64,846,935✔
3420
  } else {
3421
    if (from == -1) {
×
3422
      from = pInput->startRowIndex;
175✔
3423
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
×
3424
      return false;
175✔
3425
    }
3426
    TSKEY*           tsList = (int64_t*)pInput->pPTS->pData;
×
3427
    SColumnInfoData* pkCol = pInput->pPrimaryKey;
×
3428
    int8_t           pkType = pkCol->info.type;
×
3429
    int32_t          order = (firstOccur) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
×
3430
    __compar_fn_t    compareFunc = getKeyComparFunc(pkType, order);
×
3431
    int32_t          select = from;
517✔
3432
    char*            val = colDataGetData(pkCol, select);
517!
3433
    while (from < pInput->numOfRows + pInput->startRowIndex - 1 && tsList[from + 1] == tsList[from]) {
1,072✔
3434
      char* val1 = colDataGetData(pkCol, from + 1);
555!
3435
      if (compareFunc(val1, val) < 0) {
555!
3436
        select = from + 1;
×
3437
        val = val1;
×
3438
      }
3439
      from = from + 1;
555✔
3440
    }
3441
    *pRowIndex = select;
517✔
3442
    *nextFrom = from + 1;
517✔
3443
    return true;
517✔
3444
  }
3445
}
3446

3447
bool getForecastConfEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
26✔
3448
  pEnv->calcMemSize = sizeof(float);
26✔
3449
  return true;
26✔
3450
}
3451

3452
int32_t diffResultIsNull(SqlFunctionCtx* pCtx, SFuncInputRow* pRow) {
27,721,062✔
3453
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
27,721,062✔
3454
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
27,721,062✔
3455

3456
  if (pRow->isDataNull || !pDiffInfo->hasPrev) {
27,721,062✔
3457
    return true;
155,237✔
3458
  } else if (ignoreNegative(pDiffInfo->ignoreOption)) {
27,565,825✔
3459
    return diffIsNegtive(pDiffInfo, pCtx->input.pData[0]->info.type, pRow->pData);
32,175✔
3460
  }
3461
  return false;
27,533,650✔
3462
}
3463

3464
bool isFirstRow(SqlFunctionCtx* pCtx, SFuncInputRow* pRow) {
27,720,777✔
3465
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
27,720,777✔
3466
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
27,720,777✔
3467
  return pDiffInfo->isFirstRow;
27,720,777✔
3468
}
3469

3470
int32_t trySetPreVal(SqlFunctionCtx* pCtx, SFuncInputRow* pRow) {
56,265✔
3471
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
56,265✔
3472
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
56,265✔
3473
  pDiffInfo->isFirstRow = false;
56,265✔
3474
  if (pRow->isDataNull) {
56,265✔
3475
    return TSDB_CODE_SUCCESS;
1,872✔
3476
  }
3477

3478
  SInputColumnInfoData* pInput = &pCtx->input;
54,393✔
3479
  SColumnInfoData*      pInputCol = pInput->pData[0];
54,393✔
3480
  int8_t                inputType = pInputCol->info.type;
54,393✔
3481

3482
  char* pv = pRow->pData;
54,393✔
3483
  return doSetPrevVal(pDiffInfo, inputType, pv, pRow->ts);
54,393✔
3484
}
3485

3486
int32_t setDoDiffResult(SqlFunctionCtx* pCtx, SFuncInputRow* pRow, int32_t pos) {
27,664,797✔
3487
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
27,664,797✔
3488
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
27,664,797✔
3489

3490
  SInputColumnInfoData* pInput = &pCtx->input;
27,664,797✔
3491
  SColumnInfoData*      pInputCol = pInput->pData[0];
27,664,797✔
3492
  int8_t                inputType = pInputCol->info.type;
27,664,797✔
3493
  SColumnInfoData*      pOutput = (SColumnInfoData*)pCtx->pOutput;
27,664,797✔
3494
  int32_t               code = TSDB_CODE_SUCCESS;
27,664,797✔
3495
  if (pRow->isDataNull) {
27,664,797✔
3496
    colDataSetNull_f_s(pOutput, pos);
98,454✔
3497
    pOutput->hasNull = true;
98,454✔
3498

3499
    // handle selectivity
3500
    if (pCtx->subsidiaries.num > 0) {
98,454✔
3501
      code = appendSelectivityCols(pCtx, pRow->block, pRow->rowIndex, pos);
149✔
3502
      if (code != TSDB_CODE_SUCCESS) {
149!
3503
        return code;
×
3504
      }
3505
    }
3506
    return TSDB_CODE_SUCCESS;
98,454✔
3507
  }
3508

3509
  char* pv = pRow->pData;
27,566,343✔
3510

3511
  if (pRow->ts == pDiffInfo->prevTs) {
27,566,343✔
3512
    return TSDB_CODE_FUNC_DUP_TIMESTAMP;
21✔
3513
  }
3514
  code = doHandleDiff(pDiffInfo, inputType, pv, pOutput, pos, pRow->ts);
27,566,322✔
3515
  if (code != TSDB_CODE_SUCCESS) {
27,566,322!
3516
    return code;
×
3517
  }
3518
  // handle selectivity
3519
  if (pCtx->subsidiaries.num > 0) {
27,566,322✔
3520
    code = appendSelectivityCols(pCtx, pRow->block, pRow->rowIndex, pos);
26,701,951✔
3521
    if (code != TSDB_CODE_SUCCESS) {
26,701,951!
3522
      return code;
×
3523
    }
3524
  }
3525

3526
  return TSDB_CODE_SUCCESS;
27,566,322✔
3527
}
3528

3529
int32_t diffFunction(SqlFunctionCtx* pCtx) { return TSDB_CODE_SUCCESS; }
371,713✔
3530

3531
int32_t diffFunctionByRow(SArray* pCtxArray) {
371,557✔
3532
  int32_t code = TSDB_CODE_SUCCESS;
371,557✔
3533
  int     diffColNum = pCtxArray->size;
371,557✔
3534
  if (diffColNum == 0) {
371,557!
3535
    return TSDB_CODE_SUCCESS;
×
3536
  }
3537
  int32_t numOfElems = 0;
371,557✔
3538

3539
  SArray* pRows = taosArrayInit_s(sizeof(SFuncInputRow), diffColNum);
371,557✔
3540
  if (NULL == pRows) {
371,557!
3541
    return terrno;
×
3542
  }
3543

3544
  bool keepNull = false;
371,557✔
3545
  for (int i = 0; i < diffColNum; ++i) {
743,270✔
3546
    SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
371,713✔
3547
    if (NULL == pCtx) {
371,713!
3548
      code = terrno;
×
3549
      goto _exit;
×
3550
    }
3551
    funcInputUpdate(pCtx);
371,713✔
3552
    SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
371,713✔
3553
    SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
371,713✔
3554
    if (!ignoreNull(pDiffInfo->ignoreOption)) {
371,713✔
3555
      keepNull = true;
371,590✔
3556
    }
3557
  }
3558

3559
  SqlFunctionCtx* pCtx0 = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, 0);
371,557✔
3560
  SFuncInputRow*  pRow0 = (SFuncInputRow*)taosArrayGet(pRows, 0);
371,557✔
3561
  if (NULL == pCtx0 || NULL == pRow0) {
371,557!
3562
    code = terrno;
×
3563
    goto _exit;
×
3564
  }
3565
  int32_t startOffset = pCtx0->offset;
371,557✔
3566
  bool    result = false;
371,557✔
3567
  while (1) {
27,706,547✔
3568
    code = funcInputGetNextRow(pCtx0, pRow0, &result);
28,078,104✔
3569
    if (TSDB_CODE_SUCCESS != code) {
28,078,104!
3570
      goto _exit;
×
3571
    }
3572
    if (!result) {
28,078,104✔
3573
      break;
371,536✔
3574
    }
3575
    bool hasNotNullValue = !diffResultIsNull(pCtx0, pRow0);
27,706,568✔
3576
    for (int i = 1; i < diffColNum; ++i) {
27,721,062✔
3577
      SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
14,494✔
3578
      SFuncInputRow*  pRow = (SFuncInputRow*)taosArrayGet(pRows, i);
14,494✔
3579
      if (NULL == pCtx || NULL == pRow) {
14,494!
3580
        code = terrno;
×
3581
        goto _exit;
×
3582
      }
3583
      code = funcInputGetNextRow(pCtx, pRow, &result);
14,494✔
3584
      if (TSDB_CODE_SUCCESS != code) {
14,494!
3585
        goto _exit;
×
3586
      }
3587
      if (!result) {
14,494!
3588
        // rows are not equal
3589
        code = TSDB_CODE_QRY_EXECUTOR_INTERNAL_ERROR;
×
3590
        goto _exit;
×
3591
      }
3592
      if (!diffResultIsNull(pCtx, pRow)) {
14,494✔
3593
        hasNotNullValue = true;
14,052✔
3594
      }
3595
    }
3596
    int32_t pos = startOffset + numOfElems;
27,706,568✔
3597

3598
    bool newRow = false;
27,706,568✔
3599
    for (int i = 0; i < diffColNum; ++i) {
55,427,609✔
3600
      SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
27,721,062✔
3601
      SFuncInputRow*  pRow = (SFuncInputRow*)taosArrayGet(pRows, i);
27,721,062✔
3602
      if (NULL == pCtx || NULL == pRow) {
27,721,062!
3603
        code = terrno;
×
3604
        goto _exit;
×
3605
      }
3606
      if ((keepNull || hasNotNullValue) && !isFirstRow(pCtx, pRow)) {
27,721,062✔
3607
        code = setDoDiffResult(pCtx, pRow, pos);
27,664,797✔
3608
        if (code != TSDB_CODE_SUCCESS) {
27,664,797✔
3609
          goto _exit;
21✔
3610
        }
3611
        newRow = true;
27,664,776✔
3612
      } else {
3613
        code = trySetPreVal(pCtx, pRow);
56,265✔
3614
        if (code != TSDB_CODE_SUCCESS) {
56,265!
3615
          goto _exit;
×
3616
        }
3617
      }
3618
    }
3619
    if (newRow) ++numOfElems;
27,706,547✔
3620
  }
3621

3622
  for (int i = 0; i < diffColNum; ++i) {
743,225✔
3623
    SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
371,689✔
3624
    if (NULL == pCtx) {
371,689!
3625
      code = terrno;
×
3626
      goto _exit;
×
3627
    }
3628
    SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
371,689✔
3629
    pResInfo->numOfRes = numOfElems;
371,689✔
3630
  }
3631

3632
_exit:
371,536✔
3633
  if (pRows) {
371,557!
3634
    taosArrayDestroy(pRows);
371,557✔
3635
    pRows = NULL;
371,557✔
3636
  }
3637
  return code;
371,557✔
3638
}
3639

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

3642
bool getTopBotFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
11,084✔
3643
  SValueNode* pkNode = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
11,084✔
3644
  pEnv->calcMemSize = sizeof(STopBotRes) + pkNode->datum.i * sizeof(STopBotResItem);
11,089✔
3645
  return true;
11,089✔
3646
}
3647

3648
int32_t topBotFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
24,381✔
3649
  if (pResInfo->initialized) {
24,381!
3650
    return TSDB_CODE_SUCCESS;
×
3651
  }
3652
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
24,381!
3653
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
3654
  }
3655

3656
  STopBotRes*           pRes = GET_ROWCELL_INTERBUF(pResInfo);
24,378✔
3657
  SInputColumnInfoData* pInput = &pCtx->input;
24,378✔
3658

3659
  pRes->maxSize = pCtx->param[1].param.i;
24,378✔
3660

3661
  pRes->nullTupleSaved = false;
24,378✔
3662
  pRes->nullTuplePos.pageId = -1;
24,378✔
3663
  return TSDB_CODE_SUCCESS;
24,378✔
3664
}
3665

3666
static STopBotRes* getTopBotOutputInfo(SqlFunctionCtx* pCtx) {
478,785✔
3667
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
478,785✔
3668
  STopBotRes*          pRes = GET_ROWCELL_INTERBUF(pResInfo);
478,785✔
3669
  pRes->pItems = (STopBotResItem*)((char*)pRes + sizeof(STopBotRes));
478,785✔
3670

3671
  return pRes;
478,785✔
3672
}
3673

3674
static int32_t doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock,
3675
                               uint16_t type, uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery);
3676

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

3679
int32_t topFunction(SqlFunctionCtx* pCtx) {
23,748✔
3680
  int32_t              numOfElems = 0;
23,748✔
3681
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
23,748✔
3682

3683
  SInputColumnInfoData* pInput = &pCtx->input;
23,748✔
3684
  SColumnInfoData*      pCol = pInput->pData[0];
23,748✔
3685

3686
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
23,748✔
3687
  pRes->type = pInput->pData[0]->info.type;
23,746✔
3688

3689
  int32_t start = pInput->startRowIndex;
23,746✔
3690
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
375,596✔
3691
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
351,583✔
3692
      continue;
23,583✔
3693
    }
3694

3695
    numOfElems++;
328,000✔
3696
    char*   data = colDataGetData(pCol, i);
328,000!
3697
    int32_t code = doAddIntoResult(pCtx, data, i, pCtx->pSrcBlock, pRes->type, pInput->uid, pResInfo, true);
328,000✔
3698
    if (code != TSDB_CODE_SUCCESS) {
328,267!
3699
      return code;
×
3700
    }
3701
  }
3702

3703
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pRes->nullTupleSaved) {
24,013✔
3704
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pRes->nullTuplePos);
116✔
3705
    if (code != TSDB_CODE_SUCCESS) {
116!
3706
      return code;
×
3707
    }
3708
    pRes->nullTupleSaved = true;
116✔
3709
  }
3710
  return TSDB_CODE_SUCCESS;
24,013✔
3711
}
3712

3713
int32_t bottomFunction(SqlFunctionCtx* pCtx) {
3,024✔
3714
  int32_t              numOfElems = 0;
3,024✔
3715
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
3,024✔
3716

3717
  SInputColumnInfoData* pInput = &pCtx->input;
3,024✔
3718
  SColumnInfoData*      pCol = pInput->pData[0];
3,024✔
3719

3720
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
3,024✔
3721
  pRes->type = pInput->pData[0]->info.type;
3,023✔
3722

3723
  int32_t start = pInput->startRowIndex;
3,023✔
3724
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
127,727✔
3725
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
124,662✔
3726
      continue;
24,000✔
3727
    }
3728

3729
    numOfElems++;
100,662✔
3730
    char*   data = colDataGetData(pCol, i);
100,662!
3731
    int32_t code = doAddIntoResult(pCtx, data, i, pCtx->pSrcBlock, pRes->type, pInput->uid, pResInfo, false);
100,662✔
3732
    if (code != TSDB_CODE_SUCCESS) {
100,704!
3733
      return code;
×
3734
    }
3735
  }
3736

3737
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pRes->nullTupleSaved) {
3,065✔
3738
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pRes->nullTuplePos);
125✔
3739
    if (code != TSDB_CODE_SUCCESS) {
125!
3740
      return code;
×
3741
    }
3742
    pRes->nullTupleSaved = true;
125✔
3743
  }
3744

3745
  return TSDB_CODE_SUCCESS;
3,065✔
3746
}
3747

3748
static int32_t topBotResComparFn(const void* p1, const void* p2, const void* param) {
1,529,081✔
3749
  uint16_t type = *(uint16_t*)param;
1,529,081✔
3750

3751
  STopBotResItem* val1 = (STopBotResItem*)p1;
1,529,081✔
3752
  STopBotResItem* val2 = (STopBotResItem*)p2;
1,529,081✔
3753

3754
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
1,529,081!
3755
    if (val1->v.i == val2->v.i) {
828,620✔
3756
      return 0;
168,519✔
3757
    }
3758

3759
    return (val1->v.i > val2->v.i) ? 1 : -1;
660,101✔
3760
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
700,461!
3761
    if (val1->v.u == val2->v.u) {
477,618✔
3762
      return 0;
103,840✔
3763
    }
3764

3765
    return (val1->v.u > val2->v.u) ? 1 : -1;
373,778✔
3766
  } else if (TSDB_DATA_TYPE_FLOAT == type) {
222,843✔
3767
    if (val1->v.f == val2->v.f) {
27,500✔
3768
      return 0;
63✔
3769
    }
3770

3771
    return (val1->v.f > val2->v.f) ? 1 : -1;
27,437✔
3772
  }
3773

3774
  if (val1->v.d == val2->v.d) {
195,343✔
3775
    return 0;
11✔
3776
  }
3777

3778
  return (val1->v.d > val2->v.d) ? 1 : -1;
195,332✔
3779
}
3780

3781
int32_t doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, uint16_t type,
428,376✔
3782
                        uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery) {
3783
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
428,376✔
3784
  int32_t     code = TSDB_CODE_SUCCESS;
428,000✔
3785

3786
  SVariant val = {0};
428,000✔
3787
  TAOS_CHECK_RETURN(taosVariantCreateFromBinary(&val, pData, tDataTypes[type].bytes, type));
428,000!
3788

3789
  STopBotResItem* pItems = pRes->pItems;
428,766✔
3790

3791
  // not full yet
3792
  if (pEntryInfo->numOfRes < pRes->maxSize) {
428,766✔
3793
    STopBotResItem* pItem = &pItems[pEntryInfo->numOfRes];
113,331✔
3794
    pItem->v = val;
113,331✔
3795
    pItem->uid = uid;
113,331✔
3796

3797
    // save the data of this tuple
3798
    if (pCtx->subsidiaries.num > 0) {
113,331✔
3799
      code = saveTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
44,998✔
3800
      if (code != TSDB_CODE_SUCCESS) {
44,910!
3801
        return code;
×
3802
      }
3803
    }
3804
#ifdef BUF_PAGE_DEBUG
3805
    qDebug("page_saveTuple i:%d, item:%p,pageId:%d, offset:%d\n", pEntryInfo->numOfRes, pItem, pItem->tuplePos.pageId,
3806
           pItem->tuplePos.offset);
3807
#endif
3808
    // allocate the buffer and keep the data of this row into the new allocated buffer
3809
    pEntryInfo->numOfRes++;
113,243✔
3810
    code = taosheapsort((void*)pItems, sizeof(STopBotResItem), pEntryInfo->numOfRes, (const void*)&type,
113,243✔
3811
                        topBotResComparFn, !isTopQuery);
113,243✔
3812
    if (code != TSDB_CODE_SUCCESS) {
113,647!
3813
      return code;
×
3814
    }
3815
  } else {  // replace the minimum value in the result
3816
    if ((isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i > pItems[0].v.i) ||
315,435!
3817
                        (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u > pItems[0].v.u) ||
167,748✔
3818
                        (TSDB_DATA_TYPE_FLOAT == type && val.f > pItems[0].v.f) ||
113,253✔
3819
                        (TSDB_DATA_TYPE_DOUBLE == type && val.d > pItems[0].v.d))) ||
112,094✔
3820
        (!isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i < pItems[0].v.i) ||
175,152!
3821
                         (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u < pItems[0].v.u) ||
76,945!
3822
                         (TSDB_DATA_TYPE_FLOAT == type && val.f < pItems[0].v.f) ||
75,973✔
3823
                         (TSDB_DATA_TYPE_DOUBLE == type && val.d < pItems[0].v.d)))) {
74,995✔
3824
      // replace the old data and the coresponding tuple data
3825
      STopBotResItem* pItem = &pItems[0];
149,197✔
3826
      pItem->v = val;
149,197✔
3827
      pItem->uid = uid;
149,197✔
3828

3829
      // save the data of this tuple by over writing the old data
3830
      if (pCtx->subsidiaries.num > 0) {
149,197✔
3831
        code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
115,806✔
3832
        if (code != TSDB_CODE_SUCCESS) {
115,183!
3833
          return code;
×
3834
        }
3835
      }
3836
#ifdef BUF_PAGE_DEBUG
3837
      qDebug("page_copyTuple pageId:%d, offset:%d", pItem->tuplePos.pageId, pItem->tuplePos.offset);
3838
#endif
3839
      code = taosheapadjust((void*)pItems, sizeof(STopBotResItem), 0, pEntryInfo->numOfRes - 1, (const void*)&type,
148,574✔
3840
                            topBotResComparFn, NULL, !isTopQuery);
148,574✔
3841
      if (code != TSDB_CODE_SUCCESS) {
149,286!
3842
        return code;
×
3843
      }
3844
    }
3845
  }
3846

3847
  return TSDB_CODE_SUCCESS;
429,171✔
3848
}
3849

3850
/*
3851
 * +------------------------------------+--------------+--------------+
3852
 * |            null bitmap             |              |              |
3853
 * |(n columns, one bit for each column)| src column #1| src column #2|
3854
 * +------------------------------------+--------------+--------------+
3855
 */
3856
int32_t serializeTupleData(const SSDataBlock* pSrcBlock, int32_t rowIndex, SSubsidiaryResInfo* pSubsidiaryies,
270,285✔
3857
                           char* buf, char** res) {
3858
  char* nullList = buf;
270,285✔
3859
  char* pStart = (char*)(nullList + sizeof(bool) * pSubsidiaryies->num);
270,285✔
3860

3861
  int32_t offset = 0;
270,285✔
3862
  for (int32_t i = 0; i < pSubsidiaryies->num; ++i) {
571,946✔
3863
    SqlFunctionCtx* pc = pSubsidiaryies->pCtx[i];
301,747✔
3864

3865
    // group_key function has its own process function
3866
    // do not process there
3867
    if (fmIsGroupKeyFunc(pc->functionId)) {
301,747!
3868
      continue;
×
3869
    }
3870

3871
    SFunctParam* pFuncParam = &pc->pExpr->base.pParam[0];
301,707✔
3872
    int32_t      srcSlotId = pFuncParam->pCol->slotId;
301,707✔
3873

3874
    SColumnInfoData* pCol = taosArrayGet(pSrcBlock->pDataBlock, srcSlotId);
301,707✔
3875
    if (NULL == pCol) {
301,661!
3876
      return TSDB_CODE_OUT_OF_RANGE;
×
3877
    }
3878
    if ((nullList[i] = colDataIsNull_s(pCol, rowIndex)) == true) {
603,322✔
3879
      offset += pCol->info.bytes;
749✔
3880
      continue;
749✔
3881
    }
3882

3883
    char* p = colDataGetData(pCol, rowIndex);
300,912!
3884
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
300,912!
3885
      (void)memcpy(pStart + offset, p, (pCol->info.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(p) : varDataTLen(p));
31,278!
3886
    } else {
3887
      (void)memcpy(pStart + offset, p, pCol->info.bytes);
269,634✔
3888
    }
3889

3890
    offset += pCol->info.bytes;
300,912✔
3891
  }
3892

3893
  *res = buf;
270,199✔
3894
  return TSDB_CODE_SUCCESS;
270,199✔
3895
}
3896

3897
static int32_t doSaveTupleData(SSerializeDataHandle* pHandle, const void* pBuf, size_t length, SWinKey* key,
429,668✔
3898
                               STuplePos* pPos, SFunctionStateStore* pStore) {
3899
  STuplePos p = {0};
429,668✔
3900
  if (pHandle->pBuf != NULL) {
429,668✔
3901
    SFilePage* pPage = NULL;
405,945✔
3902

3903
    if (pHandle->currentPage == -1) {
405,945✔
3904
      pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
21,244✔
3905
      if (pPage == NULL) {
21,253!
3906
        return terrno;
×
3907
      }
3908
      pPage->num = sizeof(SFilePage);
21,253✔
3909
    } else {
3910
      pPage = getBufPage(pHandle->pBuf, pHandle->currentPage);
384,701✔
3911
      if (pPage == NULL) {
384,688!
3912
        return terrno;
×
3913
      }
3914
      if (pPage->num + length > getBufPageSize(pHandle->pBuf)) {
384,688✔
3915
        // current page is all used, let's prepare a new buffer page
3916
        releaseBufPage(pHandle->pBuf, pPage);
9,454✔
3917
        pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
9,454✔
3918
        if (pPage == NULL) {
9,454!
3919
          return terrno;
×
3920
        }
3921
        pPage->num = sizeof(SFilePage);
9,454✔
3922
      }
3923
    }
3924

3925
    p = (STuplePos){.pageId = pHandle->currentPage, .offset = pPage->num};
405,928✔
3926
    (void)memcpy(pPage->data + pPage->num, pBuf, length);
405,928✔
3927

3928
    pPage->num += length;
405,928✔
3929
    setBufPageDirty(pPage, true);
405,928✔
3930
    releaseBufPage(pHandle->pBuf, pPage);
405,856✔
3931
  } else {  // other tuple save policy
3932
    if (pStore->streamStateFuncPut(pHandle->pState, key, pBuf, length) >= 0) {
23,723!
3933
      p.streamTupleKey = *key;
23,723✔
3934
    }
3935
  }
3936

3937
  *pPos = p;
429,491✔
3938
  return TSDB_CODE_SUCCESS;
429,491✔
3939
}
3940

3941
int32_t saveTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
97,814✔
3942
  int32_t code = prepareBuf(pCtx);
97,814✔
3943
  if (TSDB_CODE_SUCCESS != code) {
97,815!
3944
    return code;
×
3945
  }
3946

3947
  SWinKey key = {0};
97,815✔
3948
  if (pCtx->saveHandle.pBuf == NULL) {
97,815✔
3949
    SColumnInfoData* pColInfo = taosArrayGet(pSrcBlock->pDataBlock, pCtx->saveHandle.pState->tsIndex);
23,722✔
3950
    if (NULL == pColInfo) {
23,722!
3951
      return TSDB_CODE_OUT_OF_RANGE;
×
3952
    }
3953
    if (pColInfo->info.type != TSDB_DATA_TYPE_TIMESTAMP) {
23,722!
3954
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3955
    }
3956
    key.groupId = pSrcBlock->info.id.groupId;
23,722✔
3957
    key.ts = *(int64_t*)colDataGetData(pColInfo, rowIndex);
23,722!
3958
  }
3959

3960
  char* buf = NULL;
97,815✔
3961
  code = serializeTupleData(pSrcBlock, rowIndex, &pCtx->subsidiaries, pCtx->subsidiaries.buf, &buf);
97,815✔
3962
  if (TSDB_CODE_SUCCESS != code) {
97,789!
3963
    return code;
×
3964
  }
3965
  return doSaveTupleData(&pCtx->saveHandle, buf, pCtx->subsidiaries.rowLen, &key, pPos, pCtx->pStore);
97,789✔
3966
}
3967

3968
static int32_t doUpdateTupleData(SSerializeDataHandle* pHandle, const void* pBuf, size_t length, STuplePos* pPos,
172,512✔
3969
                                 SFunctionStateStore* pStore) {
3970
  if (pHandle->pBuf != NULL) {
172,512✔
3971
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
128,715✔
3972
    if (pPage == NULL) {
128,573!
3973
      return terrno;
×
3974
    }
3975
    (void)memcpy(pPage->data + pPos->offset, pBuf, length);
128,573✔
3976
    setBufPageDirty(pPage, true);
128,573✔
3977
    releaseBufPage(pHandle->pBuf, pPage);
128,521✔
3978
  } else {
3979
    int32_t code = pStore->streamStateFuncPut(pHandle->pState, &pPos->streamTupleKey, pBuf, length);
43,797✔
3980
    if (TSDB_CODE_SUCCESS != code) {
43,803!
3981
      return code;
×
3982
    }
3983
  }
3984

3985
  return TSDB_CODE_SUCCESS;
172,097✔
3986
}
3987

3988
int32_t updateTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
172,717✔
3989
  int32_t code = prepareBuf(pCtx);
172,717✔
3990
  if (TSDB_CODE_SUCCESS != code) {
172,665!
3991
    return code;
×
3992
  }
3993

3994
  char* buf = NULL;
172,665✔
3995
  code = serializeTupleData(pSrcBlock, rowIndex, &pCtx->subsidiaries, pCtx->subsidiaries.buf, &buf);
172,665✔
3996
  if (TSDB_CODE_SUCCESS != code) {
172,508!
3997
    return code;
×
3998
  }
3999
  return doUpdateTupleData(&pCtx->saveHandle, buf, pCtx->subsidiaries.rowLen, pPos, pCtx->pStore);
172,508✔
4000
}
4001

4002
static int32_t doLoadTupleData(SSerializeDataHandle* pHandle, const STuplePos* pPos, SFunctionStateStore* pStore,
96,117✔
4003
                               char** value) {
4004
  if (pHandle->pBuf != NULL) {
96,117✔
4005
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
72,419✔
4006
    if (pPage == NULL) {
72,427!
4007
      *value = NULL;
×
4008
      return terrno;
×
4009
    }
4010
    *value = pPage->data + pPos->offset;
72,427✔
4011
    releaseBufPage(pHandle->pBuf, pPage);
72,427✔
4012
    return TSDB_CODE_SUCCESS;
72,424✔
4013
  } else {
4014
    *value = NULL;
23,698✔
4015
    int32_t vLen;
4016
    int32_t code = pStore->streamStateFuncGet(pHandle->pState, &pPos->streamTupleKey, (void**)(value), &vLen);
23,698✔
4017
    if (TSDB_CODE_SUCCESS != code) {
23,696!
4018
      return code;
×
4019
    }
4020
    return TSDB_CODE_SUCCESS;
23,696✔
4021
  }
4022
}
4023

4024
int32_t loadTupleData(SqlFunctionCtx* pCtx, const STuplePos* pPos, char** value) {
96,116✔
4025
  return doLoadTupleData(&pCtx->saveHandle, pPos, pCtx->pStore, value);
96,116✔
4026
}
4027

4028
int32_t topBotFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
24,365✔
4029
  int32_t code = TSDB_CODE_SUCCESS;
24,365✔
4030

4031
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
24,365✔
4032
  STopBotRes*          pRes = getTopBotOutputInfo(pCtx);
24,365✔
4033

4034
  int16_t type = pCtx->pExpr->base.resSchema.type;
24,364✔
4035
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
24,364✔
4036

4037
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
24,364✔
4038
  if (NULL == pCol) {
24,362!
4039
    return TSDB_CODE_OUT_OF_RANGE;
×
4040
  }
4041

4042
  // todo assign the tag value and the corresponding row data
4043
  int32_t currentRow = pBlock->info.rows;
24,362✔
4044
  if (pEntryInfo->numOfRes <= 0) {
24,362✔
4045
    colDataSetNULL(pCol, currentRow);
501!
4046
    code = setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, currentRow);
501✔
4047
    return code;
501✔
4048
  }
4049
  for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
137,517✔
4050
    STopBotResItem* pItem = &pRes->pItems[i];
113,635✔
4051
    code = colDataSetVal(pCol, currentRow, (const char*)&pItem->v.i, false);
113,635✔
4052
    if (TSDB_CODE_SUCCESS != code) {
113,647!
4053
      return code;
×
4054
    }
4055
#ifdef BUF_PAGE_DEBUG
4056
    qDebug("page_finalize i:%d,item:%p,pageId:%d, offset:%d\n", i, pItem, pItem->tuplePos.pageId,
4057
           pItem->tuplePos.offset);
4058
#endif
4059
    code = setSelectivityValue(pCtx, pBlock, &pRes->pItems[i].tuplePos, currentRow);
113,647✔
4060
    if (TSDB_CODE_SUCCESS != code) {
113,656!
4061
      return code;
×
4062
    }
4063
    currentRow += 1;
113,656✔
4064
  }
4065

4066
  return code;
23,882✔
4067
}
4068

4069
int32_t addResult(SqlFunctionCtx* pCtx, STopBotResItem* pSourceItem, int16_t type, bool isTopQuery) {
×
4070
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
×
4071
  STopBotRes*          pRes = getTopBotOutputInfo(pCtx);
×
4072
  STopBotResItem*      pItems = pRes->pItems;
×
4073
  int32_t              code = TSDB_CODE_SUCCESS;
×
4074

4075
  // not full yet
4076
  if (pEntryInfo->numOfRes < pRes->maxSize) {
×
4077
    STopBotResItem* pItem = &pItems[pEntryInfo->numOfRes];
×
4078
    pItem->v = pSourceItem->v;
×
4079
    pItem->uid = pSourceItem->uid;
×
4080
    pItem->tuplePos.pageId = -1;
×
4081
    replaceTupleData(&pItem->tuplePos, &pSourceItem->tuplePos);
×
4082
    pEntryInfo->numOfRes++;
×
4083
    code = taosheapsort((void*)pItems, sizeof(STopBotResItem), pEntryInfo->numOfRes, (const void*)&type,
×
4084
                        topBotResComparFn, !isTopQuery);
×
4085
    if (TSDB_CODE_SUCCESS != code) {
×
4086
      return code;
×
4087
    }
4088
  } else {  // replace the minimum value in the result
4089
    if ((isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && pSourceItem->v.i > pItems[0].v.i) ||
×
4090
                        (IS_UNSIGNED_NUMERIC_TYPE(type) && pSourceItem->v.u > pItems[0].v.u) ||
×
4091
                        (TSDB_DATA_TYPE_FLOAT == type && pSourceItem->v.f > pItems[0].v.f) ||
×
4092
                        (TSDB_DATA_TYPE_DOUBLE == type && pSourceItem->v.d > pItems[0].v.d))) ||
×
4093
        (!isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && pSourceItem->v.i < pItems[0].v.i) ||
×
4094
                         (IS_UNSIGNED_NUMERIC_TYPE(type) && pSourceItem->v.u < pItems[0].v.u) ||
×
4095
                         (TSDB_DATA_TYPE_FLOAT == type && pSourceItem->v.f < pItems[0].v.f) ||
×
4096
                         (TSDB_DATA_TYPE_DOUBLE == type && pSourceItem->v.d < pItems[0].v.d)))) {
×
4097
      // replace the old data and the coresponding tuple data
4098
      STopBotResItem* pItem = &pItems[0];
×
4099
      pItem->v = pSourceItem->v;
×
4100
      pItem->uid = pSourceItem->uid;
×
4101

4102
      // save the data of this tuple by over writing the old data
4103
      replaceTupleData(&pItem->tuplePos, &pSourceItem->tuplePos);
×
4104
      code = taosheapadjust((void*)pItems, sizeof(STopBotResItem), 0, pEntryInfo->numOfRes - 1, (const void*)&type,
×
4105
                            topBotResComparFn, NULL, !isTopQuery);
×
4106
      if (TSDB_CODE_SUCCESS != code) {
×
4107
        return code;
×
4108
      }
4109
    }
4110
  }
4111
  return code;
×
4112
}
4113

4114
int32_t topCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4115
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4116
  STopBotRes*          pSBuf = getTopBotOutputInfo(pSourceCtx);
×
4117
  int16_t              type = pSBuf->type;
×
4118
  int32_t              code = TSDB_CODE_SUCCESS;
×
4119
  for (int32_t i = 0; i < pSResInfo->numOfRes; i++) {
×
4120
    code = addResult(pDestCtx, pSBuf->pItems + i, type, true);
×
4121
    if (TSDB_CODE_SUCCESS != code) {
×
4122
      return code;
×
4123
    }
4124
  }
4125
  return TSDB_CODE_SUCCESS;
×
4126
}
4127

4128
int32_t bottomCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4129
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4130
  STopBotRes*          pSBuf = getTopBotOutputInfo(pSourceCtx);
×
4131
  int16_t              type = pSBuf->type;
×
4132
  int32_t              code = TSDB_CODE_SUCCESS;
×
4133
  for (int32_t i = 0; i < pSResInfo->numOfRes; i++) {
×
4134
    code = addResult(pDestCtx, pSBuf->pItems + i, type, false);
×
4135
    if (TSDB_CODE_SUCCESS != code) {
×
4136
      return code;
×
4137
    }
4138
  }
4139
  return TSDB_CODE_SUCCESS;
×
4140
}
4141

4142
int32_t getSpreadInfoSize() { return (int32_t)sizeof(SSpreadInfo); }
22,694✔
4143

4144
bool getSpreadFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
57,778✔
4145
  pEnv->calcMemSize = sizeof(SSpreadInfo);
57,778✔
4146
  return true;
57,778✔
4147
}
4148

4149
int32_t spreadFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
277,746✔
4150
  if (pResultInfo->initialized) {
277,746!
4151
    return TSDB_CODE_SUCCESS;
×
4152
  }
4153
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
277,746!
4154
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
4155
  }
4156

4157
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
277,723✔
4158
  SET_DOUBLE_VAL(&pInfo->min, DBL_MAX);
277,723✔
4159
  SET_DOUBLE_VAL(&pInfo->max, -DBL_MAX);
277,723✔
4160
  pInfo->hasResult = false;
277,723✔
4161
  return TSDB_CODE_SUCCESS;
277,723✔
4162
}
4163

4164
int32_t spreadFunction(SqlFunctionCtx* pCtx) {
289,098✔
4165
  int32_t numOfElems = 0;
289,098✔
4166

4167
  // Only the pre-computing information loaded and actual data does not loaded
4168
  SInputColumnInfoData* pInput = &pCtx->input;
289,098✔
4169
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
289,098✔
4170
  int32_t               type = pInput->pData[0]->info.type;
289,098✔
4171

4172
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
289,098✔
4173

4174
  if (pInput->colDataSMAIsSet) {
289,098!
4175
    numOfElems = pInput->numOfRows - pAgg->numOfNull;
×
4176
    if (numOfElems == 0) {
×
4177
      goto _spread_over;
×
4178
    }
4179
    double tmin = 0.0, tmax = 0.0;
×
4180
    if (IS_SIGNED_NUMERIC_TYPE(type) || IS_TIMESTAMP_TYPE(type)) {
×
4181
      tmin = (double)GET_INT64_VAL(&pAgg->min);
×
4182
      tmax = (double)GET_INT64_VAL(&pAgg->max);
×
4183
    } else if (IS_FLOAT_TYPE(type)) {
×
4184
      tmin = GET_DOUBLE_VAL(&pAgg->min);
×
4185
      tmax = GET_DOUBLE_VAL(&pAgg->max);
×
4186
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
4187
      tmin = (double)GET_UINT64_VAL(&pAgg->min);
×
4188
      tmax = (double)GET_UINT64_VAL(&pAgg->max);
×
4189
    }
4190

4191
    if (GET_DOUBLE_VAL(&pInfo->min) > tmin) {
×
4192
      SET_DOUBLE_VAL(&pInfo->min, tmin);
×
4193
    }
4194

4195
    if (GET_DOUBLE_VAL(&pInfo->max) < tmax) {
×
4196
      SET_DOUBLE_VAL(&pInfo->max, tmax);
×
4197
    }
4198

4199
  } else {  // computing based on the true data block
4200
    SColumnInfoData* pCol = pInput->pData[0];
289,098✔
4201

4202
    int32_t start = pInput->startRowIndex;
289,098✔
4203
    // check the valid data one by one
4204
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
5,705,915✔
4205
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
5,416,657✔
4206
        continue;
1,837,576✔
4207
      }
4208

4209
      char* data = colDataGetData(pCol, i);
3,579,081!
4210

4211
      double v = 0;
3,579,081✔
4212
      GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pCol->info));
3,579,081!
4213
      if (v < GET_DOUBLE_VAL(&pInfo->min)) {
3,579,241✔
4214
        SET_DOUBLE_VAL(&pInfo->min, v);
263,897✔
4215
      }
4216

4217
      if (v > GET_DOUBLE_VAL(&pInfo->max)) {
3,579,241✔
4218
        SET_DOUBLE_VAL(&pInfo->max, v);
681,479✔
4219
      }
4220

4221
      numOfElems += 1;
3,579,241✔
4222
    }
4223
  }
4224

4225
_spread_over:
289,258✔
4226
  // data in the check operation are all null, not output
4227
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
289,258✔
4228
  if (numOfElems > 0) {
289,258✔
4229
    pInfo->hasResult = true;
252,865✔
4230
  }
4231

4232
  return TSDB_CODE_SUCCESS;
289,258✔
4233
}
4234

4235
static void spreadTransferInfo(SSpreadInfo* pInput, SSpreadInfo* pOutput) {
21,111✔
4236
  pOutput->hasResult = pInput->hasResult;
21,111✔
4237
  if (pInput->max > pOutput->max) {
21,111✔
4238
    pOutput->max = pInput->max;
16,693✔
4239
  }
4240

4241
  if (pInput->min < pOutput->min) {
21,111✔
4242
    pOutput->min = pInput->min;
16,704✔
4243
  }
4244
}
21,111✔
4245

4246
int32_t spreadFunctionMerge(SqlFunctionCtx* pCtx) {
17,175✔
4247
  SInputColumnInfoData* pInput = &pCtx->input;
17,175✔
4248
  SColumnInfoData*      pCol = pInput->pData[0];
17,175✔
4249

4250
  if (IS_NULL_TYPE(pCol->info.type)) {
17,175!
4251
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
4252
    return TSDB_CODE_SUCCESS;
×
4253
  }
4254

4255
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
17,175!
4256
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
4257
  }
4258

4259
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
17,175✔
4260

4261
  int32_t start = pInput->startRowIndex;
17,175✔
4262
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
38,518✔
4263
    if (colDataIsNull_s(pCol, i)) continue;
42,686!
4264
    char*        data = colDataGetData(pCol, i);
21,343!
4265
    SSpreadInfo* pInputInfo = (SSpreadInfo*)varDataVal(data);
21,343✔
4266
    if (pInputInfo->hasResult) {
21,343✔
4267
      spreadTransferInfo(pInputInfo, pInfo);
21,110✔
4268
    }
4269
  }
4270

4271
  if (pInfo->hasResult) {
17,175✔
4272
    GET_RES_INFO(pCtx)->numOfRes = 1;
17,011✔
4273
  }
4274

4275
  return TSDB_CODE_SUCCESS;
17,175✔
4276
}
4277

4278
int32_t spreadFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
247,029✔
4279
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
247,029✔
4280
  if (pInfo->hasResult == true) {
247,029✔
4281
    SET_DOUBLE_VAL(&pInfo->result, pInfo->max - pInfo->min);
211,254✔
4282
  } else {
4283
    GET_RES_INFO(pCtx)->isNullRes = 1;
35,775✔
4284
  }
4285
  return functionFinalize(pCtx, pBlock);
247,029✔
4286
}
4287

4288
int32_t spreadPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
21,137✔
4289
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
21,137✔
4290
  SSpreadInfo*         pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
21,137✔
4291
  int32_t              resultBytes = getSpreadInfoSize();
21,137✔
4292
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
21,137!
4293

4294
  if (NULL == res) {
21,137!
4295
    return terrno;
×
4296
  }
4297
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
21,137✔
4298
  varDataSetLen(res, resultBytes);
21,137✔
4299

4300
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
21,137✔
4301
  int32_t          code = TSDB_CODE_SUCCESS;
21,137✔
4302
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
21,137✔
4303
  if (NULL == pCol) {
21,137!
4304
    code = terrno;
×
4305
    goto _exit;
×
4306
  }
4307

4308
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
21,137✔
4309
  if (TSDB_CODE_SUCCESS != code) {
21,136!
4310
    goto _exit;
×
4311
  }
4312

4313
_exit:
21,136✔
4314
  taosMemoryFree(res);
21,136!
4315
  return code;
21,136✔
4316
}
4317

4318
int32_t spreadCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
1✔
4319
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
1✔
4320
  SSpreadInfo*         pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
1✔
4321

4322
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
1✔
4323
  SSpreadInfo*         pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
1✔
4324
  spreadTransferInfo(pSBuf, pDBuf);
1✔
4325
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
1✔
4326
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
1✔
4327
  return TSDB_CODE_SUCCESS;
1✔
4328
}
4329

4330
int32_t getElapsedInfoSize() { return (int32_t)sizeof(SElapsedInfo); }
×
4331

4332
bool getElapsedFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
20,730✔
4333
  pEnv->calcMemSize = sizeof(SElapsedInfo);
20,730✔
4334
  return true;
20,730✔
4335
}
4336

4337
int32_t elapsedFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
38,779✔
4338
  if (pResultInfo->initialized) {
38,779!
4339
    return TSDB_CODE_SUCCESS;
×
4340
  }
4341
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
38,779!
4342
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
4343
  }
4344

4345
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
38,786✔
4346
  pInfo->result = 0;
38,786✔
4347
  pInfo->min = TSKEY_MAX;
38,786✔
4348
  pInfo->max = 0;
38,786✔
4349

4350
  if (pCtx->numOfParams > 1) {
38,786✔
4351
    pInfo->timeUnit = pCtx->param[1].param.i;
23,529✔
4352
  } else {
4353
    pInfo->timeUnit = 1;
15,257✔
4354
  }
4355

4356
  return TSDB_CODE_SUCCESS;
38,786✔
4357
}
4358

4359
int32_t elapsedFunction(SqlFunctionCtx* pCtx) {
38,824✔
4360
  int32_t numOfElems = 0;
38,824✔
4361

4362
  // Only the pre-computing information loaded and actual data does not loaded
4363
  SInputColumnInfoData* pInput = &pCtx->input;
38,824✔
4364
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
38,824✔
4365

4366
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
38,824✔
4367

4368
  numOfElems = pInput->numOfRows;  // since this is the primary timestamp, no need to exclude NULL values
38,824✔
4369
  if (numOfElems == 0) {
38,824✔
4370
    // for stream
4371
    if (pCtx->end.key != INT64_MIN) {
52!
4372
      pInfo->max = pCtx->end.key + 1;
52✔
4373
    }
4374
    goto _elapsed_over;
52✔
4375
  }
4376

4377
  if (pInput->colDataSMAIsSet) {
38,772!
4378
    if (pInfo->min == TSKEY_MAX) {
×
4379
      pInfo->min = GET_INT64_VAL(&pAgg->min);
×
4380
      pInfo->max = GET_INT64_VAL(&pAgg->max);
×
4381
    } else {
4382
      if (pCtx->order == TSDB_ORDER_ASC) {
×
4383
        pInfo->max = GET_INT64_VAL(&pAgg->max);
×
4384
      } else {
4385
        pInfo->min = GET_INT64_VAL(&pAgg->min);
×
4386
      }
4387
    }
4388
  } else {  // computing based on the true data block
4389
    if (0 == pInput->numOfRows) {
38,772!
4390
      if (pCtx->order == TSDB_ORDER_DESC) {
×
4391
        if (pCtx->end.key != INT64_MIN) {
×
4392
          pInfo->min = pCtx->end.key;
×
4393
        }
4394
      } else {
4395
        if (pCtx->end.key != INT64_MIN) {
×
4396
          pInfo->max = pCtx->end.key + 1;
×
4397
        }
4398
      }
4399
      goto _elapsed_over;
×
4400
    }
4401

4402
    SColumnInfoData* pCol = pInput->pData[0];
38,772✔
4403

4404
    int32_t start = pInput->startRowIndex;
38,772✔
4405
    TSKEY*  ptsList = (int64_t*)colDataGetData(pCol, 0);
38,772!
4406
    if (pCtx->order == TSDB_ORDER_DESC) {
38,772✔
4407
      if (pCtx->start.key == INT64_MIN) {
216!
4408
        pInfo->max = (pInfo->max < ptsList[start]) ? ptsList[start] : pInfo->max;
216✔
4409
      } else {
4410
        pInfo->max = pCtx->start.key + 1;
×
4411
      }
4412

4413
      if (pCtx->end.key == INT64_MIN) {
216!
4414
        pInfo->min =
216✔
4415
            (pInfo->min > ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->min;
216✔
4416
      } else {
4417
        pInfo->min = pCtx->end.key;
×
4418
      }
4419
    } else {
4420
      if (pCtx->start.key == INT64_MIN) {
38,556✔
4421
        pInfo->min = (pInfo->min > ptsList[start]) ? ptsList[start] : pInfo->min;
36,635✔
4422
      } else {
4423
        pInfo->min = pCtx->start.key;
1,921✔
4424
      }
4425

4426
      if (pCtx->end.key == INT64_MIN) {
38,556✔
4427
        pInfo->max =
36,320✔
4428
            (pInfo->max < ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->max;
36,320✔
4429
      } else {
4430
        pInfo->max = pCtx->end.key + 1;
2,236✔
4431
      }
4432
    }
4433
  }
4434

4435
_elapsed_over:
38,824✔
4436
  // data in the check operation are all null, not output
4437
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
38,824✔
4438

4439
  return TSDB_CODE_SUCCESS;
38,824✔
4440
}
4441

4442
static void elapsedTransferInfo(SElapsedInfo* pInput, SElapsedInfo* pOutput) {
×
4443
  pOutput->timeUnit = pInput->timeUnit;
×
4444
  if (pOutput->min > pInput->min) {
×
4445
    pOutput->min = pInput->min;
×
4446
  }
4447

4448
  if (pOutput->max < pInput->max) {
×
4449
    pOutput->max = pInput->max;
×
4450
  }
4451
}
×
4452

4453
int32_t elapsedFunctionMerge(SqlFunctionCtx* pCtx) {
×
4454
  SInputColumnInfoData* pInput = &pCtx->input;
×
4455
  SColumnInfoData*      pCol = pInput->pData[0];
×
4456
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
×
4457
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
4458
  }
4459

4460
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
×
4461

4462
  int32_t start = pInput->startRowIndex;
×
4463

4464
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
×
4465
    char*         data = colDataGetData(pCol, i);
×
4466
    SElapsedInfo* pInputInfo = (SElapsedInfo*)varDataVal(data);
×
4467
    elapsedTransferInfo(pInputInfo, pInfo);
×
4468
  }
4469

4470
  SET_VAL(GET_RES_INFO(pCtx), 1, 1);
×
4471
  return TSDB_CODE_SUCCESS;
×
4472
}
4473

4474
int32_t elapsedFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
38,841✔
4475
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
38,841✔
4476
  double        result = (double)pInfo->max - (double)pInfo->min;
38,841✔
4477
  result = (result >= 0) ? result : -result;
38,841✔
4478
  pInfo->result = result / pInfo->timeUnit;
38,841✔
4479
  return functionFinalize(pCtx, pBlock);
38,841✔
4480
}
4481

4482
int32_t elapsedPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
×
4483
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
×
4484
  SElapsedInfo*        pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
×
4485
  int32_t              resultBytes = getElapsedInfoSize();
×
4486
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
×
4487

4488
  if (NULL == res) {
×
4489
    return terrno;
×
4490
  }
4491
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
×
4492
  varDataSetLen(res, resultBytes);
×
4493

4494
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
×
4495
  int32_t          code = TSDB_CODE_SUCCESS;
×
4496
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
×
4497
  if (NULL == pCol) {
×
4498
    code = terrno;
×
4499
    goto _exit;
×
4500
  }
4501

4502
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
×
4503
  if (TSDB_CODE_SUCCESS != code) {
×
4504
    goto _exit;
×
4505
  }
4506
_exit:
×
4507
  taosMemoryFree(res);
×
4508
  return code;
×
4509
}
4510

4511
int32_t elapsedCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4512
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
4513
  SElapsedInfo*        pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
4514

4515
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4516
  SElapsedInfo*        pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
4517

4518
  elapsedTransferInfo(pSBuf, pDBuf);
×
4519
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
4520
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
4521
  return TSDB_CODE_SUCCESS;
×
4522
}
4523

4524
int32_t getHistogramInfoSize() {
7,844✔
4525
  return (int32_t)sizeof(SHistoFuncInfo) + HISTOGRAM_MAX_BINS_NUM * sizeof(SHistoFuncBin);
7,844✔
4526
}
4527

4528
bool getHistogramFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
10,385✔
4529
  pEnv->calcMemSize = sizeof(SHistoFuncInfo) + HISTOGRAM_MAX_BINS_NUM * sizeof(SHistoFuncBin);
10,385✔
4530
  return true;
10,385✔
4531
}
4532

4533
static int8_t getHistogramBinType(char* binTypeStr) {
7,150✔
4534
  int8_t binType;
4535
  if (strcasecmp(binTypeStr, "user_input") == 0) {
7,150✔
4536
    binType = USER_INPUT_BIN;
1,402✔
4537
  } else if (strcasecmp(binTypeStr, "linear_bin") == 0) {
5,748✔
4538
    binType = LINEAR_BIN;
4,207✔
4539
  } else if (strcasecmp(binTypeStr, "log_bin") == 0) {
1,541!
4540
    binType = LOG_BIN;
1,543✔
4541
  } else {
4542
    binType = UNKNOWN_BIN;
×
4543
  }
4544

4545
  return binType;
7,150✔
4546
}
4547

4548
static int32_t getHistogramBinDesc(SHistoFuncInfo* pInfo, char* binDescStr, int8_t binType, bool normalized) {
7,153✔
4549
  cJSON*  binDesc = cJSON_Parse(binDescStr);
7,153✔
4550
  int32_t numOfBins;
4551
  double* intervals;
4552
  if (cJSON_IsObject(binDesc)) { /* linaer/log bins */
7,153✔
4553
    int32_t numOfParams = cJSON_GetArraySize(binDesc);
5,751✔
4554
    int32_t startIndex;
4555
    if (numOfParams != 4) {
5,751!
4556
      cJSON_Delete(binDesc);
×
4557
      return TSDB_CODE_FAILED;
×
4558
    }
4559

4560
    cJSON* start = cJSON_GetObjectItem(binDesc, "start");
5,751✔
4561
    cJSON* factor = cJSON_GetObjectItem(binDesc, "factor");
5,751✔
4562
    cJSON* width = cJSON_GetObjectItem(binDesc, "width");
5,751✔
4563
    cJSON* count = cJSON_GetObjectItem(binDesc, "count");
5,751✔
4564
    cJSON* infinity = cJSON_GetObjectItem(binDesc, "infinity");
5,751✔
4565

4566
    if (!cJSON_IsNumber(start) || !cJSON_IsNumber(count) || !cJSON_IsBool(infinity)) {
5,751!
4567
      cJSON_Delete(binDesc);
×
4568
      return TSDB_CODE_FAILED;
×
4569
    }
4570

4571
    if (count->valueint <= 0 || count->valueint > 1000) {  // limit count to 1000
5,751!
4572
      cJSON_Delete(binDesc);
×
4573
      return TSDB_CODE_FAILED;
×
4574
    }
4575

4576
    if (isinf(start->valuedouble) || (width != NULL && isinf(width->valuedouble)) ||
5,751!
4577
        (factor != NULL && isinf(factor->valuedouble)) || (count != NULL && isinf(count->valuedouble))) {
5,751!
4578
      cJSON_Delete(binDesc);
×
4579
      return TSDB_CODE_FAILED;
×
4580
    }
4581

4582
    int32_t counter = (int32_t)count->valueint;
5,751✔
4583
    if (infinity->valueint == false) {
5,751✔
4584
      startIndex = 0;
3,078✔
4585
      numOfBins = counter + 1;
3,078✔
4586
    } else {
4587
      startIndex = 1;
2,673✔
4588
      numOfBins = counter + 3;
2,673✔
4589
    }
4590

4591
    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
5,751✔
4592
    if (NULL == intervals) {
5,751!
4593
      cJSON_Delete(binDesc);
×
4594
      qError("histogram function out of memory");
×
4595
      return terrno;
×
4596
    }
4597
    if (cJSON_IsNumber(width) && factor == NULL && binType == LINEAR_BIN) {
5,751!
4598
      // linear bin process
4599
      if (width->valuedouble == 0) {
4,207!
4600
        taosMemoryFree(intervals);
×
4601
        cJSON_Delete(binDesc);
×
4602
        return TSDB_CODE_FAILED;
×
4603
      }
4604
      for (int i = 0; i < counter + 1; ++i) {
27,150✔
4605
        intervals[startIndex] = start->valuedouble + i * width->valuedouble;
22,943✔
4606
        if (isinf(intervals[startIndex])) {
22,943!
4607
          taosMemoryFree(intervals);
×
4608
          cJSON_Delete(binDesc);
×
4609
          return TSDB_CODE_FAILED;
×
4610
        }
4611
        startIndex++;
22,943✔
4612
      }
4613
    } else if (cJSON_IsNumber(factor) && width == NULL && binType == LOG_BIN) {
1,543!
4614
      // log bin process
4615
      if (start->valuedouble == 0) {
1,543!
4616
        taosMemoryFree(intervals);
×
4617
        cJSON_Delete(binDesc);
×
4618
        return TSDB_CODE_FAILED;
×
4619
      }
4620
      if (factor->valuedouble < 0 || factor->valuedouble == 0 || factor->valuedouble == 1) {
1,543!
4621
        taosMemoryFree(intervals);
×
4622
        cJSON_Delete(binDesc);
×
4623
        return TSDB_CODE_FAILED;
×
4624
      }
4625
      for (int i = 0; i < counter + 1; ++i) {
8,497✔
4626
        intervals[startIndex] = start->valuedouble * pow(factor->valuedouble, i * 1.0);
6,954✔
4627
        if (isinf(intervals[startIndex])) {
6,954!
4628
          taosMemoryFree(intervals);
×
4629
          cJSON_Delete(binDesc);
×
4630
          return TSDB_CODE_FAILED;
×
4631
        }
4632
        startIndex++;
6,954✔
4633
      }
4634
    } else {
4635
      taosMemoryFree(intervals);
×
4636
      cJSON_Delete(binDesc);
×
4637
      return TSDB_CODE_FAILED;
×
4638
    }
4639

4640
    if (infinity->valueint == true) {
5,750✔
4641
      intervals[0] = -INFINITY;
2,672✔
4642
      intervals[numOfBins - 1] = INFINITY;
2,672✔
4643
      // in case of desc bin orders, -inf/inf should be swapped
4644
      if (numOfBins < 4) {
2,672!
4645
        return TSDB_CODE_FAILED;
×
4646
      }
4647
      if (intervals[1] > intervals[numOfBins - 2]) {
2,672!
4648
        TSWAP(intervals[0], intervals[numOfBins - 1]);
×
4649
      }
4650
    }
4651
  } else if (cJSON_IsArray(binDesc)) { /* user input bins */
1,402!
4652
    if (binType != USER_INPUT_BIN) {
1,402!
4653
      cJSON_Delete(binDesc);
×
4654
      return TSDB_CODE_FAILED;
×
4655
    }
4656
    numOfBins = cJSON_GetArraySize(binDesc);
1,402✔
4657
    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
1,402!
4658
    if (NULL == intervals) {
1,402!
4659
      cJSON_Delete(binDesc);
×
4660
      qError("histogram function out of memory");
×
4661
      return terrno;
×
4662
    }
4663
    cJSON* bin = binDesc->child;
1,402✔
4664
    if (bin == NULL) {
1,402!
4665
      taosMemoryFree(intervals);
×
4666
      cJSON_Delete(binDesc);
×
4667
      return TSDB_CODE_FAILED;
×
4668
    }
4669
    int i = 0;
1,402✔
4670
    while (bin) {
4,705✔
4671
      intervals[i] = bin->valuedouble;
3,303✔
4672
      if (!cJSON_IsNumber(bin)) {
3,303!
4673
        taosMemoryFree(intervals);
×
4674
        cJSON_Delete(binDesc);
×
4675
        return TSDB_CODE_FAILED;
×
4676
      }
4677
      if (i != 0 && intervals[i] <= intervals[i - 1]) {
3,303!
4678
        taosMemoryFree(intervals);
×
4679
        cJSON_Delete(binDesc);
×
4680
        return TSDB_CODE_FAILED;
×
4681
      }
4682
      bin = bin->next;
3,303✔
4683
      i++;
3,303✔
4684
    }
4685
  } else {
4686
    cJSON_Delete(binDesc);
×
4687
    return TSDB_CODE_FAILED;
×
4688
  }
4689

4690
  pInfo->numOfBins = numOfBins - 1;
7,152✔
4691
  pInfo->normalized = normalized;
7,152✔
4692
  for (int32_t i = 0; i < pInfo->numOfBins; ++i) {
38,542✔
4693
    pInfo->bins[i].lower = intervals[i] < intervals[i + 1] ? intervals[i] : intervals[i + 1];
31,390✔
4694
    pInfo->bins[i].upper = intervals[i + 1] > intervals[i] ? intervals[i + 1] : intervals[i];
31,390✔
4695
    pInfo->bins[i].count = 0;
31,390✔
4696
  }
4697

4698
  taosMemoryFree(intervals);
7,152!
4699
  cJSON_Delete(binDesc);
7,153✔
4700

4701
  return TSDB_CODE_SUCCESS;
7,153✔
4702
}
4703

4704
int32_t histogramFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
7,151✔
4705
  if (pResultInfo->initialized) {
7,151!
4706
    return TSDB_CODE_SUCCESS;
×
4707
  }
4708
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
7,151!
4709
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
4710
  }
4711

4712
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
7,151✔
4713
  pInfo->numOfBins = 0;
7,151✔
4714
  pInfo->totalCount = 0;
7,151✔
4715
  pInfo->normalized = 0;
7,151✔
4716

4717
  char* binTypeStr = taosStrndup(varDataVal(pCtx->param[1].param.pz), varDataLen(pCtx->param[1].param.pz));
7,151!
4718
  if (binTypeStr == NULL) {
7,151!
4719
    return terrno;
×
4720
  }
4721
  int8_t binType = getHistogramBinType(binTypeStr);
7,151✔
4722
  taosMemoryFree(binTypeStr);
7,152!
4723

4724
  if (binType == UNKNOWN_BIN) {
7,151!
4725
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
4726
  }
4727
  char* binDesc = taosStrndup(varDataVal(pCtx->param[2].param.pz), varDataLen(pCtx->param[2].param.pz));
7,151!
4728
  if (binDesc == NULL) {
7,152!
4729
    return terrno;
×
4730
  }
4731
  int64_t normalized = pCtx->param[3].param.i;
7,152✔
4732
  if (normalized != 0 && normalized != 1) {
7,152!
4733
    taosMemoryFree(binDesc);
×
4734
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
4735
  }
4736
  int32_t code = getHistogramBinDesc(pInfo, binDesc, binType, (bool)normalized);
7,152✔
4737
  if (TSDB_CODE_SUCCESS != code) {
7,153!
4738
    taosMemoryFree(binDesc);
×
4739
    return code;
×
4740
  }
4741
  taosMemoryFree(binDesc);
7,153!
4742

4743
  return TSDB_CODE_SUCCESS;
7,153✔
4744
}
4745

4746
static int32_t histogramFunctionImpl(SqlFunctionCtx* pCtx, bool isPartial) {
8,100✔
4747
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
8,100✔
4748

4749
  SInputColumnInfoData* pInput = &pCtx->input;
8,100✔
4750
  SColumnInfoData*      pCol = pInput->pData[0];
8,100✔
4751

4752
  int32_t type = pInput->pData[0]->info.type;
8,100✔
4753

4754
  int32_t start = pInput->startRowIndex;
8,100✔
4755
  int32_t numOfRows = pInput->numOfRows;
8,100✔
4756

4757
  int32_t numOfElems = 0;
8,100✔
4758
  for (int32_t i = start; i < numOfRows + start; ++i) {
1,221,536✔
4759
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
1,213,485✔
4760
      continue;
864,425✔
4761
    }
4762

4763
    numOfElems++;
349,060✔
4764

4765
    char*  data = colDataGetData(pCol, i);
349,060!
4766
    double v;
4767
    GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pCol->info));
349,060!
4768

4769
    for (int32_t k = 0; k < pInfo->numOfBins; ++k) {
1,449,892✔
4770
      if (v > pInfo->bins[k].lower && v <= pInfo->bins[k].upper) {
1,190,498✔
4771
        pInfo->bins[k].count++;
89,617✔
4772
        pInfo->totalCount++;
89,617✔
4773
        break;
89,617✔
4774
      }
4775
    }
4776
  }
4777

4778
  if (!isPartial) {
8,051✔
4779
    GET_RES_INFO(pCtx)->numOfRes = pInfo->numOfBins;
5,501✔
4780
  } else {
4781
    GET_RES_INFO(pCtx)->numOfRes = 1;
2,550✔
4782
  }
4783
  return TSDB_CODE_SUCCESS;
8,051✔
4784
}
4785

4786
int32_t histogramFunction(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, false); }
5,498✔
4787

4788
int32_t histogramFunctionPartial(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, true); }
2,599✔
4789

4790
static void histogramTransferInfo(SHistoFuncInfo* pInput, SHistoFuncInfo* pOutput) {
1,659✔
4791
  pOutput->normalized = pInput->normalized;
1,659✔
4792
  pOutput->numOfBins = pInput->numOfBins;
1,659✔
4793
  pOutput->totalCount += pInput->totalCount;
1,659✔
4794
  for (int32_t k = 0; k < pOutput->numOfBins; ++k) {
11,403✔
4795
    pOutput->bins[k].lower = pInput->bins[k].lower;
9,744✔
4796
    pOutput->bins[k].upper = pInput->bins[k].upper;
9,744✔
4797
    pOutput->bins[k].count += pInput->bins[k].count;
9,744✔
4798
  }
4799
}
1,659✔
4800

4801
int32_t histogramFunctionMerge(SqlFunctionCtx* pCtx) {
1,659✔
4802
  SInputColumnInfoData* pInput = &pCtx->input;
1,659✔
4803
  SColumnInfoData*      pCol = pInput->pData[0];
1,659✔
4804
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
1,659!
4805
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
4806
  }
4807

4808
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,659✔
4809

4810
  int32_t start = pInput->startRowIndex;
1,659✔
4811

4812
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
3,318✔
4813
    char*           data = colDataGetData(pCol, i);
1,659!
4814
    SHistoFuncInfo* pInputInfo = (SHistoFuncInfo*)varDataVal(data);
1,659✔
4815
    histogramTransferInfo(pInputInfo, pInfo);
1,659✔
4816
  }
4817

4818
  SET_VAL(GET_RES_INFO(pCtx), pInfo->numOfBins, pInfo->numOfBins);
1,659!
4819
  return TSDB_CODE_SUCCESS;
1,659✔
4820
}
4821

4822
int32_t histogramFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
7,033✔
4823
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
7,033✔
4824
  SHistoFuncInfo*      pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
7,033✔
4825
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
7,033✔
4826
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
7,033✔
4827
  int32_t              code = TSDB_CODE_SUCCESS;
7,034✔
4828

4829
  int32_t currentRow = pBlock->info.rows;
7,034✔
4830
  if (NULL == pCol) {
7,034!
4831
    return TSDB_CODE_OUT_OF_RANGE;
×
4832
  }
4833

4834
  if (pInfo->normalized) {
7,034✔
4835
    for (int32_t k = 0; k < pResInfo->numOfRes; ++k) {
16,188✔
4836
      if (pInfo->totalCount != 0) {
12,642✔
4837
        pInfo->bins[k].percentage = pInfo->bins[k].count / (double)pInfo->totalCount;
594✔
4838
      } else {
4839
        pInfo->bins[k].percentage = 0;
12,048✔
4840
      }
4841
    }
4842
  }
4843

4844
  for (int32_t i = 0; i < pResInfo->numOfRes; ++i) {
37,875✔
4845
    int32_t len;
4846
    char    buf[512] = {0};
30,851✔
4847
    if (!pInfo->normalized) {
30,851✔
4848
      len = tsnprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE,
18,203✔
4849
                      "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%" PRId64 "}", pInfo->bins[i].lower,
4850
                      pInfo->bins[i].upper, pInfo->bins[i].count);
4851
    } else {
4852
      len = tsnprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE,
12,648✔
4853
                      "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%lf}", pInfo->bins[i].lower, pInfo->bins[i].upper,
4854
                      pInfo->bins[i].percentage);
4855
    }
4856
    varDataSetLen(buf, len);
30,847✔
4857
    code = colDataSetVal(pCol, currentRow, buf, false);
30,847✔
4858
    if (TSDB_CODE_SUCCESS != code) {
30,841!
4859
      return code;
×
4860
    }
4861
    currentRow++;
30,841✔
4862
  }
4863

4864
  return code;
7,024✔
4865
}
4866

4867
int32_t histogramPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1,659✔
4868
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,659✔
4869
  SHistoFuncInfo*      pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,659✔
4870
  int32_t              resultBytes = getHistogramInfoSize();
1,659✔
4871
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
1,659!
4872

4873
  if (NULL == res) {
1,659!
4874
    return terrno;
×
4875
  }
4876
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
1,659✔
4877
  varDataSetLen(res, resultBytes);
1,659✔
4878

4879
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
1,659✔
4880
  int32_t          code = TSDB_CODE_SUCCESS;
1,659✔
4881
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
1,659✔
4882
  if (NULL == pCol) {
1,659!
4883
    code = terrno;
×
4884
    goto _exit;
×
4885
  }
4886
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
1,659✔
4887

4888
_exit:
1,659✔
4889
  taosMemoryFree(res);
1,659!
4890
  return code;
1,659✔
4891
}
4892

4893
int32_t histogramCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4894
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
4895
  SHistoFuncInfo*      pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
4896

4897
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4898
  SHistoFuncInfo*      pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
4899

4900
  histogramTransferInfo(pSBuf, pDBuf);
×
4901
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
4902
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
4903
  return TSDB_CODE_SUCCESS;
×
4904
}
4905

4906
int32_t getHLLInfoSize() { return (int32_t)sizeof(SHLLInfo); }
10,294✔
4907

4908
bool getHLLFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
63,476✔
4909
  pEnv->calcMemSize = sizeof(SHLLInfo);
63,476✔
4910
  return true;
63,476✔
4911
}
4912

4913
static uint8_t hllCountNum(void* data, int32_t bytes, int32_t* buk) {
3,466,962✔
4914
  uint64_t hash = MurmurHash3_64(data, bytes);
3,466,962✔
4915
  int32_t  index = hash & HLL_BUCKET_MASK;
3,465,384✔
4916
  hash >>= HLL_BUCKET_BITS;
3,465,384✔
4917
  hash |= ((uint64_t)1 << HLL_DATA_BITS);
3,465,384✔
4918
  uint64_t bit = 1;
3,465,384✔
4919
  uint8_t  count = 1;
3,465,384✔
4920
  while ((hash & bit) == 0) {
7,033,630✔
4921
    count++;
3,568,246✔
4922
    bit <<= 1;
3,568,246✔
4923
  }
4924
  *buk = index;
3,465,384✔
4925
  return count;
3,465,384✔
4926
}
4927

4928
static void hllBucketHisto(uint8_t* buckets, int32_t* bucketHisto) {
238,979✔
4929
  uint64_t* word = (uint64_t*)buckets;
238,979✔
4930
  uint8_t*  bytes;
4931

4932
  for (int32_t j = 0; j < HLL_BUCKETS >> 3; j++) {
482,577,679✔
4933
    if (*word == 0) {
482,338,700✔
4934
      bucketHisto[0] += 8;
481,549,573✔
4935
    } else {
4936
      bytes = (uint8_t*)word;
789,127✔
4937
      bucketHisto[bytes[0]]++;
789,127✔
4938
      bucketHisto[bytes[1]]++;
789,127✔
4939
      bucketHisto[bytes[2]]++;
789,127✔
4940
      bucketHisto[bytes[3]]++;
789,127✔
4941
      bucketHisto[bytes[4]]++;
789,127✔
4942
      bucketHisto[bytes[5]]++;
789,127✔
4943
      bucketHisto[bytes[6]]++;
789,127✔
4944
      bucketHisto[bytes[7]]++;
789,127✔
4945
    }
4946
    word++;
482,338,700✔
4947
  }
4948
}
238,979✔
4949
static double hllTau(double x) {
238,991✔
4950
  if (x == 0. || x == 1.) return 0.;
238,991!
4951
  double zPrime;
4952
  double y = 1.0;
×
4953
  double z = 1 - x;
×
4954
  do {
4955
    x = sqrt(x);
×
4956
    zPrime = z;
×
4957
    y *= 0.5;
×
4958
    z -= pow(1 - x, 2) * y;
×
4959
  } while (zPrime != z);
×
4960
  return z / 3;
×
4961
}
4962

4963
static double hllSigma(double x) {
238,992✔
4964
  if (x == 1.0) return INFINITY;
238,992✔
4965
  double zPrime;
4966
  double y = 1;
208,610✔
4967
  double z = x;
208,610✔
4968
  do {
4969
    x *= x;
4,092,227✔
4970
    zPrime = z;
4,092,227✔
4971
    z += x * y;
4,092,227✔
4972
    y += y;
4,092,227✔
4973
  } while (zPrime != z);
4,092,227✔
4974
  return z;
208,610✔
4975
}
4976

4977
// estimate the cardinality, the algorithm refer this paper: "New cardinality estimation algorithms for HyperLogLog
4978
// sketches"
4979
static uint64_t hllCountCnt(uint8_t* buckets) {
238,945✔
4980
  double  m = HLL_BUCKETS;
238,945✔
4981
  int32_t buckethisto[64] = {0};
238,945✔
4982
  hllBucketHisto(buckets, buckethisto);
238,945✔
4983

4984
  double z = m * hllTau((m - buckethisto[HLL_DATA_BITS + 1]) / (double)m);
238,993✔
4985
  for (int j = HLL_DATA_BITS; j >= 1; --j) {
12,184,989✔
4986
    z += buckethisto[j];
11,945,998✔
4987
    z *= 0.5;
11,945,998✔
4988
  }
4989

4990
  z += m * hllSigma(buckethisto[0] / (double)m);
238,991✔
4991
  double E = (double)llroundl(HLL_ALPHA_INF * m * m / z);
239,004✔
4992

4993
  return (uint64_t)E;
239,004✔
4994
}
4995

4996
int32_t hllFunction(SqlFunctionCtx* pCtx) {
261,553✔
4997
  SHLLInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
261,553✔
4998

4999
  SInputColumnInfoData* pInput = &pCtx->input;
261,553✔
5000
  SColumnInfoData*      pCol = pInput->pData[0];
261,553✔
5001

5002
  int32_t type = pCol->info.type;
261,553✔
5003
  int32_t bytes = pCol->info.bytes;
261,553✔
5004

5005
  int32_t start = pInput->startRowIndex;
261,553✔
5006
  int32_t numOfRows = pInput->numOfRows;
261,553✔
5007

5008
  int32_t numOfElems = 0;
261,553✔
5009
  if (IS_NULL_TYPE(type)) {
261,553✔
5010
    goto _hll_over;
1,564✔
5011
  }
5012

5013
  for (int32_t i = start; i < numOfRows + start; ++i) {
4,830,742✔
5014
    if (pCol->hasNull && colDataIsNull_s(pCol, i)) {
6,441,917!
5015
      continue;
1,104,055✔
5016
    }
5017

5018
    numOfElems++;
3,467,562✔
5019

5020
    char* data = colDataGetData(pCol, i);
3,467,562!
5021
    if (IS_VAR_DATA_TYPE(type)) {
3,467,562!
5022
      bytes = varDataLen(data);
1,078,591✔
5023
      data = varDataVal(data);
1,078,591✔
5024
    }
5025

5026
    int32_t index = 0;
3,467,562✔
5027
    uint8_t count = hllCountNum(data, bytes, &index);
3,467,562✔
5028
    uint8_t oldcount = pInfo->buckets[index];
3,466,698✔
5029
    if (count > oldcount) {
3,466,698✔
5030
      pInfo->buckets[index] = count;
805,182✔
5031
    }
5032
  }
5033

5034
_hll_over:
259,125✔
5035
  pInfo->totalCount += numOfElems;
260,689✔
5036

5037
  if (pInfo->totalCount == 0 && !tsCountAlwaysReturnValue) {
260,689✔
5038
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
2,307✔
5039
  } else {
5040
    SET_VAL(GET_RES_INFO(pCtx), 1, 1);
258,382✔
5041
  }
5042

5043
  return TSDB_CODE_SUCCESS;
260,689✔
5044
}
5045

5046
static void hllTransferInfo(SHLLInfo* pInput, SHLLInfo* pOutput) {
10,571✔
5047
  for (int32_t k = 0; k < HLL_BUCKETS; ++k) {
168,786,027✔
5048
    if (pOutput->buckets[k] < pInput->buckets[k]) {
168,775,456✔
5049
      pOutput->buckets[k] = pInput->buckets[k];
143,792✔
5050
    }
5051
  }
5052
  pOutput->totalCount += pInput->totalCount;
10,571✔
5053
}
10,571✔
5054

5055
int32_t hllFunctionMerge(SqlFunctionCtx* pCtx) {
10,524✔
5056
  SInputColumnInfoData* pInput = &pCtx->input;
10,524✔
5057
  SColumnInfoData*      pCol = pInput->pData[0];
10,524✔
5058

5059
  if (IS_NULL_TYPE(pCol->info.type)) {
10,524!
5060
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
5061
    return TSDB_CODE_SUCCESS;
×
5062
  }
5063

5064
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
10,524!
5065
    return TSDB_CODE_SUCCESS;
×
5066
  }
5067

5068
  SHLLInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
10,524✔
5069

5070
  int32_t start = pInput->startRowIndex;
10,524✔
5071

5072
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
21,094✔
5073
    if (colDataIsNull_s(pCol, i)) continue;
21,140!
5074
    char*     data = colDataGetData(pCol, i);
10,570!
5075
    SHLLInfo* pInputInfo = (SHLLInfo*)varDataVal(data);
10,570✔
5076
    hllTransferInfo(pInputInfo, pInfo);
10,570✔
5077
  }
5078

5079
  if (pInfo->totalCount == 0 && !tsCountAlwaysReturnValue) {
10,524✔
5080
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
3✔
5081
  } else {
5082
    SET_VAL(GET_RES_INFO(pCtx), 1, 1);
10,521✔
5083
  }
5084

5085
  return TSDB_CODE_SUCCESS;
10,524✔
5086
}
5087

5088
int32_t hllFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
238,947✔
5089
  SResultRowEntryInfo* pInfo = GET_RES_INFO(pCtx);
238,947✔
5090

5091
  SHLLInfo* pHllInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
238,947✔
5092
  pHllInfo->result = hllCountCnt(pHllInfo->buckets);
238,947✔
5093
  if (tsCountAlwaysReturnValue && pHllInfo->result == 0) {
239,006✔
5094
    pInfo->numOfRes = 1;
28,097✔
5095
  }
5096

5097
  return functionFinalize(pCtx, pBlock);
239,006✔
5098
}
5099

5100
int32_t hllPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
10,294✔
5101
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
10,294✔
5102
  SHLLInfo*            pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
10,294✔
5103
  int32_t              resultBytes = getHLLInfoSize();
10,294✔
5104
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
10,294!
5105

5106
  if (NULL == res) {
10,296!
5107
    return terrno;
×
5108
  }
5109
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
10,296✔
5110
  varDataSetLen(res, resultBytes);
10,296✔
5111

5112
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
10,296✔
5113
  int32_t          code = TSDB_CODE_SUCCESS;
10,296✔
5114
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
10,296✔
5115
  if (NULL == pCol) {
10,295!
5116
    code = terrno;
×
5117
    goto _exit;
×
5118
  }
5119

5120
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
10,295✔
5121

5122
_exit:
10,295✔
5123
  taosMemoryFree(res);
10,295!
5124
  return code;
10,296✔
5125
}
5126

5127
int32_t hllCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
1✔
5128
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
1✔
5129
  SHLLInfo*            pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
1✔
5130

5131
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
1✔
5132
  SHLLInfo*            pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
1✔
5133

5134
  hllTransferInfo(pSBuf, pDBuf);
1✔
5135
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
1✔
5136
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
1✔
5137
  return TSDB_CODE_SUCCESS;
1✔
5138
}
5139

5140
bool getStateFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
7,744✔
5141
  pEnv->calcMemSize = sizeof(SStateInfo);
7,744✔
5142
  return true;
7,744✔
5143
}
5144

5145
static int8_t getStateOpType(char* opStr) {
7,973✔
5146
  int8_t opType;
5147
  if (strncasecmp(opStr, "LT", 2) == 0) {
7,973✔
5148
    opType = STATE_OPER_LT;
3,061✔
5149
  } else if (strncasecmp(opStr, "GT", 2) == 0) {
4,912✔
5150
    opType = STATE_OPER_GT;
770✔
5151
  } else if (strncasecmp(opStr, "LE", 2) == 0) {
4,142✔
5152
    opType = STATE_OPER_LE;
496✔
5153
  } else if (strncasecmp(opStr, "GE", 2) == 0) {
3,646✔
5154
    opType = STATE_OPER_GE;
592✔
5155
  } else if (strncasecmp(opStr, "NE", 2) == 0) {
3,054✔
5156
    opType = STATE_OPER_NE;
1,527✔
5157
  } else if (strncasecmp(opStr, "EQ", 2) == 0) {
1,527!
5158
    opType = STATE_OPER_EQ;
1,527✔
5159
  } else {
5160
    opType = STATE_OPER_INVALID;
×
5161
  }
5162

5163
  return opType;
7,973✔
5164
}
5165

5166
static bool checkStateOp(int8_t op, SColumnInfoData* pCol, int32_t index, SVariant param) {
539,453✔
5167
  char* data = colDataGetData(pCol, index);
539,453!
5168
  switch (pCol->info.type) {
539,453!
5169
    case TSDB_DATA_TYPE_TINYINT: {
164,248✔
5170
      int8_t v = *(int8_t*)data;
164,248✔
5171
      STATE_COMP(op, v, param);
164,248!
5172
      break;
×
5173
    }
5174
    case TSDB_DATA_TYPE_UTINYINT: {
2,880✔
5175
      uint8_t v = *(uint8_t*)data;
2,880✔
5176
      STATE_COMP(op, v, param);
2,880!
5177
      break;
×
5178
    }
5179
    case TSDB_DATA_TYPE_SMALLINT: {
40,456✔
5180
      int16_t v = *(int16_t*)data;
40,456✔
5181
      STATE_COMP(op, v, param);
40,456!
5182
      break;
×
5183
    }
5184
    case TSDB_DATA_TYPE_USMALLINT: {
2,880✔
5185
      uint16_t v = *(uint16_t*)data;
2,880✔
5186
      STATE_COMP(op, v, param);
2,880!
5187
      break;
×
5188
    }
5189
    case TSDB_DATA_TYPE_INT: {
154,574✔
5190
      int32_t v = *(int32_t*)data;
154,574✔
5191
      STATE_COMP(op, v, param);
154,574!
5192
      break;
×
5193
    }
5194
    case TSDB_DATA_TYPE_UINT: {
2,880✔
5195
      uint32_t v = *(uint32_t*)data;
2,880✔
5196
      STATE_COMP(op, v, param);
2,880!
5197
      break;
×
5198
    }
5199
    case TSDB_DATA_TYPE_BIGINT: {
62,984✔
5200
      int64_t v = *(int64_t*)data;
62,984✔
5201
      STATE_COMP(op, v, param);
62,984!
5202
      break;
×
5203
    }
5204
    case TSDB_DATA_TYPE_UBIGINT: {
2,880✔
5205
      uint64_t v = *(uint64_t*)data;
2,880✔
5206
      STATE_COMP(op, v, param);
2,880!
5207
      break;
×
5208
    }
5209
    case TSDB_DATA_TYPE_FLOAT: {
93,056✔
5210
      float v = *(float*)data;
93,056✔
5211
      STATE_COMP(op, v, param);
93,056!
5212
      break;
×
5213
    }
5214
    case TSDB_DATA_TYPE_DOUBLE: {
14,278✔
5215
      double v = *(double*)data;
14,278✔
5216
      STATE_COMP(op, v, param);
14,278!
5217
      break;
×
5218
    }
5219
    default: {
×
5220
      return false;
×
5221
    }
5222
  }
5223
  return false;
×
5224
}
5225

5226
int32_t stateCountFunction(SqlFunctionCtx* pCtx) {
2,889✔
5227
  int32_t              code = TSDB_CODE_SUCCESS;
2,889✔
5228
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,889✔
5229
  SStateInfo*          pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,889✔
5230

5231
  SInputColumnInfoData* pInput = &pCtx->input;
2,889✔
5232
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
2,889✔
5233

5234
  SColumnInfoData* pInputCol = pInput->pData[0];
2,889✔
5235

5236
  int32_t          numOfElems = 0;
2,889✔
5237
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
2,889✔
5238

5239
  int8_t op = getStateOpType(varDataVal(pCtx->param[1].param.pz));
2,889✔
5240
  if (STATE_OPER_INVALID == op) {
2,889!
5241
    return 0;
×
5242
  }
5243

5244
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
532,441✔
5245
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
529,541!
5246
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5247
    } else {
5248
      pInfo->prevTs = tsList[i];
529,541✔
5249
    }
5250

5251
    pInfo->isPrevTsSet = true;
529,541✔
5252
    numOfElems++;
529,541✔
5253

5254
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
529,541✔
5255
      colDataSetNULL(pOutput, i);
143,912!
5256
      // handle selectivity
5257
      if (pCtx->subsidiaries.num > 0) {
143,912✔
5258
        code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
18✔
5259
        if (TSDB_CODE_SUCCESS != code) {
18!
5260
          return code;
×
5261
        }
5262
      }
5263
      continue;
143,912✔
5264
    }
5265

5266
    bool ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
385,629✔
5267

5268
    int64_t output = -1;
385,602✔
5269
    if (ret) {
385,602✔
5270
      output = ++pInfo->count;
144,229✔
5271
    } else {
5272
      pInfo->count = 0;
241,373✔
5273
    }
5274
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
385,602✔
5275
    if (TSDB_CODE_SUCCESS != code) {
385,640!
5276
      return code;
×
5277
    }
5278

5279
    // handle selectivity
5280
    if (pCtx->subsidiaries.num > 0) {
385,640✔
5281
      code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
216✔
5282
      if (TSDB_CODE_SUCCESS != code) {
216!
5283
        return code;
×
5284
      }
5285
    }
5286
  }
5287

5288
  pResInfo->numOfRes = numOfElems;
2,900✔
5289
  return TSDB_CODE_SUCCESS;
2,900✔
5290
}
5291

5292
int32_t stateDurationFunction(SqlFunctionCtx* pCtx) {
5,084✔
5293
  int32_t              code = TSDB_CODE_SUCCESS;
5,084✔
5294
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5,084✔
5295
  SStateInfo*          pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5,084✔
5296

5297
  SInputColumnInfoData* pInput = &pCtx->input;
5,084✔
5298
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
5,084✔
5299

5300
  SColumnInfoData* pInputCol = pInput->pData[0];
5,084✔
5301

5302
  int32_t          numOfElems = 0;
5,084✔
5303
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
5,084✔
5304

5305
  // TODO: process timeUnit for different db precisions
5306
  int32_t timeUnit = 1;
5,084✔
5307
  if (pCtx->numOfParams == 5) {  // TODO: param number incorrect
5,084✔
5308
    timeUnit = pCtx->param[3].param.i;
4,102✔
5309
  }
5310

5311
  int8_t op = getStateOpType(varDataVal(pCtx->param[1].param.pz));
5,084✔
5312
  if (STATE_OPER_INVALID == op) {
5,084!
5313
    return TSDB_CODE_INVALID_PARA;
×
5314
  }
5315

5316
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
378,680✔
5317
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
373,596!
5318
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5319
    } else {
5320
      pInfo->prevTs = tsList[i];
373,596✔
5321
    }
5322

5323
    pInfo->isPrevTsSet = true;
373,596✔
5324
    numOfElems++;
373,596✔
5325

5326
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
373,596✔
5327
      colDataSetNULL(pOutput, i);
219,292!
5328
      // handle selectivity
5329
      if (pCtx->subsidiaries.num > 0) {
219,292✔
5330
        code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
26✔
5331
        if (TSDB_CODE_SUCCESS != code) {
26!
5332
          return code;
×
5333
        }
5334
      }
5335
      continue;
219,292✔
5336
    }
5337

5338
    bool    ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
154,304✔
5339
    int64_t output = -1;
154,304✔
5340
    if (ret) {
154,304✔
5341
      if (pInfo->durationStart == 0) {
34,625✔
5342
        output = 0;
4,031✔
5343
        pInfo->durationStart = tsList[i];
4,031✔
5344
      } else {
5345
        output = (tsList[i] - pInfo->durationStart) / timeUnit;
30,594✔
5346
      }
5347
    } else {
5348
      pInfo->durationStart = 0;
119,679✔
5349
    }
5350
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
154,304✔
5351
    if (TSDB_CODE_SUCCESS != code) {
154,304!
5352
      return code;
×
5353
    }
5354

5355
    // handle selectivity
5356
    if (pCtx->subsidiaries.num > 0) {
154,304✔
5357
      code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
312✔
5358
      if (TSDB_CODE_SUCCESS != code) {
312!
5359
        return code;
×
5360
      }
5361
    }
5362
  }
5363

5364
  pResInfo->numOfRes = numOfElems;
5,084✔
5365
  return TSDB_CODE_SUCCESS;
5,084✔
5366
}
5367

5368
bool getCsumFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
5,276✔
5369
  pEnv->calcMemSize = sizeof(SSumRes);
5,276✔
5370
  return true;
5,276✔
5371
}
5372

5373
int32_t csumFunction(SqlFunctionCtx* pCtx) {
5,898✔
5374
  int32_t              code = TSDB_CODE_SUCCESS;
5,898✔
5375
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5,898✔
5376
  SSumRes*             pSumRes = GET_ROWCELL_INTERBUF(pResInfo);
5,898✔
5377

5378
  SInputColumnInfoData* pInput = &pCtx->input;
5,898✔
5379
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
5,898✔
5380

5381
  SColumnInfoData* pInputCol = pInput->pData[0];
5,898✔
5382
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
5,898✔
5383

5384
  int32_t numOfElems = 0;
5,898✔
5385
  int32_t type = pInputCol->info.type;
5,898✔
5386
  int32_t startOffset = pCtx->offset;
5,898✔
5387
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
881,168✔
5388
    if (pSumRes->isPrevTsSet == true && tsList[i] == pSumRes->prevTs) {
875,268✔
5389
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
18✔
5390
    } else {
5391
      pSumRes->prevTs = tsList[i];
875,250✔
5392
    }
5393
    pSumRes->isPrevTsSet = true;
875,250✔
5394

5395
    int32_t pos = startOffset + numOfElems;
875,250✔
5396
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
875,250✔
5397
      // colDataSetNULL(pOutput, i);
5398
      continue;
480,633✔
5399
    }
5400

5401
    char* data = colDataGetData(pInputCol, i);
394,617!
5402
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
584,850✔
5403
      int64_t v;
5404
      GET_TYPED_DATA(v, int64_t, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
190,213!
5405
      pSumRes->isum += v;
190,213✔
5406
      code = colDataSetVal(pOutput, pos, (char*)&pSumRes->isum, false);
190,213✔
5407
      if (TSDB_CODE_SUCCESS != code) {
190,233!
5408
        return code;
×
5409
      }
5410
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
205,084!
5411
      uint64_t v;
5412
      GET_TYPED_DATA(v, uint64_t, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
680!
5413
      pSumRes->usum += v;
680✔
5414
      code = colDataSetVal(pOutput, pos, (char*)&pSumRes->usum, false);
680✔
5415
      if (TSDB_CODE_SUCCESS != code) {
680!
5416
        return code;
×
5417
      }
5418
    } else if (IS_FLOAT_TYPE(type)) {
203,724!
5419
      double v;
5420
      GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
204,700!
5421
      pSumRes->dsum += v;
204,700✔
5422
      // check for overflow
5423
      if (isinf(pSumRes->dsum) || isnan(pSumRes->dsum)) {
204,700!
5424
        colDataSetNULL(pOutput, pos);
8!
5425
      } else {
5426
        code = colDataSetVal(pOutput, pos, (char*)&pSumRes->dsum, false);
204,692✔
5427
        if (TSDB_CODE_SUCCESS != code) {
204,692!
5428
          return code;
×
5429
        }
5430
      }
5431
    }
5432

5433
    // handle selectivity
5434
    if (pCtx->subsidiaries.num > 0) {
394,637✔
5435
      code = appendSelectivityValue(pCtx, i, pos);
194✔
5436
      if (TSDB_CODE_SUCCESS != code) {
194!
5437
        return code;
×
5438
      }
5439
    }
5440

5441
    numOfElems++;
394,637✔
5442
  }
5443

5444
  pResInfo->numOfRes = numOfElems;
5,900✔
5445
  return TSDB_CODE_SUCCESS;
5,900✔
5446
}
5447

5448
bool getMavgFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
3,820✔
5449
  pEnv->calcMemSize = sizeof(SMavgInfo) + MAVG_MAX_POINTS_NUM * sizeof(double);
3,820✔
5450
  return true;
3,820✔
5451
}
5452

5453
int32_t mavgFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
8,228✔
5454
  if (pResultInfo->initialized) {
8,228✔
5455
    return TSDB_CODE_SUCCESS;
3,718✔
5456
  }
5457
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
4,510!
5458
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5459
  }
5460

5461
  SMavgInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
4,511✔
5462
  pInfo->pos = 0;
4,511✔
5463
  pInfo->sum = 0;
4,511✔
5464
  pInfo->prevTs = -1;
4,511✔
5465
  pInfo->isPrevTsSet = false;
4,511✔
5466
  pInfo->numOfPoints = pCtx->param[1].param.i;
4,511✔
5467
  if (pInfo->numOfPoints < 1 || pInfo->numOfPoints > MAVG_MAX_POINTS_NUM) {
4,511!
5468
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
5469
  }
5470
  pInfo->pointsMeet = false;
4,511✔
5471

5472
  return TSDB_CODE_SUCCESS;
4,511✔
5473
}
5474

5475
int32_t mavgFunction(SqlFunctionCtx* pCtx) {
4,407✔
5476
  int32_t              code = TSDB_CODE_SUCCESS;
4,407✔
5477
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
4,407✔
5478
  SMavgInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
4,407✔
5479

5480
  SInputColumnInfoData* pInput = &pCtx->input;
4,407✔
5481
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
4,407✔
5482

5483
  SColumnInfoData* pInputCol = pInput->pData[0];
4,407✔
5484
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
4,407✔
5485
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
4,407✔
5486

5487
  int32_t numOfElems = 0;
4,407✔
5488
  int32_t type = pInputCol->info.type;
4,407✔
5489
  int32_t startOffset = pCtx->offset;
4,407✔
5490
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
717,572✔
5491
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
713,170!
5492
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5493
    } else {
5494
      pInfo->prevTs = tsList[i];
713,170✔
5495
    }
5496
    pInfo->isPrevTsSet = true;
713,170✔
5497

5498
    int32_t pos = startOffset + numOfElems;
713,170✔
5499
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
713,170✔
5500
      // colDataSetNULL(pOutput, i);
5501
      continue;
188,195✔
5502
    }
5503

5504
    char*  data = colDataGetData(pInputCol, i);
524,975!
5505
    double v;
5506
    GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
524,975!
5507

5508
    if (!pInfo->pointsMeet && (pInfo->pos < pInfo->numOfPoints - 1)) {
524,970✔
5509
      pInfo->points[pInfo->pos] = v;
509,546✔
5510
      pInfo->sum += v;
509,546✔
5511
    } else {
5512
      if (!pInfo->pointsMeet && (pInfo->pos == pInfo->numOfPoints - 1)) {
15,424!
5513
        pInfo->sum += v;
638✔
5514
        pInfo->pointsMeet = true;
638✔
5515
      } else {
5516
        pInfo->sum = pInfo->sum + v - pInfo->points[pInfo->pos];
14,786✔
5517
      }
5518

5519
      pInfo->points[pInfo->pos] = v;
15,424✔
5520
      double result = pInfo->sum / pInfo->numOfPoints;
15,424✔
5521
      // check for overflow
5522
      if (isinf(result) || isnan(result)) {
15,424!
5523
        colDataSetNULL(pOutput, pos);
×
5524
      } else {
5525
        code = colDataSetVal(pOutput, pos, (char*)&result, false);
15,424✔
5526
        if (TSDB_CODE_SUCCESS != code) {
15,424!
5527
          return code;
×
5528
        }
5529
      }
5530

5531
      // handle selectivity
5532
      if (pCtx->subsidiaries.num > 0) {
15,424✔
5533
        code = appendSelectivityValue(pCtx, i, pos);
210✔
5534
        if (TSDB_CODE_SUCCESS != code) {
210!
5535
          return code;
×
5536
        }
5537
      }
5538

5539
      numOfElems++;
15,424✔
5540
    }
5541

5542
    pInfo->pos++;
524,970✔
5543
    if (pInfo->pos == pInfo->numOfPoints) {
524,970✔
5544
      pInfo->pos = 0;
2,191✔
5545
    }
5546
  }
5547

5548
  pResInfo->numOfRes = numOfElems;
4,402✔
5549
  return TSDB_CODE_SUCCESS;
4,402✔
5550
}
5551

5552
static SSampleInfo* getSampleOutputInfo(SqlFunctionCtx* pCtx) {
24,968✔
5553
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
24,968✔
5554
  SSampleInfo*         pInfo = GET_ROWCELL_INTERBUF(pResInfo);
24,968✔
5555

5556
  pInfo->data = (char*)pInfo + sizeof(SSampleInfo);
24,968✔
5557
  pInfo->tuplePos = (STuplePos*)((char*)pInfo + sizeof(SSampleInfo) + pInfo->samples * pInfo->colBytes);
24,968✔
5558

5559
  return pInfo;
24,968✔
5560
}
5561

5562
bool getSampleFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
5,920✔
5563
  SColumnNode* pCol = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
5,920✔
5564
  SValueNode*  pVal = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
5,925✔
5565
  int32_t      numOfSamples = pVal->datum.i;
5,928✔
5566
  pEnv->calcMemSize = sizeof(SSampleInfo) + numOfSamples * (pCol->node.resType.bytes + sizeof(STuplePos));
5,928✔
5567
  return true;
5,928✔
5568
}
5569

5570
int32_t sampleFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
11,742✔
5571
  if (pResultInfo->initialized) {
11,742!
5572
    return TSDB_CODE_SUCCESS;
×
5573
  }
5574
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
11,742!
5575
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5576
  }
5577

5578
  taosSeedRand(taosSafeRand());
11,742✔
5579

5580
  SSampleInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
11,742✔
5581
  pInfo->samples = pCtx->param[1].param.i;
11,742✔
5582
  pInfo->totalPoints = 0;
11,742✔
5583
  pInfo->numSampled = 0;
11,742✔
5584
  pInfo->colType = pCtx->resDataInfo.type;
11,742✔
5585
  pInfo->colBytes = pCtx->resDataInfo.bytes;
11,742✔
5586
  pInfo->nullTuplePos.pageId = -1;
11,742✔
5587
  pInfo->nullTupleSaved = false;
11,742✔
5588
  pInfo->data = (char*)pInfo + sizeof(SSampleInfo);
11,742✔
5589
  pInfo->tuplePos = (STuplePos*)((char*)pInfo + sizeof(SSampleInfo) + pInfo->samples * pInfo->colBytes);
11,742✔
5590

5591
  return TSDB_CODE_SUCCESS;
11,742✔
5592
}
5593

5594
static void sampleAssignResult(SSampleInfo* pInfo, char* data, int32_t index) {
423,706✔
5595
  assignVal(pInfo->data + index * pInfo->colBytes, data, pInfo->colBytes, pInfo->colType);
423,706✔
5596
}
423,702✔
5597

5598
static int32_t doReservoirSample(SqlFunctionCtx* pCtx, SSampleInfo* pInfo, char* data, int32_t index) {
455,060✔
5599
  pInfo->totalPoints++;
455,060✔
5600
  if (pInfo->numSampled < pInfo->samples) {
455,060✔
5601
    sampleAssignResult(pInfo, data, pInfo->numSampled);
373,466✔
5602
    if (pCtx->subsidiaries.num > 0) {
373,468✔
5603
      int32_t code = saveTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[pInfo->numSampled]);
6,167✔
5604
      if (code != TSDB_CODE_SUCCESS) {
6,180!
5605
        return code;
×
5606
      }
5607
    }
5608
    pInfo->numSampled++;
373,481✔
5609
  } else {
5610
    int32_t j = taosRand() % (pInfo->totalPoints);
81,594✔
5611
    if (j < pInfo->samples) {
82,973✔
5612
      sampleAssignResult(pInfo, data, j);
51,221✔
5613
      if (pCtx->subsidiaries.num > 0) {
51,226✔
5614
        int32_t code = updateTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[j]);
1,490✔
5615
        if (code != TSDB_CODE_SUCCESS) {
206!
5616
          return code;
×
5617
        }
5618
      }
5619
    }
5620
  }
5621

5622
  return TSDB_CODE_SUCCESS;
455,175✔
5623
}
5624

5625
int32_t sampleFunction(SqlFunctionCtx* pCtx) {
13,228✔
5626
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
13,228✔
5627
  SSampleInfo*         pInfo = getSampleOutputInfo(pCtx);
13,228✔
5628

5629
  SInputColumnInfoData* pInput = &pCtx->input;
13,228✔
5630

5631
  SColumnInfoData* pInputCol = pInput->pData[0];
13,228✔
5632
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
907,868✔
5633
    if (colDataIsNull_s(pInputCol, i)) {
1,784,782✔
5634
      continue;
439,512✔
5635
    }
5636

5637
    char*   data = colDataGetData(pInputCol, i);
452,879!
5638
    int32_t code = doReservoirSample(pCtx, pInfo, data, i);
452,879✔
5639
    if (code != TSDB_CODE_SUCCESS) {
455,128!
5640
      return code;
×
5641
    }
5642
  }
5643

5644
  if (pInfo->numSampled == 0 && pCtx->subsidiaries.num > 0 && !pInfo->nullTupleSaved) {
15,477✔
5645
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pInfo->nullTuplePos);
12✔
5646
    if (code != TSDB_CODE_SUCCESS) {
12!
5647
      return code;
×
5648
    }
5649
    pInfo->nullTupleSaved = true;
12✔
5650
  }
5651

5652
  SET_VAL(pResInfo, pInfo->numSampled, pInfo->numSampled);
15,477✔
5653
  return TSDB_CODE_SUCCESS;
15,477✔
5654
}
5655

5656
int32_t sampleFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
11,740✔
5657
  int32_t              code = TSDB_CODE_SUCCESS;
11,740✔
5658
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
11,740✔
5659

5660
  SSampleInfo* pInfo = getSampleOutputInfo(pCtx);
11,740✔
5661
  pEntryInfo->complete = true;
11,740✔
5662

5663
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
11,740✔
5664
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
11,740✔
5665
  if (NULL == pCol) {
11,741!
5666
    return TSDB_CODE_OUT_OF_RANGE;
×
5667
  }
5668

5669
  int32_t currentRow = pBlock->info.rows;
11,741✔
5670
  if (pInfo->numSampled == 0) {
11,741✔
5671
    colDataSetNULL(pCol, currentRow);
2,599✔
5672
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
2,599✔
5673
    return code;
2,599✔
5674
  }
5675
  for (int32_t i = 0; i < pInfo->numSampled; ++i) {
382,177✔
5676
    code = colDataSetVal(pCol, currentRow + i, pInfo->data + i * pInfo->colBytes, false);
373,045✔
5677
    if (TSDB_CODE_SUCCESS != code) {
373,209!
5678
      return code;
×
5679
    }
5680
    code = setSelectivityValue(pCtx, pBlock, &pInfo->tuplePos[i], currentRow + i);
373,209✔
5681
    if (TSDB_CODE_SUCCESS != code) {
373,035!
5682
      return code;
×
5683
    }
5684
  }
5685

5686
  return code;
9,132✔
5687
}
5688

5689
bool getTailFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
×
5690
#if 0
5691
  SColumnNode* pCol = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
5692
  SValueNode*  pVal = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
5693
  int32_t      numOfPoints = pVal->datum.i;
5694
  pEnv->calcMemSize = sizeof(STailInfo) + numOfPoints * (POINTER_BYTES + sizeof(STailItem) + pCol->node.resType.bytes);
5695
#endif
5696
  return true;
×
5697
}
5698

5699
int32_t tailFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
×
5700
#if 0
5701
  if (!functionSetup(pCtx, pResultInfo)) {
5702
    return false;
5703
  }
5704

5705
  STailInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
5706
  pInfo->numAdded = 0;
5707
  pInfo->numOfPoints = pCtx->param[1].param.i;
5708
  if (pCtx->numOfParams == 4) {
5709
    pInfo->offset = pCtx->param[2].param.i;
5710
  } else {
5711
    pInfo->offset = 0;
5712
  }
5713
  pInfo->colType = pCtx->resDataInfo.type;
5714
  pInfo->colBytes = pCtx->resDataInfo.bytes;
5715
  if ((pInfo->numOfPoints < 1 || pInfo->numOfPoints > TAIL_MAX_POINTS_NUM) ||
5716
      (pInfo->numOfPoints < 0 || pInfo->numOfPoints > TAIL_MAX_OFFSET)) {
5717
    return false;
5718
  }
5719

5720
  pInfo->pItems = (STailItem**)((char*)pInfo + sizeof(STailInfo));
5721
  char* pItem = (char*)pInfo->pItems + pInfo->numOfPoints * POINTER_BYTES;
5722

5723
  size_t unitSize = sizeof(STailItem) + pInfo->colBytes;
5724
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
5725
    pInfo->pItems[i] = (STailItem*)(pItem + i * unitSize);
5726
    pInfo->pItems[i]->isNull = false;
5727
  }
5728
#endif
5729

5730
  return TSDB_CODE_SUCCESS;
×
5731
}
5732

5733
static void tailAssignResult(STailItem* pItem, char* data, int32_t colBytes, TSKEY ts, bool isNull) {
×
5734
#if 0
5735
  pItem->timestamp = ts;
5736
  if (isNull) {
5737
    pItem->isNull = true;
5738
  } else {
5739
    pItem->isNull = false;
5740
    memcpy(pItem->data, data, colBytes);
5741
  }
5742
#endif
5743
}
×
5744

5745
#if 0
5746
static int32_t tailCompFn(const void* p1, const void* p2, const void* param) {
5747
  STailItem* d1 = *(STailItem**)p1;
5748
  STailItem* d2 = *(STailItem**)p2;
5749
  return compareInt64Val(&d1->timestamp, &d2->timestamp);
5750
}
5751

5752
static void doTailAdd(STailInfo* pInfo, char* data, TSKEY ts, bool isNull) {
5753
  STailItem** pList = pInfo->pItems;
5754
  if (pInfo->numAdded < pInfo->numOfPoints) {
5755
    tailAssignResult(pList[pInfo->numAdded], data, pInfo->colBytes, ts, isNull);
5756
    taosheapsort((void*)pList, sizeof(STailItem**), pInfo->numAdded + 1, NULL, tailCompFn, 0);
5757
    pInfo->numAdded++;
5758
  } else if (pList[0]->timestamp < ts) {
5759
    tailAssignResult(pList[0], data, pInfo->colBytes, ts, isNull);
5760
    taosheapadjust((void*)pList, sizeof(STailItem**), 0, pInfo->numOfPoints - 1, NULL, tailCompFn, NULL, 0);
5761
  }
5762
}
5763
#endif
5764

5765
int32_t tailFunction(SqlFunctionCtx* pCtx) {
×
5766
#if 0
5767
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5768
  STailInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5769

5770
  SInputColumnInfoData* pInput = &pCtx->input;
5771
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
5772

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

5776
  int32_t startOffset = pCtx->offset;
5777
  if (pInfo->offset >= pInput->numOfRows) {
5778
    return 0;
5779
  } else {
5780
    pInfo->numOfPoints = TMIN(pInfo->numOfPoints, pInput->numOfRows - pInfo->offset);
5781
  }
5782
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex - pInfo->offset; i += 1) {
5783
    char* data = colDataGetData(pInputCol, i);
5784
    doTailAdd(pInfo, data, tsList[i], colDataIsNull_s(pInputCol, i));
5785
  }
5786

5787
  taosqsort(pInfo->pItems, pInfo->numOfPoints, POINTER_BYTES, NULL, tailCompFn);
5788

5789
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
5790
    int32_t    pos = startOffset + i;
5791
    STailItem* pItem = pInfo->pItems[i];
5792
    if (pItem->isNull) {
5793
      colDataSetNULL(pOutput, pos);
5794
    } else {
5795
      colDataSetVal(pOutput, pos, pItem->data, false);
5796
    }
5797
  }
5798

5799
  return pInfo->numOfPoints;
5800
#endif
5801
  return 0;
×
5802
}
5803

5804
int32_t tailFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
×
5805
#if 0
5806
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
5807
  STailInfo*           pInfo = GET_ROWCELL_INTERBUF(pEntryInfo);
5808
  pEntryInfo->complete = true;
5809

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

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

5815
  // todo assign the tag value and the corresponding row data
5816
  int32_t currentRow = pBlock->info.rows;
5817
  for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
5818
    STailItem* pItem = pInfo->pItems[i];
5819
    colDataSetVal(pCol, currentRow, pItem->data, false);
5820
    currentRow += 1;
5821
  }
5822

5823
  return pEntryInfo->numOfRes;
5824
#endif
5825
  return 0;
×
5826
}
5827

5828
bool getUniqueFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
×
5829
#if 0
5830
  pEnv->calcMemSize = sizeof(SUniqueInfo) + UNIQUE_MAX_RESULT_SIZE;
5831
#endif
5832
  return true;
×
5833
}
5834

5835
int32_t uniqueFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
×
5836
#if 0
5837
  if (!functionSetup(pCtx, pResInfo)) {
5838
    return false;
5839
  }
5840

5841
  SUniqueInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5842
  pInfo->numOfPoints = 0;
5843
  pInfo->colType = pCtx->resDataInfo.type;
5844
  pInfo->colBytes = pCtx->resDataInfo.bytes;
5845
  if (pInfo->pHash != NULL) {
5846
    taosHashClear(pInfo->pHash);
5847
  } else {
5848
    pInfo->pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
5849
  }
5850
#endif
5851
  return TSDB_CODE_SUCCESS;
×
5852
}
5853

5854
#if 0
5855
static void doUniqueAdd(SUniqueInfo* pInfo, char* data, TSKEY ts, bool isNull) {
5856
  // handle null elements
5857
  if (isNull == true) {
5858
    int32_t      size = sizeof(SUniqueItem) + pInfo->colBytes;
5859
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + pInfo->numOfPoints * size);
5860
    if (pInfo->hasNull == false && pItem->isNull == false) {
5861
      pItem->timestamp = ts;
5862
      pItem->isNull = true;
5863
      pInfo->numOfPoints++;
5864
      pInfo->hasNull = true;
5865
    } else if (pItem->timestamp > ts && pItem->isNull == true) {
5866
      pItem->timestamp = ts;
5867
    }
5868
    return;
5869
  }
5870

5871
  int32_t      hashKeyBytes = IS_VAR_DATA_TYPE(pInfo->colType) ? varDataTLen(data) : pInfo->colBytes;
5872
  SUniqueItem* pHashItem = taosHashGet(pInfo->pHash, data, hashKeyBytes);
5873
  if (pHashItem == NULL) {
5874
    int32_t      size = sizeof(SUniqueItem) + pInfo->colBytes;
5875
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + pInfo->numOfPoints * size);
5876
    pItem->timestamp = ts;
5877
    memcpy(pItem->data, data, pInfo->colBytes);
5878

5879
    taosHashPut(pInfo->pHash, data, hashKeyBytes, (char*)pItem, sizeof(SUniqueItem*));
5880
    pInfo->numOfPoints++;
5881
  } else if (pHashItem->timestamp > ts) {
5882
    pHashItem->timestamp = ts;
5883
  }
5884
}
5885
#endif
5886

5887
int32_t uniqueFunction(SqlFunctionCtx* pCtx) {
×
5888
#if 0
5889
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5890
  SUniqueInfo*         pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5891

5892
  SInputColumnInfoData* pInput = &pCtx->input;
5893
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
5894

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

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

5904
    if (sizeof(SUniqueInfo) + pInfo->numOfPoints * (sizeof(SUniqueItem) + pInfo->colBytes) >= UNIQUE_MAX_RESULT_SIZE) {
5905
      taosHashCleanup(pInfo->pHash);
5906
      return 0;
5907
    }
5908
  }
5909

5910
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
5911
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + i * (sizeof(SUniqueItem) + pInfo->colBytes));
5912
    if (pItem->isNull == true) {
5913
      colDataSetNULL(pOutput, i);
5914
    } else {
5915
      colDataSetVal(pOutput, i, pItem->data, false);
5916
    }
5917
    if (pTsOutput != NULL) {
5918
      colDataSetInt64(pTsOutput, i, &pItem->timestamp);
5919
    }
5920
  }
5921

5922
  return pInfo->numOfPoints;
5923
#endif
5924
  return 0;
×
5925
}
5926

5927
bool getModeFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
5,562✔
5928
  pEnv->calcMemSize = sizeof(SModeInfo);
5,562✔
5929
  return true;
5,562✔
5930
}
5931

5932
int32_t modeFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
5,278✔
5933
  if (pResInfo->initialized) {
5,278!
5934
    return TSDB_CODE_SUCCESS;
×
5935
  }
5936
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
5,278!
5937
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5938
  }
5939

5940
  SModeInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5,278✔
5941
  pInfo->colType = pCtx->resDataInfo.type;
5,278✔
5942
  pInfo->colBytes = pCtx->resDataInfo.bytes;
5,278✔
5943
  if (pInfo->pHash != NULL) {
5,278!
5944
    taosHashClear(pInfo->pHash);
×
5945
  } else {
5946
    pInfo->pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
5,278✔
5947
    if (NULL == pInfo->pHash) {
5,278!
5948
      return terrno;
×
5949
    }
5950
  }
5951
  pInfo->nullTupleSaved = false;
5,278✔
5952
  pInfo->nullTuplePos.pageId = -1;
5,278✔
5953

5954
  pInfo->buf = taosMemoryMalloc(pInfo->colBytes);
5,278!
5955
  if (NULL == pInfo->buf) {
5,278!
5956
    taosHashCleanup(pInfo->pHash);
×
5957
    pInfo->pHash = NULL;
×
5958
    return terrno;
×
5959
  }
5960
  pCtx->needCleanup = true;
5,278✔
5961
  return TSDB_CODE_SUCCESS;
5,278✔
5962
}
5963

5964
static void modeFunctionCleanup(SModeInfo* pInfo) {
5,278✔
5965
  taosHashCleanup(pInfo->pHash);
5,278✔
5966
  pInfo->pHash = NULL;
5,278✔
5967
  taosMemoryFreeClear(pInfo->buf);
5,278!
5968
}
5,278✔
5969

5970
void modeFunctionCleanupExt(SqlFunctionCtx* pCtx) {
×
5971
  if (pCtx == NULL || GET_RES_INFO(pCtx) == NULL || GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)) == NULL) {
×
5972
    return;
×
5973
  }
5974
  modeFunctionCleanup(GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)));
×
5975
}
5976

5977
static int32_t saveModeTupleData(SqlFunctionCtx* pCtx, char* data, SModeInfo* pInfo, STuplePos* pPos) {
331,878✔
5978
  if (IS_VAR_DATA_TYPE(pInfo->colType)) {
331,878!
5979
    if (pInfo->colType == TSDB_DATA_TYPE_JSON) {
106,230!
5980
      (void)memcpy(pInfo->buf, data, getJsonValueLen(data));
×
5981
    } else {
5982
      (void)memcpy(pInfo->buf, data, varDataTLen(data));
106,230✔
5983
    }
5984
  } else {
5985
    (void)memcpy(pInfo->buf, data, pInfo->colBytes);
225,648✔
5986
  }
5987

5988
  return doSaveTupleData(&pCtx->saveHandle, pInfo->buf, pInfo->colBytes, NULL, pPos, pCtx->pStore);
331,878✔
5989
}
5990

5991
static int32_t doModeAdd(SModeInfo* pInfo, int32_t rowIndex, SqlFunctionCtx* pCtx, char* data) {
472,626✔
5992
  int32_t code = TSDB_CODE_SUCCESS;
472,626✔
5993
  int32_t hashKeyBytes;
5994
  if (IS_VAR_DATA_TYPE(pInfo->colType)) {
472,626!
5995
    if (pInfo->colType == TSDB_DATA_TYPE_JSON) {
105,735!
5996
      hashKeyBytes = getJsonValueLen(data);
×
5997
    } else {
5998
      hashKeyBytes = varDataTLen(data);
105,735✔
5999
    }
6000
  } else {
6001
    hashKeyBytes = pInfo->colBytes;
366,891✔
6002
  }
6003

6004
  SModeItem* pHashItem = (SModeItem*)taosHashGet(pInfo->pHash, data, hashKeyBytes);
473,150✔
6005
  if (pHashItem == NULL) {
472,441✔
6006
    int32_t   size = sizeof(SModeItem);
331,715✔
6007
    SModeItem item = {0};
331,715✔
6008

6009
    item.count += 1;
331,715✔
6010
    code = saveModeTupleData(pCtx, data, pInfo, &item.dataPos);
331,715✔
6011
    if (code != TSDB_CODE_SUCCESS) {
331,747!
6012
      return code;
×
6013
    }
6014

6015
    if (pCtx->subsidiaries.num > 0) {
331,747✔
6016
      code = saveTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &item.tuplePos);
325✔
6017
      if (code != TSDB_CODE_SUCCESS) {
325!
6018
        return code;
×
6019
      }
6020
    }
6021

6022
    code = taosHashPut(pInfo->pHash, data, hashKeyBytes, &item, sizeof(SModeItem));
331,747✔
6023
    if (code != TSDB_CODE_SUCCESS) {
332,090!
6024
      return code;
×
6025
    }
6026
  } else {
6027
    pHashItem->count += 1;
140,726✔
6028
    if (pCtx->subsidiaries.num > 0) {
140,726✔
6029
      code = updateTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &pHashItem->tuplePos);
109✔
6030
      if (code != TSDB_CODE_SUCCESS) {
109!
6031
        return code;
×
6032
      }
6033
    }
6034
  }
6035

6036
  return code;
472,816✔
6037
}
6038

6039
int32_t modeFunction(SqlFunctionCtx* pCtx) {
6,338✔
6040
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
6,338✔
6041
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
6,338✔
6042

6043
  SInputColumnInfoData* pInput = &pCtx->input;
6,338✔
6044

6045
  SColumnInfoData* pInputCol = pInput->pData[0];
6,338✔
6046
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
6,338✔
6047

6048
  int32_t numOfElems = 0;
6,338✔
6049
  int32_t startOffset = pCtx->offset;
6,338✔
6050
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
949,305✔
6051
    if (colDataIsNull_s(pInputCol, i)) {
1,885,972✔
6052
      continue;
470,901✔
6053
    }
6054
    numOfElems++;
472,085✔
6055

6056
    char*   data = colDataGetData(pInputCol, i);
472,085!
6057
    int32_t code = doModeAdd(pInfo, i, pCtx, data);
472,085✔
6058
    if (code != TSDB_CODE_SUCCESS) {
472,812✔
6059
      modeFunctionCleanup(pInfo);
746✔
6060
      return code;
×
6061
    }
6062
  }
6063

6064
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pInfo->nullTupleSaved) {
6,319!
6065
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pInfo->nullTuplePos);
30✔
6066
    if (code != TSDB_CODE_SUCCESS) {
30!
6067
      modeFunctionCleanup(pInfo);
×
6068
      return code;
×
6069
    }
6070
    pInfo->nullTupleSaved = true;
30✔
6071
  }
6072

6073
  SET_VAL(pResInfo, numOfElems, 1);
6,319✔
6074

6075
  return TSDB_CODE_SUCCESS;
6,319✔
6076
}
6077

6078
int32_t modeFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
5,278✔
6079
  int32_t              code = TSDB_CODE_SUCCESS;
5,278✔
6080
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5,278✔
6081
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5,278✔
6082
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
5,278✔
6083
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
5,278✔
6084
  int32_t              currentRow = pBlock->info.rows;
5,278✔
6085
  if (NULL == pCol) {
5,278!
6086
    modeFunctionCleanup(pInfo);
×
6087
    return TSDB_CODE_OUT_OF_RANGE;
×
6088
  }
6089

6090
  STuplePos resDataPos, resTuplePos;
6091
  int32_t   maxCount = 0;
5,278✔
6092

6093
  void* pIter = taosHashIterate(pInfo->pHash, NULL);
5,278✔
6094
  while (pIter != NULL) {
337,448✔
6095
    SModeItem* pItem = (SModeItem*)pIter;
332,170✔
6096
    if (pItem->count >= maxCount) {
332,170✔
6097
      maxCount = pItem->count;
281,730✔
6098
      resDataPos = pItem->dataPos;
281,730✔
6099
      resTuplePos = pItem->tuplePos;
281,730✔
6100
    }
6101

6102
    pIter = taosHashIterate(pInfo->pHash, pIter);
332,170✔
6103
  }
6104

6105
  if (maxCount != 0) {
5,278✔
6106
    char* pData = NULL;
2,896✔
6107
    code = loadTupleData(pCtx, &resDataPos, &pData);
2,896✔
6108
    if (pData == NULL || TSDB_CODE_SUCCESS != code) {
2,896!
6109
      code = terrno = TSDB_CODE_NOT_FOUND;
×
6110
      qError("Load tuple data failed since %s, groupId:%" PRIu64 ", ts:%" PRId64, terrstr(),
×
6111
             resDataPos.streamTupleKey.groupId, resDataPos.streamTupleKey.ts);
6112
      modeFunctionCleanup(pInfo);
×
6113
      return code;
×
6114
    }
6115

6116
    code = colDataSetVal(pCol, currentRow, pData, false);
2,896✔
6117
    if (TSDB_CODE_SUCCESS != code) {
2,896!
6118
      modeFunctionCleanup(pInfo);
×
6119
      return code;
×
6120
    }
6121
    code = setSelectivityValue(pCtx, pBlock, &resTuplePos, currentRow);
2,896✔
6122
  } else {
6123
    colDataSetNULL(pCol, currentRow);
2,382✔
6124
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
2,382✔
6125
  }
6126

6127
  modeFunctionCleanup(pInfo);
5,278✔
6128

6129
  return code;
5,278✔
6130
}
6131

6132
bool getTwaFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
3,781✔
6133
  pEnv->calcMemSize = sizeof(STwaInfo);
3,781✔
6134
  return true;
3,781✔
6135
}
6136

6137
int32_t twaFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
47,786✔
6138
  if (pResultInfo->initialized) {
47,786!
6139
    return TSDB_CODE_SUCCESS;
×
6140
  }
6141
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
47,786!
6142
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6143
  }
6144

6145
  STwaInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
47,790✔
6146
  pInfo->numOfElems = 0;
47,790✔
6147
  pInfo->p.key = INT64_MIN;
47,790✔
6148
  pInfo->win = TSWINDOW_INITIALIZER;
47,790✔
6149
  return TSDB_CODE_SUCCESS;
47,790✔
6150
}
6151

6152
static double twa_get_area(SPoint1 s, SPoint1 e) {
623,710✔
6153
  if (e.key == INT64_MAX || s.key == INT64_MIN) {
623,710!
6154
    return 0;
×
6155
  }
6156

6157
  if ((s.val >= 0 && e.val >= 0) || (s.val <= 0 && e.val <= 0)) {
623,939✔
6158
    return (s.val + e.val) * (e.key - s.key) / 2;
550,649✔
6159
  }
6160

6161
  double x = (s.key * e.val - e.key * s.val) / (e.val - s.val);
73,290✔
6162
  double val = (s.val * (x - s.key) + e.val * (e.key - x)) / 2;
73,290✔
6163
  return val;
73,290✔
6164
}
6165

6166
int32_t twaFunction(SqlFunctionCtx* pCtx) {
48,661✔
6167
  int32_t               code = TSDB_CODE_SUCCESS;
48,661✔
6168
  SInputColumnInfoData* pInput = &pCtx->input;
48,661✔
6169
  SColumnInfoData*      pInputCol = pInput->pData[0];
48,661✔
6170

6171
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
48,661✔
6172
  STwaInfo*            pInfo = GET_ROWCELL_INTERBUF(pResInfo);
48,661✔
6173
  SPoint1*             last = &pInfo->p;
48,661✔
6174

6175
  if (IS_NULL_TYPE(pInputCol->info.type)) {
48,661!
6176
    pInfo->numOfElems = 0;
×
6177
    goto _twa_over;
×
6178
  }
6179

6180
  funcInputUpdate(pCtx);
48,661✔
6181
  SFuncInputRow row = {0};
48,666✔
6182
  bool          result = false;
48,666✔
6183
  if (pCtx->start.key != INT64_MIN && last->key == INT64_MIN) {
48,666!
6184
    while (1) {
6185
      code = funcInputGetNextRow(pCtx, &row, &result);
13,321✔
6186
      if (TSDB_CODE_SUCCESS != code) {
13,321!
6187
        return code;
×
6188
      }
6189
      if (!result) {
13,321✔
6190
        break;
2✔
6191
      }
6192
      if (row.isDataNull) {
13,319✔
6193
        continue;
2✔
6194
      }
6195

6196
      last->key = row.ts;
13,317✔
6197

6198
      GET_TYPED_DATA(last->val, double, pInputCol->info.type, row.pData, typeGetTypeModFromColInfo(&pInputCol->info));
13,317!
6199

6200
      pInfo->dOutput += twa_get_area(pCtx->start, *last);
13,317✔
6201
      pInfo->win.skey = pCtx->start.key;
13,317✔
6202
      pInfo->numOfElems++;
13,317✔
6203
      break;
13,317✔
6204
    }
6205
  } else if (pInfo->p.key == INT64_MIN) {
35,347✔
6206
    while (1) {
6207
      code = funcInputGetNextRow(pCtx, &row, &result);
148,204✔
6208
      if (TSDB_CODE_SUCCESS != code) {
148,204!
6209
        return code;
×
6210
      }
6211
      if (!result) {
148,204✔
6212
        break;
16,333✔
6213
      }
6214
      if (row.isDataNull) {
131,871✔
6215
        continue;
113,206✔
6216
      }
6217

6218
      last->key = row.ts;
18,665✔
6219

6220
      GET_TYPED_DATA(last->val, double, pInputCol->info.type, row.pData, typeGetTypeModFromColInfo(&pInputCol->info));
18,665!
6221

6222
      pInfo->win.skey = last->key;
18,662✔
6223
      pInfo->numOfElems++;
18,662✔
6224
      break;
18,662✔
6225
    }
6226
  }
6227

6228
  SPoint1 st = {0};
48,663✔
6229

6230
  // calculate the value of
6231
  while (1) {
6232
    code = funcInputGetNextRow(pCtx, &row, &result);
646,786✔
6233
    if (TSDB_CODE_SUCCESS != code) {
647,076!
6234
      return code;
×
6235
    }
6236
    if (!result) {
647,076✔
6237
      break;
48,675✔
6238
    }
6239
    if (row.isDataNull) {
598,401✔
6240
      continue;
630✔
6241
    }
6242
    pInfo->numOfElems++;
597,771✔
6243
    switch (pInputCol->info.type) {
597,771✔
6244
      case TSDB_DATA_TYPE_TINYINT: {
66,913✔
6245
        INIT_INTP_POINT(st, row.ts, *(int8_t*)row.pData);
66,913✔
6246
        break;
66,913✔
6247
      }
6248
      case TSDB_DATA_TYPE_SMALLINT: {
71,112✔
6249
        INIT_INTP_POINT(st, row.ts, *(int16_t*)row.pData);
71,112✔
6250
        break;
71,112✔
6251
      }
6252
      case TSDB_DATA_TYPE_INT: {
92,568✔
6253
        INIT_INTP_POINT(st, row.ts, *(int32_t*)row.pData);
92,568✔
6254
        break;
92,568✔
6255
      }
6256
      case TSDB_DATA_TYPE_BIGINT: {
69,632✔
6257
        INIT_INTP_POINT(st, row.ts, *(int64_t*)row.pData);
69,632✔
6258
        break;
69,632✔
6259
      }
6260
      case TSDB_DATA_TYPE_FLOAT: {
45,041✔
6261
        INIT_INTP_POINT(st, row.ts, *(float_t*)row.pData);
45,041✔
6262
        break;
45,041✔
6263
      }
6264
      case TSDB_DATA_TYPE_DOUBLE: {
66,195✔
6265
        INIT_INTP_POINT(st, row.ts, *(double*)row.pData);
66,195✔
6266
        break;
66,195✔
6267
      }
6268
      case TSDB_DATA_TYPE_UTINYINT: {
48,428✔
6269
        INIT_INTP_POINT(st, row.ts, *(uint8_t*)row.pData);
48,428✔
6270
        break;
48,428✔
6271
      }
6272
      case TSDB_DATA_TYPE_USMALLINT: {
48,224✔
6273
        INIT_INTP_POINT(st, row.ts, *(uint16_t*)row.pData);
48,224✔
6274
        break;
48,224✔
6275
      }
6276
      case TSDB_DATA_TYPE_UINT: {
50,562✔
6277
        INIT_INTP_POINT(st, row.ts, *(uint32_t*)row.pData);
50,562✔
6278
        break;
50,562✔
6279
      }
6280
      case TSDB_DATA_TYPE_UBIGINT: {
38,549✔
6281
        INIT_INTP_POINT(st, row.ts, *(uint64_t*)row.pData);
38,549✔
6282
        break;
38,549✔
6283
      }
6284
      default: {
547✔
6285
        return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
547✔
6286
      }
6287
    }
6288
    if (pInfo->p.key == st.key) {
597,224!
6289
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6290
    }
6291

6292
    pInfo->dOutput += twa_get_area(pInfo->p, st);
597,224✔
6293
    pInfo->p = st;
597,493✔
6294
  }
6295

6296
  // the last interpolated time window value
6297
  if (pCtx->end.key != INT64_MIN) {
48,675✔
6298
    pInfo->dOutput += twa_get_area(pInfo->p, pCtx->end);
13,324✔
6299
    pInfo->p = pCtx->end;
13,324✔
6300
    pInfo->numOfElems += 1;
13,324✔
6301
  }
6302

6303
  pInfo->win.ekey = pInfo->p.key;
48,675✔
6304

6305
_twa_over:
48,675✔
6306
  SET_VAL(pResInfo, 1, 1);
48,675✔
6307
  return TSDB_CODE_SUCCESS;
48,675✔
6308
}
6309

6310
/*
6311
 * To copy the input to interResBuf to avoid the input buffer space be over writen
6312
 * by next input data. The TWA function only applies to each table, so no merge procedure
6313
 * is required, we simply copy to the resut ot interResBuffer.
6314
 */
6315
// void twa_function_copy(SQLFunctionCtx *pCtx) {
6316
//   SResultRowEntryInfo *pResInfo = GET_RES_INFO(pCtx);
6317
//
6318
//   memcpy(GET_ROWCELL_INTERBUF(pResInfo), pCtx->pInput, (size_t)pCtx->inputBytes);
6319
//   pResInfo->hasResult = ((STwaInfo *)pCtx->pInput)->hasResult;
6320
// }
6321

6322
int32_t twaFinalize(struct SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
47,905✔
6323
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
47,905✔
6324

6325
  STwaInfo* pInfo = (STwaInfo*)GET_ROWCELL_INTERBUF(pResInfo);
47,905✔
6326
  if (pInfo->numOfElems == 0) {
47,905✔
6327
    pResInfo->numOfRes = 0;
15,805✔
6328
  } else {
6329
    if (pInfo->win.ekey == pInfo->win.skey) {
32,100✔
6330
      pInfo->dTwaRes = pInfo->p.val;
11,843✔
6331
    } else if (pInfo->win.ekey == INT64_MAX || pInfo->win.skey == INT64_MIN) {  // no data in timewindow
20,257!
6332
      pInfo->dTwaRes = 0;
2✔
6333
    } else {
6334
      pInfo->dTwaRes = pInfo->dOutput / (pInfo->win.ekey - pInfo->win.skey);
20,255✔
6335
    }
6336

6337
    pResInfo->numOfRes = 1;
32,100✔
6338
  }
6339

6340
  return functionFinalize(pCtx, pBlock);
47,905✔
6341
}
6342

6343
int32_t blockDistSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
7✔
6344
  if (pResultInfo->initialized) {
7!
6345
    return TSDB_CODE_SUCCESS;
×
6346
  }
6347
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
7!
6348
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6349
  }
6350

6351
  STableBlockDistInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
7✔
6352
  pInfo->minRows = INT32_MAX;
7✔
6353
  return TSDB_CODE_SUCCESS;
7✔
6354
}
6355

6356
int32_t blockDistFunction(SqlFunctionCtx* pCtx) {
11✔
6357
  const int32_t BLOCK_DIST_RESULT_ROWS = 25;
11✔
6358

6359
  SInputColumnInfoData* pInput = &pCtx->input;
11✔
6360
  SColumnInfoData*      pInputCol = pInput->pData[0];
11✔
6361
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
11✔
6362
  STableBlockDistInfo*  pDistInfo = GET_ROWCELL_INTERBUF(pResInfo);
11✔
6363

6364
  STableBlockDistInfo p1 = {0};
11✔
6365
  if (tDeserializeBlockDistInfo(varDataVal(pInputCol->pData), varDataLen(pInputCol->pData), &p1) < 0) {
11!
6366
    qError("failed to deserialize block dist info");
×
6367
    return TSDB_CODE_FAILED;
×
6368
  }
6369

6370
  pDistInfo->numOfBlocks += p1.numOfBlocks;
11✔
6371
  pDistInfo->numOfTables += p1.numOfTables;
11✔
6372
  pDistInfo->numOfInmemRows += p1.numOfInmemRows;
11✔
6373
  pDistInfo->numOfSttRows += p1.numOfSttRows;
11✔
6374
  pDistInfo->totalSize += p1.totalSize;
11✔
6375
  pDistInfo->totalRows += p1.totalRows;
11✔
6376
  pDistInfo->numOfFiles += p1.numOfFiles;
11✔
6377

6378
  pDistInfo->defMinRows = p1.defMinRows;
11✔
6379
  pDistInfo->defMaxRows = p1.defMaxRows;
11✔
6380
  pDistInfo->rowSize = p1.rowSize;
11✔
6381

6382
  if (pDistInfo->minRows > p1.minRows) {
11✔
6383
    pDistInfo->minRows = p1.minRows;
1✔
6384
  }
6385
  if (pDistInfo->maxRows < p1.maxRows) {
11✔
6386
    pDistInfo->maxRows = p1.maxRows;
1✔
6387
  }
6388
  pDistInfo->numOfVgroups += (p1.numOfTables != 0 ? 1 : 0);
11✔
6389
  for (int32_t i = 0; i < tListLen(pDistInfo->blockRowsHisto); ++i) {
231✔
6390
    pDistInfo->blockRowsHisto[i] += p1.blockRowsHisto[i];
220✔
6391
  }
6392

6393
  pResInfo->numOfRes = BLOCK_DIST_RESULT_ROWS;  // default output rows
11✔
6394
  return TSDB_CODE_SUCCESS;
11✔
6395
}
6396

6397
int32_t tSerializeBlockDistInfo(void* buf, int32_t bufLen, const STableBlockDistInfo* pInfo) {
22✔
6398
  SEncoder encoder = {0};
22✔
6399
  int32_t  code = 0;
22✔
6400
  int32_t  lino;
6401
  int32_t  tlen;
6402
  tEncoderInit(&encoder, buf, bufLen);
22✔
6403

6404
  TAOS_CHECK_EXIT(tStartEncode(&encoder));
22!
6405
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->rowSize));
44!
6406

6407
  TAOS_CHECK_EXIT(tEncodeU16(&encoder, pInfo->numOfFiles));
44!
6408
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfBlocks));
44!
6409
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfTables));
44!
6410

6411
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalSize));
44!
6412
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalRows));
44!
6413
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->maxRows));
44!
6414
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->minRows));
44!
6415
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMaxRows));
44!
6416
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMinRows));
44!
6417
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfInmemRows));
44!
6418
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfSttRows));
44!
6419
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfVgroups));
44!
6420

6421
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
462✔
6422
    TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->blockRowsHisto[i]));
880!
6423
  }
6424

6425
  tEndEncode(&encoder);
22✔
6426

6427
_exit:
22✔
6428
  if (code) {
22!
6429
    tlen = code;
×
6430
  } else {
6431
    tlen = encoder.pos;
22✔
6432
  }
6433
  tEncoderClear(&encoder);
22✔
6434
  return tlen;
22✔
6435
}
6436

6437
int32_t tDeserializeBlockDistInfo(void* buf, int32_t bufLen, STableBlockDistInfo* pInfo) {
11✔
6438
  SDecoder decoder = {0};
11✔
6439
  int32_t  code = 0;
11✔
6440
  int32_t  lino;
6441
  tDecoderInit(&decoder, buf, bufLen);
11✔
6442

6443
  TAOS_CHECK_EXIT(tStartDecode(&decoder));
11!
6444
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->rowSize));
22!
6445

6446
  TAOS_CHECK_EXIT(tDecodeU16(&decoder, &pInfo->numOfFiles));
22!
6447
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfBlocks));
22!
6448
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfTables));
22!
6449

6450
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->totalSize));
22!
6451
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->totalRows));
22!
6452
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->maxRows));
22!
6453
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->minRows));
22!
6454
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->defMaxRows));
22!
6455
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->defMinRows));
22!
6456
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfInmemRows));
22!
6457
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfSttRows));
22!
6458
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfVgroups));
22!
6459

6460
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
231✔
6461
    TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->blockRowsHisto[i]));
440!
6462
  }
6463

6464
_exit:
11✔
6465
  tDecoderClear(&decoder);
11✔
6466
  return code;
11✔
6467
}
6468

6469
int32_t blockDistFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
7✔
6470
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
7✔
6471
  STableBlockDistInfo* pData = GET_ROWCELL_INTERBUF(pResInfo);
7✔
6472

6473
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);
7✔
6474
  if (NULL == pColInfo) {
7!
6475
    return TSDB_CODE_OUT_OF_RANGE;
×
6476
  }
6477

6478
  if (pData->totalRows == 0) {
7✔
6479
    pData->minRows = 0;
6✔
6480
  }
6481

6482
  int32_t row = 0;
7✔
6483
  char    st[256] = {0};
7✔
6484
  double  averageSize = 0;
7✔
6485
  if (pData->numOfBlocks != 0) {
7✔
6486
    averageSize = ((double)pData->totalSize) / pData->numOfBlocks;
1✔
6487
  }
6488
  uint64_t totalRawSize = pData->totalRows * pData->rowSize;
7✔
6489
  double   compRatio = 0;
7✔
6490
  if (totalRawSize != 0) {
7✔
6491
    compRatio = pData->totalSize * 100 / (double)totalRawSize;
1✔
6492
  }
6493

6494
  int32_t len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
14✔
6495
                          "Total_Blocks=[%d] Total_Size=[%.2f KiB] Average_size=[%.2f KiB] Compression_Ratio=[%.2f %c]",
6496
                          pData->numOfBlocks, pData->totalSize / 1024.0, averageSize / 1024.0, compRatio, '%');
7✔
6497

6498
  varDataSetLen(st, len);
7✔
6499
  int32_t code = colDataSetVal(pColInfo, row++, st, false);
7✔
6500
  if (TSDB_CODE_SUCCESS != code) {
7!
6501
    return code;
×
6502
  }
6503

6504
  int64_t avgRows = 0;
7✔
6505
  if (pData->numOfBlocks > 0) {
7✔
6506
    avgRows = pData->totalRows / pData->numOfBlocks;
1✔
6507
  }
6508

6509
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
7✔
6510
                  "Block_Rows=[%" PRId64 "] MinRows=[%d] MaxRows=[%d] AvgRows=[%" PRId64 "]", pData->totalRows,
6511
                  pData->minRows, pData->maxRows, avgRows);
6512
  varDataSetLen(st, len);
7✔
6513
  code = colDataSetVal(pColInfo, row++, st, false);
7✔
6514
  if (TSDB_CODE_SUCCESS != code) {
7!
6515
    return code;
×
6516
  }
6517

6518
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Inmem_Rows=[%u] Stt_Rows=[%u] ",
7✔
6519
                  pData->numOfInmemRows, pData->numOfSttRows);
6520
  varDataSetLen(st, len);
7✔
6521
  code = colDataSetVal(pColInfo, row++, st, false);
7✔
6522
  if (TSDB_CODE_SUCCESS != code) {
7!
6523
    return code;
×
6524
  }
6525

6526
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
14✔
6527
                  "Total_Tables=[%d] Total_Filesets=[%d] Total_Vgroups=[%d]", pData->numOfTables, pData->numOfFiles,
7✔
6528
                  pData->numOfVgroups);
6529

6530
  varDataSetLen(st, len);
7✔
6531
  code = colDataSetVal(pColInfo, row++, st, false);
7✔
6532
  if (TSDB_CODE_SUCCESS != code) {
7!
6533
    return code;
×
6534
  }
6535

6536
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
7✔
6537
                  "--------------------------------------------------------------------------------");
6538
  varDataSetLen(st, len);
7✔
6539
  code = colDataSetVal(pColInfo, row++, st, false);
7✔
6540
  if (TSDB_CODE_SUCCESS != code) {
7!
6541
    return code;
×
6542
  }
6543

6544
  int32_t maxVal = 0;
7✔
6545
  int32_t minVal = INT32_MAX;
7✔
6546
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
147✔
6547
    if (maxVal < pData->blockRowsHisto[i]) {
140✔
6548
      maxVal = pData->blockRowsHisto[i];
1✔
6549
    }
6550

6551
    if (minVal > pData->blockRowsHisto[i]) {
140✔
6552
      minVal = pData->blockRowsHisto[i];
8✔
6553
    }
6554
  }
6555

6556
  // maximum number of step is 80
6557
  double factor = pData->numOfBlocks / 80.0;
7✔
6558

6559
  int32_t numOfBuckets = sizeof(pData->blockRowsHisto) / sizeof(pData->blockRowsHisto[0]);
7✔
6560
  int32_t bucketRange = ceil(((double)(pData->defMaxRows - pData->defMinRows)) / numOfBuckets);
7✔
6561

6562
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
147✔
6563
    len =
140✔
6564
        tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "%04d |", pData->defMinRows + bucketRange * (i + 1));
140✔
6565

6566
    int32_t num = 0;
140✔
6567
    if (pData->blockRowsHisto[i] > 0) {
140✔
6568
      num = (pData->blockRowsHisto[i]) / factor;
1✔
6569
    }
6570

6571
    for (int32_t j = 0; j < num; ++j) {
220✔
6572
      int32_t x = tsnprintf(varDataVal(st) + len, sizeof(st) - VARSTR_HEADER_SIZE - len, "%c", '|');
80✔
6573
      len += x;
80✔
6574
    }
6575

6576
    if (pData->blockRowsHisto[i] > 0) {
140✔
6577
      double v = pData->blockRowsHisto[i] * 100.0 / pData->numOfBlocks;
1✔
6578
      len += tsnprintf(varDataVal(st) + len, sizeof(st) - VARSTR_HEADER_SIZE - len, "  %d (%.2f%c)",
1✔
6579
                       pData->blockRowsHisto[i], v, '%');
6580
    }
6581

6582
    varDataSetLen(st, len);
140✔
6583
    code = colDataSetVal(pColInfo, row++, st, false);
140✔
6584
    if (TSDB_CODE_SUCCESS != code) {
140!
6585
      return code;
×
6586
    }
6587
  }
6588

6589
  return TSDB_CODE_SUCCESS;
7✔
6590
}
6591
int32_t blockDBUsageSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
1✔
6592
  if (pResultInfo->initialized) {
1!
6593
    return TSDB_CODE_SUCCESS;
×
6594
  }
6595
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
1!
6596
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6597
  }
6598

6599
  SDBBlockUsageInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1✔
6600
  return TSDB_CODE_SUCCESS;
1✔
6601
}
6602
int32_t blockDBUsageFunction(SqlFunctionCtx* pCtx) {
2✔
6603
  const int32_t BLOCK_DISK_USAGE_RESULT_ROWS = 2;
2✔
6604

6605
  SInputColumnInfoData* pInput = &pCtx->input;
2✔
6606
  SColumnInfoData*      pInputCol = pInput->pData[0];
2✔
6607
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
2✔
6608
  SDBBlockUsageInfo*    pDistInfo = GET_ROWCELL_INTERBUF(pResInfo);
2✔
6609

6610
  SDBBlockUsageInfo p1 = {0};
2✔
6611
  if (tDeserializeBlockDbUsage(varDataVal(pInputCol->pData), varDataLen(pInputCol->pData), &p1) < 0) {
2!
6612
    qError("failed to deserialize block dist info");
×
6613
    return TSDB_CODE_FAILED;
×
6614
  }
6615

6616
  pDistInfo->dataInDiskSize += p1.dataInDiskSize;
2✔
6617
  pDistInfo->walInDiskSize += p1.walInDiskSize;
2✔
6618
  pDistInfo->rawDataSize += p1.rawDataSize;
2✔
6619
  pResInfo->numOfRes = BLOCK_DISK_USAGE_RESULT_ROWS;  // default output rows
2✔
6620
  return TSDB_CODE_SUCCESS;
2✔
6621
}
6622

6623
int32_t tSerializeBlockDbUsage(void* buf, int32_t bufLen, const SDBBlockUsageInfo* pInfo) {
3✔
6624
  SEncoder encoder = {0};
3✔
6625
  int32_t  code = 0;
3✔
6626
  int32_t  lino;
6627
  int32_t  tlen;
6628
  tEncoderInit(&encoder, buf, bufLen);
3✔
6629

6630
  TAOS_CHECK_EXIT(tStartEncode(&encoder));
4!
6631

6632
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->dataInDiskSize));
8!
6633
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->walInDiskSize));
8!
6634
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->rawDataSize));
8!
6635

6636
  tEndEncode(&encoder);
4✔
6637

6638
_exit:
4✔
6639
  if (code) {
4!
6640
    tlen = code;
×
6641
  } else {
6642
    tlen = encoder.pos;
4✔
6643
  }
6644
  tEncoderClear(&encoder);
4✔
6645
  return tlen;
4✔
6646
}
6647
int32_t tDeserializeBlockDbUsage(void* buf, int32_t bufLen, SDBBlockUsageInfo* pInfo) {
2✔
6648
  SDecoder decoder = {0};
2✔
6649
  int32_t  code = 0;
2✔
6650
  int32_t  lino;
6651
  tDecoderInit(&decoder, buf, bufLen);
2✔
6652

6653
  TAOS_CHECK_EXIT(tStartDecode(&decoder));
2!
6654
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->dataInDiskSize));
4!
6655
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->walInDiskSize));
4!
6656
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->rawDataSize));
4!
6657

6658
_exit:
2✔
6659
  tDecoderClear(&decoder);
2✔
6660
  return code;
2✔
6661
}
6662
int32_t blockDBUsageFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1✔
6663
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1✔
6664
  SDBBlockUsageInfo*   pData = GET_ROWCELL_INTERBUF(pResInfo);
1✔
6665

6666
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);
1✔
6667
  if (NULL == pColInfo) {
1!
6668
    return TSDB_CODE_OUT_OF_RANGE;
×
6669
  }
6670
  int32_t len = 0;
1✔
6671
  int32_t row = 0;
1✔
6672
  char    st[256] = {0};
1✔
6673

6674
  uint64_t totalDiskSize = pData->dataInDiskSize;
1✔
6675
  uint64_t rawDataSize = pData->rawDataSize;
1✔
6676
  double   compressRatio = 0;
1✔
6677
  if (rawDataSize != 0) {
1!
6678
    compressRatio = totalDiskSize * 100 / (double)rawDataSize;
1✔
6679
    len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Compress_ratio=[%.2f%]", compressRatio);
1✔
6680
  } else {
6681
    len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Compress_ratio=[NULL]");
×
6682
  }
6683

6684
  varDataSetLen(st, len);
1✔
6685
  int32_t code = colDataSetVal(pColInfo, row++, st, false);
1✔
6686
  if (TSDB_CODE_SUCCESS != code) {
1!
6687
    return code;
×
6688
  }
6689

6690
  len =
1✔
6691
      tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Disk_occupied=[%" PRId64 "k]", pData->dataInDiskSize);
1✔
6692
  varDataSetLen(st, len);
1✔
6693
  code = colDataSetVal(pColInfo, row++, st, false);
1✔
6694
  if (TSDB_CODE_SUCCESS != code) {
1!
6695
    return code;
×
6696
  }
6697
  return code;
1✔
6698
}
6699

6700
bool getDerivativeFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
674✔
6701
  pEnv->calcMemSize = sizeof(SDerivInfo);
674✔
6702
  return true;
674✔
6703
}
6704

6705
int32_t derivativeFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
1,445✔
6706
  if (pResInfo->initialized) {
1,445✔
6707
    return TSDB_CODE_SUCCESS;
672✔
6708
  }
6709
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
773!
6710
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6711
  }
6712

6713
  SDerivInfo* pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
773✔
6714

6715
  pDerivInfo->ignoreNegative = pCtx->param[2].param.i;
773✔
6716
  pDerivInfo->prevTs = -1;
773✔
6717
  pDerivInfo->tsWindow = pCtx->param[1].param.i;
773✔
6718
  pDerivInfo->valueSet = false;
773✔
6719
  return TSDB_CODE_SUCCESS;
773✔
6720
}
6721

6722
int32_t derivativeFunction(SqlFunctionCtx* pCtx) {
771✔
6723
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
771✔
6724
  SDerivInfo*          pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
771✔
6725

6726
  SInputColumnInfoData* pInput = &pCtx->input;
771✔
6727
  SColumnInfoData*      pInputCol = pInput->pData[0];
771✔
6728

6729
  int32_t          numOfElems = 0;
771✔
6730
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
771✔
6731
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
771✔
6732
  int32_t          code = TSDB_CODE_SUCCESS;
771✔
6733

6734
  funcInputUpdate(pCtx);
771✔
6735

6736
  double v = 0;
771✔
6737
  if (pCtx->order == TSDB_ORDER_ASC) {
771✔
6738
    SFuncInputRow row = {0};
743✔
6739
    bool          result = false;
743✔
6740
    while (1) {
71,672✔
6741
      code = funcInputGetNextRow(pCtx, &row, &result);
72,415✔
6742
      if (TSDB_CODE_SUCCESS != code) {
72,415!
6743
        return code;
×
6744
      }
6745
      if (!result) {
72,415✔
6746
        break;
743✔
6747
      }
6748
      if (row.isDataNull) {
71,672✔
6749
        continue;
31,941✔
6750
      }
6751

6752
      char* d = row.pData;
39,731✔
6753
      GET_TYPED_DATA(v, double, pInputCol->info.type, d, typeGetTypeModFromColInfo(&pInputCol->info));
39,731!
6754

6755
      int32_t pos = pCtx->offset + numOfElems;
39,731✔
6756
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
39,731✔
6757
        pDerivInfo->valueSet = true;
404✔
6758
      } else {
6759
        if (row.ts == pDerivInfo->prevTs) {
39,327!
6760
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6761
        }
6762
        double r = ((v - pDerivInfo->prevValue) * pDerivInfo->tsWindow) / (row.ts - pDerivInfo->prevTs);
39,327✔
6763
        if (pDerivInfo->ignoreNegative && r < 0) {
39,327✔
6764
        } else {
6765
          if (isinf(r) || isnan(r)) {
32,124!
6766
            colDataSetNULL(pOutput, pos);
×
6767
          } else {
6768
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
32,124✔
6769
            if (code != TSDB_CODE_SUCCESS) {
32,124!
6770
              return code;
×
6771
            }
6772
          }
6773

6774
          if (pTsOutput != NULL) {
32,124!
6775
            colDataSetInt64(pTsOutput, pos, &row.ts);
×
6776
          }
6777

6778
          // handle selectivity
6779
          if (pCtx->subsidiaries.num > 0) {
32,124✔
6780
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
62✔
6781
            if (code != TSDB_CODE_SUCCESS) {
62!
6782
              return code;
×
6783
            }
6784
          }
6785

6786
          numOfElems++;
32,124✔
6787
        }
6788
      }
6789

6790
      pDerivInfo->prevValue = v;
39,731✔
6791
      pDerivInfo->prevTs = row.ts;
39,731✔
6792
    }
6793
  } else {
6794
    SFuncInputRow row = {0};
28✔
6795
    bool          result = false;
28✔
6796
    while (1) {
702✔
6797
      code = funcInputGetNextRow(pCtx, &row, &result);
730✔
6798
      if (TSDB_CODE_SUCCESS != code) {
730!
6799
        return code;
×
6800
      }
6801
      if (!result) {
730✔
6802
        break;
28✔
6803
      }
6804
      if (row.isDataNull) {
702✔
6805
        continue;
684✔
6806
      }
6807

6808
      char* d = row.pData;
18✔
6809
      GET_TYPED_DATA(v, double, pInputCol->info.type, d, typeGetTypeModFromColInfo(&pInputCol->info));
18!
6810

6811
      int32_t pos = pCtx->offset + numOfElems;
18✔
6812
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
18✔
6813
        pDerivInfo->valueSet = true;
10✔
6814
      } else {
6815
        if (row.ts == pDerivInfo->prevTs) {
8!
6816
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6817
        }
6818
        double r = ((pDerivInfo->prevValue - v) * pDerivInfo->tsWindow) / (pDerivInfo->prevTs - row.ts);
8✔
6819
        if (pDerivInfo->ignoreNegative && r < 0) {
8!
6820
        } else {
6821
          if (isinf(r) || isnan(r)) {
8!
6822
            colDataSetNULL(pOutput, pos);
×
6823
          } else {
6824
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
8✔
6825
            if (code != TSDB_CODE_SUCCESS) {
8!
6826
              return code;
×
6827
            }
6828
          }
6829

6830
          if (pTsOutput != NULL) {
8!
6831
            colDataSetInt64(pTsOutput, pos, &pDerivInfo->prevTs);
×
6832
          }
6833

6834
          // handle selectivity
6835
          if (pCtx->subsidiaries.num > 0) {
8!
6836
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
×
6837
            if (code != TSDB_CODE_SUCCESS) {
×
6838
              return code;
×
6839
            }
6840
          }
6841
          numOfElems++;
8✔
6842
        }
6843
      }
6844

6845
      pDerivInfo->prevValue = v;
18✔
6846
      pDerivInfo->prevTs = row.ts;
18✔
6847
    }
6848
  }
6849

6850
  pResInfo->numOfRes = numOfElems;
771✔
6851

6852
  return TSDB_CODE_SUCCESS;
771✔
6853
}
6854

6855
int32_t getIrateInfoSize(int32_t pkBytes) { return (int32_t)sizeof(SRateInfo) + 2 * pkBytes; }
2,581✔
6856

6857
bool getIrateFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
2,322✔
6858
  int32_t pkBytes = (pFunc->hasPk) ? pFunc->pkBytes : 0;
2,322✔
6859
  pEnv->calcMemSize = getIrateInfoSize(pkBytes);
2,322✔
6860
  return true;
2,330✔
6861
}
6862

6863
int32_t irateFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
26,454✔
6864
  if (pResInfo->initialized) {
26,454!
6865
    return TSDB_CODE_SUCCESS;
×
6866
  }
6867
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
26,454!
6868
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6869
  }
6870

6871
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
26,454✔
6872

6873
  pInfo->firstKey = INT64_MIN;
26,454✔
6874
  pInfo->lastKey = INT64_MIN;
26,454✔
6875
  pInfo->firstValue = (double)INT64_MIN;
26,454✔
6876
  pInfo->lastValue = (double)INT64_MIN;
26,454✔
6877

6878
  pInfo->hasResult = 0;
26,454✔
6879
  return TSDB_CODE_SUCCESS;
26,454✔
6880
}
6881

6882
static void doSaveRateInfo(SRateInfo* pRateInfo, bool isFirst, int64_t ts, char* pk, double v) {
294,986✔
6883
  if (isFirst) {
294,986✔
6884
    pRateInfo->firstValue = v;
140,444✔
6885
    pRateInfo->firstKey = ts;
140,444✔
6886
    if (pRateInfo->firstPk) {
140,444✔
6887
      int32_t pkBytes;
6888
      if (IS_VAR_DATA_TYPE(pRateInfo->pkType)) {
35!
6889
        if (pRateInfo->pkType == TSDB_DATA_TYPE_JSON) {
8!
6890
          pkBytes = getJsonValueLen(pk);
×
6891
        } else {
6892
          pkBytes = varDataTLen(pk);
8✔
6893
        }
6894
      } else {
6895
        pkBytes = pRateInfo->pkBytes;
27✔
6896
      }
6897
      (void)memcpy(pRateInfo->firstPk, pk, pkBytes);
35✔
6898
    }
6899
  } else {
6900
    pRateInfo->lastValue = v;
154,542✔
6901
    pRateInfo->lastKey = ts;
154,542✔
6902
    if (pRateInfo->lastPk) {
154,542✔
6903
      int32_t pkBytes;
6904
      if (IS_VAR_DATA_TYPE(pRateInfo->pkType)) {
52!
6905
        if (pRateInfo->pkType == TSDB_DATA_TYPE_JSON) {
12!
6906
          pkBytes = getJsonValueLen(pk);
×
6907
        } else {
6908
          pkBytes = varDataTLen(pk);
12✔
6909
        }
6910
      } else {
6911
        pkBytes = pRateInfo->pkBytes;
40✔
6912
      }
6913
      (void)memcpy(pRateInfo->lastPk, pk, pkBytes);
52✔
6914
    }
6915
  }
6916
}
294,986✔
6917

6918
static void initializeRateInfo(SqlFunctionCtx* pCtx, SRateInfo* pRateInfo, bool isMerge) {
27,604✔
6919
  if (pCtx->hasPrimaryKey) {
27,604✔
6920
    if (!isMerge) {
19✔
6921
      pRateInfo->pkType = pCtx->input.pPrimaryKey->info.type;
17✔
6922
      pRateInfo->pkBytes = pCtx->input.pPrimaryKey->info.bytes;
17✔
6923
      pRateInfo->firstPk = pRateInfo->pkData;
17✔
6924
      pRateInfo->lastPk = pRateInfo->pkData + pRateInfo->pkBytes;
17✔
6925
    } else {
6926
      pRateInfo->firstPk = pRateInfo->pkData;
2✔
6927
      pRateInfo->lastPk = pRateInfo->pkData + pRateInfo->pkBytes;
2✔
6928
    }
6929
  } else {
6930
    pRateInfo->firstPk = NULL;
27,585✔
6931
    pRateInfo->lastPk = NULL;
27,585✔
6932
  }
6933
}
27,604✔
6934

6935
int32_t irateFunction(SqlFunctionCtx* pCtx) {
27,228✔
6936
  int32_t              code = TSDB_CODE_SUCCESS;
27,228✔
6937
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
27,228✔
6938
  SRateInfo*           pRateInfo = GET_ROWCELL_INTERBUF(pResInfo);
27,228✔
6939

6940
  SInputColumnInfoData* pInput = &pCtx->input;
27,228✔
6941
  SColumnInfoData*      pInputCol = pInput->pData[0];
27,228✔
6942

6943
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
27,228✔
6944

6945
  funcInputUpdate(pCtx);
27,228✔
6946

6947
  initializeRateInfo(pCtx, pRateInfo, false);
27,228✔
6948

6949
  int32_t       numOfElems = 0;
27,228✔
6950
  int32_t       type = pInputCol->info.type;
27,228✔
6951
  SFuncInputRow row = {0};
27,228✔
6952
  bool          result = false;
27,228✔
6953
  while (1) {
284,042✔
6954
    code = funcInputGetNextRow(pCtx, &row, &result);
311,270✔
6955
    if (TSDB_CODE_SUCCESS != code) {
311,306!
6956
      return code;
×
6957
    }
6958
    if (!result) {
311,306✔
6959
      break;
27,228✔
6960
    }
6961
    if (row.isDataNull) {
284,078✔
6962
      continue;
128,934✔
6963
    }
6964

6965
    char*  data = row.pData;
155,144✔
6966
    double v = 0;
155,144✔
6967
    GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
155,144!
6968

6969
    if (INT64_MIN == pRateInfo->lastKey) {
155,178✔
6970
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
14,322✔
6971
      pRateInfo->hasResult = 1;
14,322✔
6972
      continue;
14,322✔
6973
    }
6974

6975
    if (row.ts > pRateInfo->lastKey) {
140,856✔
6976
      if ((INT64_MIN == pRateInfo->firstKey) || pRateInfo->lastKey > pRateInfo->firstKey) {
140,260!
6977
        doSaveRateInfo(pRateInfo, true, pRateInfo->lastKey, pRateInfo->lastPk, pRateInfo->lastValue);
140,262✔
6978
      }
6979
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
140,237✔
6980
      continue;
140,207✔
6981
    } else if (row.ts == pRateInfo->lastKey) {
596!
6982
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6983
    }
6984

6985
    if ((INT64_MIN == pRateInfo->firstKey) || row.ts > pRateInfo->firstKey) {
596!
6986
      doSaveRateInfo(pRateInfo, true, row.ts, row.pPk, v);
4✔
6987
    } else if (row.ts == pRateInfo->firstKey) {
592!
6988
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6989
    }
6990
  }
6991

6992
  numOfElems++;
27,228✔
6993

6994
  SET_VAL(pResInfo, numOfElems, 1);
27,228!
6995
  return TSDB_CODE_SUCCESS;
27,228✔
6996
}
6997

6998
static double doCalcRate(const SRateInfo* pRateInfo, double tickPerSec) {
26,266✔
6999
  if ((INT64_MIN == pRateInfo->lastKey) || (INT64_MIN == pRateInfo->firstKey) ||
26,266✔
7000
      (pRateInfo->firstKey >= pRateInfo->lastKey)) {
1,445!
7001
    return 0.0;
24,821✔
7002
  }
7003

7004
  double diff = 0;
1,445✔
7005
  // If the previous value of the last is greater than the last value, only keep the last point instead of the delta
7006
  // value between two values.
7007
  diff = pRateInfo->lastValue;
1,445✔
7008
  if (diff >= pRateInfo->firstValue) {
1,445✔
7009
    diff -= pRateInfo->firstValue;
660✔
7010
  }
7011

7012
  int64_t duration = pRateInfo->lastKey - pRateInfo->firstKey;
1,445✔
7013
  if (duration == 0) {
1,445!
7014
    return 0;
×
7015
  }
7016

7017
  return (duration > 0) ? ((double)diff) / (duration / tickPerSec) : 0.0;
1,445!
7018
}
7019

7020
static void irateTransferInfoImpl(TSKEY inputKey, SRateInfo* pInput, SRateInfo* pOutput, bool isFirstKey) {
174✔
7021
  if (inputKey > pOutput->lastKey) {
174✔
7022
    doSaveRateInfo(pOutput, true, pOutput->lastKey, pOutput->lastPk, pOutput->lastValue);
80✔
7023
    if (isFirstKey) {
80✔
7024
      doSaveRateInfo(pOutput, false, pInput->firstKey, pInput->firstPk, pInput->firstValue);
36✔
7025
    } else {
7026
      doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
44✔
7027
    }
7028
  } else if ((inputKey < pOutput->lastKey) && (inputKey > pOutput->firstKey)) {
94!
7029
    if (isFirstKey) {
20✔
7030
      doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
10✔
7031
    } else {
7032
      doSaveRateInfo(pOutput, true, pInput->lastKey, pInput->lastPk, pInput->lastValue);
10✔
7033
    }
7034
  } else {
7035
    // inputKey < pOutput->firstKey
7036
  }
7037
}
174✔
7038

7039
static void irateCopyInfo(SRateInfo* pInput, SRateInfo* pOutput) {
93✔
7040
  doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
93✔
7041
  doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
93✔
7042
}
93✔
7043

7044
static int32_t irateTransferInfo(SRateInfo* pInput, SRateInfo* pOutput) {
180✔
7045
  if ((pInput->firstKey != INT64_MIN &&
180✔
7046
       (pInput->firstKey == pOutput->firstKey || pInput->firstKey == pOutput->lastKey)) ||
175!
7047
      (pInput->lastKey != INT64_MIN && (pInput->lastKey == pOutput->firstKey || pInput->lastKey == pOutput->lastKey))) {
180!
7048
    return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
7049
  }
7050

7051
  if (pOutput->hasResult == 0) {
180✔
7052
    irateCopyInfo(pInput, pOutput);
93✔
7053
    pOutput->hasResult = pInput->hasResult;
93✔
7054
    return TSDB_CODE_SUCCESS;
93✔
7055
  }
7056

7057
  if (pInput->firstKey != INT64_MIN) {
87!
7058
    irateTransferInfoImpl(pInput->firstKey, pInput, pOutput, true);
87✔
7059
  }
7060

7061
  if (pInput->lastKey != INT64_MIN) {
87!
7062
    irateTransferInfoImpl(pInput->lastKey, pInput, pOutput, false);
87✔
7063
  }
7064

7065
  pOutput->hasResult = pInput->hasResult;
87✔
7066
  return TSDB_CODE_SUCCESS;
87✔
7067
}
7068

7069
int32_t irateFunctionMerge(SqlFunctionCtx* pCtx) {
188✔
7070
  SInputColumnInfoData* pInput = &pCtx->input;
188✔
7071
  SColumnInfoData*      pCol = pInput->pData[0];
188✔
7072
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
188!
7073
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
7074
  }
7075

7076
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
188✔
7077
  initializeRateInfo(pCtx, pInfo, true);
188✔
7078

7079
  int32_t start = pInput->startRowIndex;
188✔
7080
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
376✔
7081
    char*      data = colDataGetData(pCol, i);
188!
7082
    SRateInfo* pInputInfo = (SRateInfo*)varDataVal(data);
188✔
7083
    initializeRateInfo(pCtx, pInfo, true);
188✔
7084
    if (pInputInfo->hasResult) {
188✔
7085
      int32_t code = irateTransferInfo(pInputInfo, pInfo);
180✔
7086
      if (code != TSDB_CODE_SUCCESS) {
180!
7087
        return code;
×
7088
      }
7089
    }
7090
  }
7091

7092
  if (pInfo->hasResult) {
188✔
7093
    GET_RES_INFO(pCtx)->numOfRes = 1;
180✔
7094
  }
7095

7096
  return TSDB_CODE_SUCCESS;
188✔
7097
}
7098

7099
int32_t iratePartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
188✔
7100
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
188✔
7101
  SRateInfo*           pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
188✔
7102
  int32_t              resultBytes = getIrateInfoSize(pInfo->pkBytes);
188✔
7103
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
188!
7104

7105
  if (NULL == res) {
188!
7106
    return terrno;
×
7107
  }
7108
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
188✔
7109
  varDataSetLen(res, resultBytes);
188✔
7110

7111
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
188✔
7112
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
188✔
7113
  if (NULL == pCol) {
188!
7114
    taosMemoryFree(res);
×
7115
    return TSDB_CODE_OUT_OF_RANGE;
×
7116
  }
7117

7118
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
188✔
7119

7120
  taosMemoryFree(res);
188!
7121
  return code;
188✔
7122
}
7123

7124
int32_t irateFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
26,266✔
7125
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
26,266✔
7126
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
26,266✔
7127
  if (NULL == pCol) {
26,266!
7128
    return TSDB_CODE_OUT_OF_RANGE;
×
7129
  }
7130

7131
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
26,266✔
7132
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
26,266✔
7133

7134
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
26,266✔
7135
  double     result = doCalcRate(pInfo, (double)TSDB_TICK_PER_SECOND(pCtx->param[1].param.i));
26,266!
7136
  int32_t    code = colDataSetVal(pCol, pBlock->info.rows, (const char*)&result, pResInfo->isNullRes);
26,266✔
7137

7138
  return code;
26,266✔
7139
}
7140

7141
int32_t groupConstValueFunction(SqlFunctionCtx* pCtx) {
105,988,199✔
7142
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
105,988,199✔
7143
  SGroupKeyInfo*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
105,988,199✔
7144

7145
  SInputColumnInfoData* pInput = &pCtx->input;
105,988,199✔
7146
  SColumnInfoData*      pInputCol = pInput->pData[0];
105,988,199✔
7147

7148
  int32_t startIndex = pInput->startRowIndex;
105,988,199✔
7149

7150
  // escape rest of data blocks to avoid first entry to be overwritten.
7151
  if (pInfo->hasResult) {
105,988,199✔
7152
    goto _group_value_over;
10,687,963✔
7153
  }
7154

7155
  if (pInputCol->pData == NULL || colDataIsNull_s(pInputCol, startIndex)) {
190,151,220✔
7156
    pInfo->isNull = true;
2,661,201✔
7157
    pInfo->hasResult = true;
2,661,201✔
7158
    goto _group_value_over;
2,661,201✔
7159
  }
7160

7161
  char* data = colDataGetData(pInputCol, startIndex);
92,639,035!
7162
  if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
92,639,035!
7163
    (void)memcpy(pInfo->data, data,
73,029,255✔
7164
                 (pInputCol->info.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(data) : varDataTLen(data));
73,029,255✔
7165
  } else {
7166
    (void)memcpy(pInfo->data, data, pInputCol->info.bytes);
19,609,780✔
7167
  }
7168
  pInfo->hasResult = true;
92,639,035✔
7169

7170
_group_value_over:
105,988,199✔
7171

7172
  SET_VAL(pResInfo, 1, 1);
105,988,199✔
7173
  return TSDB_CODE_SUCCESS;
105,988,199✔
7174
}
7175

7176
int32_t groupKeyFunction(SqlFunctionCtx* pCtx) { return groupConstValueFunction(pCtx); }
106,017,319✔
7177

7178
int32_t groupConstValueFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
94,436,640✔
7179
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
94,436,640✔
7180
  int32_t          code = TSDB_CODE_SUCCESS;
94,436,640✔
7181
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
94,436,640✔
7182
  if (NULL == pCol) {
94,436,268!
7183
    return TSDB_CODE_OUT_OF_RANGE;
×
7184
  }
7185

7186
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
94,436,268✔
7187

7188
  SGroupKeyInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
94,436,268✔
7189

7190
  if (pInfo->hasResult) {
94,436,268!
7191
    int32_t currentRow = pBlock->info.rows;
94,494,514✔
7192
    for (; currentRow < pBlock->info.rows + pResInfo->numOfRes; ++currentRow) {
189,266,315✔
7193
      code = colDataSetVal(pCol, currentRow, pInfo->data, pInfo->isNull ? true : false);
94,541,613✔
7194
      if (TSDB_CODE_SUCCESS != code) {
94,771,801!
7195
        return code;
×
7196
      }
7197
    }
7198
  } else {
7199
    pResInfo->numOfRes = 0;
×
7200
  }
7201

7202
  return code;
94,666,456✔
7203
}
7204

7205
int32_t groupKeyFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { return groupConstValueFinalize(pCtx, pBlock); }
94,416,520✔
7206

7207
int32_t groupKeyCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
7208
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
7209
  SGroupKeyInfo*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
7210

7211
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
7212
  SGroupKeyInfo*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
7213

7214
  // escape rest of data blocks to avoid first entry to be overwritten.
7215
  if (pDBuf->hasResult) {
×
7216
    goto _group_key_over;
×
7217
  }
7218

7219
  if (pSBuf->isNull) {
×
7220
    pDBuf->isNull = true;
×
7221
    pDBuf->hasResult = true;
×
7222
    goto _group_key_over;
×
7223
  }
7224

7225
  if (IS_VAR_DATA_TYPE(pSourceCtx->resDataInfo.type)) {
×
7226
    (void)memcpy(pDBuf->data, pSBuf->data,
×
7227
                 (pSourceCtx->resDataInfo.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(pSBuf->data)
×
7228
                                                                       : varDataTLen(pSBuf->data));
×
7229
  } else {
7230
    (void)memcpy(pDBuf->data, pSBuf->data, pSourceCtx->resDataInfo.bytes);
×
7231
  }
7232

7233
  pDBuf->hasResult = true;
×
7234

7235
_group_key_over:
×
7236

7237
  SET_VAL(pDResInfo, 1, 1);
×
7238
  return TSDB_CODE_SUCCESS;
×
7239
}
7240

7241
int32_t cachedLastRowFunction(SqlFunctionCtx* pCtx) {
2,454✔
7242
  int32_t numOfElems = 0;
2,454✔
7243

7244
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,454✔
7245
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,454✔
7246

7247
  SInputColumnInfoData* pInput = &pCtx->input;
2,454✔
7248
  SColumnInfoData*      pInputCol = pInput->pData[0];
2,454✔
7249

7250
  int32_t bytes = pInputCol->info.bytes;
2,454✔
7251
  pInfo->bytes = bytes;
2,454✔
7252

7253
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
2,454✔
7254
  pInfo->pkType = -1;
2,454✔
7255
  __compar_fn_t pkCompareFn = NULL;
2,454✔
7256
  if (pCtx->hasPrimaryKey) {
2,454✔
7257
    pInfo->pkType = pkCol->info.type;
20✔
7258
    pInfo->pkBytes = pkCol->info.bytes;
20✔
7259
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
20✔
7260
  }
7261

7262
  // TODO it traverse the different way.
7263
  // last_row function does not ignore the null value
7264
  for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
4,919✔
7265
    numOfElems++;
2,465✔
7266

7267
    bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
2,465✔
7268
    char* data = isNull ? NULL : colDataGetData(pInputCol, i);
2,465!
7269

7270
    TSKEY cts = getRowPTs(pInput->pPTS, i);
2,465!
7271
    if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
2,465✔
7272
      int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
2,083✔
7273
      if (code != TSDB_CODE_SUCCESS) {
2,083!
7274
        return code;
×
7275
      }
7276
      pResInfo->numOfRes = 1;
2,083✔
7277
    }
7278
  }
7279

7280
  SET_VAL(pResInfo, numOfElems, 1);
2,454!
7281
  return TSDB_CODE_SUCCESS;
2,454✔
7282
}
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