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

taosdata / TDengine / #4742

18 Sep 2025 04:31AM UTC coverage: 59.004% (+0.2%) from 58.824%
#4742

push

travis-ci

web-flow
fix: clear parse csv error syntax error msg (#33000)

136010 of 293099 branches covered (46.4%)

Branch coverage included in aggregate %.

0 of 2 new or added lines in 1 file covered. (0.0%)

361 existing lines in 69 files now uncovered.

204889 of 284660 relevant lines covered (71.98%)

18324549.91 hits per line

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

68.78
/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; }
1,451,331,357✔
33
bool ignoreNull(int8_t ignoreOption) { return (ignoreOption & 0x2) == 0x2; }
1,724,968✔
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, 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, 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, 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, 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, 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) {
24,360,436✔
210
  SFuncInputRowIter* pIter = &pCtx->rowIter;
24,360,436✔
211

212
  if (!pCtx->bInputFinished) {
24,360,436!
213
    pIter->pInput = &pCtx->input;
24,360,547✔
214
    pIter->tsList = (TSKEY*)pIter->pInput->pPTS->pData;
24,360,547✔
215
    pIter->pDataCol = pIter->pInput->pData[0];
24,360,547✔
216
    pIter->pPkCol = pIter->pInput->pPrimaryKey;
24,360,547✔
217
    pIter->rowIndex = pIter->pInput->startRowIndex;
24,360,547✔
218
    pIter->inputEndIndex = pIter->rowIndex + pIter->pInput->numOfRows - 1;
24,360,547✔
219
    pIter->pSrcBlock = pCtx->pSrcBlock;
24,360,547✔
220
    if (!pIter->hasGroupId || pIter->groupId != pIter->pSrcBlock->info.id.groupId) {
24,360,547✔
221
      pIter->hasGroupId = true;
213,158✔
222
      pIter->groupId = pIter->pSrcBlock->info.id.groupId;
213,158✔
223
      pIter->hasPrev = false;
213,158✔
224
    }
225
  } else {
226
    pIter->finalRow = true;
×
227
  }
228
}
24,360,436✔
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, 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, 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, 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, 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) {
6,382✔
345
  int32_t idx = rowIndex + 1;
6,382✔
346
  while (idx <= pIter->inputEndIndex && pIter->tsList[idx] == pIter->tsList[rowIndex]) {
90,092!
347
    ++idx;
83,710✔
348
  }
349
  pIter->rowIndex = idx;
6,382✔
350
}
6,382✔
351

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

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

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

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

398
bool funcInputGetNextRowNoPk(SFuncInputRowIter* pIter, SFuncInputRow* pRow) {
1,541,397,729✔
399
  if (pIter->rowIndex <= pIter->inputEndIndex) {
1,541,397,729✔
400
    setInputRowInfo(pRow, pIter, pIter->rowIndex, false);
1,517,094,681✔
401
    ++pIter->rowIndex;
1,517,193,651✔
402
    return true;
1,517,193,651✔
403
  } else {
404
    return false;
24,303,048✔
405
  }
406
}
407

408
int32_t funcInputGetNextRow(SqlFunctionCtx* pCtx, SFuncInputRow* pRow, bool* res) {
1,541,351,577✔
409
  SFuncInputRowIter* pIter = &pCtx->rowIter;
1,541,351,577✔
410
  if (pCtx->hasPrimaryKey) {
1,541,351,577✔
411
    if (pCtx->order == TSDB_ORDER_ASC) {
8,322!
412
      *res = funcInputGetNextRowAscPk(pIter, pRow);
8,322✔
413
      return TSDB_CODE_SUCCESS;
8,322✔
414
    } else {
415
      return funcInputGetNextRowDescPk(pIter, pRow, res);
×
416
    }
417
  } else {
418
    *res = funcInputGetNextRowNoPk(pIter, pRow);
1,541,343,255✔
419
    return TSDB_CODE_SUCCESS;
1,541,500,903✔
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) {
41,777,870✔
427
  if (pCtx->subsidiaries.num <= 0) {
41,777,870!
428
    return TSDB_CODE_SUCCESS;
×
429
  }
430

431
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
83,556,585✔
432
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
41,779,708✔
433

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

438
    SColumnInfoData* pSrcCol = taosArrayGet(pSrcBlock->pDataBlock, srcSlotId);
41,779,708✔
439
    if (NULL == pSrcCol) {
41,778,168!
440
      return TSDB_CODE_OUT_OF_RANGE;
×
441
    }
442

443
    char* pData = colDataGetData(pSrcCol, rowIndex);
41,778,168!
444

445
    // append to dest col
446
    int32_t dstSlotId = pc->pExpr->base.resSchema.slotId;
41,778,168✔
447

448
    SColumnInfoData* pDstCol = taosArrayGet(pCtx->pDstBlock->pDataBlock, dstSlotId);
41,778,168✔
449
    if (NULL == pDstCol) {
41,777,610!
450
      return TSDB_CODE_OUT_OF_RANGE;
×
451
    }
452
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
83,555,220✔
453
      colDataSetNULL(pDstCol, pos);
20!
454
    } else {
455
      int32_t code = colDataSetVal(pDstCol, pos, pData, false);
41,777,590✔
456
      if (TSDB_CODE_SUCCESS != code) {
41,778,695!
457
        return code;
×
458
      }
459
    }
460
  }
461
  return TSDB_CODE_SUCCESS;
41,776,877✔
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) {
576,251,301✔
470
  if (pResultInfo->initialized) {
576,251,301✔
471
    return TSDB_CODE_SUCCESS;  // already initialized
160,191✔
472
  }
473

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

478
  initResultRowEntry(pResultInfo, pCtx->resDataInfo.interBufSize);
576,091,110✔
479
  return TSDB_CODE_SUCCESS;
576,091,110✔
480
}
481

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

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

495
  return code;
119,270,519✔
496
}
497

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

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

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

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

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

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

525
  return code;
194✔
526
}
527

528
EFuncDataRequired countDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
110,094✔
529
  SNode* pParam = nodesListGetNode(pFunc->pParameterList, 0);
110,094✔
530
  if (QUERY_NODE_COLUMN == nodeType(pParam) && PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)pParam)->colId) {
110,120!
531
    return FUNC_DATA_REQUIRED_NOT_LOAD;
109,981✔
532
  }
533
  return FUNC_DATA_REQUIRED_SMA_LOAD;
139✔
534
}
535

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

541
static int64_t getNumOfElems(SqlFunctionCtx* pCtx) {
61,088,662✔
542
  int64_t numOfElem = 0;
61,088,662✔
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;
61,088,662✔
550
  SColumnInfoData*      pInputCol = pInput->pData[0];
61,088,662✔
551
  if (1 == pInput->numOfRows && pInput->blankFill) {
61,088,662✔
552
    return 0;
458,763✔
553
  }
554
  if (pInput->colDataSMAIsSet && pInput->totalRows == pInput->numOfRows) {
60,629,899!
555
    numOfElem = pInput->numOfRows - pInput->pColumnDataAgg[0]->numOfNull;
4,290✔
556
  } else {
557
    if (pInputCol->hasNull) {
60,625,609✔
558
      for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
370,313,288✔
559
        if (colDataIsNull(pInputCol, pInput->totalRows, i, NULL)) {
699,153,398!
560
          continue;
7,048,572✔
561
        }
562
        numOfElem += 1;
342,528,127✔
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;
39,889,020✔
568
    }
569
  }
570
  return numOfElem;
60,629,899✔
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) {
61,221,369✔
578
  int64_t numOfElem = 0;
61,221,369✔
579

580
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
61,221,369✔
581
  SInputColumnInfoData* pInput = &pCtx->input;
61,221,369✔
582

583
  int32_t type = pInput->pData[0]->info.type;
61,221,369✔
584

585
  char*   buf = GET_ROWCELL_INTERBUF(pResInfo);
61,221,369✔
586
  int64_t val = *((int64_t*)buf);
61,221,369✔
587
  if (IS_NULL_TYPE(type)) {
61,221,369✔
588
    // select count(NULL) returns 0
589
    numOfElem = 1;
196,329✔
590
    val += 0;
196,329✔
591
  } else {
592
    numOfElem = getNumOfElems(pCtx);
61,025,040✔
593
    val += numOfElem;
61,092,661✔
594
  }
595
  taosSetInt64Aligned((int64_t*)buf, val);
596

597
  if (tsCountAlwaysReturnValue) {
61,288,990✔
598
    pResInfo->numOfRes = 1;
61,262,249✔
599
  } else {
600
    SET_VAL(pResInfo, val, 1);
26,741✔
601
  }
602

603
  return TSDB_CODE_SUCCESS;
61,288,990✔
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) {
×
620
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
621
  char*                pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
622

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

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

631
int32_t sumFunction(SqlFunctionCtx* pCtx) {
37,069,410✔
632
  int32_t numOfElem = 0;
37,069,410✔
633

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

640
  void* pSumRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
37,069,410✔
641
  SUM_RES_SET_TYPE(pSumRes, pCtx->inputType, type);
37,069,410!
642

643
  if (IS_NULL_TYPE(type)) {
37,069,410✔
644
    numOfElem = 0;
380✔
645
    goto _sum_over;
380✔
646
  }
647

648
  if (pInput->colDataSMAIsSet) {
37,069,030✔
649
    numOfElem = pInput->numOfRows - pAgg->numOfNull;
4,733✔
650

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

669
    int32_t start = pInput->startRowIndex;
37,064,297✔
670
    int32_t numOfRows = pInput->numOfRows;
37,064,297✔
671

672
    if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
37,064,297!
673
      if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
35,806,514!
674
        LIST_ADD_N(SUM_RES_GET_ISUM(pSumRes), pCol, start, numOfRows, int8_t, numOfElem);
3,448,641!
675
      } else if (type == TSDB_DATA_TYPE_SMALLINT) {
34,917,295✔
676
        LIST_ADD_N(SUM_RES_GET_ISUM(pSumRes), pCol, start, numOfRows, int16_t, numOfElem);
349,069!
677
      } else if (type == TSDB_DATA_TYPE_INT) {
34,875,378✔
678
        LIST_ADD_N(SUM_RES_GET_ISUM(pSumRes), pCol, start, numOfRows, int32_t, numOfElem);
310,917,394✔
679
      } else if (type == TSDB_DATA_TYPE_BIGINT) {
6,533,960✔
680
        LIST_ADD_N(SUM_RES_GET_ISUM(pSumRes), pCol, start, numOfRows, int64_t, numOfElem);
21,001,793!
681
      }
682
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
1,257,783!
683
      if (type == TSDB_DATA_TYPE_UTINYINT) {
756✔
684
        LIST_ADD_N(SUM_RES_GET_USUM(pSumRes), pCol, start, numOfRows, uint8_t, numOfElem);
140,043!
685
      } else if (type == TSDB_DATA_TYPE_USMALLINT) {
713✔
686
        LIST_ADD_N(SUM_RES_GET_USUM(pSumRes), pCol, start, numOfRows, uint16_t, numOfElem);
140,051!
687
      } else if (type == TSDB_DATA_TYPE_UINT) {
669✔
688
        LIST_ADD_N(SUM_RES_GET_USUM(pSumRes), pCol, start, numOfRows, uint32_t, numOfElem);
142,251!
689
      } else if (type == TSDB_DATA_TYPE_UBIGINT) {
194!
690
        LIST_ADD_N(SUM_RES_GET_USUM(pSumRes), pCol, start, numOfRows, uint64_t, numOfElem);
142,062!
691
      }
692
    } else if (type == TSDB_DATA_TYPE_DOUBLE) {
1,257,027✔
693
      LIST_ADD_N(SUM_RES_GET_DSUM(pSumRes), pCol, start, numOfRows, double, numOfElem);
4,418,635✔
694
    } else if (type == TSDB_DATA_TYPE_FLOAT) {
533,739✔
695
      LIST_ADD_N(SUM_RES_GET_DSUM(pSumRes), pCol, start, numOfRows, float, numOfElem);
2,253,573!
696
    } else if (IS_DECIMAL_TYPE(type)) {
4!
697
      SUM_RES_SET_TYPE(pSumRes, pCtx->inputType, TSDB_DATA_TYPE_DECIMAL);
×
698
      int32_t overflow = false;
×
699
      if (TSDB_DATA_TYPE_DECIMAL64 == type) {
×
700
        LIST_ADD_DECIMAL_N(&SUM_RES_GET_DECIMAL_SUM(pSumRes), pCol, start, numOfRows, Decimal64, numOfElem);
×
701
      } else if (TSDB_DATA_TYPE_DECIMAL == type) {
×
702
        LIST_ADD_DECIMAL_N(&SUM_RES_GET_DECIMAL_SUM(pSumRes), pCol, start, numOfRows, Decimal128, numOfElem);
×
703
      }
704
      if (overflow) return TSDB_CODE_DECIMAL_OVERFLOW;
×
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)))) {
37,069,030!
710
    numOfElem = 0;
×
711
  }
712

713
_sum_over:
37,386,722✔
714
  if (numOfElem == 0) {
37,069,410✔
715
    if (tsCountAlwaysReturnValue && pCtx->pExpr->pExpr->_function.pFunctNode->hasOriginalFunc &&
2,135,180!
716
        fmIsCountLikeFunc(pCtx->pExpr->pExpr->_function.pFunctNode->originalFuncId)) {
729,360✔
717
      numOfElem = 1;
×
718
    }
719
  }
720
  // data in the check operation are all null, not output
721
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
37,069,410✔
722
  return TSDB_CODE_SUCCESS;
37,069,410✔
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) {
×
786
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
787
  void*                pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
788
  int16_t              type = SUM_RES_GET_TYPE(pDBuf, pDestCtx->inputType);
×
789

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

794
  if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
×
795
    SUM_RES_INC_ISUM(pDBuf, SUM_RES_GET_ISUM(pSBuf));
×
796
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
797
    SUM_RES_INC_USUM(pDBuf, SUM_RES_GET_USUM(pSBuf));
×
798
  } else if (IS_DECIMAL_TYPE(type)) {
×
799
    bool overflow = false;
×
800
    SUM_RES_INC_DECIMAL_SUM(pDBuf, &SUM_RES_GET_DECIMAL_SUM(pSBuf), type);
×
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);
×
805
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
806
  return TSDB_CODE_SUCCESS;
×
807
}
808

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

814
static bool funcNotSupportStringSma(SFunctionNode* pFunc) {
525✔
815
  SNode* pParam;
816
  switch (pFunc->funcType) {
525!
817
    case FUNCTION_TYPE_MAX:
525✔
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);
525✔
829
      if (pParam && nodesIsExprNode(pParam) && (IS_VAR_DATA_TYPE(((SExprNode*)pParam)->resType.type))) {
525!
830
        return true;
40✔
831
      }
832
      break;
485✔
833
    default:
×
834
      break;
×
835
  }
836
  return false;
485✔
837
}
838

839
EFuncDataRequired statisDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
525✔
840
  if (funcNotSupportStringSma(pFunc)) {
525✔
841
    return FUNC_DATA_REQUIRED_DATA_LOAD;
40✔
842
  }
843
  return FUNC_DATA_REQUIRED_SMA_LOAD;
485✔
844
}
845

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

854
  SMinmaxResInfo* buf = GET_ROWCELL_INTERBUF(pResultInfo);
18,390,192✔
855
  buf->assign = false;
18,390,192✔
856
  buf->tuplePos.pageId = -1;
18,390,192✔
857

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

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

870
int32_t minFunction(SqlFunctionCtx* pCtx) {
15,652,851✔
871
  int32_t numOfElems = 0;
15,652,851✔
872
  int32_t code = doMinMaxHelper(pCtx, 1, &numOfElems);
15,652,851✔
873
  if (code != TSDB_CODE_SUCCESS) {
15,677,021!
874
    return code;
×
875
  }
876
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
15,677,021✔
877
  return TSDB_CODE_SUCCESS;
15,677,021✔
878
}
879

880
int32_t maxFunction(SqlFunctionCtx* pCtx) {
7,201,984✔
881
  int32_t numOfElems = 0;
7,201,984✔
882
  int32_t code = doMinMaxHelper(pCtx, 0, &numOfElems);
7,201,984✔
883
  if (code != TSDB_CODE_SUCCESS) {
7,224,370!
884
    return code;
×
885
  }
886
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
7,224,370✔
887
  return TSDB_CODE_SUCCESS;
7,224,370✔
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) {
18,320,631✔
895
  int32_t code = TSDB_CODE_SUCCESS;
18,320,631✔
896

897
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
18,320,631✔
898
  SMinmaxResInfo*      pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
18,320,631✔
899

900
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
18,320,631✔
901
  int32_t currentRow = pBlock->info.rows;
18,320,631✔
902

903
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
18,320,631✔
904
  if (NULL == pCol) {
18,317,872!
905
    return TSDB_CODE_OUT_OF_RANGE;
×
906
  }
907
  pEntryInfo->isNullRes = (pEntryInfo->numOfRes == 0) ? 1 : 0;
18,317,872✔
908

909
  // NOTE: do nothing change it, for performance issue
910
  if (!pEntryInfo->isNullRes) {
18,317,872✔
911
    switch (pCol->info.type) {
16,901,482!
912
      case TSDB_DATA_TYPE_UBIGINT:
521,885✔
913
      case TSDB_DATA_TYPE_BIGINT:
914
        ((int64_t*)pCol->pData)[currentRow] = pRes->v;
521,885✔
915
        break;
521,885✔
916
      case TSDB_DATA_TYPE_UINT:
3,273,402✔
917
      case TSDB_DATA_TYPE_INT:
918
        colDataSetInt32(pCol, currentRow, (int32_t*)&pRes->v);
3,273,402✔
919
        break;
3,273,402✔
920
      case TSDB_DATA_TYPE_USMALLINT:
24,528✔
921
      case TSDB_DATA_TYPE_SMALLINT:
922
        colDataSetInt16(pCol, currentRow, (int16_t*)&pRes->v);
24,528✔
923
        break;
24,528✔
924
      case TSDB_DATA_TYPE_BOOL:
296,233✔
925
      case TSDB_DATA_TYPE_UTINYINT:
926
      case TSDB_DATA_TYPE_TINYINT:
927
        colDataSetInt8(pCol, currentRow, (int8_t*)&pRes->v);
296,233✔
928
        break;
296,233✔
929
      case TSDB_DATA_TYPE_DOUBLE:
2,749,423✔
930
        colDataSetDouble(pCol, currentRow, (double*)&pRes->v);
2,749,423✔
931
        break;
2,749,423✔
932
      case TSDB_DATA_TYPE_FLOAT: {
7,053,898✔
933
        float v = GET_FLOAT_VAL(&pRes->v);
7,053,898✔
934
        colDataSetFloat(pCol, currentRow, &v);
7,053,898✔
935
        break;
7,053,898✔
936
      }
937
      case TSDB_DATA_TYPE_VARBINARY:
2,988,071✔
938
      case TSDB_DATA_TYPE_VARCHAR:
939
      case TSDB_DATA_TYPE_NCHAR: {
940
        code = colDataSetVal(pCol, currentRow, pRes->str, false);
2,988,071✔
941
        if (TSDB_CODE_SUCCESS != code) {
2,988,071!
942
          return code;
×
943
        }
944
        break;
2,988,071✔
945
      }
946
      case TSDB_DATA_TYPE_DECIMAL64:
×
947
        code = colDataSetVal(pCol, currentRow, (const char*)&pRes->v, false);
×
948
        break;
×
949
      case TSDB_DATA_TYPE_DECIMAL:
×
950
        code = colDataSetVal(pCol, currentRow, (void*)pRes->dec, false);
×
951
        break;
×
952
    }
953
  } else {
954
    colDataSetNULL(pCol, currentRow);
1,416,390!
955
  }
956

957
  if (IS_VAR_DATA_TYPE(pCol->info.type)) taosMemoryFreeClear(pRes->str);
18,317,872!
958
  if (pCtx->subsidiaries.num > 0) {
18,317,872✔
959
    if (pEntryInfo->numOfRes > 0) {
11,997,564✔
960
      code = setSelectivityValue(pCtx, pBlock, &pRes->tuplePos, currentRow);
11,995,970✔
961
    } else {
962
      code = setNullSelectivityValue(pCtx, pBlock, currentRow);
1,594✔
963
    }
964
  }
965

966
  return code;
18,316,240✔
967
}
968

969
int32_t setNullSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t rowIndex) {
12,097✔
970
  if (pCtx->subsidiaries.num <= 0) {
12,097✔
971
    return TSDB_CODE_SUCCESS;
10,396✔
972
  }
973

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

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

985
  return TSDB_CODE_SUCCESS;
1,701✔
986
}
987

988
int32_t setSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, const STuplePos* pTuplePos, int32_t rowIndex) {
235,168,942✔
989
  if (pCtx->subsidiaries.num <= 0) {
235,168,942✔
990
    return TSDB_CODE_SUCCESS;
104,066,385✔
991
  }
992

993
  if ((pCtx->saveHandle.pBuf != NULL && pTuplePos->pageId != -1) ||
131,102,557!
994
      (pCtx->saveHandle.pState && pTuplePos->streamTupleKey.ts > 0)) {
×
995
    int32_t numOfCols = pCtx->subsidiaries.num;
131,126,135✔
996
    char*   p = NULL;
131,126,135✔
997
    int32_t code = loadTupleData(pCtx, pTuplePos, &p);
131,126,135✔
998
    if (p == NULL || TSDB_CODE_SUCCESS != code) {
134,197,545!
UNCOV
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;
134,200,763✔
1005
    char* pStart = (char*)(nullList + numOfCols * sizeof(bool));
134,200,763✔
1006

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

1012
      SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId);
134,199,379✔
1013
      if (NULL == pDstCol) {
133,715,136!
1014
        return terrno;
×
1015
      }
1016
      if (nullList[j]) {
133,719,374✔
1017
        colDataSetNULL(pDstCol, rowIndex);
221✔
1018
      } else {
1019
        code = colDataSetValOrCover(pDstCol, rowIndex, pStart, false);
133,719,153✔
1020
        if (TSDB_CODE_SUCCESS != code) {
133,371,383!
1021
          return code;
×
1022
        }
1023
      }
1024
      pStart += pDstCol->info.bytes;
133,371,604✔
1025
    }
1026
  }
1027

1028
  return TSDB_CODE_SUCCESS;
133,349,410✔
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) {
54,115,439✔
1034
  if (pCtx->subsidiaries.num <= 0) {
54,115,439!
1035
    return TSDB_CODE_SUCCESS;
×
1036
  }
1037

1038
  int32_t code = TSDB_CODE_SUCCESS;
54,115,439✔
1039
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
108,191,678✔
1040
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
54,117,904✔
1041

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

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

1051
    char* pData = colDataGetData(pSrcCol, rowIndex);
54,049,890!
1052

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

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

1061
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
108,079,740✔
1062
      colDataSetNULL(pDstCol, pos);
480✔
1063
    } else {
1064
      code = colDataSetVal(pDstCol, pos, pData, false);
54,039,390✔
1065
      if (TSDB_CODE_SUCCESS != code) {
54,075,759!
1066
        return code;
×
1067
      }
1068
    }
1069
  }
1070
  return code;
54,073,774✔
1071
}
1072

1073
void replaceTupleData(STuplePos* pDestPos, STuplePos* pSourcePos) { *pDestPos = *pSourcePos; }
×
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) {
×
1077
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
1078
  SMinmaxResInfo*      pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
1079

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

1084
  switch (type) {
×
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:
×
1094
    case TSDB_DATA_TYPE_INT:
1095
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(int32_t) || !pDBuf->assign)) {
×
1096
        pDBuf->v = pSBuf->v;
×
1097
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1098
        pDBuf->assign = true;
×
1099
      }
1100
      break;
×
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:
×
1119
    case TSDB_DATA_TYPE_FLOAT: {
1120
      if (pSBuf->assign && (COMPARE_MINMAX_DATA(double) || !pDBuf->assign)) {
×
1121
        pDBuf->v = pSBuf->v;
×
1122
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1123
        pDBuf->assign = true;
×
1124
      }
1125
      break;
×
1126
    }
1127
    case TSDB_DATA_TYPE_DECIMAL64: {
×
1128
      const SDecimalOps* pOps = getDecimalOps(type);
×
1129
      if (pSBuf->assign &&
×
1130
          ((pOps->lt(&pDBuf->v, &pSBuf->v, DECIMAL_WORD_NUM(Decimal64)) ^ isMinFunc) || !pDBuf->assign)) {
×
1131
        pDBuf->v = pSBuf->v;
×
1132
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1133
        pDBuf->assign = true;
×
1134
      }
1135
    } break;
×
1136
    case TSDB_DATA_TYPE_DECIMAL: {
×
1137
      const SDecimalOps* pOps = getDecimalOps(type);
×
1138
      if (pSBuf->assign && (pOps->lt(pDBuf->dec, pSBuf->dec, DECIMAL_WORD_NUM(Decimal)) ^ isMinFunc) ||
×
1139
          !pDBuf->assign) {
×
1140
        memcpy(pDBuf->dec, pSBuf->dec, DECIMAL128_BYTES);
×
1141
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1142
        pDBuf->assign = true;
×
1143
      }
1144
    } break;
×
1145
    default:
×
1146
      if (pSBuf->assign && (strcmp(pDBuf->str, pSBuf->str) || !pDBuf->assign)) {
×
1147
        memcpy(pDBuf->str, pSBuf->str, varDataLen(pSBuf->str));
×
1148
        replaceTupleData(&pDBuf->tuplePos, &pSBuf->tuplePos);
×
1149
        pDBuf->assign = true;
×
1150
      }
1151
      break;
×
1152
  }
1153
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
1154
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
1155
  return TSDB_CODE_SUCCESS;
×
1156
}
1157

1158
int32_t minCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
1159
  return minMaxCombine(pDestCtx, pSourceCtx, 1);
×
1160
}
1161
int32_t maxCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
1162
  return minMaxCombine(pDestCtx, pSourceCtx, 0);
×
1163
}
1164

1165
int32_t getStdInfoSize() { return (int32_t)sizeof(SStdRes); }
1,108,310✔
1166

1167
bool getStdFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
120,581✔
1168
  pEnv->calcMemSize = sizeof(SStdRes);
120,581✔
1169
  return true;
120,581✔
1170
}
1171

1172
int32_t stdFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
6,284,405✔
1173
  if (pResultInfo->initialized) {
6,284,405!
1174
    return TSDB_CODE_SUCCESS;
×
1175
  }
1176
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
6,284,405!
1177
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1178
  }
1179

1180
  SStdRes* pRes = GET_ROWCELL_INTERBUF(pResultInfo);
6,284,439✔
1181
  (void)memset(pRes, 0, sizeof(SStdRes));
6,284,439✔
1182
  return TSDB_CODE_SUCCESS;
6,284,439✔
1183
}
1184

1185
int32_t stdFunction(SqlFunctionCtx* pCtx) {
5,230,661✔
1186
  int32_t numOfElem = 0;
5,230,661✔
1187

1188
  // Only the pre-computing information loaded and actual data does not loaded
1189
  SInputColumnInfoData* pInput = &pCtx->input;
5,230,661✔
1190
  int32_t               type = pInput->pData[0]->info.type;
5,230,661✔
1191

1192
  SStdRes* pStdRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
5,230,661✔
1193
  pStdRes->type = type;
5,230,661✔
1194

1195
  // computing based on the true data block
1196
  SColumnInfoData* pCol = pInput->pData[0];
5,230,661✔
1197

1198
  int32_t start = pInput->startRowIndex;
5,230,661✔
1199
  int32_t numOfRows = pInput->numOfRows;
5,230,661✔
1200

1201
  if (IS_NULL_TYPE(type)) {
5,230,661✔
1202
    numOfElem = 0;
222✔
1203
    goto _stddev_over;
222✔
1204
  }
1205

1206
  switch (type) {
5,230,439!
1207
    case TSDB_DATA_TYPE_TINYINT: {
16,373✔
1208
      int8_t* plist = (int8_t*)pCol->pData;
16,373✔
1209
      for (int32_t i = start; i < numOfRows + start; ++i) {
847,384✔
1210
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
831,011!
1211
          continue;
39,576✔
1212
        }
1213

1214
        numOfElem += 1;
791,435✔
1215
        pStdRes->count += 1;
791,435✔
1216
        pStdRes->isum += plist[i];
791,435✔
1217
        pStdRes->quadraticISum += plist[i] * plist[i];
791,435✔
1218
      }
1219

1220
      break;
16,373✔
1221
    }
1222

1223
    case TSDB_DATA_TYPE_SMALLINT: {
2,621,347✔
1224
      int16_t* plist = (int16_t*)pCol->pData;
2,621,347✔
1225
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
8,436,823✔
1226
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
5,815,476!
1227
          continue;
21,094✔
1228
        }
1229

1230
        numOfElem += 1;
5,794,382✔
1231
        pStdRes->count += 1;
5,794,382✔
1232
        pStdRes->isum += plist[i];
5,794,382✔
1233
        pStdRes->quadraticISum += plist[i] * plist[i];
5,794,382✔
1234
      }
1235
      break;
2,621,347✔
1236
    }
1237

1238
    case TSDB_DATA_TYPE_INT: {
29,525✔
1239
      int32_t* plist = (int32_t*)pCol->pData;
29,525✔
1240
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
4,129,661✔
1241
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
4,100,136!
1242
          continue;
174,533✔
1243
        }
1244

1245
        numOfElem += 1;
3,925,603✔
1246
        pStdRes->count += 1;
3,925,603✔
1247
        pStdRes->isum += plist[i];
3,925,603✔
1248
        pStdRes->quadraticISum += plist[i] * plist[i];
3,925,603✔
1249
      }
1250

1251
      break;
29,525✔
1252
    }
1253

1254
    case TSDB_DATA_TYPE_BIGINT: {
2,486,400✔
1255
      int64_t* plist = (int64_t*)pCol->pData;
2,486,400✔
1256
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
8,473,754✔
1257
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
5,987,354✔
1258
          continue;
155,540✔
1259
        }
1260

1261
        numOfElem += 1;
5,831,814✔
1262
        pStdRes->count += 1;
5,831,814✔
1263
        pStdRes->isum += plist[i];
5,831,814✔
1264
        pStdRes->quadraticISum += plist[i] * plist[i];
5,831,814✔
1265
      }
1266
      break;
2,486,400✔
1267
    }
1268

1269
    case TSDB_DATA_TYPE_UTINYINT: {
25✔
1270
      uint8_t* plist = (uint8_t*)pCol->pData;
25✔
1271
      for (int32_t i = start; i < numOfRows + start; ++i) {
80,032✔
1272
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
80,007!
1273
          continue;
4✔
1274
        }
1275

1276
        numOfElem += 1;
80,003✔
1277
        pStdRes->count += 1;
80,003✔
1278
        pStdRes->usum += plist[i];
80,003✔
1279
        pStdRes->quadraticUSum += plist[i] * plist[i];
80,003✔
1280
      }
1281

1282
      break;
25✔
1283
    }
1284

1285
    case TSDB_DATA_TYPE_USMALLINT: {
26✔
1286
      uint16_t* plist = (uint16_t*)pCol->pData;
26✔
1287
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
80,278✔
1288
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
80,252!
1289
          continue;
×
1290
        }
1291

1292
        numOfElem += 1;
80,252✔
1293
        pStdRes->count += 1;
80,252✔
1294
        pStdRes->usum += plist[i];
80,252✔
1295
        pStdRes->quadraticUSum += plist[i] * plist[i];
80,252✔
1296
      }
1297
      break;
26✔
1298
    }
1299

1300
    case TSDB_DATA_TYPE_UINT: {
25✔
1301
      uint32_t* plist = (uint32_t*)pCol->pData;
25✔
1302
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
80,030✔
1303
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
80,005!
1304
          continue;
×
1305
        }
1306

1307
        numOfElem += 1;
80,005✔
1308
        pStdRes->count += 1;
80,005✔
1309
        pStdRes->usum += plist[i];
80,005✔
1310
        pStdRes->quadraticUSum += plist[i] * plist[i];
80,005✔
1311
      }
1312

1313
      break;
25✔
1314
    }
1315

1316
    case TSDB_DATA_TYPE_UBIGINT: {
24✔
1317
      uint64_t* plist = (uint64_t*)pCol->pData;
24✔
1318
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
80,024✔
1319
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
80,000!
1320
          continue;
×
1321
        }
1322

1323
        numOfElem += 1;
80,000✔
1324
        pStdRes->count += 1;
80,000✔
1325
        pStdRes->usum += plist[i];
80,000✔
1326
        pStdRes->quadraticUSum += plist[i] * plist[i];
80,000✔
1327
      }
1328
      break;
24✔
1329
    }
1330

1331
    case TSDB_DATA_TYPE_FLOAT: {
31,479✔
1332
      float* plist = (float*)pCol->pData;
31,479✔
1333
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
3,698,906✔
1334
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
3,667,427!
1335
          continue;
88,416✔
1336
        }
1337

1338
        numOfElem += 1;
3,579,011✔
1339
        pStdRes->count += 1;
3,579,011✔
1340
        pStdRes->dsum += plist[i];
3,579,011✔
1341
        pStdRes->quadraticDSum += plist[i] * plist[i];
3,579,011✔
1342
      }
1343
      break;
31,479✔
1344
    }
1345

1346
    case TSDB_DATA_TYPE_DOUBLE: {
45,796✔
1347
      double* plist = (double*)pCol->pData;
45,796✔
1348
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
2,899,949✔
1349
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
2,854,153!
1350
          continue;
928,678✔
1351
        }
1352

1353
        numOfElem += 1;
1,925,475✔
1354
        pStdRes->count += 1;
1,925,475✔
1355
        pStdRes->dsum += plist[i];
1,925,475✔
1356
        pStdRes->quadraticDSum += plist[i] * plist[i];
1,925,475✔
1357
      }
1358
      break;
45,796✔
1359
    }
1360

UNCOV
1361
    default:
×
UNCOV
1362
      break;
×
1363
  }
1364

1365
_stddev_over:
5,230,661✔
1366
  // data in the check operation are all null, not output
1367
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
5,230,661✔
1368
  return TSDB_CODE_SUCCESS;
5,230,661✔
1369
}
1370

1371
static void stdTransferInfo(SStdRes* pInput, SStdRes* pOutput) {
1,108,115✔
1372
  if (IS_NULL_TYPE(pInput->type)) {
1,108,115✔
1373
    return;
64✔
1374
  }
1375
  pOutput->type = pInput->type;
1,108,051✔
1376
  if (IS_SIGNED_NUMERIC_TYPE(pOutput->type)) {
1,108,051!
1377
    pOutput->quadraticISum += pInput->quadraticISum;
1,093,946✔
1378
    pOutput->isum += pInput->isum;
1,093,946✔
1379
  } else if (IS_UNSIGNED_NUMERIC_TYPE(pOutput->type)) {
14,105!
1380
    pOutput->quadraticUSum += pInput->quadraticUSum;
1✔
1381
    pOutput->usum += pInput->usum;
1✔
1382
  } else {
1383
    pOutput->quadraticDSum += pInput->quadraticDSum;
14,104✔
1384
    pOutput->dsum += pInput->dsum;
14,104✔
1385
  }
1386

1387
  pOutput->count += pInput->count;
1,108,051✔
1388
}
1389

1390
int32_t stdFunctionMerge(SqlFunctionCtx* pCtx) {
1,108,112✔
1391
  SInputColumnInfoData* pInput = &pCtx->input;
1,108,112✔
1392
  SColumnInfoData*      pCol = pInput->pData[0];
1,108,112✔
1393

1394
  if (IS_NULL_TYPE(pCol->info.type)) {
1,108,112!
1395
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
1396
    return TSDB_CODE_SUCCESS;
×
1397
  }
1398

1399
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
1,108,112!
1400
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
1401
  }
1402

1403
  SStdRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,108,112✔
1404

1405
  for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
2,216,227✔
1406
    if (colDataIsNull_s(pCol, i)) continue;
2,216,230!
1407
    char*    data = colDataGetData(pCol, i);
1,108,115!
1408
    SStdRes* pInputInfo = (SStdRes*)varDataVal(data);
1,108,115✔
1409
    stdTransferInfo(pInputInfo, pInfo);
1,108,115✔
1410
  }
1411

1412
  SET_VAL(GET_RES_INFO(pCtx), 1, 1);
1,108,112✔
1413
  return TSDB_CODE_SUCCESS;
1,108,112✔
1414
}
1415

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

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

1424
  SStdRes* pStdRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1425

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

1429
  int32_t start = pInput->startRowIndex;
1430
  int32_t numOfRows = pInput->numOfRows;
1431

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

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

1483
int32_t stddevFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
5,128,651✔
1484
  SInputColumnInfoData* pInput = &pCtx->input;
5,128,651✔
1485
  SStdRes*              pStddevRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
5,128,651✔
1486
  int32_t               type = pStddevRes->type;
5,128,651✔
1487
  double                avg;
1488

1489
  if (pStddevRes->count == 0) {
5,128,651✔
1490
    GET_RES_INFO(pCtx)->numOfRes = 0;
36,881✔
1491
    return functionFinalize(pCtx, pBlock);
36,881✔
1492
  }
1493

1494
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
5,091,770!
1495
    avg = pStddevRes->isum / ((double)pStddevRes->count);
5,049,982✔
1496
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticISum / ((double)pStddevRes->count) - avg * avg));
5,049,982✔
1497
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
41,788!
1498
    avg = pStddevRes->usum / ((double)pStddevRes->count);
10✔
1499
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticUSum / ((double)pStddevRes->count) - avg * avg));
10✔
1500
  } else {
1501
    avg = pStddevRes->dsum / ((double)pStddevRes->count);
41,778✔
1502
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticDSum / ((double)pStddevRes->count) - avg * avg));
41,778✔
1503
  }
1504

1505
  // check for overflow
1506
  if (isinf(pStddevRes->result) || isnan(pStddevRes->result)) {
5,091,770!
1507
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1508
  }
1509

1510
  return functionFinalize(pCtx, pBlock);
5,091,770✔
1511
}
1512

1513
int32_t stdvarFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
13,946✔
1514
  SInputColumnInfoData* pInput = &pCtx->input;
13,946✔
1515
  SStdRes*              pStdvarRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
13,946✔
1516
  int32_t               type = pStdvarRes->type;
13,946✔
1517
  double                avg;
1518

1519
  if (pStdvarRes->count == 0) {
13,946✔
1520
    GET_RES_INFO(pCtx)->numOfRes = 0;
2✔
1521
    return functionFinalize(pCtx, pBlock);
2✔
1522
  }
1523

1524
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
13,944!
1525
    avg = pStdvarRes->isum / ((double)pStdvarRes->count);
6,984✔
1526
    pStdvarRes->result = fabs(pStdvarRes->quadraticISum / ((double)pStdvarRes->count) - avg * avg);
6,984✔
1527
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
6,960!
1528
    avg = pStdvarRes->usum / ((double)pStdvarRes->count);
×
1529
    pStdvarRes->result = fabs(pStdvarRes->quadraticUSum / ((double)pStdvarRes->count) - avg * avg);
×
1530
  } else {
1531
    avg = pStdvarRes->dsum / ((double)pStdvarRes->count);
6,960✔
1532
    pStdvarRes->result = fabs(pStdvarRes->quadraticDSum / ((double)pStdvarRes->count) - avg * avg);
6,960✔
1533
  }
1534

1535
  // check for overflow
1536
  if (isinf(pStdvarRes->result) || isnan(pStdvarRes->result)) {
13,944!
1537
    GET_RES_INFO(pCtx)->numOfRes = 0;
×
1538
  }
1539

1540
  return functionFinalize(pCtx, pBlock);
13,944✔
1541
}
1542

1543
int32_t stdPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1,108,238✔
1544
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,108,238✔
1545
  SStdRes*             pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,108,238✔
1546
  int32_t              resultBytes = getStdInfoSize();
1,108,238✔
1547
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
1,108,238!
1548

1549
  if (NULL == res) {
1,108,239!
1550
    return terrno;
×
1551
  }
1552
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
1,108,239✔
1553
  varDataSetLen(res, resultBytes);
1,108,239✔
1554

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

1562
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
1,108,239✔
1563

1564
  taosMemoryFree(res);
1,108,239!
1565
  return code;
1,108,238✔
1566
}
1567

1568
int32_t stdCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
1569
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
1570
  SStdRes*             pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
1571

1572
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
1573
  SStdRes*             pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
1574
  int16_t              type = pDBuf->type == TSDB_DATA_TYPE_NULL ? pSBuf->type : pDBuf->type;
×
1575

1576
  stdTransferInfo(pSBuf, pDBuf);
×
1577

1578
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
1579
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
1580
  return TSDB_CODE_SUCCESS;
×
1581
}
1582

1583
bool getLeastSQRFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
44,243✔
1584
  pEnv->calcMemSize = sizeof(SLeastSQRInfo);
44,243✔
1585
  return true;
44,243✔
1586
}
1587

1588
int32_t leastSQRFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
3,430,055✔
1589
  if (pResultInfo->initialized) {
3,430,055!
1590
    return TSDB_CODE_SUCCESS;
×
1591
  }
1592
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
3,430,055!
1593
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1594
  }
1595

1596
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
3,430,054✔
1597

1598
  GET_TYPED_DATA(pInfo->startVal, double, pCtx->param[1].param.nType, &pCtx->param[1].param.i,
3,430,054!
1599
                 typeGetTypeModFromCol(pCtx->param[1].pCol));
1600
  GET_TYPED_DATA(pInfo->stepVal, double, pCtx->param[2].param.nType, &pCtx->param[2].param.i,
3,430,052!
1601
                 typeGetTypeModFromCol(pCtx->param[2].pCol));
1602
  return TSDB_CODE_SUCCESS;
3,430,052✔
1603
}
1604

1605
int32_t leastSQRFunction(SqlFunctionCtx* pCtx) {
3,433,064✔
1606
  int32_t numOfElem = 0;
3,433,064✔
1607

1608
  SInputColumnInfoData* pInput = &pCtx->input;
3,433,064✔
1609
  int32_t               type = pInput->pData[0]->info.type;
3,433,064✔
1610

1611
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
3,433,064✔
1612

1613
  SColumnInfoData* pCol = pInput->pData[0];
3,433,064✔
1614

1615
  double(*param)[3] = pInfo->matrix;
3,433,064✔
1616
  double x = pInfo->startVal;
3,433,064✔
1617

1618
  int32_t start = pInput->startRowIndex;
3,433,064✔
1619
  int32_t numOfRows = pInput->numOfRows;
3,433,064✔
1620

1621
  switch (type) {
3,433,064!
1622
    case TSDB_DATA_TYPE_TINYINT: {
1,613,917✔
1623
      int8_t* plist = (int8_t*)pCol->pData;
1,613,917✔
1624
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
5,652,003✔
1625
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
4,038,086!
1626
          continue;
836✔
1627
        }
1628
        numOfElem++;
4,037,250✔
1629
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
4,037,250✔
1630
      }
1631
      break;
1,613,917✔
1632
    }
1633
    case TSDB_DATA_TYPE_SMALLINT: {
2,614✔
1634
      int16_t* plist = (int16_t*)pCol->pData;
2,614✔
1635
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
208,254✔
1636
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
205,640!
1637
          continue;
836✔
1638
        }
1639

1640
        numOfElem++;
204,804✔
1641
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
204,804✔
1642
      }
1643
      break;
2,614✔
1644
    }
1645

1646
    case TSDB_DATA_TYPE_INT: {
9,132✔
1647
      int32_t* plist = (int32_t*)pCol->pData;
9,132✔
1648
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
579,159✔
1649
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
570,027!
1650
          continue;
285,372✔
1651
        }
1652

1653
        numOfElem++;
284,655✔
1654
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
284,655✔
1655
      }
1656
      break;
9,132✔
1657
    }
1658

1659
    case TSDB_DATA_TYPE_BIGINT: {
3,230✔
1660
      int64_t* plist = (int64_t*)pCol->pData;
3,230✔
1661
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
358,834✔
1662
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
355,604!
1663
          continue;
274,336✔
1664
        }
1665

1666
        numOfElem++;
81,268✔
1667
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
81,268✔
1668
      }
1669
      break;
3,230✔
1670
    }
1671

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

1690
        numOfElem++;
80,192✔
1691
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
80,192✔
1692
      }
1693
      break;
102✔
1694
    }
1695

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

1703
        numOfElem++;
80,192✔
1704
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
80,192✔
1705
      }
1706
      break;
102✔
1707
    }
1708

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

1716
        numOfElem++;
80,192✔
1717
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
80,192✔
1718
      }
1719
      break;
102✔
1720
    }
1721

1722
    case TSDB_DATA_TYPE_FLOAT: {
13,184✔
1723
      float* plist = (float*)pCol->pData;
13,184✔
1724
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
528,519✔
1725
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
515,335!
1726
          continue;
138,136✔
1727
        }
1728

1729
        numOfElem++;
377,199✔
1730
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
377,199✔
1731
      }
1732
      break;
13,184✔
1733
    }
1734

1735
    case TSDB_DATA_TYPE_DOUBLE: {
1,790,580✔
1736
      double* plist = (double*)pCol->pData;
1,790,580✔
1737
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
6,392,281✔
1738
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
4,601,701!
1739
          continue;
148,399✔
1740
        }
1741

1742
        numOfElem++;
4,453,302✔
1743
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
4,453,302✔
1744
      }
1745
      break;
1,790,580✔
1746
    }
1747
    case TSDB_DATA_TYPE_NULL: {
×
1748
      GET_RES_INFO(pCtx)->isNullRes = 1;
×
1749
      numOfElem = 1;
×
1750
      break;
×
1751
    }
1752

1753
    default:
×
1754
      break;
×
1755
  }
1756

1757
  pInfo->startVal = x;
3,433,064✔
1758
  pInfo->num += numOfElem;
3,433,064✔
1759

1760
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
3,433,064✔
1761

1762
  return TSDB_CODE_SUCCESS;
3,433,064✔
1763
}
1764

1765
int32_t leastSQRFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
3,426,644✔
1766
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
3,426,644✔
1767
  SLeastSQRInfo*       pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
3,426,644✔
1768
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
3,426,644✔
1769
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
3,426,644✔
1770

1771
  if (NULL == pCol) {
3,426,644!
1772
    return TSDB_CODE_OUT_OF_RANGE;
×
1773
  }
1774
  int32_t currentRow = pBlock->info.rows;
3,426,644✔
1775

1776
  if (0 == pInfo->num) {
3,426,644✔
1777
    colDataSetNULL(pCol, currentRow);
17,510!
1778
    return TSDB_CODE_SUCCESS;
17,510✔
1779
  }
1780

1781
  double(*param)[3] = pInfo->matrix;
3,409,134✔
1782

1783
  param[1][1] = (double)pInfo->num;
3,409,134✔
1784
  param[1][0] = param[0][1];
3,409,134✔
1785

1786
  double param00 = param[0][0] - param[1][0] * (param[0][1] / param[1][1]);
3,409,134✔
1787
  double param02 = param[0][2] - param[1][2] * (param[0][1] / param[1][1]);
3,409,134✔
1788

1789
  if (0 == param00) {
3,409,134✔
1790
    colDataSetNULL(pCol, currentRow);
2,952,903!
1791
    return TSDB_CODE_SUCCESS;
2,952,903✔
1792
  }
1793

1794
  // param[0][1] = 0;
1795
  double param12 = param[1][2] - param02 * (param[1][0] / param00);
456,231✔
1796
  // param[1][0] = 0;
1797
  param02 /= param00;
456,231✔
1798

1799
  param12 /= param[1][1];
456,231✔
1800

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

1816
  int32_t code = colDataSetVal(pCol, currentRow, buf, pResInfo->isNullRes);
456,236✔
1817

1818
  return code;
456,236✔
1819
}
1820

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

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

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

1848
int32_t percentileFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
3,654✔
1849
  if (pResultInfo->initialized) {
3,654!
1850
    return TSDB_CODE_SUCCESS;
×
1851
  }
1852
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
3,654!
1853
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
1854
  }
1855

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

1862
  return TSDB_CODE_SUCCESS;
3,654✔
1863
}
1864

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

1876
int32_t percentileFunction(SqlFunctionCtx* pCtx) {
2,400,480✔
1877
  int32_t              code = TSDB_CODE_SUCCESS;
2,400,480✔
1878
  int32_t              numOfElems = 0;
2,400,480✔
1879
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,400,480✔
1880

1881
  SInputColumnInfoData* pInput = &pCtx->input;
2,400,480✔
1882
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
2,400,480✔
1883

1884
  SColumnInfoData* pCol = pInput->pData[0];
2,400,480✔
1885
  int32_t          type = pCol->info.type;
2,400,480✔
1886

1887
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,400,480✔
1888
  if (pCtx->scanFlag == MAIN_SCAN && pInfo->stage == 0) {
2,400,480✔
1889
    pInfo->stage += 1;
3,654✔
1890

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

1904
  // the first stage, only acquire the min/max value
1905
  if (pInfo->stage == 0) {
2,399,278✔
1906
    if (pCtx->input.colDataSMAIsSet) {
1,200,240✔
1907
      double tmin = 0.0, tmax = 0.0;
1,195,012✔
1908
      if (IS_SIGNED_NUMERIC_TYPE(type)) {
1,195,012!
1909
        tmin = (double)GET_INT64_VAL(&pAgg->min);
×
1910
        tmax = (double)GET_INT64_VAL(&pAgg->max);
×
1911
      } else if (IS_FLOAT_TYPE(type)) {
1,195,012!
1912
        tmin = GET_DOUBLE_VAL(&pAgg->min);
1,195,012✔
1913
        tmax = GET_DOUBLE_VAL(&pAgg->max);
1,195,012✔
1914
      } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
1915
        tmin = (double)GET_UINT64_VAL(&pAgg->min);
×
1916
        tmax = (double)GET_UINT64_VAL(&pAgg->max);
×
1917
      }
1918

1919
      if (GET_DOUBLE_VAL(&pInfo->minval) > tmin) {
1,195,012✔
1920
        SET_DOUBLE_VAL(&pInfo->minval, tmin);
14✔
1921
      }
1922

1923
      if (GET_DOUBLE_VAL(&pInfo->maxval) < tmax) {
1,195,012✔
1924
        SET_DOUBLE_VAL(&pInfo->maxval, tmax);
14✔
1925
      }
1926

1927
      pInfo->numOfElems += (pInput->numOfRows - pAgg->numOfNull);
1,195,012✔
1928
    } else {
1929
      // check the valid data one by one
1930
      int32_t start = pInput->startRowIndex;
5,228✔
1931
      for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
2,908,091✔
1932
        if (colDataIsNull_f(pCol, i)) {
2,902,863!
1933
          continue;
1,532✔
1934
        }
1935

1936
        char* data = colDataGetData(pCol, i);
2,901,331!
1937

1938
        double v = 0;
2,901,331✔
1939
        GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pCol->info));
2,901,331!
1940
        if (v < GET_DOUBLE_VAL(&pInfo->minval)) {
2,901,331✔
1941
          SET_DOUBLE_VAL(&pInfo->minval, v);
3,045✔
1942
        }
1943

1944
        if (v > GET_DOUBLE_VAL(&pInfo->maxval)) {
2,901,331✔
1945
          SET_DOUBLE_VAL(&pInfo->maxval, v);
410,419✔
1946
        }
1947

1948
        pInfo->numOfElems += 1;
2,901,331✔
1949
      }
1950
    }
1951
  } else {
1952
    // the second stage, calculate the true percentile value
1953
    int32_t start = pInput->startRowIndex;
1,199,038✔
1954
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
2,147,483,647✔
1955
      if (colDataIsNull_f(pCol, i)) {
2,147,483,647!
1956
        continue;
×
1957
      }
1958

1959
      char* data = colDataGetData(pCol, i);
2,147,483,647!
1960
      numOfElems += 1;
2,147,483,647✔
1961
      code = tMemBucketPut(pInfo->pMemBucket, data, 1);
2,147,483,647✔
1962
      if (code != TSDB_CODE_SUCCESS) {
2,147,483,647✔
1963
        tMemBucketDestroy(&(pInfo->pMemBucket));
2✔
1964
        return code;
2✔
1965
      }
1966
    }
1967

1968
    SET_VAL(pResInfo, numOfElems, 1);
1,199,036!
1969
  }
1970

1971
  pCtx->needCleanup = true;
2,399,276✔
1972
  return TSDB_CODE_SUCCESS;
2,399,276✔
1973
}
1974

1975
int32_t percentileFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
3,650✔
1976
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
3,650✔
1977
  SPercentileInfo*     ppInfo = (SPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
3,650✔
1978

1979
  int32_t code = 0;
3,650✔
1980
  double  v = 0;
3,650✔
1981

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

1990
      varDataVal(buf)[0] = '[';
34✔
1991
      for (int32_t i = 1; i < pCtx->numOfParams; ++i) {
342✔
1992
        SVariant* pVal = &pCtx->param[i].param;
308✔
1993

1994
        GET_TYPED_DATA(v, double, pVal->nType, &pVal->i, typeGetTypeModFromCol(pCtx->param[i].pCol));
308!
1995

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

2001
        if (i == pCtx->numOfParams - 1) {
308✔
2002
          len += tsnprintf(varDataVal(buf) + len, sizeof(buf) - VARSTR_HEADER_SIZE - len, "%.6lf]", ppInfo->result);
34✔
2003
        } else {
2004
          len += tsnprintf(varDataVal(buf) + len, sizeof(buf) - VARSTR_HEADER_SIZE - len, "%.6lf, ", ppInfo->result);
274✔
2005
        }
2006
      }
2007

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

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

2021
      tMemBucketDestroy(pMemBucket);
34✔
2022
      return TSDB_CODE_SUCCESS;
34✔
2023
    } else {
2024
      SVariant* pVal = &pCtx->param[1].param;
2,414✔
2025

2026
      GET_TYPED_DATA(v, double, pVal->nType, &pVal->i, typeGetTypeModFromCol(pCtx->param[1].pCol));
2,414!
2027

2028
      code = getPercentile((*pMemBucket), v, &ppInfo->result);
2,414✔
2029
      if (code != TSDB_CODE_SUCCESS) {
2,414!
2030
        goto _fin_error;
×
2031
      }
2032

2033
      tMemBucketDestroy(pMemBucket);
2,414✔
2034
      return functionFinalize(pCtx, pBlock);
2,414✔
2035
    }
2036
  } else {
2037
    return functionFinalize(pCtx, pBlock);
1,202✔
2038
  }
2039

2040
_fin_error:
×
2041

2042
  tMemBucketDestroy(pMemBucket);
×
2043
  return code;
×
2044
}
2045

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

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

2061
static int8_t getApercentileAlgo(char* algoStr) {
26,426✔
2062
  int8_t algoType;
2063
  if (strcasecmp(algoStr, "default") == 0) {
26,426✔
2064
    algoType = APERCT_ALGO_DEFAULT;
11,423✔
2065
  } else if (strcasecmp(algoStr, "t-digest") == 0) {
15,003!
2066
    algoType = APERCT_ALGO_TDIGEST;
15,005✔
2067
  } else {
2068
    algoType = APERCT_ALGO_UNKNOWN;
×
2069
  }
2070

2071
  return algoType;
26,426✔
2072
}
2073

2074
static void buildHistogramInfo(SAPercentileInfo* pInfo) {
268,236✔
2075
  pInfo->pHisto = (SHistogramInfo*)((char*)pInfo + sizeof(SAPercentileInfo));
268,236✔
2076
  pInfo->pHisto->elems = (SHistBin*)((char*)pInfo->pHisto + sizeof(SHistogramInfo));
268,236✔
2077
}
268,236✔
2078

2079
static void buildTDigestInfo(SAPercentileInfo* pInfo) {
39,893✔
2080
  pInfo->pTDigest = (TDigest*)((char*)pInfo + sizeof(SAPercentileInfo));
39,893✔
2081
}
39,893✔
2082

2083
int32_t apercentileFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
107,208✔
2084
  if (pResultInfo->initialized) {
107,208!
2085
    return TSDB_CODE_SUCCESS;
×
2086
  }
2087
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
107,208!
2088
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
2089
  }
2090

2091
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
107,220✔
2092

2093
  SVariant* pVal = &pCtx->param[1].param;
107,220✔
2094
  pInfo->percent = 0;
107,220✔
2095
  GET_TYPED_DATA(pInfo->percent, double, pVal->nType, &pVal->i, typeGetTypeModFromCol(pCtx->param[1].pCol));
107,220!
2096

2097
  if (pCtx->numOfParams == 2) {
107,224✔
2098
    pInfo->algo = APERCT_ALGO_DEFAULT;
80,798✔
2099
  } else if (pCtx->numOfParams == 3) {
26,426!
2100
    pInfo->algo = getApercentileAlgo(varDataVal(pCtx->param[2].param.pz));
26,426✔
2101
    if (pInfo->algo == APERCT_ALGO_UNKNOWN) {
26,425!
2102
      return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
2103
    }
2104
  }
2105

2106
  char* tmp = (char*)pInfo + sizeof(SAPercentileInfo);
107,223✔
2107
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
107,223✔
2108
    pInfo->pTDigest = tdigestNewFrom(tmp, COMPRESSION);
15,003✔
2109
  } else {
2110
    buildHistogramInfo(pInfo);
92,220✔
2111
    pInfo->pHisto = tHistogramCreateFrom(tmp, MAX_HISTOGRAM_BIN);
92,218✔
2112
    qDebug("%s set up histogram, numOfElems:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
92,217✔
2113
           pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2114
  }
2115

2116
  return TSDB_CODE_SUCCESS;
107,229✔
2117
}
2118

2119
int32_t apercentileFunction(SqlFunctionCtx* pCtx) {
122,443✔
2120
  int32_t               numOfElems = 0;
122,443✔
2121
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
122,443✔
2122
  SInputColumnInfoData* pInput = &pCtx->input;
122,443✔
2123

2124
  SColumnInfoData* pCol = pInput->pData[0];
122,443✔
2125
  int32_t          type = pCol->info.type;
122,443✔
2126

2127
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
122,443✔
2128

2129
  int32_t start = pInput->startRowIndex;
122,443✔
2130
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
122,443✔
2131
    buildTDigestInfo(pInfo);
24,014✔
2132
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
24,014✔
2133
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
2,460,482✔
2134
      if (colDataIsNull_f(pCol, i)) {
2,436,470✔
2135
        continue;
420,980✔
2136
      }
2137
      numOfElems += 1;
2,015,490✔
2138
      char* data = colDataGetData(pCol, i);
2,015,490!
2139

2140
      double  v = 0;  // value
2,015,490✔
2141
      int64_t w = 1;  // weigth
2,015,490✔
2142
      GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pCol->info));
2,015,490!
2143
      int32_t code = tdigestAdd(pInfo->pTDigest, v, w);
2,015,490✔
2144
      if (code != TSDB_CODE_SUCCESS) {
2,015,488!
2145
        return code;
×
2146
      }
2147
    }
2148
  } else {
2149
    // might be a race condition here that pHisto can be overwritten or setup function
2150
    // has not been called, need to relink the buffer pHisto points to.
2151
    buildHistogramInfo(pInfo);
98,429✔
2152
    qDebug("%s before add %d elements into histogram, total:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems: %p",
98,428✔
2153
           __FUNCTION__, numOfElems, pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto,
2154
           pInfo->pHisto->elems);
2155
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
2,419,674✔
2156
      if (colDataIsNull_f(pCol, i)) {
2,321,238!
2157
        continue;
977,068✔
2158
      }
2159
      numOfElems += 1;
1,344,170✔
2160
      char* data = colDataGetData(pCol, i);
1,344,170!
2161

2162
      double v = 0;
1,344,170✔
2163
      GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pCol->info));
1,344,170!
2164
      int32_t code = tHistogramAdd(&pInfo->pHisto, v);
1,344,170✔
2165
      if (code != TSDB_CODE_SUCCESS) {
1,344,171!
2166
        return code;
×
2167
      }
2168
    }
2169

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

2175
  SET_VAL(pResInfo, numOfElems, 1);
122,454✔
2176
  return TSDB_CODE_SUCCESS;
122,454✔
2177
}
2178

2179
static int32_t apercentileTransferInfo(SAPercentileInfo* pInput, SAPercentileInfo* pOutput, bool* hasRes) {
1,394✔
2180
  pOutput->percent = pInput->percent;
1,394✔
2181
  pOutput->algo = pInput->algo;
1,394✔
2182
  if (pOutput->algo == APERCT_ALGO_TDIGEST) {
1,394✔
2183
    buildTDigestInfo(pInput);
925✔
2184
    tdigestAutoFill(pInput->pTDigest, COMPRESSION);
925✔
2185

2186
    if (pInput->pTDigest->num_centroids == 0 && pInput->pTDigest->num_buffered_pts == 0) {
925✔
2187
      return TSDB_CODE_SUCCESS;
1✔
2188
    }
2189

2190
    if (hasRes) {
924!
2191
      *hasRes = true;
924✔
2192
    }
2193

2194
    buildTDigestInfo(pOutput);
924✔
2195
    TDigest* pTDigest = pOutput->pTDigest;
924✔
2196
    tdigestAutoFill(pTDigest, COMPRESSION);
924✔
2197

2198
    if (pTDigest->num_centroids <= 0 && pTDigest->num_buffered_pts == 0) {
924!
2199
      (void)memcpy(pTDigest, pInput->pTDigest, (size_t)TDIGEST_SIZE(COMPRESSION));
924✔
2200
      tdigestAutoFill(pTDigest, COMPRESSION);
924✔
2201
    } else {
2202
      int32_t code = tdigestMerge(pTDigest, pInput->pTDigest);
×
2203
      if (TSDB_CODE_SUCCESS != code) {
×
2204
        return code;
×
2205
      }
2206
    }
2207
  } else {
2208
    buildHistogramInfo(pInput);
469✔
2209
    if (pInput->pHisto->numOfElems <= 0) {
469✔
2210
      return TSDB_CODE_SUCCESS;
47✔
2211
    }
2212

2213
    if (hasRes) {
422!
2214
      *hasRes = true;
422✔
2215
    }
2216

2217
    buildHistogramInfo(pOutput);
422✔
2218
    SHistogramInfo* pHisto = pOutput->pHisto;
422✔
2219

2220
    if (pHisto->numOfElems <= 0) {
422✔
2221
      (void)memcpy(pHisto, pInput->pHisto, sizeof(SHistogramInfo) + sizeof(SHistBin) * (MAX_HISTOGRAM_BIN + 1));
355✔
2222
      pHisto->elems = (SHistBin*)((char*)pHisto + sizeof(SHistogramInfo));
355✔
2223

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

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

2240
      qDebug("%s merge histo, total:%" PRId64 ", entry:%d, %p", __FUNCTION__, pHisto->numOfElems, pHisto->numOfEntries,
67!
2241
             pHisto);
2242
      tHistogramDestroy(&pRes);
67✔
2243
    }
2244
  }
2245
  return TSDB_CODE_SUCCESS;
1,346✔
2246
}
2247

2248
int32_t apercentileFunctionMerge(SqlFunctionCtx* pCtx) {
1,386✔
2249
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,386✔
2250

2251
  SInputColumnInfoData* pInput = &pCtx->input;
1,386✔
2252

2253
  SColumnInfoData* pCol = pInput->pData[0];
1,386✔
2254
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
1,386!
2255
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
2256
  }
2257

2258
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
1,386✔
2259

2260
  qDebug("%s total %" PRId64 " rows will merge, %p", __FUNCTION__, pInput->numOfRows, pInfo->pHisto);
1,386✔
2261

2262
  bool    hasRes = false;
1,386✔
2263
  int32_t start = pInput->startRowIndex;
1,386✔
2264
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
2,780✔
2265
    char* data = colDataGetData(pCol, i);
1,394!
2266

2267
    SAPercentileInfo* pInputInfo = (SAPercentileInfo*)varDataVal(data);
1,394✔
2268
    int32_t           code = apercentileTransferInfo(pInputInfo, pInfo, &hasRes);
1,394✔
2269
    if (TSDB_CODE_SUCCESS != code) {
1,394!
2270
      return code;
×
2271
    }
2272
  }
2273

2274
  if (pInfo->algo != APERCT_ALGO_TDIGEST) {
1,386✔
2275
    buildHistogramInfo(pInfo);
461✔
2276
    qDebug("%s after merge, total:%" PRId64 ", numOfEntry:%d, %p", __FUNCTION__, pInfo->pHisto->numOfElems,
461✔
2277
           pInfo->pHisto->numOfEntries, pInfo->pHisto);
2278
  }
2279

2280
  SET_VAL(pResInfo, hasRes ? 1 : 0, 1);
1,386✔
2281
  return TSDB_CODE_SUCCESS;
1,386✔
2282
}
2283

2284
int32_t apercentileFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
90,310✔
2285
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
90,310✔
2286
  SAPercentileInfo*    pInfo = (SAPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
90,310✔
2287

2288
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
90,310✔
2289
    buildTDigestInfo(pInfo);
14,038✔
2290
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
14,038✔
2291
    if (pInfo->pTDigest->size > 0) {
14,039!
2292
      pInfo->result = tdigestQuantile(pInfo->pTDigest, pInfo->percent / 100);
14,039✔
2293
    } else {  // no need to free
2294
      // setNull(pCtx->pOutput, pCtx->outputType, pCtx->outputBytes);
2295
      return TSDB_CODE_SUCCESS;
×
2296
    }
2297
  } else {
2298
    buildHistogramInfo(pInfo);
76,272✔
2299
    if (pInfo->pHisto->numOfElems > 0) {
76,272✔
2300
      qDebug("%s get the final res, elements:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
47,995✔
2301
             pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2302

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

2321
  return functionFinalize(pCtx, pBlock);
90,322✔
2322
}
2323

2324
int32_t apercentilePartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1,493✔
2325
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,493✔
2326
  SAPercentileInfo*    pInfo = (SAPercentileInfo*)GET_ROWCELL_INTERBUF(pResInfo);
1,493✔
2327

2328
  int32_t resultBytes = getApercentileMaxSize();
1,493✔
2329
  char*   res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
1,493!
2330
  if (NULL == res) {
1,493!
2331
    return terrno;
×
2332
  }
2333

2334
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
1,493✔
2335
    (void)memcpy(varDataVal(res), pInfo, resultBytes);
955✔
2336
    varDataSetLen(res, resultBytes);
955✔
2337
  } else {
2338
    (void)memcpy(varDataVal(res), pInfo, resultBytes);
538✔
2339
    varDataSetLen(res, resultBytes);
538✔
2340
  }
2341

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

2349
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
1,493✔
2350

2351
  taosMemoryFree(res);
1,493!
2352
  return code;
1,493✔
2353
}
2354

2355
int32_t apercentileCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
2356
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
2357
  SAPercentileInfo*    pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
2358

2359
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
2360
  SAPercentileInfo*    pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
2361

2362
  qDebug("%s start to combine apercentile, %p", __FUNCTION__, pDBuf->pHisto);
×
2363

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

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

2397
EFuncDataRequired firstDynDataReq(void* pRes, SDataBlockInfo* pBlockInfo) {
8,562✔
2398
  SResultRowEntryInfo* pEntry = (SResultRowEntryInfo*)pRes;
8,562✔
2399

2400
  // not initialized yet, data is required
2401
  if (pEntry == NULL) {
8,562!
2402
    return FUNC_DATA_REQUIRED_DATA_LOAD;
×
2403
  }
2404

2405
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
8,562✔
2406
  if (pResult->hasResult) {
8,562✔
2407
    if (pResult->pkBytes > 0) {
8,514✔
2408
      pResult->pkData = pResult->buf + pResult->bytes;
1,954✔
2409
    } else {
2410
      pResult->pkData = NULL;
6,560✔
2411
    }
2412
    if (pResult->ts < pBlockInfo->window.skey) {
8,514✔
2413
      return FUNC_DATA_REQUIRED_NOT_LOAD;
5,659✔
2414
    } else if (pResult->ts == pBlockInfo->window.skey) {
2,855✔
2415
      if (NULL == pResult->pkData) {
1,361✔
2416
        return FUNC_DATA_REQUIRED_NOT_LOAD;
317✔
2417
      }
2418
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 0, TSDB_ORDER_ASC) < 0) {
1,044✔
2419
        return FUNC_DATA_REQUIRED_NOT_LOAD;
185✔
2420
      }
2421
    }
2422
    return FUNC_DATA_REQUIRED_DATA_LOAD;
2,353✔
2423
  } else {
2424
    return FUNC_DATA_REQUIRED_DATA_LOAD;
48✔
2425
  }
2426
}
2427

2428
EFuncDataRequired lastDynDataReq(void* pRes, SDataBlockInfo* pBlockInfo) {
16,173✔
2429
  SResultRowEntryInfo* pEntry = (SResultRowEntryInfo*)pRes;
16,173✔
2430

2431
  // not initialized yet, data is required
2432
  if (pEntry == NULL) {
16,173!
2433
    return FUNC_DATA_REQUIRED_DATA_LOAD;
×
2434
  }
2435

2436
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
16,173✔
2437
  if (pResult->hasResult) {
16,173✔
2438
    if (pResult->pkBytes > 0) {
16,124✔
2439
      pResult->pkData = pResult->buf + pResult->bytes;
3,862✔
2440
    } else {
2441
      pResult->pkData = NULL;
12,262✔
2442
    }
2443
    if (pResult->ts > pBlockInfo->window.ekey) {
16,124✔
2444
      return FUNC_DATA_REQUIRED_NOT_LOAD;
7,756✔
2445
    } else if (pResult->ts == pBlockInfo->window.ekey && pResult->pkData) {
8,368✔
2446
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 1, TSDB_ORDER_DESC) < 0) {
1,652✔
2447
        return FUNC_DATA_REQUIRED_NOT_LOAD;
473✔
2448
      }
2449
    }
2450
    return FUNC_DATA_REQUIRED_DATA_LOAD;
7,894✔
2451
  } else {
2452
    return FUNC_DATA_REQUIRED_DATA_LOAD;
49✔
2453
  }
2454
}
2455

2456
// TODO modify it to include primary key bytes
2457
int32_t getFirstLastInfoSize(int32_t resBytes, int32_t pkBytes) { return sizeof(SFirstLastRes) + resBytes + pkBytes; }
56,902,336✔
2458

2459
bool getFirstLastFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
1,801,342✔
2460
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
1,801,342✔
2461
  // TODO: change SFunctionNode to add pk info
2462
  int32_t pkBytes = (pFunc->hasPk) ? pFunc->pkBytes : 0;
1,802,800✔
2463
  pEnv->calcMemSize = getFirstLastInfoSize(pNode->node.resType.bytes, pkBytes);
1,802,800✔
2464
  return true;
1,802,785✔
2465
}
2466

2467
bool getSelectivityFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
1,243,222✔
2468
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
1,243,222✔
2469
  pEnv->calcMemSize = pNode->node.resType.bytes;
1,244,206✔
2470
  return true;
1,244,206✔
2471
}
2472

2473
bool getGroupKeyFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
244,358✔
2474
  SColumnNode* pNode = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
244,358✔
2475
  pEnv->calcMemSize = sizeof(SGroupKeyInfo) + pNode->node.resType.bytes;
244,519✔
2476
  return true;
244,519✔
2477
}
2478

2479
static FORCE_INLINE TSKEY getRowPTs(SColumnInfoData* pTsColInfo, int32_t rowIndex) {
2480
  if (pTsColInfo == NULL || pTsColInfo->pData == NULL) {
321,803,619!
2481
    return 0;
×
2482
  }
2483

2484
  return *(TSKEY*)colDataGetData(pTsColInfo, rowIndex);
321,816,921!
2485
}
2486

2487
int32_t firstLastFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
21,361,594✔
2488
  if (pResInfo->initialized) {
21,361,594!
2489
    return TSDB_CODE_SUCCESS;
×
2490
  }
2491
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
21,361,594!
2492
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
2493
  }
2494

2495
  SFirstLastRes* pRes = GET_ROWCELL_INTERBUF(pResInfo);
21,362,487✔
2496
  pRes->nullTupleSaved = false;
21,362,487✔
2497
  pRes->nullTuplePos.pageId = -1;
21,362,487✔
2498
  return TSDB_CODE_SUCCESS;
21,362,487✔
2499
}
2500

2501
static int32_t prepareBuf(SqlFunctionCtx* pCtx) {
193,350,704✔
2502
  if (pCtx->subsidiaries.rowLen == 0) {
193,350,704✔
2503
    int32_t rowLen = 0;
671,558✔
2504
    for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
1,348,255✔
2505
      SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
676,697✔
2506
      rowLen += pc->pExpr->base.resSchema.bytes;
676,697✔
2507
    }
2508

2509
    pCtx->subsidiaries.rowLen = rowLen + pCtx->subsidiaries.num * sizeof(bool);
671,558✔
2510
    pCtx->subsidiaries.buf = taosMemoryMalloc(pCtx->subsidiaries.rowLen);
671,558!
2511
    if (NULL == pCtx->subsidiaries.buf) {
670,755!
2512
      return terrno;
×
2513
    }
2514
  }
2515
  return TSDB_CODE_SUCCESS;
193,349,901✔
2516
}
2517

2518
static int32_t firstlastSaveTupleData(const SSDataBlock* pSrcBlock, int32_t rowIndex, SqlFunctionCtx* pCtx,
185,638,109✔
2519
                                      SFirstLastRes* pInfo, bool noElements) {
2520
  int32_t code = TSDB_CODE_SUCCESS;
185,638,109✔
2521

2522
  if (pCtx->subsidiaries.num <= 0) {
185,638,109✔
2523
    return TSDB_CODE_SUCCESS;
70,362,566✔
2524
  }
2525

2526
  if (!pInfo->hasResult) {
115,275,543✔
2527
    code = saveTupleData(pCtx, rowIndex, pSrcBlock, &pInfo->pos);
92,357,732✔
2528
  } else if (!noElements) {
22,917,811!
2529
    code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pInfo->pos);
23,019,288✔
2530
  } else {
2531
  }  // dothing
2532

2533
  return code;
115,159,123✔
2534
}
2535

2536
static int32_t doSaveCurrentVal(SqlFunctionCtx* pCtx, int32_t rowIndex, int64_t currentTs, char* pkData, int32_t type,
67,380,140✔
2537
                                char* pData) {
2538
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
67,380,140✔
2539
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
67,380,140✔
2540

2541
  if (IS_VAR_DATA_TYPE(type)) {
67,380,140!
2542
    pInfo->bytes = calcStrBytesByType(type, pData);
3,733,222✔
2543
    // if (type == TSDB_DATA_TYPE_JSON) {
2544
    //   pInfo->bytes = getJsonValueLen(pData);
2545
    // } else {
2546
    //   pInfo->bytes = varDataTLen(pData);
2547
    // }
2548
  }
2549

2550
  (void)memcpy(pInfo->buf, pData, pInfo->bytes);
67,400,068✔
2551
  if (pkData != NULL) {
67,400,068✔
2552
    if (IS_VAR_DATA_TYPE(pInfo->pkType)) {
284,565!
2553
      pInfo->pkBytes = calcStrBytesByType(pInfo->pkType, pkData);
94,777✔
2554
      // if (pInfo->pkType == TSDB_DATA_TYPE_JSON) {
2555
      //   pInfo->pkBytes = getJsonValueLen(pkData);
2556
      // } else {
2557
      //   pInfo->pkBytes = varDataTLen(pkData);
2558
      // }
2559
    }
2560
    (void)memcpy(pInfo->buf + pInfo->bytes, pkData, pInfo->pkBytes);
284,605✔
2561
    pInfo->pkData = pInfo->buf + pInfo->bytes;
284,605✔
2562
  }
2563

2564
  pInfo->ts = currentTs;
67,400,108✔
2565
  int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pInfo, false);
67,400,108✔
2566
  if (code != TSDB_CODE_SUCCESS) {
67,320,669!
2567
    return code;
×
2568
  }
2569

2570
  pInfo->hasResult = true;
67,320,669✔
2571
  return TSDB_CODE_SUCCESS;
67,320,669✔
2572
}
2573

2574
// This ordinary first function does not care if current scan is ascending order or descending order scan
2575
// the OPTIMIZED version of first function will only handle the ascending order scan
2576
int32_t firstFunction(SqlFunctionCtx* pCtx) {
28,626,764✔
2577
  int32_t numOfElems = 0;
28,626,764✔
2578

2579
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
28,626,764✔
2580
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
28,626,764✔
2581

2582
  SInputColumnInfoData* pInput = &pCtx->input;
28,626,764✔
2583
  SColumnInfoData*      pInputCol = pInput->pData[0];
28,626,764✔
2584

2585
  pInfo->bytes = pInputCol->info.bytes;
28,626,764✔
2586

2587
  if (IS_NULL_TYPE(pInputCol->info.type)) {
28,626,764✔
2588
    return TSDB_CODE_SUCCESS;
3,748✔
2589
  }
2590

2591
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
28,623,016✔
2592
  pInfo->pkType = -1;
28,623,016✔
2593
  __compar_fn_t pkCompareFn = NULL;
28,623,016✔
2594
  if (pCtx->hasPrimaryKey) {
28,623,016✔
2595
    pInfo->pkType = pkCol->info.type;
79,514✔
2596
    pInfo->pkBytes = pkCol->info.bytes;
79,514✔
2597
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_ASC);
79,514✔
2598
  }
2599

2600
  // All null data column, return directly.
2601
  if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) &&
28,623,824!
2602
      pInputCol->hasNull == true) {
×
2603
    // save selectivity value for column consisted of all null values
2604
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
×
2605
    if (code != TSDB_CODE_SUCCESS) {
×
2606
      return code;
×
2607
    }
2608
    pInfo->nullTupleSaved = true;
×
2609
    return TSDB_CODE_SUCCESS;
×
2610
  }
2611

2612
  SColumnDataAgg* pColAgg = (pInput->colDataSMAIsSet) ? pInput->pColumnDataAgg[0] : NULL;
28,623,824!
2613

2614
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
28,623,824!
2615
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
28,623,824!
2616

2617
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
28,623,824✔
2618

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

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

2635
      numOfElems++;
2636

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

2653
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
2654
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2655
        continue;
2656
      }
2657

2658
      numOfElems++;
2659

2660
      char* data = colDataGetData(pInputCol, i);
2661
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2662

2663
      if (pResInfo->numOfRes == 0 || pInfo->ts > cts) {
2664
        doSaveCurrentVal(pCtx, i, cts, pInputCol->info.type, data);
2665
        break;
2666
      }
2667
    }
2668
  }
2669
#else
2670
  int64_t* pts = (int64_t*)pInput->pPTS->pData;
28,623,824✔
2671

2672
  int     from = -1;
28,623,824✔
2673
  int32_t i = -1;
28,623,824✔
2674
  while (funcInputGetNextRowIndex(pInput, from, true, &i, &from)) {
113,782,359✔
2675
    if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
110,064,157!
2676
      continue;
63,084✔
2677
    }
2678

2679
    numOfElems++;
85,096,230✔
2680
    char* data = colDataGetData(pInputCol, i);
85,096,230!
2681
    char* pkData = NULL;
85,096,230✔
2682
    if (pCtx->hasPrimaryKey) {
85,096,230✔
2683
      pkData = colDataGetData(pkCol, i);
294,030!
2684
    }
2685
    TSKEY cts = pts[i];
85,096,230✔
2686
    if (pResInfo->numOfRes == 0 || pInfo->ts > cts ||
85,096,230✔
2687
        (pInfo->ts == cts && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
55,507,303!
2688
      int32_t code = doSaveCurrentVal(pCtx, i, cts, pkData, pInputCol->info.type, data);
29,588,927✔
2689
      if (code != TSDB_CODE_SUCCESS) {
29,588,150!
2690
        return code;
×
2691
      }
2692
      pResInfo->numOfRes = 1;
29,588,150✔
2693
    }
2694
  }
2695
#endif
2696

2697
  if (numOfElems == 0) {
28,611,194✔
2698
    // save selectivity value for column consisted of all null values
2699
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
13,226✔
2700
    if (code != TSDB_CODE_SUCCESS) {
13,226!
2701
      return code;
×
2702
    }
2703
    pInfo->nullTupleSaved = true;
13,226✔
2704
  }
2705
  SET_VAL(pResInfo, numOfElems, 1);
28,611,194✔
2706
  return TSDB_CODE_SUCCESS;
28,611,194✔
2707
}
2708

2709
int32_t lastFunction(SqlFunctionCtx* pCtx) {
24,608,468✔
2710
  int32_t numOfElems = 0;
24,608,468✔
2711

2712
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
24,608,468✔
2713
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
24,608,468✔
2714

2715
  SInputColumnInfoData* pInput = &pCtx->input;
24,608,468✔
2716
  SColumnInfoData*      pInputCol = pInput->pData[0];
24,608,468✔
2717

2718
  int32_t type = pInputCol->info.type;
24,608,468✔
2719
  int32_t bytes = pInputCol->info.bytes;
24,608,468✔
2720

2721
  if (IS_NULL_TYPE(type)) {
24,608,468✔
2722
    return TSDB_CODE_SUCCESS;
3,732✔
2723
  }
2724
  pInfo->bytes = bytes;
24,604,736✔
2725

2726
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
24,604,736✔
2727
  pInfo->pkType = -1;
24,604,736✔
2728
  __compar_fn_t pkCompareFn = NULL;
24,604,736✔
2729
  if (pCtx->hasPrimaryKey) {
24,604,736✔
2730
    pInfo->pkType = pkCol->info.type;
85,145✔
2731
    pInfo->pkBytes = pkCol->info.bytes;
85,145✔
2732
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
85,145✔
2733
  }
2734

2735
  // All null data column, return directly.
2736
  if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) &&
24,615,713!
2737
      pInputCol->hasNull == true) {
×
2738
    // save selectivity value for column consisted of all null values
2739
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
×
2740
    if (code != TSDB_CODE_SUCCESS) {
×
2741
      return code;
×
2742
    }
2743
    pInfo->nullTupleSaved = true;
×
2744
    return TSDB_CODE_SUCCESS;
×
2745
  }
2746

2747
  SColumnDataAgg* pColAgg = (pInput->colDataSMAIsSet) ? pInput->pColumnDataAgg[0] : NULL;
24,615,713!
2748

2749
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
24,615,713!
2750
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
24,615,713!
2751

2752
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
24,615,713✔
2753

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

2762
      numOfElems++;
2763

2764
      char* data = colDataGetData(pInputCol, i);
2765
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2766
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
2767
        doSaveCurrentVal(pCtx, i, cts, type, data);
2768
      }
2769

2770
      break;
2771
    }
2772
  } else {  // descending order
2773
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
2774
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2775
        continue;
2776
      }
2777

2778
      numOfElems++;
2779

2780
      char* data = colDataGetData(pInputCol, i);
2781
      TSKEY cts = getRowPTs(pInput->pPTS, i);
2782
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
2783
        doSaveCurrentVal(pCtx, i, cts, type, data);
2784
      }
2785
      break;
2786
    }
2787
  }
2788
#else
2789
  int64_t* pts = (int64_t*)pInput->pPTS->pData;
24,615,713✔
2790

2791
#if 0
2792
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
2793
      if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
2794
        continue;
2795
      }
2796

2797
      numOfElems++;
2798
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i]) {
2799
        char* data = colDataGetData(pInputCol, i);
2800
        doSaveCurrentVal(pCtx, i, pts[i], type, data);
2801
        pResInfo->numOfRes = 1;
2802
      }
2803
    }
2804
#else
2805

2806
  // todo refactor
2807
  if (!pInputCol->hasNull && !pCtx->hasPrimaryKey) {
37,957,135✔
2808
    numOfElems = 1;
13,401,849✔
2809

2810
    int32_t round = pInput->numOfRows >> 2;
13,401,849✔
2811
    int32_t reminder = pInput->numOfRows & 0x03;
13,401,849✔
2812

2813
    for (int32_t i = pInput->startRowIndex, tick = 0; tick < round; i += 4, tick += 1) {
27,305,248✔
2814
      int64_t cts = pts[i];
13,919,923✔
2815
      int32_t chosen = i;
13,919,923✔
2816

2817
      if (cts < pts[i + 1]) {
13,919,923✔
2818
        cts = pts[i + 1];
168,884✔
2819
        chosen = i + 1;
168,884✔
2820
      }
2821

2822
      if (cts < pts[i + 2]) {
13,919,923✔
2823
        cts = pts[i + 2];
168,888✔
2824
        chosen = i + 2;
168,888✔
2825
      }
2826

2827
      if (cts < pts[i + 3]) {
13,919,923✔
2828
        cts = pts[i + 3];
168,884✔
2829
        chosen = i + 3;
168,884✔
2830
      }
2831

2832
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
13,919,923✔
2833
        char*   data = colDataGetData(pInputCol, chosen);
1,902,692!
2834
        int32_t code = doSaveCurrentVal(pCtx, chosen, cts, NULL, type, data);
1,902,692✔
2835
        if (code != TSDB_CODE_SUCCESS) {
1,886,168!
2836
          return code;
×
2837
        }
2838
        pResInfo->numOfRes = 1;
1,886,168✔
2839
      }
2840
    }
2841

2842
    for (int32_t i = pInput->startRowIndex + round * 4; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
31,834,440✔
2843
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i]) {
18,493,018✔
2844
        char*   data = colDataGetData(pInputCol, i);
10,958,726!
2845
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], NULL, type, data);
10,958,726✔
2846
        if (code != TSDB_CODE_SUCCESS) {
10,914,823!
2847
          return code;
×
2848
        }
2849
        pResInfo->numOfRes = 1;
10,914,823✔
2850
      }
2851
    }
2852
  } else {
2853
    int     from = -1;
11,213,864✔
2854
    int32_t i = -1;
11,213,864✔
2855
    while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
74,859,224✔
2856
      if (colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
127,297,222✔
2857
        continue;
2,043,601✔
2858
      }
2859

2860
      numOfElems++;
61,605,010✔
2861
      char* pkData = NULL;
61,605,010✔
2862
      if (pCtx->hasPrimaryKey) {
61,605,010✔
2863
        pkData = colDataGetData(pkCol, i);
293,821!
2864
      }
2865
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i] ||
61,605,010✔
2866
          (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
36,682,770!
2867
        char*   data = colDataGetData(pInputCol, i);
24,956,061!
2868
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], pkData, type, data);
24,956,061✔
2869
        if (code != TSDB_CODE_SUCCESS) {
24,952,816!
2870
          return code;
×
2871
        }
2872
        pResInfo->numOfRes = 1;
24,952,816✔
2873
      }
2874
    }
2875
  }
2876
#endif
2877

2878
#endif
2879

2880
  // save selectivity value for column consisted of all null values
2881
  if (numOfElems == 0) {
24,613,795✔
2882
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
3,013✔
2883
    if (code != TSDB_CODE_SUCCESS) {
3,013!
2884
      return code;
×
2885
    }
2886
    pInfo->nullTupleSaved = true;
3,013✔
2887
  }
2888

2889
  return TSDB_CODE_SUCCESS;
24,613,795✔
2890
}
2891

2892
static bool firstLastTransferInfoImpl(SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst) {
55,435,767✔
2893
  if (!pInput->hasResult) {
55,435,767!
2894
    return false;
×
2895
  }
2896
  __compar_fn_t pkCompareFn = NULL;
55,435,767✔
2897
  if (pInput->pkData) {
55,435,767✔
2898
    pkCompareFn = getKeyComparFunc(pInput->pkType, (isFirst) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC);
7,744✔
2899
  }
2900
  if (pOutput->hasResult) {
55,442,670✔
2901
    if (isFirst) {
17,114,335✔
2902
      if (pInput->ts > pOutput->ts ||
704,427✔
2903
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
379,357✔
2904
        return false;
325,119✔
2905
      }
2906
    } else {
2907
      if (pInput->ts < pOutput->ts ||
16,409,908✔
2908
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
8,365,834✔
2909
        return false;
8,045,095✔
2910
      }
2911
    }
2912
  }
2913

2914
  pOutput->isNull = pInput->isNull;
47,072,456✔
2915
  pOutput->ts = pInput->ts;
47,072,456✔
2916
  pOutput->bytes = pInput->bytes;
47,072,456✔
2917
  pOutput->pkType = pInput->pkType;
47,072,456✔
2918

2919
  (void)memcpy(pOutput->buf, pInput->buf, pOutput->bytes);
47,072,456✔
2920
  if (pInput->pkData) {
47,072,456✔
2921
    pOutput->pkBytes = pInput->pkBytes;
7,398✔
2922
    (void)memcpy(pOutput->buf + pOutput->bytes, pInput->pkData, pOutput->pkBytes);
7,398✔
2923
    pOutput->pkData = pOutput->buf + pOutput->bytes;
7,398✔
2924
  }
2925
  return true;
47,072,456✔
2926
}
2927

2928
static int32_t firstLastTransferInfo(SqlFunctionCtx* pCtx, SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst,
55,434,579✔
2929
                                     int32_t rowIndex) {
2930
  if (firstLastTransferInfoImpl(pInput, pOutput, isFirst)) {
55,434,579✔
2931
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pOutput, false);
47,071,180✔
2932
    if (TSDB_CODE_SUCCESS != code) {
47,063,784!
2933
      return code;
×
2934
    }
2935
    pOutput->hasResult = true;
47,063,784✔
2936
  }
2937
  return TSDB_CODE_SUCCESS;
55,429,125✔
2938
}
2939

2940
static int32_t firstLastFunctionMergeImpl(SqlFunctionCtx* pCtx, bool isFirstQuery) {
39,030,607✔
2941
  SInputColumnInfoData* pInput = &pCtx->input;
39,030,607✔
2942
  SColumnInfoData*      pCol = pInput->pData[0];
39,030,607✔
2943

2944
  if (IS_NULL_TYPE(pCol->info.type)) {
39,030,607!
2945
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
2946
    return TSDB_CODE_SUCCESS;
×
2947
  }
2948

2949
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
39,030,607!
2950
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
2951
  }
2952

2953
  SFirstLastRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
39,030,607✔
2954

2955
  int32_t start = pInput->startRowIndex;
39,030,607✔
2956
  int32_t numOfElems = 0;
39,030,607✔
2957

2958
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
94,459,833✔
2959
    if (colDataIsNull_s(pCol, i)) {
110,886,094✔
2960
      continue;
1,028✔
2961
    }
2962
    char*          data = colDataGetData(pCol, i);
55,442,019!
2963
    SFirstLastRes* pInputInfo = (SFirstLastRes*)varDataVal(data);
55,442,019✔
2964
    if (pCtx->hasPrimaryKey) {
55,442,019✔
2965
      pInputInfo->pkData = pInputInfo->buf + pInputInfo->bytes;
7,744✔
2966
    } else {
2967
      pInputInfo->pkData = NULL;
55,434,275✔
2968
    }
2969

2970
    int32_t code = firstLastTransferInfo(pCtx, pInputInfo, pInfo, isFirstQuery, i);
55,442,019✔
2971
    if (code != TSDB_CODE_SUCCESS) {
55,428,198!
2972
      return code;
×
2973
    }
2974
    if (!numOfElems) {
55,428,198✔
2975
      numOfElems = pInputInfo->hasResult ? 1 : 0;
39,029,551✔
2976
    }
2977
  }
2978

2979
  if (numOfElems == 0) {
39,016,786✔
2980
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
1,028✔
2981
    if (code != TSDB_CODE_SUCCESS) {
1,028!
2982
      return code;
×
2983
    }
2984
    pInfo->nullTupleSaved = true;
1,028✔
2985
  }
2986

2987
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
39,016,786✔
2988
  return TSDB_CODE_SUCCESS;
39,016,786✔
2989
}
2990

2991
int32_t firstFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, true); }
9,999,284✔
2992

2993
int32_t lastFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, false); }
29,040,078✔
2994

2995
int32_t firstLastFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
93,814,925✔
2996
  int32_t          code = TSDB_CODE_SUCCESS;
93,814,925✔
2997
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
93,814,925✔
2998
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
93,814,925✔
2999
  if (NULL == pCol) {
93,598,186!
3000
    return TSDB_CODE_OUT_OF_RANGE;
×
3001
  }
3002

3003
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
93,598,186✔
3004
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
93,598,186✔
3005

3006
  SFirstLastRes* pRes = GET_ROWCELL_INTERBUF(pResInfo);
93,598,186✔
3007

3008
  if (pResInfo->isNullRes) {
93,598,186✔
3009
    colDataSetNULL(pCol, pBlock->info.rows);
9,384✔
3010
    return setNullSelectivityValue(pCtx, pBlock, pBlock->info.rows);
9,384✔
3011
  }
3012
  code = colDataSetVal(pCol, pBlock->info.rows, pRes->buf, pRes->isNull || pResInfo->isNullRes);
93,588,802!
3013
  if (TSDB_CODE_SUCCESS != code) {
93,352,348!
3014
    return code;
×
3015
  }
3016

3017
  // handle selectivity
3018
  code = setSelectivityValue(pCtx, pBlock, &pRes->pos, pBlock->info.rows);
93,352,348✔
3019

3020
  return code;
93,409,032✔
3021
}
3022

3023
int32_t firstLastPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
55,047,166✔
3024
  int32_t code = TSDB_CODE_SUCCESS;
55,047,166✔
3025

3026
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
55,047,166✔
3027
  SFirstLastRes*       pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
55,047,166✔
3028

3029
  int32_t resultBytes = getFirstLastInfoSize(pRes->bytes, pRes->pkBytes);
55,047,166✔
3030

3031
  // todo check for failure
3032
  char* res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
55,063,060!
3033
  if (NULL == res) {
55,381,670!
3034
    return terrno;
×
3035
  }
3036
  (void)memcpy(varDataVal(res), pRes, resultBytes);
55,381,670✔
3037

3038
  varDataSetLen(res, resultBytes);
55,381,670✔
3039

3040
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
55,381,670✔
3041
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
55,381,670✔
3042
  if (NULL == pCol) {
54,874,093!
3043
    taosMemoryFree(res);
×
3044
    return TSDB_CODE_OUT_OF_RANGE;
×
3045
  }
3046

3047
  if (pEntryInfo->numOfRes == 0) {
54,875,971✔
3048
    colDataSetNULL(pCol, pBlock->info.rows);
1,117!
3049
    code = setNullSelectivityValue(pCtx, pBlock, pBlock->info.rows);
1,117✔
3050
  } else {
3051
    code = colDataSetVal(pCol, pBlock->info.rows, res, false);
54,874,854✔
3052
    if (TSDB_CODE_SUCCESS != code) {
54,345,687!
3053
      taosMemoryFree(res);
×
3054
      return code;
×
3055
    }
3056
    code = setSelectivityValue(pCtx, pBlock, &pRes->pos, pBlock->info.rows);
54,345,687✔
3057
  }
3058
  taosMemoryFree(res);
54,484,124!
3059
  return code;
55,337,676✔
3060
}
3061

3062
int32_t lastCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
3063
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
3064
  SFirstLastRes*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
3065
  int32_t              bytes = pDBuf->bytes;
×
3066

3067
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
3068
  SFirstLastRes*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
3069

3070
  pDBuf->hasResult = firstLastTransferInfoImpl(pSBuf, pDBuf, false);
×
3071
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
3072
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
3073
  return TSDB_CODE_SUCCESS;
×
3074
}
3075

3076
static int32_t doSaveLastrow(SqlFunctionCtx* pCtx, char* pData, int32_t rowIndex, int64_t cts, SFirstLastRes* pInfo) {
71,258,785✔
3077
  SInputColumnInfoData* pInput = &pCtx->input;
71,258,785✔
3078
  SColumnInfoData*      pInputCol = pInput->pData[0];
71,258,785✔
3079
  SColumnInfoData*      pkCol = pInput->pPrimaryKey;
71,258,785✔
3080

3081
  if (colDataIsNull_s(pInputCol, rowIndex)) {
142,517,570✔
3082
    pInfo->isNull = true;
3,026✔
3083
  } else {
3084
    pInfo->isNull = false;
71,255,759✔
3085

3086
    if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
71,255,759!
3087
      pInfo->bytes = calcStrBytesByType(pInputCol->info.type, pData);
38,568,195✔
3088
      // if (pInputCol->info.type == TSDB_DATA_TYPE_JSON) {
3089
      //   pInfo->bytes = getJsonValueLen(pData);
3090
      // } else {
3091
      //   pInfo->bytes = varDataTLen(pData);
3092
      // }
3093
    }
3094

3095
    (void)memcpy(pInfo->buf, pData, pInfo->bytes);
71,238,402✔
3096
  }
3097

3098
  if (pCtx->hasPrimaryKey && !colDataIsNull_s(pkCol, rowIndex)) {
71,257,190✔
3099
    char* pkData = colDataGetData(pkCol, rowIndex);
15,760!
3100
    if (IS_VAR_DATA_TYPE(pInfo->pkType)) {
15,760!
3101
      pInfo->pkBytes = calcStrBytesByType(pInfo->pkType, pkData);
5,254✔
3102
    }
3103
    (void)memcpy(pInfo->buf + pInfo->bytes, pkData, pInfo->pkBytes);
15,764✔
3104
    pInfo->pkData = pInfo->buf + pInfo->bytes;
15,764✔
3105
  }
3106
  pInfo->ts = cts;
71,241,432✔
3107
  int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pInfo, false);
71,241,432✔
3108
  if (code != TSDB_CODE_SUCCESS) {
71,216,913!
3109
    return code;
×
3110
  }
3111

3112
  pInfo->hasResult = true;
71,216,913✔
3113

3114
  return TSDB_CODE_SUCCESS;
71,216,913✔
3115
}
3116

3117
int32_t lastRowFunction(SqlFunctionCtx* pCtx) {
71,703,204✔
3118
  int32_t numOfElems = 0;
71,703,204✔
3119

3120
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
71,703,204✔
3121
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
71,703,204✔
3122

3123
  SInputColumnInfoData* pInput = &pCtx->input;
71,703,204✔
3124
  SColumnInfoData*      pInputCol = pInput->pData[0];
71,703,204✔
3125

3126
  int32_t type = pInputCol->info.type;
71,703,204✔
3127
  int32_t bytes = pInputCol->info.bytes;
71,703,204✔
3128
  pInfo->bytes = bytes;
71,703,204✔
3129

3130
  if (IS_NULL_TYPE(type)) {
71,703,204✔
3131
    return TSDB_CODE_SUCCESS;
90✔
3132
  }
3133
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
71,703,114✔
3134
  pInfo->pkType = -1;
71,703,114✔
3135
  __compar_fn_t pkCompareFn = NULL;
71,703,114✔
3136
  if (pCtx->hasPrimaryKey) {
71,703,114✔
3137
    pInfo->pkType = pkCol->info.type;
80,329✔
3138
    pInfo->pkBytes = pkCol->info.bytes;
80,329✔
3139
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
80,329✔
3140
  }
3141
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
71,747,512!
3142
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
71,747,512!
3143

3144
  if (pCtx->order == TSDB_ORDER_ASC && !pCtx->hasPrimaryKey) {
71,747,512✔
3145
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
75,570,765!
3146
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
37,789,236✔
3147
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
37,789,236!
3148
      TSKEY cts = getRowPTs(pInput->pPTS, i);
37,789,236✔
3149
      numOfElems++;
37,789,236✔
3150

3151
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
37,789,236✔
3152
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
37,202,209✔
3153
        if (code != TSDB_CODE_SUCCESS) return code;
37,196,329!
3154
      }
3155

3156
      break;
37,783,356✔
3157
    }
3158
  } else if (!pCtx->hasPrimaryKey && pCtx->order == TSDB_ORDER_DESC) {
33,960,103✔
3159
    // the optimized version only valid if all tuples in one block are monotonious increasing or descreasing.
3160
    // this assumption is NOT always works if project operator exists in downstream.
3161
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
67,878,885!
3162
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
33,972,397✔
3163
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
33,972,397!
3164
      TSKEY cts = getRowPTs(pInput->pPTS, i);
33,972,397✔
3165
      numOfElems++;
33,972,397✔
3166

3167
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
33,972,397✔
3168
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
33,755,443✔
3169
        if (code != TSDB_CODE_SUCCESS) return code;
33,711,256!
3170
      }
3171
      break;
33,928,210✔
3172
    }
3173
  } else {
3174
    int64_t* pts = (int64_t*)pInput->pPTS->pData;
9,428✔
3175
    int      from = -1;
9,428✔
3176
    int32_t  i = -1;
9,428✔
3177
    while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
1,057,172✔
3178
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
1,047,719✔
3179
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
1,047,719!
3180
      TSKEY cts = pts[i];
1,047,719✔
3181

3182
      numOfElems++;
1,047,719✔
3183
      char* pkData = NULL;
1,047,719✔
3184
      if (pCtx->hasPrimaryKey) {
1,047,719✔
3185
        pkData = colDataGetData(pkCol, i);
277,765!
3186
      }
3187
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts ||
1,047,719✔
3188
          (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
735,667✔
3189
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
312,058✔
3190
        if (code != TSDB_CODE_SUCCESS) {
312,083!
3191
          return code;
×
3192
        }
3193
        pResInfo->numOfRes = 1;
312,083✔
3194
      }
3195
    }
3196
  }
3197

3198
  SET_VAL(pResInfo, numOfElems, 1);
71,772,169!
3199
  return TSDB_CODE_SUCCESS;
71,772,169✔
3200
}
3201

3202
bool getDiffFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
37,985✔
3203
  pEnv->calcMemSize = sizeof(SDiffInfo);
37,985✔
3204
  return true;
37,985✔
3205
}
3206

3207
int32_t diffFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
1,762,951✔
3208
  if (pResInfo->initialized) {
1,762,951✔
3209
    return TSDB_CODE_SUCCESS;
1,683,027✔
3210
  }
3211
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
79,924!
3212
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
3213
  }
3214
  SDiffInfo* pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
79,925✔
3215
  pDiffInfo->hasPrev = false;
79,925✔
3216
  pDiffInfo->isFirstRow = true;
79,925✔
3217
  pDiffInfo->prev.i64 = 0;
79,925✔
3218
  pDiffInfo->prevTs = -1;
79,925✔
3219
  if (pCtx->numOfParams > 1) {
79,925!
3220
    pDiffInfo->ignoreOption = pCtx->param[1].param.i;  // TODO set correct param
79,925✔
3221
  } else {
3222
    pDiffInfo->ignoreOption = 0;
×
3223
  }
3224
  return TSDB_CODE_SUCCESS;
79,925✔
3225
}
3226

3227
static int32_t doSetPrevVal(SDiffInfo* pDiffInfo, int32_t type, const char* pv, int64_t ts) {
2,757,524✔
3228
  switch (type) {
2,757,524!
3229
    case TSDB_DATA_TYPE_BOOL:
37✔
3230
      pDiffInfo->prev.i64 = *(bool*)pv ? 1 : 0;
37✔
3231
      break;
37✔
3232
    case TSDB_DATA_TYPE_UTINYINT:
553,435✔
3233
    case TSDB_DATA_TYPE_TINYINT:
3234
      pDiffInfo->prev.i64 = *(int8_t*)pv;
553,435✔
3235
      break;
553,435✔
3236
    case TSDB_DATA_TYPE_UINT:
42,829✔
3237
    case TSDB_DATA_TYPE_INT:
3238
      pDiffInfo->prev.i64 = *(int32_t*)pv;
42,829✔
3239
      break;
42,829✔
3240
    case TSDB_DATA_TYPE_USMALLINT:
148,383✔
3241
    case TSDB_DATA_TYPE_SMALLINT:
3242
      pDiffInfo->prev.i64 = *(int16_t*)pv;
148,383✔
3243
      break;
148,383✔
3244
    case TSDB_DATA_TYPE_TIMESTAMP:
629✔
3245
    case TSDB_DATA_TYPE_UBIGINT:
3246
    case TSDB_DATA_TYPE_BIGINT:
3247
      pDiffInfo->prev.i64 = *(int64_t*)pv;
629✔
3248
      break;
629✔
3249
    case TSDB_DATA_TYPE_FLOAT:
215,552✔
3250
      pDiffInfo->prev.d64 = *(float*)pv;
215,552✔
3251
      break;
215,552✔
3252
    case TSDB_DATA_TYPE_DOUBLE:
1,796,659✔
3253
      pDiffInfo->prev.d64 = *(double*)pv;
1,796,659✔
3254
      break;
1,796,659✔
3255
    default:
×
3256
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3257
  }
3258
  pDiffInfo->prevTs = ts;
2,757,524✔
3259
  pDiffInfo->hasPrev = true;
2,757,524✔
3260
  return TSDB_CODE_SUCCESS;
2,757,524✔
3261
}
3262

3263
static bool diffIsNegtive(SDiffInfo* pDiffInfo, int32_t type, const char* pv) {
8,338,002✔
3264
  switch (type) {
8,338,002!
3265
    case TSDB_DATA_TYPE_UINT: {
×
3266
      int64_t v = *(uint32_t*)pv;
×
3267
      return v < pDiffInfo->prev.i64;
×
3268
    }
3269
    case TSDB_DATA_TYPE_INT: {
2,638✔
3270
      int64_t v = *(int32_t*)pv;
2,638✔
3271
      return v < pDiffInfo->prev.i64;
2,638✔
3272
    }
3273
    case TSDB_DATA_TYPE_BOOL: {
×
3274
      int64_t v = *(bool*)pv;
×
3275
      return v < pDiffInfo->prev.i64;
×
3276
    }
3277
    case TSDB_DATA_TYPE_UTINYINT: {
×
3278
      int64_t v = *(uint8_t*)pv;
×
3279
      return v < pDiffInfo->prev.i64;
×
3280
    }
3281
    case TSDB_DATA_TYPE_TINYINT: {
1,666,947✔
3282
      int64_t v = *(int8_t*)pv;
1,666,947✔
3283
      return v < pDiffInfo->prev.i64;
1,666,947✔
3284
    }
3285
    case TSDB_DATA_TYPE_USMALLINT: {
×
3286
      int64_t v = *(uint16_t*)pv;
×
3287
      return v < pDiffInfo->prev.i64;
×
3288
    }
3289
    case TSDB_DATA_TYPE_SMALLINT: {
413,916✔
3290
      int64_t v = *(int16_t*)pv;
413,916✔
3291
      return v < pDiffInfo->prev.i64;
413,916✔
3292
    }
3293
    case TSDB_DATA_TYPE_UBIGINT: {
40✔
3294
      uint64_t v = *(uint64_t*)pv;
40✔
3295
      return v < (uint64_t)pDiffInfo->prev.i64;
40✔
3296
    }
3297
    case TSDB_DATA_TYPE_TIMESTAMP:
4,329✔
3298
    case TSDB_DATA_TYPE_BIGINT: {
3299
      int64_t v = *(int64_t*)pv;
4,329✔
3300
      return v < pDiffInfo->prev.i64;
4,329✔
3301
    }
3302
    case TSDB_DATA_TYPE_FLOAT: {
833,466✔
3303
      float v = *(float*)pv;
833,466✔
3304
      return v < pDiffInfo->prev.d64;
833,466✔
3305
    }
3306
    case TSDB_DATA_TYPE_DOUBLE: {
5,416,666✔
3307
      double v = *(double*)pv;
5,416,666✔
3308
      return v < pDiffInfo->prev.d64;
5,416,666✔
3309
    }
3310
    default:
×
3311
      return false;
×
3312
  }
3313

3314
  return false;
3315
}
3316

3317
static void tryToSetInt64(SDiffInfo* pDiffInfo, int32_t type, SColumnInfoData* pOutput, int64_t v, int32_t pos) {
1,437,432,575✔
3318
  bool isNegative = v < pDiffInfo->prev.i64;
1,437,432,575✔
3319
  if (type == TSDB_DATA_TYPE_UBIGINT) {
1,437,432,575✔
3320
    isNegative = (uint64_t)v < (uint64_t)pDiffInfo->prev.i64;
1,491✔
3321
  }
3322
  int64_t delta = v - pDiffInfo->prev.i64;
1,437,432,575✔
3323
  if (isNegative && ignoreNegative(pDiffInfo->ignoreOption)) {
1,437,432,575✔
3324
    colDataSetNull_f_s(pOutput, pos);
354,288✔
3325
    pOutput->hasNull = true;
354,288✔
3326
  } else {
3327
    colDataSetInt64(pOutput, pos, &delta);
1,437,078,287✔
3328
  }
3329
  pDiffInfo->prev.i64 = v;
1,437,432,575✔
3330
}
1,437,432,575✔
3331

3332
static void tryToSetDouble(SDiffInfo* pDiffInfo, SColumnInfoData* pOutput, double v, int32_t pos) {
4,685,161✔
3333
  double delta = v - pDiffInfo->prev.d64;
4,685,161✔
3334
  if (delta < 0 && ignoreNegative(pDiffInfo->ignoreOption)) {
4,685,161✔
3335
    colDataSetNull_f_s(pOutput, pos);
1,190,286✔
3336
  } else {
3337
    colDataSetDouble(pOutput, pos, &delta);
3,494,875✔
3338
  }
3339
  pDiffInfo->prev.d64 = v;
4,685,161✔
3340
}
4,685,161✔
3341

3342
static int32_t doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, SColumnInfoData* pOutput, int32_t pos,
1,441,861,036✔
3343
                            int64_t ts) {
3344
  if (!pDiffInfo->hasPrev) {
1,441,861,036✔
3345
    colDataSetNull_f_s(pOutput, pos);
500✔
3346
    return doSetPrevVal(pDiffInfo, type, pv, ts);
500✔
3347
  }
3348
  pDiffInfo->prevTs = ts;
1,441,860,536✔
3349
  switch (type) {
1,441,860,536!
3350
    case TSDB_DATA_TYPE_UINT: {
1,421✔
3351
      int64_t v = *(uint32_t*)pv;
1,421✔
3352
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
1,421✔
3353
      break;
1,421✔
3354
    }
3355
    case TSDB_DATA_TYPE_INT: {
20,959,850✔
3356
      int64_t v = *(int32_t*)pv;
20,959,850✔
3357
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
20,959,850✔
3358
      break;
20,959,850✔
3359
    }
3360
    case TSDB_DATA_TYPE_BOOL: {
878✔
3361
      int64_t v = *(bool*)pv;
878✔
3362
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
878✔
3363
      break;
878✔
3364
    }
3365
    case TSDB_DATA_TYPE_UTINYINT: {
675✔
3366
      int64_t v = *(uint8_t*)pv;
675✔
3367
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
675✔
3368
      break;
675✔
3369
    }
3370
    case TSDB_DATA_TYPE_TINYINT: {
1,123,537✔
3371
      int64_t v = *(int8_t*)pv;
1,123,537✔
3372
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
1,123,537✔
3373
      break;
1,123,537✔
3374
    }
3375
    case TSDB_DATA_TYPE_USMALLINT: {
675✔
3376
      int64_t v = *(uint16_t*)pv;
675✔
3377
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
675✔
3378
      break;
675✔
3379
    }
3380
    case TSDB_DATA_TYPE_SMALLINT: {
276,492✔
3381
      int64_t v = *(int16_t*)pv;
276,492✔
3382
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
276,492✔
3383
      break;
276,492✔
3384
    }
3385
    case TSDB_DATA_TYPE_TIMESTAMP:
1,415,111,447✔
3386
    case TSDB_DATA_TYPE_UBIGINT:
3387
    case TSDB_DATA_TYPE_BIGINT: {
3388
      int64_t v = *(int64_t*)pv;
1,415,111,447✔
3389
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
1,415,111,447✔
3390
      break;
1,415,111,447✔
3391
    }
3392
    case TSDB_DATA_TYPE_FLOAT: {
1,036,039✔
3393
      double v = *(float*)pv;
1,036,039✔
3394
      tryToSetDouble(pDiffInfo, pOutput, v, pos);
1,036,039✔
3395
      break;
1,036,039✔
3396
    }
3397
    case TSDB_DATA_TYPE_DOUBLE: {
3,649,122✔
3398
      double v = *(double*)pv;
3,649,122✔
3399
      tryToSetDouble(pDiffInfo, pOutput, v, pos);
3,649,122✔
3400
      break;
3,649,122✔
3401
    }
3402
    default:
×
3403
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3404
  }
3405
  pDiffInfo->hasPrev = true;
1,442,160,136✔
3406
  return TSDB_CODE_SUCCESS;
1,442,160,136✔
3407
}
3408

3409
// TODO: the primary key compare can be skipped for ordered pk if knonwn before
3410
// TODO: for desc ordered, pk shall select the smallest one for one ts. if across block boundaries.
3411
bool funcInputGetNextRowIndex(SInputColumnInfoData* pInput, int32_t from, bool firstOccur, int32_t* pRowIndex,
189,762,516✔
3412
                              int32_t* nextFrom) {
3413
  if (pInput->pPrimaryKey == NULL) {
189,762,516✔
3414
    if (from == -1) {
188,660,760✔
3415
      from = pInput->startRowIndex;
39,757,159✔
3416
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
148,903,601✔
3417
      return false;
39,746,178✔
3418
    }
3419
    *pRowIndex = from;
148,914,582✔
3420
    *nextFrom = from + 1;
148,914,582✔
3421
    return true;
148,914,582✔
3422
  } else {
3423
    if (from == -1) {
1,101,756✔
3424
      from = pInput->startRowIndex;
244,938✔
3425
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
856,818✔
3426
      return false;
245,043✔
3427
    }
3428
    TSKEY*           tsList = (int64_t*)pInput->pPTS->pData;
856,713✔
3429
    SColumnInfoData* pkCol = pInput->pPrimaryKey;
856,713✔
3430
    int8_t           pkType = pkCol->info.type;
856,713✔
3431
    int32_t          order = (firstOccur) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
856,713✔
3432
    __compar_fn_t    compareFunc = getKeyComparFunc(pkType, order);
856,713✔
3433
    int32_t          select = from;
865,833✔
3434
    char*            val = colDataGetData(pkCol, select);
865,833!
3435
    while (from < pInput->numOfRows + pInput->startRowIndex - 1 && tsList[from + 1] == tsList[from]) {
2,166,628✔
3436
      char* val1 = colDataGetData(pkCol, from + 1);
1,301,011!
3437
      if (compareFunc(val1, val) < 0) {
1,301,011✔
3438
        select = from + 1;
395,104✔
3439
        val = val1;
395,104✔
3440
      }
3441
      from = from + 1;
1,300,795✔
3442
    }
3443
    *pRowIndex = select;
865,617✔
3444
    *nextFrom = from + 1;
865,617✔
3445
    return true;
865,617✔
3446
  }
3447
}
3448

3449
bool getForecastConfEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
×
3450
  pEnv->calcMemSize = sizeof(double);
×
3451
  return true;
×
3452
}
3453

3454
int32_t diffResultIsNull(SqlFunctionCtx* pCtx, SFuncInputRow* pRow) {
1,444,796,288✔
3455
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,444,796,288✔
3456
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
1,444,796,288✔
3457

3458
  if (pRow->isDataNull || !pDiffInfo->hasPrev) {
1,444,796,288✔
3459
    return true;
130,119✔
3460
  } else if (ignoreNegative(pDiffInfo->ignoreOption)) {
1,444,666,169✔
3461
    return diffIsNegtive(pDiffInfo, pCtx->input.pData[0]->info.type, pRow->pData);
8,166,498✔
3462
  }
3463
  return false;
1,436,500,466✔
3464
}
3465

3466
bool isFirstRow(SqlFunctionCtx* pCtx, SFuncInputRow* pRow) {
1,441,857,889✔
3467
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,441,857,889✔
3468
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
1,441,857,889✔
3469
  return pDiffInfo->isFirstRow;
1,441,857,889✔
3470
}
3471

3472
int32_t trySetPreVal(SqlFunctionCtx* pCtx, SFuncInputRow* pRow) {
2,758,361✔
3473
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,758,361✔
3474
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,758,361✔
3475
  pDiffInfo->isFirstRow = false;
2,758,361✔
3476
  if (pRow->isDataNull) {
2,758,361✔
3477
    return TSDB_CODE_SUCCESS;
1,337✔
3478
  }
3479

3480
  SInputColumnInfoData* pInput = &pCtx->input;
2,757,024✔
3481
  SColumnInfoData*      pInputCol = pInput->pData[0];
2,757,024✔
3482
  int8_t                inputType = pInputCol->info.type;
2,757,024✔
3483

3484
  char* pv = pRow->pData;
2,757,024✔
3485
  return doSetPrevVal(pDiffInfo, inputType, pv, pRow->ts);
2,757,024✔
3486
}
3487

3488
int32_t setDoDiffResult(SqlFunctionCtx* pCtx, SFuncInputRow* pRow, int32_t pos) {
1,441,823,041✔
3489
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,441,823,041✔
3490
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
1,441,823,041✔
3491

3492
  SInputColumnInfoData* pInput = &pCtx->input;
1,441,823,041✔
3493
  SColumnInfoData*      pInputCol = pInput->pData[0];
1,441,823,041✔
3494
  int8_t                inputType = pInputCol->info.type;
1,441,823,041✔
3495
  SColumnInfoData*      pOutput = (SColumnInfoData*)pCtx->pOutput;
1,441,823,041✔
3496
  int32_t               code = TSDB_CODE_SUCCESS;
1,441,823,041✔
3497
  if (pRow->isDataNull) {
1,441,823,041✔
3498
    colDataSetNull_f_s(pOutput, pos);
53,346✔
3499
    pOutput->hasNull = true;
53,346✔
3500

3501
    // handle selectivity
3502
    if (pCtx->subsidiaries.num > 0) {
53,346✔
3503
      code = appendSelectivityCols(pCtx, pRow->block, pRow->rowIndex, pos);
203✔
3504
      if (code != TSDB_CODE_SUCCESS) {
203!
3505
        return code;
×
3506
      }
3507
    }
3508
    return TSDB_CODE_SUCCESS;
53,346✔
3509
  }
3510

3511
  char* pv = pRow->pData;
1,441,769,695✔
3512

3513
  if (pRow->ts == pDiffInfo->prevTs) {
1,441,769,695✔
3514
    return TSDB_CODE_FUNC_DUP_TIMESTAMP;
22✔
3515
  }
3516
  code = doHandleDiff(pDiffInfo, inputType, pv, pOutput, pos, pRow->ts);
1,441,769,673✔
3517
  if (code != TSDB_CODE_SUCCESS) {
1,442,050,348!
3518
    return code;
×
3519
  }
3520
  // handle selectivity
3521
  if (pCtx->subsidiaries.num > 0) {
1,442,050,348✔
3522
    code = appendSelectivityCols(pCtx, pRow->block, pRow->rowIndex, pos);
40,485,250✔
3523
    if (code != TSDB_CODE_SUCCESS) {
40,485,250!
3524
      return code;
×
3525
    }
3526
  }
3527

3528
  return TSDB_CODE_SUCCESS;
1,442,050,348✔
3529
}
3530

3531
int32_t diffFunction(SqlFunctionCtx* pCtx) { return TSDB_CODE_SUCCESS; }
1,724,963✔
3532

3533
int32_t diffFunctionByRow(SArray* pCtxArray) {
1,724,730✔
3534
  int32_t code = TSDB_CODE_SUCCESS;
1,724,730✔
3535
  int     diffColNum = pCtxArray->size;
1,724,730✔
3536
  if (diffColNum == 0) {
1,724,730!
3537
    return TSDB_CODE_SUCCESS;
×
3538
  }
3539
  int32_t numOfElems = 0;
1,724,730✔
3540

3541
  SArray* pRows = taosArrayInit_s(sizeof(SFuncInputRow), diffColNum);
1,724,730✔
3542
  if (NULL == pRows) {
1,724,730!
3543
    return terrno;
×
3544
  }
3545

3546
  bool keepNull = false;
1,724,730✔
3547
  for (int i = 0; i < diffColNum; ++i) {
3,449,698✔
3548
    SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
1,724,969✔
3549
    if (NULL == pCtx) {
1,724,969!
3550
      code = terrno;
×
3551
      goto _exit;
×
3552
    }
3553
    funcInputUpdate(pCtx);
1,724,969✔
3554
    SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,724,969✔
3555
    SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
1,724,969✔
3556
    if (!ignoreNull(pDiffInfo->ignoreOption)) {
1,724,969✔
3557
      keepNull = true;
1,697,200✔
3558
    }
3559
  }
3560

3561
  SqlFunctionCtx* pCtx0 = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, 0);
1,724,729✔
3562
  SFuncInputRow*  pRow0 = (SFuncInputRow*)taosArrayGet(pRows, 0);
1,724,725✔
3563
  if (NULL == pCtx0 || NULL == pRow0) {
1,724,725!
3564
    code = terrno;
×
3565
    goto _exit;
×
3566
  }
3567
  int32_t startOffset = pCtx0->offset;
1,724,726✔
3568
  bool    result = false;
1,724,726✔
3569
  while (1) {
1,444,757,386✔
3570
    code = funcInputGetNextRow(pCtx0, pRow0, &result);
1,446,482,112✔
3571
    if (TSDB_CODE_SUCCESS != code) {
1,446,514,004!
3572
      goto _exit;
×
3573
    }
3574
    if (!result) {
1,446,514,004✔
3575
      break;
1,724,707✔
3576
    }
3577
    bool hasNotNullValue = !diffResultIsNull(pCtx0, pRow0);
1,444,789,297✔
3578
    for (int i = 1; i < diffColNum; ++i) {
1,444,718,085✔
3579
      SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
7,381✔
3580
      SFuncInputRow*  pRow = (SFuncInputRow*)taosArrayGet(pRows, i);
7,381✔
3581
      if (NULL == pCtx || NULL == pRow) {
7,381!
3582
        code = terrno;
×
3583
        goto _exit;
×
3584
      }
3585
      code = funcInputGetNextRow(pCtx, pRow, &result);
7,381✔
3586
      if (TSDB_CODE_SUCCESS != code) {
7,381!
3587
        goto _exit;
×
3588
      }
3589
      if (!result) {
7,381!
3590
        // rows are not equal
3591
        code = TSDB_CODE_QRY_EXECUTOR_INTERNAL_ERROR;
×
3592
        goto _exit;
×
3593
      }
3594
      if (!diffResultIsNull(pCtx, pRow)) {
7,381✔
3595
        hasNotNullValue = true;
6,717✔
3596
      }
3597
    }
3598
    int32_t pos = startOffset + numOfElems;
1,444,710,704✔
3599

3600
    bool newRow = false;
1,444,710,704✔
3601
    for (int i = 0; i < diffColNum; ++i) {
2,147,483,647✔
3602
      SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
1,444,711,145✔
3603
      SFuncInputRow*  pRow = (SFuncInputRow*)taosArrayGet(pRows, i);
1,444,382,995✔
3604
      if (NULL == pCtx || NULL == pRow) {
1,444,353,075!
3605
        code = terrno;
×
3606
        goto _exit;
×
3607
      }
3608
      if ((keepNull || hasNotNullValue) && !isFirstRow(pCtx, pRow)) {
1,444,355,692✔
3609
        code = setDoDiffResult(pCtx, pRow, pos);
1,441,802,924✔
3610
        if (code != TSDB_CODE_SUCCESS) {
1,441,999,488✔
3611
          goto _exit;
22✔
3612
        }
3613
        newRow = true;
1,441,999,466✔
3614
      } else {
3615
        code = trySetPreVal(pCtx, pRow);
2,757,863✔
3616
        if (code != TSDB_CODE_SUCCESS) {
2,758,361!
3617
          goto _exit;
×
3618
        }
3619
      }
3620
    }
3621
    if (newRow) ++numOfElems;
1,444,757,386✔
3622
  }
3623

3624
  for (int i = 0; i < diffColNum; ++i) {
3,449,649✔
3625
    SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
1,724,942✔
3626
    if (NULL == pCtx) {
1,724,942!
3627
      code = terrno;
×
3628
      goto _exit;
×
3629
    }
3630
    SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,724,942✔
3631
    pResInfo->numOfRes = numOfElems;
1,724,942✔
3632
  }
3633

3634
_exit:
1,724,707✔
3635
  if (pRows) {
1,724,729!
3636
    taosArrayDestroy(pRows);
1,724,729✔
3637
    pRows = NULL;
1,724,730✔
3638
  }
3639
  return code;
1,724,730✔
3640
}
3641

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

3644
bool getTopBotFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
87,811✔
3645
  SValueNode* pkNode = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
87,811✔
3646
  pEnv->calcMemSize = sizeof(STopBotRes) + pkNode->datum.i * sizeof(STopBotResItem);
87,852✔
3647
  return true;
87,852✔
3648
}
3649

3650
int32_t topBotFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
36,714,380✔
3651
  if (pResInfo->initialized) {
36,714,380!
3652
    return TSDB_CODE_SUCCESS;
×
3653
  }
3654
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
36,714,380!
3655
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
3656
  }
3657

3658
  STopBotRes*           pRes = GET_ROWCELL_INTERBUF(pResInfo);
36,748,871✔
3659
  SInputColumnInfoData* pInput = &pCtx->input;
36,748,871✔
3660

3661
  pRes->maxSize = pCtx->param[1].param.i;
36,748,871✔
3662

3663
  pRes->nullTupleSaved = false;
36,748,871✔
3664
  pRes->nullTuplePos.pageId = -1;
36,748,871✔
3665
  return TSDB_CODE_SUCCESS;
36,748,871✔
3666
}
3667

3668
static STopBotRes* getTopBotOutputInfo(SqlFunctionCtx* pCtx) {
174,645,547✔
3669
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
174,645,547✔
3670
  STopBotRes*          pRes = GET_ROWCELL_INTERBUF(pResInfo);
174,645,547✔
3671
  pRes->pItems = (STopBotResItem*)((char*)pRes + sizeof(STopBotRes));
174,645,547✔
3672

3673
  return pRes;
174,645,547✔
3674
}
3675

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

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

3681
int32_t topFunction(SqlFunctionCtx* pCtx) {
26,207,178✔
3682
  int32_t              numOfElems = 0;
26,207,178✔
3683
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
26,207,178✔
3684

3685
  SInputColumnInfoData* pInput = &pCtx->input;
26,207,178✔
3686
  SColumnInfoData*      pCol = pInput->pData[0];
26,207,178✔
3687

3688
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
26,207,178✔
3689
  pRes->type = pInput->pData[0]->info.type;
26,206,612✔
3690

3691
  int32_t start = pInput->startRowIndex;
26,206,612✔
3692
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
84,507,814✔
3693
    if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
58,285,680!
3694
      continue;
19,644✔
3695
    }
3696

3697
    numOfElems++;
58,266,036✔
3698
    char*   data = colDataGetData(pCol, i);
58,266,036!
3699
    int32_t code = doAddIntoResult(pCtx, data, i, pCtx->pSrcBlock, pRes->type, pInput->uid, pResInfo, true);
58,266,036✔
3700
    if (code != TSDB_CODE_SUCCESS) {
58,281,558!
3701
      return code;
×
3702
    }
3703
  }
3704

3705
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pRes->nullTupleSaved) {
26,222,134✔
3706
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pRes->nullTuplePos);
3,208✔
3707
    if (code != TSDB_CODE_SUCCESS) {
3,208!
3708
      return code;
×
3709
    }
3710
    pRes->nullTupleSaved = true;
3,208✔
3711
  }
3712
  return TSDB_CODE_SUCCESS;
26,222,134✔
3713
}
3714

3715
int32_t bottomFunction(SqlFunctionCtx* pCtx) {
11,088,679✔
3716
  int32_t              numOfElems = 0;
11,088,679✔
3717
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
11,088,679✔
3718

3719
  SInputColumnInfoData* pInput = &pCtx->input;
11,088,679✔
3720
  SColumnInfoData*      pCol = pInput->pData[0];
11,088,679✔
3721

3722
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
11,088,679✔
3723
  pRes->type = pInput->pData[0]->info.type;
11,088,452✔
3724

3725
  int32_t start = pInput->startRowIndex;
11,088,452✔
3726
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
53,997,230✔
3727
    if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
42,891,200✔
3728
      continue;
16,880✔
3729
    }
3730

3731
    numOfElems++;
42,874,320✔
3732
    char*   data = colDataGetData(pCol, i);
42,874,320!
3733
    int32_t code = doAddIntoResult(pCtx, data, i, pCtx->pSrcBlock, pRes->type, pInput->uid, pResInfo, false);
42,874,320✔
3734
    if (code != TSDB_CODE_SUCCESS) {
42,891,898!
3735
      return code;
×
3736
    }
3737
  }
3738

3739
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pRes->nullTupleSaved) {
11,106,030✔
3740
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pRes->nullTuplePos);
63✔
3741
    if (code != TSDB_CODE_SUCCESS) {
63!
3742
      return code;
×
3743
    }
3744
    pRes->nullTupleSaved = true;
63✔
3745
  }
3746

3747
  return TSDB_CODE_SUCCESS;
11,106,030✔
3748
}
3749

3750
static int32_t topBotResComparFn(const void* p1, const void* p2, const void* param) {
650,246,726✔
3751
  uint16_t type = *(uint16_t*)param;
650,246,726✔
3752

3753
  STopBotResItem* val1 = (STopBotResItem*)p1;
650,246,726✔
3754
  STopBotResItem* val2 = (STopBotResItem*)p2;
650,246,726✔
3755

3756
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
650,246,726!
3757
    if (val1->v.i == val2->v.i) {
536,109,301✔
3758
      return 0;
217,173✔
3759
    }
3760

3761
    return (val1->v.i > val2->v.i) ? 1 : -1;
535,892,128✔
3762
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
114,137,425✔
3763
    if (val1->v.u == val2->v.u) {
740,974✔
3764
      return 0;
152,637✔
3765
    }
3766

3767
    return (val1->v.u > val2->v.u) ? 1 : -1;
588,337✔
3768
  } else if (TSDB_DATA_TYPE_FLOAT == type) {
113,396,451✔
3769
    if (val1->v.f == val2->v.f) {
6,797,561✔
3770
      return 0;
63✔
3771
    }
3772

3773
    return (val1->v.f > val2->v.f) ? 1 : -1;
6,797,498✔
3774
  }
3775

3776
  if (val1->v.d == val2->v.d) {
106,598,890✔
3777
    return 0;
11✔
3778
  }
3779

3780
  return (val1->v.d > val2->v.d) ? 1 : -1;
106,598,879✔
3781
}
3782

3783
int32_t doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, uint16_t type,
101,095,440✔
3784
                        uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery) {
3785
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
101,095,440✔
3786
  int32_t     code = TSDB_CODE_SUCCESS;
101,063,803✔
3787

3788
  SVariant val = {0};
101,063,803✔
3789
  TAOS_CHECK_RETURN(taosVariantCreateFromBinary(&val, pData, tDataTypes[type].bytes, type));
101,063,803!
3790

3791
  STopBotResItem* pItems = pRes->pItems;
101,125,025✔
3792

3793
  // not full yet
3794
  if (pEntryInfo->numOfRes < pRes->maxSize) {
101,125,025✔
3795
    STopBotResItem* pItem = &pItems[pEntryInfo->numOfRes];
65,953,969✔
3796
    pItem->v = val;
65,953,969✔
3797
    pItem->uid = uid;
65,953,969✔
3798

3799
    // save the data of this tuple
3800
    if (pCtx->subsidiaries.num > 0) {
65,953,969✔
3801
      code = saveTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
29,171,555✔
3802
      if (code != TSDB_CODE_SUCCESS) {
29,151,805!
3803
        return code;
×
3804
      }
3805
    }
3806
#ifdef BUF_PAGE_DEBUG
3807
    qDebug("page_saveTuple i:%d, item:%p,pageId:%d, offset:%d\n", pEntryInfo->numOfRes, pItem, pItem->tuplePos.pageId,
3808
           pItem->tuplePos.offset);
3809
#endif
3810
    // allocate the buffer and keep the data of this row into the new allocated buffer
3811
    pEntryInfo->numOfRes++;
65,934,219✔
3812
    code = taosheapsort((void*)pItems, sizeof(STopBotResItem), pEntryInfo->numOfRes, (const void*)&type,
65,934,219✔
3813
                        topBotResComparFn, !isTopQuery);
65,934,219✔
3814
    if (code != TSDB_CODE_SUCCESS) {
66,000,621!
3815
      return code;
×
3816
    }
3817
  } else {  // replace the minimum value in the result
3818
    if ((isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i > pItems[0].v.i) ||
35,171,056!
3819
                        (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u > pItems[0].v.u) ||
15,000,420!
3820
                        (TSDB_DATA_TYPE_FLOAT == type && val.f > pItems[0].v.f) ||
14,908,853✔
3821
                        (TSDB_DATA_TYPE_DOUBLE == type && val.d > pItems[0].v.d))) ||
14,668,696✔
3822
        (!isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i < pItems[0].v.i) ||
30,393,592!
3823
                         (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u < pItems[0].v.u) ||
12,398,651!
3824
                         (TSDB_DATA_TYPE_FLOAT == type && val.f < pItems[0].v.f) ||
12,396,541✔
3825
                         (TSDB_DATA_TYPE_DOUBLE == type && val.d < pItems[0].v.d)))) {
12,395,356!
3826
      // replace the old data and the coresponding tuple data
3827
      STopBotResItem* pItem = &pItems[0];
9,860,820✔
3828
      pItem->v = val;
9,860,820✔
3829
      pItem->uid = uid;
9,860,820✔
3830

3831
      // save the data of this tuple by over writing the old data
3832
      if (pCtx->subsidiaries.num > 0) {
9,860,820✔
3833
        code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
5,675,081✔
3834
        if (code != TSDB_CODE_SUCCESS) {
5,673,276!
3835
          return code;
×
3836
        }
3837
      }
3838
#ifdef BUF_PAGE_DEBUG
3839
      qDebug("page_copyTuple pageId:%d, offset:%d", pItem->tuplePos.pageId, pItem->tuplePos.offset);
3840
#endif
3841
      code = taosheapadjust((void*)pItems, sizeof(STopBotResItem), 0, pEntryInfo->numOfRes - 1, (const void*)&type,
9,859,015✔
3842
                            topBotResComparFn, NULL, !isTopQuery);
9,859,015✔
3843
      if (code != TSDB_CODE_SUCCESS) {
9,803,924!
3844
        return code;
×
3845
      }
3846
    }
3847
  }
3848

3849
  return TSDB_CODE_SUCCESS;
101,114,781✔
3850
}
3851

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

3863
  int32_t offset = 0;
193,338,833✔
3864
  for (int32_t i = 0; i < pSubsidiaryies->num; ++i) {
386,071,646✔
3865
    SqlFunctionCtx* pc = pSubsidiaryies->pCtx[i];
193,372,496✔
3866

3867
    // group_key function has its own process function
3868
    // do not process there
3869
    if (fmIsGroupKeyFunc(pc->functionId)) {
193,372,496!
3870
      continue;
×
3871
    }
3872

3873
    SFunctParam* pFuncParam = &pc->pExpr->base.pParam[0];
193,352,348✔
3874
    int32_t      srcSlotId = pFuncParam->pCol->slotId;
193,352,348✔
3875

3876
    SColumnInfoData* pCol = taosArrayGet(pSrcBlock->pDataBlock, srcSlotId);
193,352,348✔
3877
    if (NULL == pCol) {
192,545,459!
3878
      return TSDB_CODE_OUT_OF_RANGE;
×
3879
    }
3880
    if ((nullList[i] = colDataIsNull_s(pCol, rowIndex)) == true) {
385,090,918✔
3881
      offset += pCol->info.bytes;
709✔
3882
      continue;
709✔
3883
    }
3884

3885
    char* p = colDataGetData(pCol, rowIndex);
192,544,750!
3886
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
192,544,750!
UNCOV
3887
      int32_t bytes = calcStrBytesByType(pCol->info.type, p);
×
3888
      (void)memcpy(pStart + offset, p, bytes);
46,562✔
3889
    } else {
3890
      (void)memcpy(pStart + offset, p, pCol->info.bytes);
192,685,542✔
3891
    }
3892

3893
    offset += pCol->info.bytes;
192,732,104✔
3894
  }
3895

3896
  *res = buf;
192,699,150✔
3897
  return TSDB_CODE_SUCCESS;
192,699,150✔
3898
}
3899

3900
static int32_t doSaveTupleData(SSerializeDataHandle* pHandle, const void* pBuf, size_t length, SWinKey* key,
156,469,369✔
3901
                               STuplePos* pPos, SFunctionStateStore* pStore) {
3902
  STuplePos p = {0};
156,469,369✔
3903
  if (pHandle->pBuf != NULL) {
156,469,369!
3904
    SFilePage* pPage = NULL;
156,529,568✔
3905

3906
    if (pHandle->currentPage == -1) {
156,529,568✔
3907
      pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
680,341✔
3908
      if (pPage == NULL) {
680,370!
3909
        return terrno;
×
3910
      }
3911
      pPage->num = sizeof(SFilePage);
680,371✔
3912
    } else {
3913
      pPage = getBufPage(pHandle->pBuf, pHandle->currentPage);
155,849,227✔
3914
      if (pPage == NULL) {
155,875,958!
3915
        return terrno;
×
3916
      }
3917
      if (pPage->num + length > getBufPageSize(pHandle->pBuf)) {
155,875,958✔
3918
        // current page is all used, let's prepare a new buffer page
3919
        releaseBufPage(pHandle->pBuf, pPage);
670,536✔
3920
        pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
670,536✔
3921
        if (pPage == NULL) {
670,537!
3922
          return terrno;
×
3923
        }
3924
        pPage->num = sizeof(SFilePage);
670,537✔
3925
      }
3926
    }
3927

3928
    p = (STuplePos){.pageId = pHandle->currentPage, .offset = pPage->num};
156,542,525✔
3929
    (void)memcpy(pPage->data + pPage->num, pBuf, length);
156,542,525✔
3930

3931
    pPage->num += length;
156,542,525✔
3932
    setBufPageDirty(pPage, true);
156,542,525✔
3933
    releaseBufPage(pHandle->pBuf, pPage);
156,498,775✔
3934
  } else {  // other tuple save policy
3935
    if (pStore->streamStateFuncPut(pHandle->pState, key, pBuf, length) >= 0) {
×
3936
      p.streamTupleKey = *key;
×
3937
    }
3938
  }
3939

3940
  *pPos = p;
156,454,694✔
3941
  return TSDB_CODE_SUCCESS;
156,454,694✔
3942
}
3943

3944
int32_t saveTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
140,308,233✔
3945
  int32_t code = prepareBuf(pCtx);
140,308,233✔
3946
  if (TSDB_CODE_SUCCESS != code) {
140,289,880!
3947
    return code;
×
3948
  }
3949

3950
  SWinKey key = {0};
140,289,880✔
3951
  if (pCtx->saveHandle.pBuf == NULL) {
140,289,880!
3952
    SColumnInfoData* pColInfo = taosArrayGet(pSrcBlock->pDataBlock, pCtx->saveHandle.pState->tsIndex);
×
3953
    if (NULL == pColInfo) {
×
3954
      return TSDB_CODE_OUT_OF_RANGE;
×
3955
    }
3956
    if (pColInfo->info.type != TSDB_DATA_TYPE_TIMESTAMP) {
×
3957
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3958
    }
3959
    key.groupId = pSrcBlock->info.id.groupId;
×
3960
    key.ts = *(int64_t*)colDataGetData(pColInfo, rowIndex);
×
3961
    key.numInGroup = pCtx->pExpr->pExpr->_function.bindExprID;
×
3962
  }
3963

3964
  char* buf = NULL;
140,289,880✔
3965
  code = serializeTupleData(pSrcBlock, rowIndex, &pCtx->subsidiaries, pCtx->subsidiaries.buf, &buf);
140,289,880✔
3966
  if (TSDB_CODE_SUCCESS != code) {
139,968,690!
3967
    return code;
×
3968
  }
3969
  return doSaveTupleData(&pCtx->saveHandle, buf, pCtx->subsidiaries.rowLen, &key, pPos, pCtx->pStore);
139,968,690✔
3970
}
3971

3972
static int32_t doUpdateTupleData(SSerializeDataHandle* pHandle, const void* pBuf, size_t length, STuplePos* pPos,
53,102,703✔
3973
                                 SFunctionStateStore* pStore) {
3974
  if (pHandle->pBuf != NULL) {
53,102,703!
3975
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
53,102,857✔
3976
    if (pPage == NULL) {
53,104,259!
3977
      return terrno;
×
3978
    }
3979
    (void)memcpy(pPage->data + pPos->offset, pBuf, length);
53,104,259✔
3980
    setBufPageDirty(pPage, true);
53,104,259✔
3981
    releaseBufPage(pHandle->pBuf, pPage);
53,101,541✔
3982
  } else {
3983
    int32_t code = pStore->streamStateFuncPut(pHandle->pState, &pPos->streamTupleKey, pBuf, length);
×
3984
    if (TSDB_CODE_SUCCESS != code) {
×
3985
      return code;
×
3986
    }
3987
  }
3988

3989
  return TSDB_CODE_SUCCESS;
53,097,909✔
3990
}
3991

3992
int32_t updateTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
53,111,940✔
3993
  int32_t code = prepareBuf(pCtx);
53,111,940✔
3994
  if (TSDB_CODE_SUCCESS != code) {
53,110,357!
3995
    return code;
×
3996
  }
3997

3998
  char* buf = NULL;
53,110,357✔
3999
  code = serializeTupleData(pSrcBlock, rowIndex, &pCtx->subsidiaries, pCtx->subsidiaries.buf, &buf);
53,110,357✔
4000
  if (TSDB_CODE_SUCCESS != code) {
53,094,211!
4001
    return code;
×
4002
  }
4003
  return doUpdateTupleData(&pCtx->saveHandle, buf, pCtx->subsidiaries.rowLen, pPos, pCtx->pStore);
53,094,211✔
4004
}
4005

4006
static int32_t doLoadTupleData(SSerializeDataHandle* pHandle, const STuplePos* pPos, SFunctionStateStore* pStore,
133,707,389✔
4007
                               char** value) {
4008
  if (pHandle->pBuf != NULL) {
133,707,389!
4009
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
133,751,664✔
4010
    if (pPage == NULL) {
134,260,736!
4011
      *value = NULL;
×
4012
      return terrno;
×
4013
    }
4014
    *value = pPage->data + pPos->offset;
134,260,736✔
4015
    releaseBufPage(pHandle->pBuf, pPage);
134,260,736✔
4016
    return TSDB_CODE_SUCCESS;
134,222,877✔
4017
  } else {
4018
    *value = NULL;
×
4019
    int32_t vLen;
4020
    int32_t code = pStore->streamStateFuncGet(pHandle->pState, &pPos->streamTupleKey, (void**)(value), &vLen);
×
4021
    if (TSDB_CODE_SUCCESS != code) {
×
4022
      return code;
×
4023
    }
4024
    return TSDB_CODE_SUCCESS;
×
4025
  }
4026
}
4027

4028
int32_t loadTupleData(SqlFunctionCtx* pCtx, const STuplePos* pPos, char** value) {
133,358,499✔
4029
  return doLoadTupleData(&pCtx->saveHandle, pPos, pCtx->pStore, value);
133,358,499✔
4030
}
4031

4032
int32_t topBotFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
36,581,242✔
4033
  int32_t code = TSDB_CODE_SUCCESS;
36,581,242✔
4034

4035
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
36,581,242✔
4036
  STopBotRes*          pRes = getTopBotOutputInfo(pCtx);
36,581,242✔
4037

4038
  int16_t type = pCtx->pExpr->base.resSchema.type;
36,582,516✔
4039
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
36,582,516✔
4040

4041
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
36,582,516✔
4042
  if (NULL == pCol) {
36,493,017!
4043
    return TSDB_CODE_OUT_OF_RANGE;
×
4044
  }
4045

4046
  // todo assign the tag value and the corresponding row data
4047
  int32_t currentRow = pBlock->info.rows;
36,493,017✔
4048
  if (pEntryInfo->numOfRes <= 0) {
36,493,017✔
4049
    colDataSetNULL(pCol, currentRow);
336!
4050
    code = setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, currentRow);
336✔
4051
    return code;
336✔
4052
  }
4053
  for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
101,178,318✔
4054
    STopBotResItem* pItem = &pRes->pItems[i];
64,959,282✔
4055
    code = colDataSetVal(pCol, currentRow, (const char*)&pItem->v.i, false);
64,959,282✔
4056
    if (TSDB_CODE_SUCCESS != code) {
64,648,353!
4057
      return code;
×
4058
    }
4059
#ifdef BUF_PAGE_DEBUG
4060
    qDebug("page_finalize i:%d,item:%p,pageId:%d, offset:%d\n", i, pItem, pItem->tuplePos.pageId,
4061
           pItem->tuplePos.offset);
4062
#endif
4063
    code = setSelectivityValue(pCtx, pBlock, &pRes->pItems[i].tuplePos, currentRow);
64,648,353✔
4064
    if (TSDB_CODE_SUCCESS != code) {
64,685,637!
4065
      return code;
×
4066
    }
4067
    currentRow += 1;
64,685,637✔
4068
  }
4069

4070
  return code;
36,219,036✔
4071
}
4072

4073
int32_t addResult(SqlFunctionCtx* pCtx, STopBotResItem* pSourceItem, int16_t type, bool isTopQuery) {
×
4074
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
×
4075
  STopBotRes*          pRes = getTopBotOutputInfo(pCtx);
×
4076
  STopBotResItem*      pItems = pRes->pItems;
×
4077
  int32_t              code = TSDB_CODE_SUCCESS;
×
4078

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

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

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

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

4146
int32_t getSpreadInfoSize() { return (int32_t)sizeof(SSpreadInfo); }
910,953✔
4147

4148
bool getSpreadFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
69,821✔
4149
  pEnv->calcMemSize = sizeof(SSpreadInfo);
69,821✔
4150
  return true;
69,821✔
4151
}
4152

4153
int32_t spreadFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
3,144,974✔
4154
  if (pResultInfo->initialized) {
3,144,974!
4155
    return TSDB_CODE_SUCCESS;
×
4156
  }
4157
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
3,144,974!
4158
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
4159
  }
4160

4161
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
3,144,974✔
4162
  SET_DOUBLE_VAL(&pInfo->min, DBL_MAX);
3,144,974✔
4163
  SET_DOUBLE_VAL(&pInfo->max, -DBL_MAX);
3,144,974✔
4164
  pInfo->hasResult = false;
3,144,974✔
4165
  return TSDB_CODE_SUCCESS;
3,144,974✔
4166
}
4167

4168
int32_t spreadFunction(SqlFunctionCtx* pCtx) {
2,267,755✔
4169
  int32_t numOfElems = 0;
2,267,755✔
4170

4171
  // Only the pre-computing information loaded and actual data does not loaded
4172
  SInputColumnInfoData* pInput = &pCtx->input;
2,267,755✔
4173
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
2,267,755✔
4174
  int32_t               type = pInput->pData[0]->info.type;
2,267,755✔
4175

4176
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,267,755✔
4177

4178
  if (pInput->colDataSMAIsSet) {
2,267,755!
4179
    numOfElems = pInput->numOfRows - pAgg->numOfNull;
×
4180
    if (numOfElems == 0) {
×
4181
      goto _spread_over;
×
4182
    }
4183
    double tmin = 0.0, tmax = 0.0;
×
4184
    if (IS_SIGNED_NUMERIC_TYPE(type) || IS_TIMESTAMP_TYPE(type)) {
×
4185
      tmin = (double)GET_INT64_VAL(&pAgg->min);
×
4186
      tmax = (double)GET_INT64_VAL(&pAgg->max);
×
4187
    } else if (IS_FLOAT_TYPE(type)) {
×
4188
      tmin = GET_DOUBLE_VAL(&pAgg->min);
×
4189
      tmax = GET_DOUBLE_VAL(&pAgg->max);
×
4190
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
×
4191
      tmin = (double)GET_UINT64_VAL(&pAgg->min);
×
4192
      tmax = (double)GET_UINT64_VAL(&pAgg->max);
×
4193
    }
4194

4195
    if (GET_DOUBLE_VAL(&pInfo->min) > tmin) {
×
4196
      SET_DOUBLE_VAL(&pInfo->min, tmin);
×
4197
    }
4198

4199
    if (GET_DOUBLE_VAL(&pInfo->max) < tmax) {
×
4200
      SET_DOUBLE_VAL(&pInfo->max, tmax);
×
4201
    }
4202

4203
  } else {  // computing based on the true data block
4204
    SColumnInfoData* pCol = pInput->pData[0];
2,267,755✔
4205

4206
    int32_t start = pInput->startRowIndex;
2,267,755✔
4207
    // check the valid data one by one
4208
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
11,710,246✔
4209
      if (colDataIsNull_f(pCol, i)) {
9,442,682✔
4210
        continue;
1,402,790✔
4211
      }
4212

4213
      char* data = colDataGetData(pCol, i);
8,039,892!
4214

4215
      double v = 0;
8,039,892✔
4216
      GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pCol->info));
8,039,892!
4217
      if (v < GET_DOUBLE_VAL(&pInfo->min)) {
8,039,701✔
4218
        SET_DOUBLE_VAL(&pInfo->min, v);
2,529,808✔
4219
      }
4220

4221
      if (v > GET_DOUBLE_VAL(&pInfo->max)) {
8,039,701✔
4222
        SET_DOUBLE_VAL(&pInfo->max, v);
3,159,723✔
4223
      }
4224

4225
      numOfElems += 1;
8,039,701✔
4226
    }
4227
  }
4228

4229
_spread_over:
2,267,564✔
4230
  // data in the check operation are all null, not output
4231
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
2,267,564✔
4232
  if (numOfElems > 0) {
2,267,564✔
4233
    pInfo->hasResult = true;
2,245,421✔
4234
  }
4235

4236
  return TSDB_CODE_SUCCESS;
2,267,564✔
4237
}
4238

4239
static void spreadTransferInfo(SSpreadInfo* pInput, SSpreadInfo* pOutput) {
910,792✔
4240
  pOutput->hasResult = pInput->hasResult;
910,792✔
4241
  if (pInput->max > pOutput->max) {
910,792✔
4242
    pOutput->max = pInput->max;
906,633✔
4243
  }
4244

4245
  if (pInput->min < pOutput->min) {
910,792✔
4246
    pOutput->min = pInput->min;
906,624✔
4247
  }
4248
}
910,792✔
4249

4250
int32_t spreadFunctionMerge(SqlFunctionCtx* pCtx) {
906,779✔
4251
  SInputColumnInfoData* pInput = &pCtx->input;
906,779✔
4252
  SColumnInfoData*      pCol = pInput->pData[0];
906,779✔
4253

4254
  if (IS_NULL_TYPE(pCol->info.type)) {
906,779!
4255
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
4256
    return TSDB_CODE_SUCCESS;
×
4257
  }
4258

4259
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
906,779!
4260
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
4261
  }
4262

4263
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
906,779✔
4264

4265
  int32_t start = pInput->startRowIndex;
906,779✔
4266
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
1,817,599✔
4267
    if (colDataIsNull_s(pCol, i)) continue;
1,821,640!
4268
    char*        data = colDataGetData(pCol, i);
910,820!
4269
    SSpreadInfo* pInputInfo = (SSpreadInfo*)varDataVal(data);
910,820✔
4270
    if (pInputInfo->hasResult) {
910,820✔
4271
      spreadTransferInfo(pInputInfo, pInfo);
910,792✔
4272
    }
4273
  }
4274

4275
  if (pInfo->hasResult) {
906,779✔
4276
    GET_RES_INFO(pCtx)->numOfRes = 1;
906,751✔
4277
  }
4278

4279
  return TSDB_CODE_SUCCESS;
906,779✔
4280
}
4281

4282
int32_t spreadFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
2,218,738✔
4283
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,218,738✔
4284
  if (pInfo->hasResult == true) {
2,218,738✔
4285
    SET_DOUBLE_VAL(&pInfo->result, pInfo->max - pInfo->min);
2,196,537✔
4286
  } else {
4287
    GET_RES_INFO(pCtx)->isNullRes = 1;
22,201✔
4288
  }
4289
  return functionFinalize(pCtx, pBlock);
2,218,738✔
4290
}
4291

4292
int32_t spreadPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
910,953✔
4293
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
910,953✔
4294
  SSpreadInfo*         pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
910,953✔
4295
  int32_t              resultBytes = getSpreadInfoSize();
910,953✔
4296
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
910,953!
4297

4298
  if (NULL == res) {
910,953!
4299
    return terrno;
×
4300
  }
4301
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
910,953✔
4302
  varDataSetLen(res, resultBytes);
910,953✔
4303

4304
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
910,953✔
4305
  int32_t          code = TSDB_CODE_SUCCESS;
910,953✔
4306
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
910,953✔
4307
  if (NULL == pCol) {
910,953!
4308
    code = terrno;
×
4309
    goto _exit;
×
4310
  }
4311

4312
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
910,953✔
4313
  if (TSDB_CODE_SUCCESS != code) {
910,953!
4314
    goto _exit;
×
4315
  }
4316

4317
_exit:
910,953✔
4318
  taosMemoryFree(res);
910,953!
4319
  return code;
910,953✔
4320
}
4321

4322
int32_t spreadCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4323
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
4324
  SSpreadInfo*         pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
4325

4326
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4327
  SSpreadInfo*         pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
4328
  spreadTransferInfo(pSBuf, pDBuf);
×
4329
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
4330
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
4331
  return TSDB_CODE_SUCCESS;
×
4332
}
4333

4334
int32_t getElapsedInfoSize() { return (int32_t)sizeof(SElapsedInfo); }
×
4335

4336
bool getElapsedFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
94,395✔
4337
  pEnv->calcMemSize = sizeof(SElapsedInfo);
94,395✔
4338
  return true;
94,395✔
4339
}
4340

4341
int32_t elapsedFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
9,503,507✔
4342
  if (pResultInfo->initialized) {
9,503,507!
4343
    return TSDB_CODE_SUCCESS;
×
4344
  }
4345
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
9,503,507!
4346
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
4347
  }
4348

4349
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
9,503,505✔
4350
  pInfo->result = 0;
9,503,505✔
4351
  pInfo->min = TSKEY_MAX;
9,503,505✔
4352
  pInfo->max = 0;
9,503,505✔
4353

4354
  if (pCtx->numOfParams > 1) {
9,503,505✔
4355
    pInfo->timeUnit = pCtx->param[1].param.i;
23,427✔
4356
  } else {
4357
    pInfo->timeUnit = 1;
9,480,078✔
4358
  }
4359

4360
  return TSDB_CODE_SUCCESS;
9,503,505✔
4361
}
4362

4363
int32_t elapsedFunction(SqlFunctionCtx* pCtx) {
9,524,345✔
4364
  int32_t numOfElems = 0;
9,524,345✔
4365

4366
  // Only the pre-computing information loaded and actual data does not loaded
4367
  SInputColumnInfoData* pInput = &pCtx->input;
9,524,345✔
4368
  SColumnDataAgg*       pAgg = pInput->pColumnDataAgg[0];
9,524,345✔
4369

4370
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
9,524,345✔
4371

4372
  numOfElems = pInput->numOfRows;  // since this is the primary timestamp, no need to exclude NULL values
9,524,345✔
4373
  if (numOfElems == 0) {
9,524,345✔
4374
    // for stream
4375
    if (pCtx->end.key != INT64_MIN) {
1,556!
4376
      pInfo->max = pCtx->end.key + 1;
×
4377
    }
4378
    goto _elapsed_over;
1,556✔
4379
  }
4380

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

4406
    SColumnInfoData* pCol = pInput->pData[0];
9,522,789✔
4407

4408
    int32_t start = pInput->startRowIndex;
9,522,789✔
4409
    TSKEY*  ptsList = (int64_t*)colDataGetData(pCol, 0);
9,522,789!
4410
    if (pCtx->order == TSDB_ORDER_DESC) {
9,522,789✔
4411
      if (pCtx->start.key == INT64_MIN) {
540!
4412
        pInfo->max = (pInfo->max < ptsList[start]) ? ptsList[start] : pInfo->max;
540✔
4413
      } else {
4414
        pInfo->max = pCtx->start.key + 1;
×
4415
      }
4416

4417
      if (pCtx->end.key == INT64_MIN) {
540!
4418
        pInfo->min =
540✔
4419
            (pInfo->min > ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->min;
540✔
4420
      } else {
4421
        pInfo->min = pCtx->end.key;
×
4422
      }
4423
    } else {
4424
      if (pCtx->start.key == INT64_MIN) {
9,522,249✔
4425
        pInfo->min = (pInfo->min > ptsList[start]) ? ptsList[start] : pInfo->min;
4,120,609✔
4426
      } else {
4427
        pInfo->min = pCtx->start.key;
5,401,640✔
4428
      }
4429

4430
      if (pCtx->end.key == INT64_MIN) {
9,522,249✔
4431
        pInfo->max =
3,751,518✔
4432
            (pInfo->max < ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->max;
3,751,518✔
4433
      } else {
4434
        pInfo->max = pCtx->end.key + 1;
5,770,731✔
4435
      }
4436
    }
4437
  }
4438

4439
_elapsed_over:
9,524,345✔
4440
  // data in the check operation are all null, not output
4441
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
9,524,345✔
4442

4443
  return TSDB_CODE_SUCCESS;
9,524,345✔
4444
}
4445

4446
static void elapsedTransferInfo(SElapsedInfo* pInput, SElapsedInfo* pOutput) {
×
4447
  pOutput->timeUnit = pInput->timeUnit;
×
4448
  if (pOutput->min > pInput->min) {
×
4449
    pOutput->min = pInput->min;
×
4450
  }
4451

4452
  if (pOutput->max < pInput->max) {
×
4453
    pOutput->max = pInput->max;
×
4454
  }
4455
}
×
4456

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

4464
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
×
4465

4466
  int32_t start = pInput->startRowIndex;
×
4467

4468
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
×
4469
    char*         data = colDataGetData(pCol, i);
×
4470
    SElapsedInfo* pInputInfo = (SElapsedInfo*)varDataVal(data);
×
4471
    elapsedTransferInfo(pInputInfo, pInfo);
×
4472
  }
4473

4474
  SET_VAL(GET_RES_INFO(pCtx), 1, 1);
×
4475
  return TSDB_CODE_SUCCESS;
×
4476
}
4477

4478
int32_t elapsedFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
9,474,180✔
4479
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
9,474,180✔
4480
  double        result = (double)(pInfo->max - pInfo->min);
9,474,180✔
4481
  pInfo->result = fabs(result) / pInfo->timeUnit;
9,474,180✔
4482
  return functionFinalize(pCtx, pBlock);
9,474,180✔
4483
}
4484

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

4491
  if (NULL == res) {
×
4492
    return terrno;
×
4493
  }
4494
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
×
4495
  varDataSetLen(res, resultBytes);
×
4496

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

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

4514
int32_t elapsedCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4515
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
4516
  SElapsedInfo*        pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
4517

4518
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4519
  SElapsedInfo*        pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
4520

4521
  elapsedTransferInfo(pSBuf, pDBuf);
×
4522
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
4523
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
4524
  return TSDB_CODE_SUCCESS;
×
4525
}
4526

4527
int32_t getHistogramInfoSize() {
2,567,564✔
4528
  return (int32_t)sizeof(SHistoFuncInfo) + HISTOGRAM_MAX_BINS_NUM * sizeof(SHistoFuncBin);
2,567,564✔
4529
}
4530

4531
bool getHistogramFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
110,759✔
4532
  pEnv->calcMemSize = sizeof(SHistoFuncInfo) + HISTOGRAM_MAX_BINS_NUM * sizeof(SHistoFuncBin);
110,759✔
4533
  return true;
110,759✔
4534
}
4535

4536
static int8_t getHistogramBinType(char* binTypeStr) {
13,994,893✔
4537
  int8_t binType;
4538
  if (strcasecmp(binTypeStr, "user_input") == 0) {
13,994,893✔
4539
    binType = USER_INPUT_BIN;
2,751✔
4540
  } else if (strcasecmp(binTypeStr, "linear_bin") == 0) {
13,992,142✔
4541
    binType = LINEAR_BIN;
1,292✔
4542
  } else if (strcasecmp(binTypeStr, "log_bin") == 0) {
13,990,850!
4543
    binType = LOG_BIN;
13,991,650✔
4544
  } else {
UNCOV
4545
    binType = UNKNOWN_BIN;
×
4546
  }
4547

4548
  return binType;
13,994,893✔
4549
}
4550

4551
static int32_t getHistogramBinDesc(SHistoFuncInfo* pInfo, char* binDescStr, int8_t binType, bool normalized) {
13,995,050✔
4552
  cJSON*  binDesc = cJSON_Parse(binDescStr);
13,995,050✔
4553
  int32_t numOfBins;
4554
  double* intervals;
4555
  if (cJSON_IsObject(binDesc)) { /* linaer/log bins */
13,996,511✔
4556
    int32_t numOfParams = cJSON_GetArraySize(binDesc);
13,993,772✔
4557
    int32_t startIndex;
4558
    if (numOfParams != 4) {
13,993,603!
4559
      cJSON_Delete(binDesc);
×
4560
      return TSDB_CODE_FAILED;
×
4561
    }
4562

4563
    cJSON* start = cJSON_GetObjectItem(binDesc, "start");
13,993,603✔
4564
    cJSON* factor = cJSON_GetObjectItem(binDesc, "factor");
13,993,429✔
4565
    cJSON* width = cJSON_GetObjectItem(binDesc, "width");
13,993,594✔
4566
    cJSON* count = cJSON_GetObjectItem(binDesc, "count");
13,993,483✔
4567
    cJSON* infinity = cJSON_GetObjectItem(binDesc, "infinity");
13,993,612✔
4568

4569
    if (!cJSON_IsNumber(start) || !cJSON_IsNumber(count) || !cJSON_IsBool(infinity)) {
13,993,639!
4570
      cJSON_Delete(binDesc);
×
4571
      return TSDB_CODE_FAILED;
×
4572
    }
4573

4574
    if (count->valueint <= 0 || count->valueint > 1000) {  // limit count to 1000
13,993,579!
4575
      cJSON_Delete(binDesc);
80✔
4576
      return TSDB_CODE_FAILED;
×
4577
    }
4578

4579
    if (isinf(start->valuedouble) || (width != NULL && isinf(width->valuedouble)) ||
13,993,499!
4580
        (factor != NULL && isinf(factor->valuedouble)) || (count != NULL && isinf(count->valuedouble))) {
13,993,499!
4581
      cJSON_Delete(binDesc);
×
4582
      return TSDB_CODE_FAILED;
×
4583
    }
4584

4585
    int32_t counter = (int32_t)count->valueint;
13,993,499✔
4586
    if (infinity->valueint == false) {
13,993,499✔
4587
      startIndex = 0;
5,417✔
4588
      numOfBins = counter + 1;
5,417✔
4589
    } else {
4590
      startIndex = 1;
13,988,082✔
4591
      numOfBins = counter + 3;
13,988,082✔
4592
    }
4593

4594
    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
13,993,499!
4595
    if (NULL == intervals) {
13,992,802!
4596
      cJSON_Delete(binDesc);
×
4597
      qError("histogram function out of memory");
×
4598
      return terrno;
×
4599
    }
4600
    if (cJSON_IsNumber(width) && factor == NULL && binType == LINEAR_BIN) {
13,992,802!
4601
      // linear bin process
4602
      if (width->valuedouble == 0) {
1,293!
4603
        taosMemoryFree(intervals);
×
4604
        cJSON_Delete(binDesc);
×
4605
        return TSDB_CODE_FAILED;
×
4606
      }
4607
      for (int i = 0; i < counter + 1; ++i) {
12,275✔
4608
        intervals[startIndex] = start->valuedouble + i * width->valuedouble;
10,982✔
4609
        if (isinf(intervals[startIndex])) {
10,982!
4610
          taosMemoryFree(intervals);
×
4611
          cJSON_Delete(binDesc);
×
4612
          return TSDB_CODE_FAILED;
×
4613
        }
4614
        startIndex++;
10,982✔
4615
      }
4616
    } else if (cJSON_IsNumber(factor) && width == NULL && binType == LOG_BIN) {
13,991,417!
4617
      // log bin process
4618
      if (start->valuedouble == 0) {
13,991,264!
4619
        taosMemoryFree(intervals);
×
4620
        cJSON_Delete(binDesc);
×
4621
        return TSDB_CODE_FAILED;
×
4622
      }
4623
      if (factor->valuedouble < 0 || factor->valuedouble == 0 || factor->valuedouble == 1) {
13,991,264!
4624
        taosMemoryFree(intervals);
27!
4625
        cJSON_Delete(binDesc);
×
4626
        return TSDB_CODE_FAILED;
×
4627
      }
4628
      for (int i = 0; i < counter + 1; ++i) {
97,926,805✔
4629
        intervals[startIndex] = start->valuedouble * pow(factor->valuedouble, i * 1.0);
83,935,568✔
4630
        if (isinf(intervals[startIndex])) {
83,935,568!
4631
          taosMemoryFree(intervals);
×
4632
          cJSON_Delete(binDesc);
×
4633
          return TSDB_CODE_FAILED;
×
4634
        }
4635
        startIndex++;
83,935,568✔
4636
      }
4637
    } else {
4638
      taosMemoryFree(intervals);
21!
4639
      cJSON_Delete(binDesc);
×
4640
      return TSDB_CODE_FAILED;
×
4641
    }
4642

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

4693
  pInfo->numOfBins = numOfBins - 1;
13,995,280✔
4694
  pInfo->normalized = normalized;
13,995,280✔
4695
  for (int32_t i = 0; i < pInfo->numOfBins; ++i) {
111,935,779✔
4696
    pInfo->bins[i].lower = intervals[i] < intervals[i + 1] ? intervals[i] : intervals[i + 1];
97,940,499✔
4697
    pInfo->bins[i].upper = intervals[i + 1] > intervals[i] ? intervals[i + 1] : intervals[i];
97,940,499✔
4698
    pInfo->bins[i].count = 0;
97,940,499✔
4699
  }
4700

4701
  taosMemoryFree(intervals);
13,995,280!
4702
  cJSON_Delete(binDesc);
13,994,988✔
4703

4704
  return TSDB_CODE_SUCCESS;
13,996,463✔
4705
}
4706

4707
int32_t histogramFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
13,995,117✔
4708
  if (pResultInfo->initialized) {
13,995,117!
4709
    return TSDB_CODE_SUCCESS;
×
4710
  }
4711
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
13,995,117!
4712
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
4713
  }
4714

4715
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
13,995,715✔
4716
  pInfo->numOfBins = 0;
13,995,715✔
4717
  pInfo->totalCount = 0;
13,995,715✔
4718
  pInfo->normalized = 0;
13,995,715✔
4719

4720
  char* binTypeStr = taosStrndup(varDataVal(pCtx->param[1].param.pz), varDataLen(pCtx->param[1].param.pz));
13,995,715!
4721
  if (binTypeStr == NULL) {
13,994,967!
4722
    return terrno;
×
4723
  }
4724
  int8_t binType = getHistogramBinType(binTypeStr);
13,994,967✔
4725
  taosMemoryFree(binTypeStr);
13,995,452!
4726

4727
  if (binType == UNKNOWN_BIN) {
13,994,566!
4728
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
4729
  }
4730
  char* binDesc = taosStrndup(varDataVal(pCtx->param[2].param.pz), varDataLen(pCtx->param[2].param.pz));
13,994,566!
4731
  if (binDesc == NULL) {
13,995,107!
4732
    return terrno;
×
4733
  }
4734
  int64_t normalized = pCtx->param[3].param.i;
13,995,107✔
4735
  if (normalized != 0 && normalized != 1) {
13,995,107!
4736
    taosMemoryFree(binDesc);
×
4737
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
4738
  }
4739
  int32_t code = getHistogramBinDesc(pInfo, binDesc, binType, (bool)normalized);
13,995,107✔
4740
  if (TSDB_CODE_SUCCESS != code) {
13,996,361!
4741
    taosMemoryFree(binDesc);
×
4742
    return code;
×
4743
  }
4744
  taosMemoryFree(binDesc);
13,996,361!
4745

4746
  return TSDB_CODE_SUCCESS;
13,995,920✔
4747
}
4748

4749
static int32_t histogramFunctionImpl(SqlFunctionCtx* pCtx, bool isPartial) {
16,512,824✔
4750
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
16,512,824✔
4751

4752
  SInputColumnInfoData* pInput = &pCtx->input;
16,512,824✔
4753
  SColumnInfoData*      pCol = pInput->pData[0];
16,512,824✔
4754

4755
  int32_t type = pInput->pData[0]->info.type;
16,512,824✔
4756

4757
  int32_t start = pInput->startRowIndex;
16,512,824✔
4758
  int32_t numOfRows = pInput->numOfRows;
16,512,824✔
4759

4760
  int32_t numOfElems = 0;
16,512,824✔
4761
  for (int32_t i = start; i < numOfRows + start; ++i) {
62,579,935✔
4762
    if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
46,067,960!
4763
      continue;
743,263✔
4764
    }
4765

4766
    numOfElems++;
45,324,697✔
4767

4768
    char*  data = colDataGetData(pCol, i);
45,324,697!
4769
    double v;
4770
    GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pCol->info));
45,324,697!
4771

4772
    for (int32_t k = 0; k < pInfo->numOfBins; ++k) {
111,346,946✔
4773
      if (v > pInfo->bins[k].lower && v <= pInfo->bins[k].upper) {
110,536,276✔
4774
        pInfo->bins[k].count++;
44,513,178✔
4775
        pInfo->totalCount++;
44,513,178✔
4776
        break;
44,513,178✔
4777
      }
4778
    }
4779
  }
4780

4781
  if (!isPartial) {
16,511,975✔
4782
    GET_RES_INFO(pCtx)->numOfRes = pInfo->numOfBins;
11,469,360✔
4783
  } else {
4784
    GET_RES_INFO(pCtx)->numOfRes = 1;
5,042,615✔
4785
  }
4786
  return TSDB_CODE_SUCCESS;
16,511,975✔
4787
}
4788

4789
int32_t histogramFunction(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, false); }
11,469,301✔
4790

4791
int32_t histogramFunctionPartial(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, true); }
5,045,105✔
4792

4793
static void histogramTransferInfo(SHistoFuncInfo* pInput, SHistoFuncInfo* pOutput) {
2,538,259✔
4794
  pOutput->normalized = pInput->normalized;
2,538,259✔
4795
  pOutput->numOfBins = pInput->numOfBins;
2,538,259✔
4796
  pOutput->totalCount += pInput->totalCount;
2,538,259✔
4797
  for (int32_t k = 0; k < pOutput->numOfBins; ++k) {
20,307,481✔
4798
    pOutput->bins[k].lower = pInput->bins[k].lower;
17,769,222✔
4799
    pOutput->bins[k].upper = pInput->bins[k].upper;
17,769,222✔
4800
    pOutput->bins[k].count += pInput->bins[k].count;
17,769,222✔
4801
  }
4802
}
2,538,259✔
4803

4804
int32_t histogramFunctionMerge(SqlFunctionCtx* pCtx) {
2,538,259✔
4805
  SInputColumnInfoData* pInput = &pCtx->input;
2,538,259✔
4806
  SColumnInfoData*      pCol = pInput->pData[0];
2,538,259✔
4807
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
2,538,259!
4808
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
4809
  }
4810

4811
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,538,259✔
4812

4813
  int32_t start = pInput->startRowIndex;
2,538,259✔
4814

4815
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
5,076,518✔
4816
    char*           data = colDataGetData(pCol, i);
2,538,259!
4817
    SHistoFuncInfo* pInputInfo = (SHistoFuncInfo*)varDataVal(data);
2,538,259✔
4818
    histogramTransferInfo(pInputInfo, pInfo);
2,538,259✔
4819
  }
4820

4821
  SET_VAL(GET_RES_INFO(pCtx), pInfo->numOfBins, pInfo->numOfBins);
2,538,259!
4822
  return TSDB_CODE_SUCCESS;
2,538,259✔
4823
}
4824

4825
int32_t histogramFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
13,888,588✔
4826
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
13,888,588✔
4827
  SHistoFuncInfo*      pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
13,888,588✔
4828
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
13,888,588✔
4829
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
13,888,588✔
4830
  int32_t              code = TSDB_CODE_SUCCESS;
13,884,596✔
4831

4832
  int32_t currentRow = pBlock->info.rows;
13,884,596✔
4833
  if (NULL == pCol) {
13,884,596!
4834
    return TSDB_CODE_OUT_OF_RANGE;
×
4835
  }
4836

4837
  if (pInfo->normalized) {
13,884,596✔
4838
    for (int32_t k = 0; k < pResInfo->numOfRes; ++k) {
111,008,333✔
4839
      if (pInfo->totalCount != 0) {
97,130,570✔
4840
        pInfo->bins[k].percentage = pInfo->bins[k].count / (double)pInfo->totalCount;
97,119,868✔
4841
      } else {
4842
        pInfo->bins[k].percentage = 0;
10,702✔
4843
      }
4844
    }
4845
  }
4846

4847
  for (int32_t i = 0; i < pResInfo->numOfRes; ++i) {
110,472,399✔
4848
    int32_t len;
4849
    char    buf[512] = {0};
97,174,268✔
4850
    if (!pInfo->normalized) {
97,174,268✔
4851
      len = tsnprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE,
37,199✔
4852
                      "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%" PRId64 "}", pInfo->bins[i].lower,
4853
                      pInfo->bins[i].upper, pInfo->bins[i].count);
4854
    } else {
4855
      len = tsnprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE,
97,137,069✔
4856
                      "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%lf}", pInfo->bins[i].lower, pInfo->bins[i].upper,
4857
                      pInfo->bins[i].percentage);
4858
    }
4859
    varDataSetLen(buf, len);
97,187,921✔
4860
    code = colDataSetVal(pCol, currentRow, buf, false);
97,187,921✔
4861
    if (TSDB_CODE_SUCCESS != code) {
96,587,803!
4862
      return code;
×
4863
    }
4864
    currentRow++;
96,587,803✔
4865
  }
4866

4867
  return code;
13,298,131✔
4868
}
4869

4870
int32_t histogramPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
2,567,564✔
4871
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,567,564✔
4872
  SHistoFuncInfo*      pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,567,564✔
4873
  int32_t              resultBytes = getHistogramInfoSize();
2,567,564✔
4874
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
2,567,564!
4875

4876
  if (NULL == res) {
2,567,565!
4877
    return terrno;
×
4878
  }
4879
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
2,567,565✔
4880
  varDataSetLen(res, resultBytes);
2,567,565✔
4881

4882
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
2,567,565✔
4883
  int32_t          code = TSDB_CODE_SUCCESS;
2,567,565✔
4884
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
2,567,565✔
4885
  if (NULL == pCol) {
2,567,564!
4886
    code = terrno;
×
4887
    goto _exit;
×
4888
  }
4889
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
2,567,564✔
4890

4891
_exit:
2,567,563✔
4892
  taosMemoryFree(res);
2,567,563!
4893
  return code;
2,567,565✔
4894
}
4895

4896
int32_t histogramCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
4897
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
4898
  SHistoFuncInfo*      pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
4899

4900
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
4901
  SHistoFuncInfo*      pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
4902

4903
  histogramTransferInfo(pSBuf, pDBuf);
×
4904
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
4905
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
4906
  return TSDB_CODE_SUCCESS;
×
4907
}
4908

4909
int32_t getHLLInfoSize() { return (int32_t)sizeof(SHLLInfo); }
3,166✔
4910

4911
bool getHLLFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
33,550✔
4912
  pEnv->calcMemSize = sizeof(SHLLInfo);
33,550✔
4913
  return true;
33,550✔
4914
}
4915

4916
static uint8_t hllCountNum(void* data, int32_t bytes, int32_t* buk) {
2,745,137✔
4917
  uint64_t hash = MurmurHash3_64(data, bytes);
2,745,137✔
4918
  int32_t  index = hash & HLL_BUCKET_MASK;
2,744,667✔
4919
  hash >>= HLL_BUCKET_BITS;
2,744,667✔
4920
  hash |= ((uint64_t)1 << HLL_DATA_BITS);
2,744,667✔
4921
  uint64_t bit = 1;
2,744,667✔
4922
  uint8_t  count = 1;
2,744,667✔
4923
  while ((hash & bit) == 0) {
5,833,854✔
4924
    count++;
3,089,187✔
4925
    bit <<= 1;
3,089,187✔
4926
  }
4927
  *buk = index;
2,744,667✔
4928
  return count;
2,744,667✔
4929
}
4930

4931
static void hllBucketHisto(uint8_t* buckets, int32_t* bucketHisto) {
82,862✔
4932
  uint64_t* word = (uint64_t*)buckets;
82,862✔
4933
  uint8_t*  bytes;
4934

4935
  for (int32_t j = 0; j < HLL_BUCKETS >> 3; j++) {
164,605,567✔
4936
    if (*word == 0) {
164,522,705✔
4937
      bucketHisto[0] += 8;
164,069,347✔
4938
    } else {
4939
      bytes = (uint8_t*)word;
453,358✔
4940
      bucketHisto[bytes[0]]++;
453,358✔
4941
      bucketHisto[bytes[1]]++;
453,358✔
4942
      bucketHisto[bytes[2]]++;
453,358✔
4943
      bucketHisto[bytes[3]]++;
453,358✔
4944
      bucketHisto[bytes[4]]++;
453,358✔
4945
      bucketHisto[bytes[5]]++;
453,358✔
4946
      bucketHisto[bytes[6]]++;
453,358✔
4947
      bucketHisto[bytes[7]]++;
453,358✔
4948
    }
4949
    word++;
164,522,705✔
4950
  }
4951
}
82,862✔
4952
static double hllTau(double x) {
82,859✔
4953
  if (x == 0. || x == 1.) return 0.;
82,859!
4954
  double zPrime;
4955
  double y = 1.0;
×
4956
  double z = 1 - x;
×
4957
  do {
4958
    x = sqrt(x);
×
4959
    zPrime = z;
×
4960
    y *= 0.5;
×
4961
    z -= pow(1 - x, 2) * y;
×
4962
  } while (zPrime != z);
×
4963
  return z / 3;
×
4964
}
4965

4966
static double hllSigma(double x) {
82,862✔
4967
  if (x == 1.0) return INFINITY;
82,862✔
4968
  double zPrime;
4969
  double y = 1;
62,674✔
4970
  double z = x;
62,674✔
4971
  do {
4972
    x *= x;
1,221,555✔
4973
    zPrime = z;
1,221,555✔
4974
    z += x * y;
1,221,555✔
4975
    y += y;
1,221,555✔
4976
  } while (zPrime != z);
1,221,555✔
4977
  return z;
62,674✔
4978
}
4979

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

4987
  double z = m * hllTau((m - buckethisto[HLL_DATA_BITS + 1]) / (double)m);
82,861✔
4988
  for (int j = HLL_DATA_BITS; j >= 1; --j) {
4,223,202✔
4989
    z += buckethisto[j];
4,140,339✔
4990
    z *= 0.5;
4,140,339✔
4991
  }
4992

4993
  z += m * hllSigma(buckethisto[0] / (double)m);
82,863✔
4994
  double E = (double)llroundl(HLL_ALPHA_INF * m * m / z);
82,863✔
4995

4996
  return (uint64_t)E;
82,863✔
4997
}
4998

4999
int32_t hllFunction(SqlFunctionCtx* pCtx) {
87,091✔
5000
  SHLLInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
87,091✔
5001

5002
  SInputColumnInfoData* pInput = &pCtx->input;
87,091✔
5003
  SColumnInfoData*      pCol = pInput->pData[0];
87,091✔
5004

5005
  int32_t type = pCol->info.type;
87,091✔
5006
  int32_t bytes = pCol->info.bytes;
87,091✔
5007

5008
  int32_t start = pInput->startRowIndex;
87,091✔
5009
  int32_t numOfRows = pInput->numOfRows;
87,091✔
5010

5011
  int32_t numOfElems = 0;
87,091✔
5012
  if (IS_NULL_TYPE(type)) {
87,091✔
5013
    goto _hll_over;
1,241✔
5014
  }
5015

5016
  for (int32_t i = start; i < numOfRows + start; ++i) {
4,103,049✔
5017
    if (pCol->hasNull && colDataIsNull_s(pCol, i)) {
5,871,866!
5018
      continue;
1,271,901✔
5019
    }
5020

5021
    numOfElems++;
2,745,471✔
5022

5023
    char* data = colDataGetData(pCol, i);
2,745,471!
5024
    if (IS_VAR_DATA_TYPE(type)) {
2,745,471!
5025
      if (IS_STR_DATA_BLOB(type)) {
673,204!
5026
        bytes = blobDataLen(data);
×
5027
        data = blobDataVal(data);
×
5028
      } else {
5029
        bytes = varDataLen(data);
673,204✔
5030
        data = varDataVal(data);
673,204✔
5031
      }
5032
    }
5033

5034
    int32_t index = 0;
2,745,471✔
5035
    uint8_t count = hllCountNum(data, bytes, &index);
2,745,471✔
5036
    uint8_t oldcount = pInfo->buckets[index];
2,745,298✔
5037
    if (count > oldcount) {
2,745,298✔
5038
      pInfo->buckets[index] = count;
475,247✔
5039
    }
5040
  }
5041

5042
_hll_over:
85,677✔
5043
  pInfo->totalCount += numOfElems;
86,918✔
5044

5045
  if (pInfo->totalCount == 0 && !tsCountAlwaysReturnValue) {
86,918✔
5046
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
3,684✔
5047
  } else {
5048
    SET_VAL(GET_RES_INFO(pCtx), 1, 1);
83,234✔
5049
  }
5050

5051
  return TSDB_CODE_SUCCESS;
86,918✔
5052
}
5053

5054
static void hllTransferInfo(SHLLInfo* pInput, SHLLInfo* pOutput) {
2,462✔
5055
  for (int32_t k = 0; k < HLL_BUCKETS; ++k) {
39,622,702✔
5056
    if (pOutput->buckets[k] < pInput->buckets[k]) {
39,620,240✔
5057
      pOutput->buckets[k] = pInput->buckets[k];
37,069✔
5058
    }
5059
  }
5060
  pOutput->totalCount += pInput->totalCount;
2,462✔
5061
}
2,462✔
5062

5063
int32_t hllFunctionMerge(SqlFunctionCtx* pCtx) {
2,462✔
5064
  SInputColumnInfoData* pInput = &pCtx->input;
2,462✔
5065
  SColumnInfoData*      pCol = pInput->pData[0];
2,462✔
5066

5067
  if (IS_NULL_TYPE(pCol->info.type)) {
2,462!
5068
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
×
5069
    return TSDB_CODE_SUCCESS;
×
5070
  }
5071

5072
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
2,462!
5073
    return TSDB_CODE_SUCCESS;
×
5074
  }
5075

5076
  SHLLInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,462✔
5077

5078
  int32_t start = pInput->startRowIndex;
2,462✔
5079

5080
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
4,924✔
5081
    if (colDataIsNull_s(pCol, i)) continue;
4,924!
5082
    char*     data = colDataGetData(pCol, i);
2,462!
5083
    SHLLInfo* pInputInfo = (SHLLInfo*)varDataVal(data);
2,462✔
5084
    hllTransferInfo(pInputInfo, pInfo);
2,462✔
5085
  }
5086

5087
  if (pInfo->totalCount == 0 && !tsCountAlwaysReturnValue) {
2,462✔
5088
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
3✔
5089
  } else {
5090
    SET_VAL(GET_RES_INFO(pCtx), 1, 1);
2,459✔
5091
  }
5092

5093
  return TSDB_CODE_SUCCESS;
2,462✔
5094
}
5095

5096
int32_t hllFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
82,834✔
5097
  SResultRowEntryInfo* pInfo = GET_RES_INFO(pCtx);
82,834✔
5098

5099
  SHLLInfo* pHllInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
82,834✔
5100
  pHllInfo->result = hllCountCnt(pHllInfo->buckets);
82,834✔
5101
  if (tsCountAlwaysReturnValue && pHllInfo->result == 0) {
82,867✔
5102
    pInfo->numOfRes = 1;
16,536✔
5103
  }
5104

5105
  return functionFinalize(pCtx, pBlock);
82,867✔
5106
}
5107

5108
int32_t hllPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
3,166✔
5109
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
3,166✔
5110
  SHLLInfo*            pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
3,166✔
5111
  int32_t              resultBytes = getHLLInfoSize();
3,166✔
5112
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
3,166!
5113

5114
  if (NULL == res) {
3,167!
5115
    return terrno;
×
5116
  }
5117
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
3,167✔
5118
  varDataSetLen(res, resultBytes);
3,167✔
5119

5120
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
3,167✔
5121
  int32_t          code = TSDB_CODE_SUCCESS;
3,167✔
5122
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
3,167✔
5123
  if (NULL == pCol) {
3,167!
5124
    code = terrno;
×
5125
    goto _exit;
×
5126
  }
5127

5128
  code = colDataSetVal(pCol, pBlock->info.rows, res, false);
3,167✔
5129

5130
_exit:
3,167✔
5131
  taosMemoryFree(res);
3,167!
5132
  return code;
3,167✔
5133
}
5134

5135
int32_t hllCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
5136
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
5137
  SHLLInfo*            pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
5138

5139
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
5140
  SHLLInfo*            pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
5141

5142
  hllTransferInfo(pSBuf, pDBuf);
×
5143
  pDResInfo->numOfRes = TMAX(pDResInfo->numOfRes, pSResInfo->numOfRes);
×
5144
  pDResInfo->isNullRes &= pSResInfo->isNullRes;
×
5145
  return TSDB_CODE_SUCCESS;
×
5146
}
5147

5148
bool getStateFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
20,855✔
5149
  pEnv->calcMemSize = sizeof(SStateInfo);
20,855✔
5150
  return true;
20,855✔
5151
}
5152

5153
static int8_t getStateOpType(char* opStr) {
141,300✔
5154
  int8_t opType;
5155
  if (strncasecmp(opStr, "LT", 2) == 0) {
141,300✔
5156
    opType = STATE_OPER_LT;
2,219✔
5157
  } else if (strncasecmp(opStr, "GT", 2) == 0) {
139,081✔
5158
    opType = STATE_OPER_GT;
108,268✔
5159
  } else if (strncasecmp(opStr, "LE", 2) == 0) {
30,813✔
5160
    opType = STATE_OPER_LE;
992✔
5161
  } else if (strncasecmp(opStr, "GE", 2) == 0) {
29,821✔
5162
    opType = STATE_OPER_GE;
2,468✔
5163
  } else if (strncasecmp(opStr, "NE", 2) == 0) {
27,353✔
5164
    opType = STATE_OPER_NE;
1,115✔
5165
  } else if (strncasecmp(opStr, "EQ", 2) == 0) {
26,238!
5166
    opType = STATE_OPER_EQ;
26,238✔
5167
  } else {
5168
    opType = STATE_OPER_INVALID;
×
5169
  }
5170

5171
  return opType;
141,300✔
5172
}
5173

5174
static bool checkStateOp(int8_t op, SColumnInfoData* pCol, int32_t index, SVariant param) {
34,909,823✔
5175
  char* data = colDataGetData(pCol, index);
34,909,823!
5176
  switch (pCol->info.type) {
34,909,823!
5177
    case TSDB_DATA_TYPE_TINYINT: {
6,953,196✔
5178
      int8_t v = *(int8_t*)data;
6,953,196✔
5179
      STATE_COMP(op, v, param);
6,953,196!
5180
      break;
×
5181
    }
5182
    case TSDB_DATA_TYPE_UTINYINT: {
5,760✔
5183
      uint8_t v = *(uint8_t*)data;
5,760✔
5184
      STATE_COMP(op, v, param);
5,760!
5185
      break;
×
5186
    }
5187
    case TSDB_DATA_TYPE_SMALLINT: {
61,612✔
5188
      int16_t v = *(int16_t*)data;
61,612✔
5189
      STATE_COMP(op, v, param);
61,612!
5190
      break;
×
5191
    }
5192
    case TSDB_DATA_TYPE_USMALLINT: {
5,760✔
5193
      uint16_t v = *(uint16_t*)data;
5,760✔
5194
      STATE_COMP(op, v, param);
5,760!
5195
      break;
×
5196
    }
5197
    case TSDB_DATA_TYPE_INT: {
22,490,539✔
5198
      int32_t v = *(int32_t*)data;
22,490,539✔
5199
      STATE_COMP(op, v, param);
22,490,539!
5200
      break;
×
5201
    }
5202
    case TSDB_DATA_TYPE_UINT: {
5,760✔
5203
      uint32_t v = *(uint32_t*)data;
5,760✔
5204
      STATE_COMP(op, v, param);
5,760!
5205
      break;
×
5206
    }
5207
    case TSDB_DATA_TYPE_BIGINT: {
5,236,345✔
5208
      int64_t v = *(int64_t*)data;
5,236,345✔
5209
      STATE_COMP(op, v, param);
5,236,345!
5210
      break;
×
5211
    }
5212
    case TSDB_DATA_TYPE_UBIGINT: {
5,760✔
5213
      uint64_t v = *(uint64_t*)data;
5,760✔
5214
      STATE_COMP(op, v, param);
5,760!
5215
      break;
×
5216
    }
5217
    case TSDB_DATA_TYPE_FLOAT: {
72,812✔
5218
      float v = *(float*)data;
72,812✔
5219
      STATE_COMP(op, v, param);
72,812!
5220
      break;
×
5221
    }
5222
    case TSDB_DATA_TYPE_DOUBLE: {
72,356✔
5223
      double v = *(double*)data;
72,356✔
5224
      STATE_COMP(op, v, param);
72,356!
5225
      break;
×
5226
    }
5227
    default: {
×
5228
      return false;
×
5229
    }
5230
  }
5231
  return false;
×
5232
}
5233

5234
int32_t stateCountFunction(SqlFunctionCtx* pCtx) {
26,776✔
5235
  int32_t              code = TSDB_CODE_SUCCESS;
26,776✔
5236
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
26,776✔
5237
  SStateInfo*          pInfo = GET_ROWCELL_INTERBUF(pResInfo);
26,776✔
5238

5239
  SInputColumnInfoData* pInput = &pCtx->input;
26,776✔
5240
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
26,776✔
5241

5242
  SColumnInfoData* pInputCol = pInput->pData[0];
26,776✔
5243

5244
  int32_t          numOfElems = 0;
26,776✔
5245
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
26,776✔
5246

5247
  int8_t op = getStateOpType(varDataVal(pCtx->param[1].param.pz));
26,776✔
5248
  if (STATE_OPER_INVALID == op) {
26,776!
5249
    return 0;
×
5250
  }
5251

5252
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
5,484,889✔
5253
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
5,458,113!
5254
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5255
    } else {
5256
      pInfo->prevTs = tsList[i];
5,458,113✔
5257
    }
5258

5259
    pInfo->isPrevTsSet = true;
5,458,113✔
5260
    numOfElems++;
5,458,113✔
5261

5262
    if (colDataIsNull_f(pInputCol, i)) {
5,458,113✔
5263
      colDataSetNULL(pOutput, i);
154,524!
5264
      // handle selectivity
5265
      if (pCtx->subsidiaries.num > 0) {
154,524✔
5266
        code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
36✔
5267
        if (TSDB_CODE_SUCCESS != code) {
36!
5268
          return code;
×
5269
        }
5270
      }
5271
      continue;
154,524✔
5272
    }
5273

5274
    bool ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
5,303,589✔
5275

5276
    int64_t output = -1;
5,303,589✔
5277
    if (ret) {
5,303,589✔
5278
      output = ++pInfo->count;
39,621✔
5279
    } else {
5280
      pInfo->count = 0;
5,263,968✔
5281
    }
5282
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
5,303,589✔
5283
    if (TSDB_CODE_SUCCESS != code) {
5,303,589!
5284
      return code;
×
5285
    }
5286

5287
    // handle selectivity
5288
    if (pCtx->subsidiaries.num > 0) {
5,303,589✔
5289
      code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
432✔
5290
      if (TSDB_CODE_SUCCESS != code) {
432!
5291
        return code;
×
5292
      }
5293
    }
5294
  }
5295

5296
  pResInfo->numOfRes = numOfElems;
26,776✔
5297
  return TSDB_CODE_SUCCESS;
26,776✔
5298
}
5299

5300
int32_t stateDurationFunction(SqlFunctionCtx* pCtx) {
114,524✔
5301
  int32_t              code = TSDB_CODE_SUCCESS;
114,524✔
5302
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
114,524✔
5303
  SStateInfo*          pInfo = GET_ROWCELL_INTERBUF(pResInfo);
114,524✔
5304

5305
  SInputColumnInfoData* pInput = &pCtx->input;
114,524✔
5306
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
114,524✔
5307

5308
  SColumnInfoData* pInputCol = pInput->pData[0];
114,524✔
5309

5310
  int32_t          numOfElems = 0;
114,524✔
5311
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
114,524✔
5312

5313
  // TODO: process timeUnit for different db precisions
5314
  int32_t timeUnit = 1;
114,524✔
5315
  if (pCtx->numOfParams == 5) {  // TODO: param number incorrect
114,524✔
5316
    timeUnit = pCtx->param[3].param.i;
112,564✔
5317
  }
5318

5319
  int8_t op = getStateOpType(varDataVal(pCtx->param[1].param.pz));
114,524✔
5320
  if (STATE_OPER_INVALID == op) {
114,524!
5321
    return TSDB_CODE_INVALID_PARA;
×
5322
  }
5323

5324
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
29,813,015✔
5325
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
29,698,495!
5326
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5327
    } else {
5328
      pInfo->prevTs = tsList[i];
29,698,495✔
5329
    }
5330

5331
    pInfo->isPrevTsSet = true;
29,698,495✔
5332
    numOfElems++;
29,698,495✔
5333

5334
    if (colDataIsNull_f(pInputCol, i)) {
29,698,495✔
5335
      colDataSetNULL(pOutput, i);
92,184!
5336
      // handle selectivity
5337
      if (pCtx->subsidiaries.num > 0) {
92,184✔
5338
        code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
52✔
5339
        if (TSDB_CODE_SUCCESS != code) {
52!
5340
          return code;
×
5341
        }
5342
      }
5343
      continue;
92,184✔
5344
    }
5345

5346
    bool    ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
29,606,311✔
5347
    int64_t output = -1;
29,606,311✔
5348
    if (ret) {
29,606,311✔
5349
      if (pInfo->durationStart == 0) {
12,759,049✔
5350
        output = 0;
6,913,989✔
5351
        pInfo->durationStart = tsList[i];
6,913,989✔
5352
      } else {
5353
        output = (tsList[i] - pInfo->durationStart) / timeUnit;
5,845,060✔
5354
      }
5355
    } else {
5356
      pInfo->durationStart = 0;
16,847,262✔
5357
    }
5358
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
29,606,311✔
5359
    if (TSDB_CODE_SUCCESS != code) {
29,606,307!
5360
      return code;
×
5361
    }
5362

5363
    // handle selectivity
5364
    if (pCtx->subsidiaries.num > 0) {
29,606,307✔
5365
      code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
20,044,560✔
5366
      if (TSDB_CODE_SUCCESS != code) {
20,044,560!
5367
        return code;
×
5368
      }
5369
    }
5370
  }
5371

5372
  pResInfo->numOfRes = numOfElems;
114,520✔
5373
  return TSDB_CODE_SUCCESS;
114,520✔
5374
}
5375

5376
bool getCsumFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
13,982✔
5377
  pEnv->calcMemSize = sizeof(SSumRes);
13,982✔
5378
  return true;
13,982✔
5379
}
5380

5381
int32_t csumFunction(SqlFunctionCtx* pCtx) {
19,700✔
5382
  int32_t              code = TSDB_CODE_SUCCESS;
19,700✔
5383
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
19,700✔
5384
  SSumRes*             pSumRes = GET_ROWCELL_INTERBUF(pResInfo);
19,700✔
5385

5386
  SInputColumnInfoData* pInput = &pCtx->input;
19,700✔
5387
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
19,700✔
5388

5389
  SColumnInfoData* pInputCol = pInput->pData[0];
19,700✔
5390
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
19,700✔
5391

5392
  int32_t numOfElems = 0;
19,700✔
5393
  int32_t type = pInputCol->info.type;
19,700✔
5394
  int32_t startOffset = pCtx->offset;
19,700✔
5395
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
3,648,698✔
5396
    if (pSumRes->isPrevTsSet == true && tsList[i] == pSumRes->prevTs) {
3,629,058✔
5397
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
18✔
5398
    } else {
5399
      pSumRes->prevTs = tsList[i];
3,629,040✔
5400
    }
5401
    pSumRes->isPrevTsSet = true;
3,629,040✔
5402

5403
    int32_t pos = startOffset + numOfElems;
3,629,040✔
5404
    if (colDataIsNull_f(pInputCol, i)) {
3,629,040✔
5405
      // colDataSetNULL(pOutput, i);
5406
      continue;
268,675✔
5407
    }
5408

5409
    char* data = colDataGetData(pInputCol, i);
3,360,365!
5410
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
4,568,449!
5411
      int64_t v;
5412
      GET_TYPED_DATA(v, int64_t, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
1,207,965!
5413
      pSumRes->isum += v;
1,207,965✔
5414
      code = colDataSetVal(pOutput, pos, (char*)&pSumRes->isum, false);
1,207,965✔
5415
      if (TSDB_CODE_SUCCESS != code) {
1,208,084!
5416
        return code;
×
5417
      }
5418
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
2,152,960!
5419
      uint64_t v;
5420
      GET_TYPED_DATA(v, uint64_t, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
560!
5421
      pSumRes->usum += v;
560✔
5422
      code = colDataSetVal(pOutput, pos, (char*)&pSumRes->usum, false);
560✔
5423
      if (TSDB_CODE_SUCCESS != code) {
560!
5424
        return code;
×
5425
      }
5426
    } else if (IS_FLOAT_TYPE(type)) {
2,151,840!
5427
      double v;
5428
      GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
2,157,090!
5429
      pSumRes->dsum += v;
2,157,090✔
5430
      // check for overflow
5431
      if (isinf(pSumRes->dsum) || isnan(pSumRes->dsum)) {
2,157,090!
5432
        colDataSetNULL(pOutput, pos);
8!
5433
      } else {
5434
        code = colDataSetVal(pOutput, pos, (char*)&pSumRes->dsum, false);
2,157,082✔
5435
        if (TSDB_CODE_SUCCESS != code) {
2,157,082!
5436
          return code;
×
5437
        }
5438
      }
5439
    }
5440

5441
    // handle selectivity
5442
    if (pCtx->subsidiaries.num > 0) {
3,360,484✔
5443
      code = appendSelectivityValue(pCtx, i, pos);
2,013,223✔
5444
      if (TSDB_CODE_SUCCESS != code) {
2,013,062!
5445
        return code;
×
5446
      }
5447
    }
5448

5449
    numOfElems++;
3,360,323✔
5450
  }
5451

5452
  pResInfo->numOfRes = numOfElems;
19,640✔
5453
  return TSDB_CODE_SUCCESS;
19,640✔
5454
}
5455

5456
bool getMavgFuncEnv(SFunctionNode* UNUSED_PARAM(pFunc), SFuncExecEnv* pEnv) {
12,215✔
5457
  pEnv->calcMemSize = sizeof(SMavgInfo) + MAVG_MAX_POINTS_NUM * sizeof(double);
12,215✔
5458
  return true;
12,215✔
5459
}
5460

5461
int32_t mavgFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
64,130✔
5462
  if (pResultInfo->initialized) {
64,130✔
5463
    return TSDB_CODE_SUCCESS;
51,163✔
5464
  }
5465
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
12,967!
5466
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5467
  }
5468

5469
  SMavgInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
12,967✔
5470
  pInfo->pos = 0;
12,967✔
5471
  pInfo->sum = 0;
12,967✔
5472
  pInfo->prevTs = -1;
12,967✔
5473
  pInfo->isPrevTsSet = false;
12,967✔
5474
  pInfo->numOfPoints = pCtx->param[1].param.i;
12,967✔
5475
  if (pInfo->numOfPoints < 1 || pInfo->numOfPoints > MAVG_MAX_POINTS_NUM) {
12,967!
5476
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
5477
  }
5478
  pInfo->pointsMeet = false;
12,967✔
5479

5480
  return TSDB_CODE_SUCCESS;
12,967✔
5481
}
5482

5483
int32_t mavgFunction(SqlFunctionCtx* pCtx) {
51,915✔
5484
  int32_t              code = TSDB_CODE_SUCCESS;
51,915✔
5485
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
51,915✔
5486
  SMavgInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
51,915✔
5487

5488
  SInputColumnInfoData* pInput = &pCtx->input;
51,915✔
5489
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
51,915✔
5490

5491
  SColumnInfoData* pInputCol = pInput->pData[0];
51,915✔
5492
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
51,915✔
5493
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
51,915✔
5494

5495
  int32_t numOfElems = 0;
51,915✔
5496
  int32_t type = pInputCol->info.type;
51,915✔
5497
  int32_t startOffset = pCtx->offset;
51,915✔
5498
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
58,471,937✔
5499
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
58,420,022!
5500
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5501
    } else {
5502
      pInfo->prevTs = tsList[i];
58,420,022✔
5503
    }
5504
    pInfo->isPrevTsSet = true;
58,420,022✔
5505

5506
    int32_t pos = startOffset + numOfElems;
58,420,022✔
5507
    if (colDataIsNull_f(pInputCol, i)) {
58,420,022!
5508
      // colDataSetNULL(pOutput, i);
5509
      continue;
233,465✔
5510
    }
5511

5512
    char*  data = colDataGetData(pInputCol, i);
58,186,557!
5513
    double v;
5514
    GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
58,186,557!
5515

5516
    if (!pInfo->pointsMeet && (pInfo->pos < pInfo->numOfPoints - 1)) {
58,186,557✔
5517
      pInfo->points[pInfo->pos] = v;
6,420,460✔
5518
      pInfo->sum += v;
6,420,460✔
5519
    } else {
5520
      if (!pInfo->pointsMeet && (pInfo->pos == pInfo->numOfPoints - 1)) {
51,766,097!
5521
        pInfo->sum += v;
10,538✔
5522
        pInfo->pointsMeet = true;
10,538✔
5523
      } else {
5524
        pInfo->sum = pInfo->sum + v - pInfo->points[pInfo->pos];
51,755,559✔
5525
      }
5526

5527
      pInfo->points[pInfo->pos] = v;
51,766,097✔
5528
      double result = pInfo->sum / pInfo->numOfPoints;
51,766,097✔
5529
      // check for overflow
5530
      if (isinf(result) || isnan(result)) {
51,766,097!
5531
        colDataSetNULL(pOutput, pos);
×
5532
      } else {
5533
        code = colDataSetVal(pOutput, pos, (char*)&result, false);
51,766,097✔
5534
        if (TSDB_CODE_SUCCESS != code) {
51,766,097!
5535
          return code;
×
5536
        }
5537
      }
5538

5539
      // handle selectivity
5540
      if (pCtx->subsidiaries.num > 0) {
51,766,097✔
5541
        code = appendSelectivityValue(pCtx, i, pos);
32,318,324✔
5542
        if (TSDB_CODE_SUCCESS != code) {
32,318,324!
5543
          return code;
×
5544
        }
5545
      }
5546

5547
      numOfElems++;
51,766,097✔
5548
    }
5549

5550
    pInfo->pos++;
58,186,557✔
5551
    if (pInfo->pos == pInfo->numOfPoints) {
58,186,557✔
5552
      pInfo->pos = 0;
148,174✔
5553
    }
5554
  }
5555

5556
  pResInfo->numOfRes = numOfElems;
51,915✔
5557
  return TSDB_CODE_SUCCESS;
51,915✔
5558
}
5559

5560
static SSampleInfo* getSampleOutputInfo(SqlFunctionCtx* pCtx) {
13,449,941✔
5561
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
13,449,941✔
5562
  SSampleInfo*         pInfo = GET_ROWCELL_INTERBUF(pResInfo);
13,449,941✔
5563

5564
  pInfo->data = (char*)pInfo + sizeof(SSampleInfo);
13,449,941✔
5565
  pInfo->tuplePos = (STuplePos*)((char*)pInfo + sizeof(SSampleInfo) + pInfo->samples * pInfo->colBytes);
13,449,941✔
5566

5567
  return pInfo;
13,449,941✔
5568
}
5569

5570
bool getSampleFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
28,722✔
5571
  SColumnNode* pCol = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
28,722✔
5572
  SValueNode*  pVal = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
28,725✔
5573
  int32_t      numOfSamples = pVal->datum.i;
28,725✔
5574
  pEnv->calcMemSize = sizeof(SSampleInfo) + numOfSamples * (pCol->node.resType.bytes + sizeof(STuplePos));
28,725✔
5575
  return true;
28,725✔
5576
}
5577

5578
int32_t sampleFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
6,788,856✔
5579
  if (pResultInfo->initialized) {
6,788,856!
5580
    return TSDB_CODE_SUCCESS;
×
5581
  }
5582
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
6,788,856!
5583
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5584
  }
5585

5586
  taosSeedRand(taosSafeRand());
6,788,858✔
5587

5588
  SSampleInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
6,788,859✔
5589
  pInfo->samples = pCtx->param[1].param.i;
6,788,859✔
5590
  pInfo->totalPoints = 0;
6,788,859✔
5591
  pInfo->numSampled = 0;
6,788,859✔
5592
  pInfo->colType = pCtx->resDataInfo.type;
6,788,859✔
5593
  pInfo->colBytes = pCtx->resDataInfo.bytes;
6,788,859✔
5594
  pInfo->nullTuplePos.pageId = -1;
6,788,859✔
5595
  pInfo->nullTupleSaved = false;
6,788,859✔
5596
  pInfo->data = (char*)pInfo + sizeof(SSampleInfo);
6,788,859✔
5597
  pInfo->tuplePos = (STuplePos*)((char*)pInfo + sizeof(SSampleInfo) + pInfo->samples * pInfo->colBytes);
6,788,859✔
5598

5599
  return TSDB_CODE_SUCCESS;
6,788,859✔
5600
}
5601

5602
static void sampleAssignResult(SSampleInfo* pInfo, char* data, int32_t index) {
14,340,194✔
5603
  assignVal(pInfo->data + index * pInfo->colBytes, data, pInfo->colBytes, pInfo->colType);
14,340,194✔
5604
}
14,340,302✔
5605

5606
static int32_t doReservoirSample(SqlFunctionCtx* pCtx, SSampleInfo* pInfo, char* data, int32_t index) {
15,292,850✔
5607
  pInfo->totalPoints++;
15,292,850✔
5608
  if (pInfo->numSampled < pInfo->samples) {
15,292,850✔
5609
    sampleAssignResult(pInfo, data, pInfo->numSampled);
13,111,662✔
5610
    if (pCtx->subsidiaries.num > 0) {
13,111,709✔
5611
      int32_t code = saveTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[pInfo->numSampled]);
982,250✔
5612
      if (code != TSDB_CODE_SUCCESS) {
982,402!
5613
        return code;
×
5614
      }
5615
    }
5616
    pInfo->numSampled++;
13,111,861✔
5617
  } else {
5618
    int32_t j = taosRand() % (pInfo->totalPoints);
2,181,188✔
5619
    if (j < pInfo->samples) {
2,184,266✔
5620
      sampleAssignResult(pInfo, data, j);
1,229,672✔
5621
      if (pCtx->subsidiaries.num > 0) {
1,229,630✔
5622
        int32_t code = updateTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[j]);
661,501✔
5623
        if (code != TSDB_CODE_SUCCESS) {
658,689!
5624
          return code;
×
5625
        }
5626
      }
5627
    }
5628
  }
5629

5630
  return TSDB_CODE_SUCCESS;
15,293,273✔
5631
}
5632

5633
int32_t sampleFunction(SqlFunctionCtx* pCtx) {
6,790,870✔
5634
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
6,790,870✔
5635
  SSampleInfo*         pInfo = getSampleOutputInfo(pCtx);
6,790,870✔
5636

5637
  SInputColumnInfoData* pInput = &pCtx->input;
6,790,870✔
5638

5639
  SColumnInfoData* pInputCol = pInput->pData[0];
6,790,870✔
5640
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
22,292,676✔
5641
    if (colDataIsNull_s(pInputCol, i)) {
31,005,220✔
5642
      continue;
208,879✔
5643
    }
5644

5645
    char*   data = colDataGetData(pInputCol, i);
15,293,731!
5646
    int32_t code = doReservoirSample(pCtx, pInfo, data, i);
15,293,731✔
5647
    if (code != TSDB_CODE_SUCCESS) {
15,292,927!
5648
      return code;
×
5649
    }
5650
  }
5651

5652
  if (pInfo->numSampled == 0 && pCtx->subsidiaries.num > 0 && !pInfo->nullTupleSaved) {
6,790,066✔
5653
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pInfo->nullTuplePos);
19✔
5654
    if (code != TSDB_CODE_SUCCESS) {
19!
5655
      return code;
×
5656
    }
5657
    pInfo->nullTupleSaved = true;
19✔
5658
  }
5659

5660
  SET_VAL(pResInfo, pInfo->numSampled, pInfo->numSampled);
6,790,066✔
5661
  return TSDB_CODE_SUCCESS;
6,790,066✔
5662
}
5663

5664
int32_t sampleFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
6,659,075✔
5665
  int32_t              code = TSDB_CODE_SUCCESS;
6,659,075✔
5666
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
6,659,075✔
5667

5668
  SSampleInfo* pInfo = getSampleOutputInfo(pCtx);
6,659,075✔
5669
  pEntryInfo->complete = true;
6,659,075✔
5670

5671
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
6,659,075✔
5672
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
6,659,075✔
5673
  if (NULL == pCol) {
6,659,071!
5674
    return TSDB_CODE_OUT_OF_RANGE;
×
5675
  }
5676

5677
  int32_t currentRow = pBlock->info.rows;
6,659,071✔
5678
  if (pInfo->numSampled == 0) {
6,659,071✔
5679
    colDataSetNULL(pCol, currentRow);
1,499✔
5680
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
1,499✔
5681
    return code;
1,499✔
5682
  }
5683
  for (int32_t i = 0; i < pInfo->numSampled; ++i) {
19,569,285✔
5684
    code = colDataSetVal(pCol, currentRow + i, pInfo->data + i * pInfo->colBytes, false);
12,913,691✔
5685
    if (TSDB_CODE_SUCCESS != code) {
12,908,805!
5686
      return code;
×
5687
    }
5688
    code = setSelectivityValue(pCtx, pBlock, &pInfo->tuplePos[i], currentRow + i);
12,908,805✔
5689
    if (TSDB_CODE_SUCCESS != code) {
12,911,713!
5690
      return code;
×
5691
    }
5692
  }
5693

5694
  return code;
6,655,594✔
5695
}
5696

5697
bool getTailFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
×
5698
#if 0
5699
  SColumnNode* pCol = (SColumnNode*)nodesListGetNode(pFunc->pParameterList, 0);
5700
  SValueNode*  pVal = (SValueNode*)nodesListGetNode(pFunc->pParameterList, 1);
5701
  int32_t      numOfPoints = pVal->datum.i;
5702
  pEnv->calcMemSize = sizeof(STailInfo) + numOfPoints * (POINTER_BYTES + sizeof(STailItem) + pCol->node.resType.bytes);
5703
#endif
5704
  return true;
×
5705
}
5706

5707
int32_t tailFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
×
5708
#if 0
5709
  if (!functionSetup(pCtx, pResultInfo)) {
5710
    return false;
5711
  }
5712

5713
  STailInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
5714
  pInfo->numAdded = 0;
5715
  pInfo->numOfPoints = pCtx->param[1].param.i;
5716
  if (pCtx->numOfParams == 4) {
5717
    pInfo->offset = pCtx->param[2].param.i;
5718
  } else {
5719
    pInfo->offset = 0;
5720
  }
5721
  pInfo->colType = pCtx->resDataInfo.type;
5722
  pInfo->colBytes = pCtx->resDataInfo.bytes;
5723
  if ((pInfo->numOfPoints < 1 || pInfo->numOfPoints > TAIL_MAX_POINTS_NUM) ||
5724
      (pInfo->numOfPoints < 0 || pInfo->numOfPoints > TAIL_MAX_OFFSET)) {
5725
    return false;
5726
  }
5727

5728
  pInfo->pItems = (STailItem**)((char*)pInfo + sizeof(STailInfo));
5729
  char* pItem = (char*)pInfo->pItems + pInfo->numOfPoints * POINTER_BYTES;
5730

5731
  size_t unitSize = sizeof(STailItem) + pInfo->colBytes;
5732
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
5733
    pInfo->pItems[i] = (STailItem*)(pItem + i * unitSize);
5734
    pInfo->pItems[i]->isNull = false;
5735
  }
5736
#endif
5737

5738
  return TSDB_CODE_SUCCESS;
×
5739
}
5740

5741
static void tailAssignResult(STailItem* pItem, char* data, int32_t colBytes, TSKEY ts, bool isNull) {
×
5742
#if 0
5743
  pItem->timestamp = ts;
5744
  if (isNull) {
5745
    pItem->isNull = true;
5746
  } else {
5747
    pItem->isNull = false;
5748
    memcpy(pItem->data, data, colBytes);
5749
  }
5750
#endif
5751
}
×
5752

5753
#if 0
5754
static int32_t tailCompFn(const void* p1, const void* p2, const void* param) {
5755
  STailItem* d1 = *(STailItem**)p1;
5756
  STailItem* d2 = *(STailItem**)p2;
5757
  return compareInt64Val(&d1->timestamp, &d2->timestamp);
5758
}
5759

5760
static void doTailAdd(STailInfo* pInfo, char* data, TSKEY ts, bool isNull) {
5761
  STailItem** pList = pInfo->pItems;
5762
  if (pInfo->numAdded < pInfo->numOfPoints) {
5763
    tailAssignResult(pList[pInfo->numAdded], data, pInfo->colBytes, ts, isNull);
5764
    taosheapsort((void*)pList, sizeof(STailItem**), pInfo->numAdded + 1, NULL, tailCompFn, 0);
5765
    pInfo->numAdded++;
5766
  } else if (pList[0]->timestamp < ts) {
5767
    tailAssignResult(pList[0], data, pInfo->colBytes, ts, isNull);
5768
    taosheapadjust((void*)pList, sizeof(STailItem**), 0, pInfo->numOfPoints - 1, NULL, tailCompFn, NULL, 0);
5769
  }
5770
}
5771
#endif
5772

5773
int32_t tailFunction(SqlFunctionCtx* pCtx) {
×
5774
#if 0
5775
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5776
  STailInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5777

5778
  SInputColumnInfoData* pInput = &pCtx->input;
5779
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
5780

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

5784
  int32_t startOffset = pCtx->offset;
5785
  if (pInfo->offset >= pInput->numOfRows) {
5786
    return 0;
5787
  } else {
5788
    pInfo->numOfPoints = TMIN(pInfo->numOfPoints, pInput->numOfRows - pInfo->offset);
5789
  }
5790
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex - pInfo->offset; i += 1) {
5791
    char* data = colDataGetData(pInputCol, i);
5792
    doTailAdd(pInfo, data, tsList[i], colDataIsNull_s(pInputCol, i));
5793
  }
5794

5795
  taosqsort(pInfo->pItems, pInfo->numOfPoints, POINTER_BYTES, NULL, tailCompFn);
5796

5797
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
5798
    int32_t    pos = startOffset + i;
5799
    STailItem* pItem = pInfo->pItems[i];
5800
    if (pItem->isNull) {
5801
      colDataSetNULL(pOutput, pos);
5802
    } else {
5803
      colDataSetVal(pOutput, pos, pItem->data, false);
5804
    }
5805
  }
5806

5807
  return pInfo->numOfPoints;
5808
#endif
5809
  return 0;
×
5810
}
5811

5812
int32_t tailFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
×
5813
#if 0
5814
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
5815
  STailInfo*           pInfo = GET_ROWCELL_INTERBUF(pEntryInfo);
5816
  pEntryInfo->complete = true;
5817

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

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

5823
  // todo assign the tag value and the corresponding row data
5824
  int32_t currentRow = pBlock->info.rows;
5825
  for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
5826
    STailItem* pItem = pInfo->pItems[i];
5827
    colDataSetVal(pCol, currentRow, pItem->data, false);
5828
    currentRow += 1;
5829
  }
5830

5831
  return pEntryInfo->numOfRes;
5832
#endif
5833
  return 0;
×
5834
}
5835

5836
bool getUniqueFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
×
5837
#if 0
5838
  pEnv->calcMemSize = sizeof(SUniqueInfo) + UNIQUE_MAX_RESULT_SIZE;
5839
#endif
5840
  return true;
×
5841
}
5842

5843
int32_t uniqueFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
×
5844
#if 0
5845
  if (!functionSetup(pCtx, pResInfo)) {
5846
    return false;
5847
  }
5848

5849
  SUniqueInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5850
  pInfo->numOfPoints = 0;
5851
  pInfo->colType = pCtx->resDataInfo.type;
5852
  pInfo->colBytes = pCtx->resDataInfo.bytes;
5853
  if (pInfo->pHash != NULL) {
5854
    taosHashClear(pInfo->pHash);
5855
  } else {
5856
    pInfo->pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
5857
  }
5858
#endif
5859
  return TSDB_CODE_SUCCESS;
×
5860
}
5861

5862
#if 0
5863
static void doUniqueAdd(SUniqueInfo* pInfo, char* data, TSKEY ts, bool isNull) {
5864
  // handle null elements
5865
  if (isNull == true) {
5866
    int32_t      size = sizeof(SUniqueItem) + pInfo->colBytes;
5867
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + pInfo->numOfPoints * size);
5868
    if (pInfo->hasNull == false && pItem->isNull == false) {
5869
      pItem->timestamp = ts;
5870
      pItem->isNull = true;
5871
      pInfo->numOfPoints++;
5872
      pInfo->hasNull = true;
5873
    } else if (pItem->timestamp > ts && pItem->isNull == true) {
5874
      pItem->timestamp = ts;
5875
    }
5876
    return;
5877
  }
5878

5879
  int32_t      hashKeyBytes = IS_VAR_DATA_TYPE(pInfo->colType) ? varDataTLen(data) : pInfo->colBytes;
5880
  SUniqueItem* pHashItem = taosHashGet(pInfo->pHash, data, hashKeyBytes);
5881
  if (pHashItem == NULL) {
5882
    int32_t      size = sizeof(SUniqueItem) + pInfo->colBytes;
5883
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + pInfo->numOfPoints * size);
5884
    pItem->timestamp = ts;
5885
    memcpy(pItem->data, data, pInfo->colBytes);
5886

5887
    taosHashPut(pInfo->pHash, data, hashKeyBytes, (char*)pItem, sizeof(SUniqueItem*));
5888
    pInfo->numOfPoints++;
5889
  } else if (pHashItem->timestamp > ts) {
5890
    pHashItem->timestamp = ts;
5891
  }
5892
}
5893
#endif
5894

5895
int32_t uniqueFunction(SqlFunctionCtx* pCtx) {
×
5896
#if 0
5897
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5898
  SUniqueInfo*         pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5899

5900
  SInputColumnInfoData* pInput = &pCtx->input;
5901
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
5902

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

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

5912
    if (sizeof(SUniqueInfo) + pInfo->numOfPoints * (sizeof(SUniqueItem) + pInfo->colBytes) >= UNIQUE_MAX_RESULT_SIZE) {
5913
      taosHashCleanup(pInfo->pHash);
5914
      return 0;
5915
    }
5916
  }
5917

5918
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
5919
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + i * (sizeof(SUniqueItem) + pInfo->colBytes));
5920
    if (pItem->isNull == true) {
5921
      colDataSetNULL(pOutput, i);
5922
    } else {
5923
      colDataSetVal(pOutput, i, pItem->data, false);
5924
    }
5925
    if (pTsOutput != NULL) {
5926
      colDataSetInt64(pTsOutput, i, &pItem->timestamp);
5927
    }
5928
  }
5929

5930
  return pInfo->numOfPoints;
5931
#endif
5932
  return 0;
×
5933
}
5934

5935
bool getModeFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
22,896✔
5936
  pEnv->calcMemSize = sizeof(SModeInfo);
22,896✔
5937
  return true;
22,896✔
5938
}
5939

5940
int32_t modeFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
20,678✔
5941
  if (pResInfo->initialized) {
20,678!
5942
    return TSDB_CODE_SUCCESS;
×
5943
  }
5944
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
20,678!
5945
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5946
  }
5947

5948
  SModeInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
20,678✔
5949
  pInfo->colType = pCtx->resDataInfo.type;
20,678✔
5950
  pInfo->colBytes = pCtx->resDataInfo.bytes;
20,678✔
5951
  if (pInfo->pHash != NULL) {
20,678!
5952
    taosHashClear(pInfo->pHash);
×
5953
  } else {
5954
    pInfo->pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
20,678✔
5955
    if (NULL == pInfo->pHash) {
20,678!
5956
      return terrno;
×
5957
    }
5958
  }
5959
  pInfo->nullTupleSaved = false;
20,678✔
5960
  pInfo->nullTuplePos.pageId = -1;
20,678✔
5961

5962
  pInfo->buf = taosMemoryMalloc(pInfo->colBytes);
20,678!
5963
  if (NULL == pInfo->buf) {
20,678!
5964
    taosHashCleanup(pInfo->pHash);
×
5965
    pInfo->pHash = NULL;
×
5966
    return terrno;
×
5967
  }
5968
  pCtx->needCleanup = true;
20,678✔
5969
  return TSDB_CODE_SUCCESS;
20,678✔
5970
}
5971

5972
static void modeFunctionCleanup(SModeInfo* pInfo) {
20,678✔
5973
  taosHashCleanup(pInfo->pHash);
20,678✔
5974
  pInfo->pHash = NULL;
20,678✔
5975
  taosMemoryFreeClear(pInfo->buf);
20,678!
5976
}
20,678✔
5977

5978
void modeFunctionCleanupExt(SqlFunctionCtx* pCtx) {
×
5979
  if (pCtx == NULL || GET_RES_INFO(pCtx) == NULL || GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)) == NULL) {
×
5980
    return;
×
5981
  }
5982
  modeFunctionCleanup(GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)));
×
5983
}
5984

5985
static int32_t saveModeTupleData(SqlFunctionCtx* pCtx, char* data, SModeInfo* pInfo, STuplePos* pPos) {
16,415,721✔
5986
  if (IS_VAR_DATA_TYPE(pInfo->colType)) {
16,415,721!
5987
    if (pInfo->colType == TSDB_DATA_TYPE_JSON) {
8,258,725✔
5988
      (void)memcpy(pInfo->buf, data, getJsonValueLen(data));
1,188✔
5989
    } else if (IS_STR_DATA_BLOB(pInfo->colType)) {
8,257,537!
5990
      (void)memcpy(pInfo->buf, data, blobDataTLen(data));
×
5991
    } else {
5992
      (void)memcpy(pInfo->buf, data, varDataTLen(data));
8,257,557✔
5993
    }
5994
  } else {
5995
    (void)memcpy(pInfo->buf, data, pInfo->colBytes);
8,156,996✔
5996
  }
5997

5998
  return doSaveTupleData(&pCtx->saveHandle, pInfo->buf, pInfo->colBytes, NULL, pPos, pCtx->pStore);
16,415,721✔
5999
}
6000

6001
static int32_t doModeAdd(SModeInfo* pInfo, int32_t rowIndex, SqlFunctionCtx* pCtx, char* data) {
49,403,763✔
6002
  int32_t code = TSDB_CODE_SUCCESS;
49,403,763✔
6003
  int32_t hashKeyBytes;
6004
  if (IS_VAR_DATA_TYPE(pInfo->colType)) {
49,403,763!
6005
    hashKeyBytes = calcStrBytesByType(pInfo->colType, data);
8,259,459✔
6006
  } else {
6007
    hashKeyBytes = pInfo->colBytes;
41,144,304✔
6008
  }
6009

6010
  SModeItem* pHashItem = (SModeItem*)taosHashGet(pInfo->pHash, data, hashKeyBytes);
49,403,745✔
6011
  if (pHashItem == NULL) {
49,403,025✔
6012
    int32_t   size = sizeof(SModeItem);
16,415,592✔
6013
    SModeItem item = {0};
16,415,592✔
6014

6015
    item.count += 1;
16,415,592✔
6016
    code = saveModeTupleData(pCtx, data, pInfo, &item.dataPos);
16,415,592✔
6017
    if (code != TSDB_CODE_SUCCESS) {
16,415,584!
6018
      return code;
×
6019
    }
6020

6021
    if (pCtx->subsidiaries.num > 0) {
16,415,584✔
6022
      code = saveTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &item.tuplePos);
5,797,642✔
6023
      if (code != TSDB_CODE_SUCCESS) {
5,797,642!
6024
        return code;
×
6025
      }
6026
    }
6027

6028
    code = taosHashPut(pInfo->pHash, data, hashKeyBytes, &item, sizeof(SModeItem));
16,415,584✔
6029
    if (code != TSDB_CODE_SUCCESS) {
16,416,466!
6030
      return code;
×
6031
    }
6032
  } else {
6033
    pHashItem->count += 1;
32,987,433✔
6034
    if (pCtx->subsidiaries.num > 0) {
32,987,433✔
6035
      code = updateTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &pHashItem->tuplePos);
22,898,364✔
6036
      if (code != TSDB_CODE_SUCCESS) {
22,898,364!
6037
        return code;
×
6038
      }
6039
    }
6040
  }
6041

6042
  return code;
49,403,899✔
6043
}
6044

6045
int32_t modeFunction(SqlFunctionCtx* pCtx) {
214,255✔
6046
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
214,255✔
6047
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
214,255✔
6048

6049
  SInputColumnInfoData* pInput = &pCtx->input;
214,255✔
6050

6051
  SColumnInfoData* pInputCol = pInput->pData[0];
214,255✔
6052
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
214,255✔
6053

6054
  int32_t numOfElems = 0;
214,255✔
6055
  int32_t startOffset = pCtx->offset;
214,255✔
6056
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
49,850,867✔
6057
    if (colDataIsNull_s(pInputCol, i)) {
99,273,220✔
6058
      continue;
233,268✔
6059
    }
6060
    numOfElems++;
49,403,342✔
6061

6062
    char*   data = colDataGetData(pInputCol, i);
49,403,342!
6063
    int32_t code = doModeAdd(pInfo, i, pCtx, data);
49,403,342✔
6064
    if (code != TSDB_CODE_SUCCESS) {
49,403,897✔
6065
      modeFunctionCleanup(pInfo);
553✔
6066
      return code;
×
6067
    }
6068
  }
6069

6070
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pInfo->nullTupleSaved) {
214,257!
6071
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pInfo->nullTuplePos);
30✔
6072
    if (code != TSDB_CODE_SUCCESS) {
30!
6073
      modeFunctionCleanup(pInfo);
×
6074
      return code;
×
6075
    }
6076
    pInfo->nullTupleSaved = true;
30✔
6077
  }
6078

6079
  SET_VAL(pResInfo, numOfElems, 1);
214,257✔
6080

6081
  return TSDB_CODE_SUCCESS;
214,257✔
6082
}
6083

6084
int32_t modeFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
20,678✔
6085
  int32_t              code = TSDB_CODE_SUCCESS;
20,678✔
6086
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
20,678✔
6087
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
20,678✔
6088
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
20,678✔
6089
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
20,678✔
6090
  int32_t              currentRow = pBlock->info.rows;
20,678✔
6091
  if (NULL == pCol) {
20,678!
6092
    modeFunctionCleanup(pInfo);
×
6093
    return TSDB_CODE_OUT_OF_RANGE;
×
6094
  }
6095

6096
  STuplePos resDataPos, resTuplePos;
6097
  int32_t   maxCount = 0;
20,678✔
6098

6099
  void* pIter = taosHashIterate(pInfo->pHash, NULL);
20,678✔
6100
  while (pIter != NULL) {
16,437,280✔
6101
    SModeItem* pItem = (SModeItem*)pIter;
16,416,602✔
6102
    if (pItem->count >= maxCount) {
16,416,602✔
6103
      maxCount = pItem->count;
13,406,245✔
6104
      resDataPos = pItem->dataPos;
13,406,245✔
6105
      resTuplePos = pItem->tuplePos;
13,406,245✔
6106
    }
6107

6108
    pIter = taosHashIterate(pInfo->pHash, pIter);
16,416,602✔
6109
  }
6110

6111
  if (maxCount != 0) {
20,678✔
6112
    char* pData = NULL;
19,248✔
6113
    code = loadTupleData(pCtx, &resDataPos, &pData);
19,248✔
6114
    if (pData == NULL || TSDB_CODE_SUCCESS != code) {
19,248!
6115
      code = terrno = TSDB_CODE_NOT_FOUND;
×
6116
      qError("Load tuple data failed since %s, groupId:%" PRIu64 ", ts:%" PRId64, terrstr(),
×
6117
             resDataPos.streamTupleKey.groupId, resDataPos.streamTupleKey.ts);
6118
      modeFunctionCleanup(pInfo);
×
6119
      return code;
×
6120
    }
6121

6122
    code = colDataSetVal(pCol, currentRow, pData, false);
19,248✔
6123
    if (TSDB_CODE_SUCCESS != code) {
19,248!
6124
      modeFunctionCleanup(pInfo);
×
6125
      return code;
×
6126
    }
6127
    code = setSelectivityValue(pCtx, pBlock, &resTuplePos, currentRow);
19,248✔
6128
  } else {
6129
    colDataSetNULL(pCol, currentRow);
1,430✔
6130
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
1,430✔
6131
  }
6132

6133
  modeFunctionCleanup(pInfo);
20,678✔
6134

6135
  return code;
20,678✔
6136
}
6137

6138
bool getTwaFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
75,696✔
6139
  pEnv->calcMemSize = sizeof(STwaInfo);
75,696✔
6140
  return true;
75,696✔
6141
}
6142

6143
int32_t twaFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
11,010,634✔
6144
  if (pResultInfo->initialized) {
11,010,634!
6145
    return TSDB_CODE_SUCCESS;
×
6146
  }
6147
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
11,010,634!
6148
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6149
  }
6150

6151
  STwaInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
11,010,652✔
6152
  pInfo->numOfElems = 0;
11,010,652✔
6153
  pInfo->p.key = INT64_MIN;
11,010,652✔
6154
  pInfo->win = TSWINDOW_INITIALIZER;
11,010,652✔
6155
  return TSDB_CODE_SUCCESS;
11,010,652✔
6156
}
6157

6158
static double twa_get_area(SPoint1 s, SPoint1 e) {
27,751,940✔
6159
  if (e.key == INT64_MAX || s.key == INT64_MIN) {
27,751,940!
6160
    return 0;
×
6161
  }
6162

6163
  if ((s.val >= 0 && e.val >= 0) || (s.val <= 0 && e.val <= 0)) {
27,752,048✔
6164
    return (s.val + e.val) * (e.key - s.key) / 2;
15,475,575✔
6165
  }
6166

6167
  double x = (s.key * e.val - e.key * s.val) / (e.val - s.val);
12,276,473✔
6168
  double val = (s.val * (x - s.key) + e.val * (e.key - x)) / 2;
12,276,473✔
6169
  return val;
12,276,473✔
6170
}
6171

6172
int32_t twaFunction(SqlFunctionCtx* pCtx) {
11,016,417✔
6173
  int32_t               code = TSDB_CODE_SUCCESS;
11,016,417✔
6174
  SInputColumnInfoData* pInput = &pCtx->input;
11,016,417✔
6175
  SColumnInfoData*      pInputCol = pInput->pData[0];
11,016,417✔
6176

6177
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
11,016,417✔
6178
  STwaInfo*            pInfo = GET_ROWCELL_INTERBUF(pResInfo);
11,016,417✔
6179
  SPoint1*             last = &pInfo->p;
11,016,417✔
6180

6181
  if (IS_NULL_TYPE(pInputCol->info.type)) {
11,016,417!
6182
    pInfo->numOfElems = 0;
×
6183
    goto _twa_over;
×
6184
  }
6185

6186
  funcInputUpdate(pCtx);
11,016,417✔
6187
  SFuncInputRow row = {0};
11,016,559✔
6188
  bool          result = false;
11,016,559✔
6189
  if (pCtx->start.key != INT64_MIN && last->key == INT64_MIN) {
11,016,559!
6190
    while (1) {
6191
      code = funcInputGetNextRow(pCtx, &row, &result);
3,682,935✔
6192
      if (TSDB_CODE_SUCCESS != code) {
3,682,934!
6193
        return code;
×
6194
      }
6195
      if (!result) {
3,682,934✔
6196
        break;
2✔
6197
      }
6198
      if (row.isDataNull) {
3,682,932✔
6199
        continue;
2✔
6200
      }
6201

6202
      last->key = row.ts;
3,682,930✔
6203

6204
      GET_TYPED_DATA(last->val, double, pInputCol->info.type, row.pData, typeGetTypeModFromColInfo(&pInputCol->info));
3,682,930!
6205

6206
      pInfo->dOutput += twa_get_area(pCtx->start, *last);
3,682,930✔
6207
      pInfo->win.skey = pCtx->start.key;
3,682,921✔
6208
      pInfo->numOfElems++;
3,682,921✔
6209
      break;
3,682,921✔
6210
    }
6211
  } else if (pInfo->p.key == INT64_MIN) {
7,333,626✔
6212
    while (1) {
6213
      code = funcInputGetNextRow(pCtx, &row, &result);
7,390,751✔
6214
      if (TSDB_CODE_SUCCESS != code) {
7,390,674!
6215
        return code;
×
6216
      }
6217
      if (!result) {
7,390,674✔
6218
        break;
8,192✔
6219
      }
6220
      if (row.isDataNull) {
7,382,482✔
6221
        continue;
62,233✔
6222
      }
6223

6224
      last->key = row.ts;
7,320,249✔
6225

6226
      GET_TYPED_DATA(last->val, double, pInputCol->info.type, row.pData, typeGetTypeModFromColInfo(&pInputCol->info));
7,320,249!
6227

6228
      pInfo->win.skey = last->key;
7,320,215✔
6229
      pInfo->numOfElems++;
7,320,215✔
6230
      break;
7,320,215✔
6231
    }
6232
  }
6233

6234
  SPoint1 st = {0};
11,016,438✔
6235

6236
  // calculate the value of
6237
  while (1) {
6238
    code = funcInputGetNextRow(pCtx, &row, &result);
31,285,769✔
6239
    if (TSDB_CODE_SUCCESS != code) {
31,284,126!
6240
      return code;
×
6241
    }
6242
    if (!result) {
31,284,126✔
6243
      break;
11,016,762✔
6244
    }
6245
    if (row.isDataNull) {
20,267,364✔
6246
      continue;
624✔
6247
    }
6248
    pInfo->numOfElems++;
20,266,740✔
6249
    switch (pInputCol->info.type) {
20,266,740!
6250
      case TSDB_DATA_TYPE_TINYINT: {
18,493,555✔
6251
        INIT_INTP_POINT(st, row.ts, *(int8_t*)row.pData);
18,493,555✔
6252
        break;
18,493,555✔
6253
      }
6254
      case TSDB_DATA_TYPE_SMALLINT: {
906,215✔
6255
        INIT_INTP_POINT(st, row.ts, *(int16_t*)row.pData);
906,215✔
6256
        break;
906,215✔
6257
      }
6258
      case TSDB_DATA_TYPE_INT: {
108,546✔
6259
        INIT_INTP_POINT(st, row.ts, *(int32_t*)row.pData);
108,546✔
6260
        break;
108,546✔
6261
      }
6262
      case TSDB_DATA_TYPE_BIGINT: {
83,032✔
6263
        INIT_INTP_POINT(st, row.ts, *(int64_t*)row.pData);
83,032✔
6264
        break;
83,032✔
6265
      }
6266
      case TSDB_DATA_TYPE_FLOAT: {
57,493✔
6267
        INIT_INTP_POINT(st, row.ts, *(float_t*)row.pData);
57,493✔
6268
        break;
57,493✔
6269
      }
6270
      case TSDB_DATA_TYPE_DOUBLE: {
354,597✔
6271
        INIT_INTP_POINT(st, row.ts, *(double*)row.pData);
354,597✔
6272
        break;
354,597✔
6273
      }
6274
      case TSDB_DATA_TYPE_UTINYINT: {
69,028✔
6275
        INIT_INTP_POINT(st, row.ts, *(uint8_t*)row.pData);
69,028✔
6276
        break;
69,028✔
6277
      }
6278
      case TSDB_DATA_TYPE_USMALLINT: {
68,997✔
6279
        INIT_INTP_POINT(st, row.ts, *(uint16_t*)row.pData);
68,997✔
6280
        break;
68,997✔
6281
      }
6282
      case TSDB_DATA_TYPE_UINT: {
67,689✔
6283
        INIT_INTP_POINT(st, row.ts, *(uint32_t*)row.pData);
67,689✔
6284
        break;
67,689✔
6285
      }
6286
      case TSDB_DATA_TYPE_UBIGINT: {
59,431✔
6287
        INIT_INTP_POINT(st, row.ts, *(uint64_t*)row.pData);
59,431✔
6288
        break;
59,431✔
6289
      }
6290
      default: {
×
6291
        return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
6292
      }
6293
    }
6294
    if (pInfo->p.key == st.key) {
20,268,583!
6295
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6296
    }
6297

6298
    pInfo->dOutput += twa_get_area(pInfo->p, st);
20,268,583✔
6299
    pInfo->p = st;
20,268,707✔
6300
  }
6301

6302
  // the last interpolated time window value
6303
  if (pCtx->end.key != INT64_MIN) {
11,016,762✔
6304
    pInfo->dOutput += twa_get_area(pInfo->p, pCtx->end);
3,801,752✔
6305
    pInfo->p = pCtx->end;
3,801,745✔
6306
    pInfo->numOfElems += 1;
3,801,745✔
6307
  }
6308

6309
  pInfo->win.ekey = pInfo->p.key;
11,016,755✔
6310

6311
_twa_over:
11,016,755✔
6312
  SET_VAL(pResInfo, 1, 1);
11,016,755✔
6313
  return TSDB_CODE_SUCCESS;
11,016,755✔
6314
}
6315

6316
/*
6317
 * To copy the input to interResBuf to avoid the input buffer space be over writen
6318
 * by next input data. The TWA function only applies to each table, so no merge procedure
6319
 * is required, we simply copy to the resut ot interResBuffer.
6320
 */
6321
// void twa_function_copy(SQLFunctionCtx *pCtx) {
6322
//   SResultRowEntryInfo *pResInfo = GET_RES_INFO(pCtx);
6323
//
6324
//   memcpy(GET_ROWCELL_INTERBUF(pResInfo), pCtx->pInput, (size_t)pCtx->inputBytes);
6325
//   pResInfo->hasResult = ((STwaInfo *)pCtx->pInput)->hasResult;
6326
// }
6327

6328
int32_t twaFinalize(struct SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
11,006,099✔
6329
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
11,006,099✔
6330

6331
  STwaInfo* pInfo = (STwaInfo*)GET_ROWCELL_INTERBUF(pResInfo);
11,006,099✔
6332
  if (pInfo->numOfElems == 0) {
11,006,099✔
6333
    pResInfo->numOfRes = 0;
8,073✔
6334
  } else {
6335
    if (pInfo->win.ekey == pInfo->win.skey) {
10,998,026✔
6336
      pInfo->dTwaRes = pInfo->p.val;
5,953,321✔
6337
    } else if (pInfo->win.ekey == INT64_MAX || pInfo->win.skey == INT64_MIN) {  // no data in timewindow
5,044,705!
UNCOV
6338
      pInfo->dTwaRes = 0;
×
6339
    } else {
6340
      pInfo->dTwaRes = pInfo->dOutput / (pInfo->win.ekey - pInfo->win.skey);
5,045,489✔
6341
    }
6342

6343
    pResInfo->numOfRes = 1;
10,998,026✔
6344
  }
6345

6346
  return functionFinalize(pCtx, pBlock);
11,006,099✔
6347
}
6348

6349
int32_t blockDistSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
1,632✔
6350
  if (pResultInfo->initialized) {
1,632!
6351
    return TSDB_CODE_SUCCESS;
×
6352
  }
6353
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
1,632!
6354
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6355
  }
6356

6357
  STableBlockDistInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,632✔
6358
  pInfo->minRows = INT32_MAX;
1,632✔
6359
  return TSDB_CODE_SUCCESS;
1,632✔
6360
}
6361

6362
int32_t blockDistFunction(SqlFunctionCtx* pCtx) {
3,262✔
6363
  const int32_t BLOCK_DIST_RESULT_ROWS = 25;
3,262✔
6364

6365
  SInputColumnInfoData* pInput = &pCtx->input;
3,262✔
6366
  SColumnInfoData*      pInputCol = pInput->pData[0];
3,262✔
6367
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
3,262✔
6368
  STableBlockDistInfo*  pDistInfo = GET_ROWCELL_INTERBUF(pResInfo);
3,262✔
6369

6370
  STableBlockDistInfo p1 = {0};
3,262✔
6371
  if (tDeserializeBlockDistInfo(varDataVal(pInputCol->pData), varDataLen(pInputCol->pData), &p1) < 0) {
3,262!
6372
    qError("failed to deserialize block dist info");
×
6373
    return TSDB_CODE_FAILED;
×
6374
  }
6375

6376
  pDistInfo->numOfBlocks += p1.numOfBlocks;
3,262✔
6377
  pDistInfo->numOfTables += p1.numOfTables;
3,262✔
6378
  pDistInfo->numOfInmemRows += p1.numOfInmemRows;
3,262✔
6379
  pDistInfo->numOfSttRows += p1.numOfSttRows;
3,262✔
6380
  pDistInfo->totalSize += p1.totalSize;
3,262✔
6381
  pDistInfo->totalRows += p1.totalRows;
3,262✔
6382
  pDistInfo->numOfFiles += p1.numOfFiles;
3,262✔
6383

6384
  pDistInfo->defMinRows = p1.defMinRows;
3,262✔
6385
  pDistInfo->defMaxRows = p1.defMaxRows;
3,262✔
6386
  pDistInfo->rowSize = p1.rowSize;
3,262✔
6387

6388
  if (pDistInfo->minRows > p1.minRows) {
3,262✔
6389
    pDistInfo->minRows = p1.minRows;
3✔
6390
  }
6391
  if (pDistInfo->maxRows < p1.maxRows) {
3,262✔
6392
    pDistInfo->maxRows = p1.maxRows;
3✔
6393
  }
6394
  pDistInfo->numOfVgroups += (p1.numOfTables != 0 ? 1 : 0);
3,262✔
6395
  for (int32_t i = 0; i < tListLen(pDistInfo->blockRowsHisto); ++i) {
68,502✔
6396
    pDistInfo->blockRowsHisto[i] += p1.blockRowsHisto[i];
65,240✔
6397
  }
6398

6399
  pResInfo->numOfRes = BLOCK_DIST_RESULT_ROWS;  // default output rows
3,262✔
6400
  return TSDB_CODE_SUCCESS;
3,262✔
6401
}
6402

6403
int32_t tSerializeBlockDistInfo(void* buf, int32_t bufLen, const STableBlockDistInfo* pInfo) {
6,507✔
6404
  SEncoder encoder = {0};
6,507✔
6405
  int32_t  code = 0;
6,507✔
6406
  int32_t  lino;
6407
  int32_t  tlen;
6408
  tEncoderInit(&encoder, buf, bufLen);
6,507✔
6409

6410
  TAOS_CHECK_EXIT(tStartEncode(&encoder));
6,511!
6411
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->rowSize));
13,022!
6412

6413
  TAOS_CHECK_EXIT(tEncodeU16(&encoder, pInfo->numOfFiles));
13,022!
6414
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfBlocks));
13,022!
6415
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfTables));
13,022!
6416

6417
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalSize));
13,022!
6418
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalRows));
13,022!
6419
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->maxRows));
13,022!
6420
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->minRows));
13,022!
6421
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMaxRows));
13,022!
6422
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMinRows));
13,022!
6423
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfInmemRows));
13,022!
6424
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfSttRows));
13,022!
6425
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfVgroups));
13,022!
6426

6427
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
136,577✔
6428
    TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->blockRowsHisto[i]));
260,132!
6429
  }
6430

6431
  tEndEncode(&encoder);
6,511✔
6432

6433
_exit:
6,519✔
6434
  if (code) {
6,519!
6435
    tlen = code;
×
6436
  } else {
6437
    tlen = encoder.pos;
6,519✔
6438
  }
6439
  tEncoderClear(&encoder);
6,519✔
6440
  return tlen;
6,513✔
6441
}
6442

6443
int32_t tDeserializeBlockDistInfo(void* buf, int32_t bufLen, STableBlockDistInfo* pInfo) {
3,262✔
6444
  SDecoder decoder = {0};
3,262✔
6445
  int32_t  code = 0;
3,262✔
6446
  int32_t  lino;
6447
  tDecoderInit(&decoder, buf, bufLen);
3,262✔
6448

6449
  TAOS_CHECK_EXIT(tStartDecode(&decoder));
3,262!
6450
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->rowSize));
6,524!
6451

6452
  TAOS_CHECK_EXIT(tDecodeU16(&decoder, &pInfo->numOfFiles));
6,524!
6453
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfBlocks));
6,524!
6454
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfTables));
6,524!
6455

6456
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->totalSize));
6,524!
6457
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->totalRows));
6,524!
6458
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->maxRows));
6,524!
6459
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->minRows));
6,524!
6460
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->defMaxRows));
6,524!
6461
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->defMinRows));
6,524!
6462
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfInmemRows));
6,524!
6463
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfSttRows));
6,524!
6464
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfVgroups));
6,524!
6465

6466
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
68,502✔
6467
    TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->blockRowsHisto[i]));
130,480!
6468
  }
6469

6470
_exit:
3,262✔
6471
  tDecoderClear(&decoder);
3,262✔
6472
  return code;
3,262✔
6473
}
6474

6475
int32_t blockDistFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1,632✔
6476
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,632✔
6477
  STableBlockDistInfo* pData = GET_ROWCELL_INTERBUF(pResInfo);
1,632✔
6478

6479
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);
1,632✔
6480
  if (NULL == pColInfo) {
1,632!
6481
    return TSDB_CODE_OUT_OF_RANGE;
×
6482
  }
6483

6484
  if (pData->totalRows == 0) {
1,632✔
6485
    pData->minRows = 0;
1,629✔
6486
  }
6487

6488
  int32_t row = 0;
1,632✔
6489
  char    st[256] = {0};
1,632✔
6490
  double  averageSize = 0;
1,632✔
6491
  if (pData->numOfBlocks != 0) {
1,632✔
6492
    averageSize = ((double)pData->totalSize) / pData->numOfBlocks;
3✔
6493
  }
6494
  uint64_t totalRawSize = pData->totalRows * pData->rowSize;
1,632✔
6495
  double   compRatio = 0;
1,632✔
6496
  if (totalRawSize != 0) {
1,632✔
6497
    compRatio = pData->totalSize * 100 / (double)totalRawSize;
3✔
6498
  }
6499

6500
  int32_t len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
3,264✔
6501
                          "Total_Blocks=[%d] Total_Size=[%.2f KiB] Average_size=[%.2f KiB] Compression_Ratio=[%.2f %c]",
6502
                          pData->numOfBlocks, pData->totalSize / 1024.0, averageSize / 1024.0, compRatio, '%');
1,632✔
6503

6504
  varDataSetLen(st, len);
1,632✔
6505
  int32_t code = colDataSetVal(pColInfo, row++, st, false);
1,632✔
6506
  if (TSDB_CODE_SUCCESS != code) {
1,632!
6507
    return code;
×
6508
  }
6509

6510
  int64_t avgRows = 0;
1,632✔
6511
  if (pData->numOfBlocks > 0) {
1,632✔
6512
    avgRows = pData->totalRows / pData->numOfBlocks;
3✔
6513
  }
6514

6515
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
1,632✔
6516
                  "Block_Rows=[%" PRId64 "] MinRows=[%d] MaxRows=[%d] AvgRows=[%" PRId64 "]", pData->totalRows,
6517
                  pData->minRows, pData->maxRows, avgRows);
6518
  varDataSetLen(st, len);
1,632✔
6519
  code = colDataSetVal(pColInfo, row++, st, false);
1,632✔
6520
  if (TSDB_CODE_SUCCESS != code) {
1,632!
6521
    return code;
×
6522
  }
6523

6524
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Inmem_Rows=[%u] Stt_Rows=[%u] ",
1,632✔
6525
                  pData->numOfInmemRows, pData->numOfSttRows);
6526
  varDataSetLen(st, len);
1,632✔
6527
  code = colDataSetVal(pColInfo, row++, st, false);
1,632✔
6528
  if (TSDB_CODE_SUCCESS != code) {
1,632!
6529
    return code;
×
6530
  }
6531

6532
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
3,264✔
6533
                  "Total_Tables=[%d] Total_Filesets=[%d] Total_Vgroups=[%d]", pData->numOfTables, pData->numOfFiles,
1,632✔
6534
                  pData->numOfVgroups);
6535

6536
  varDataSetLen(st, len);
1,632✔
6537
  code = colDataSetVal(pColInfo, row++, st, false);
1,632✔
6538
  if (TSDB_CODE_SUCCESS != code) {
1,632!
6539
    return code;
×
6540
  }
6541

6542
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
1,632✔
6543
                  "--------------------------------------------------------------------------------");
6544
  varDataSetLen(st, len);
1,632✔
6545
  code = colDataSetVal(pColInfo, row++, st, false);
1,632✔
6546
  if (TSDB_CODE_SUCCESS != code) {
1,632!
6547
    return code;
×
6548
  }
6549

6550
  int32_t maxVal = 0;
1,632✔
6551
  int32_t minVal = INT32_MAX;
1,632✔
6552
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
34,272✔
6553
    if (maxVal < pData->blockRowsHisto[i]) {
32,640✔
6554
      maxVal = pData->blockRowsHisto[i];
5✔
6555
    }
6556

6557
    if (minVal > pData->blockRowsHisto[i]) {
32,640✔
6558
      minVal = pData->blockRowsHisto[i];
1,633✔
6559
    }
6560
  }
6561

6562
  // maximum number of step is 80
6563
  double factor = pData->numOfBlocks / 80.0;
1,632✔
6564

6565
  int32_t numOfBuckets = sizeof(pData->blockRowsHisto) / sizeof(pData->blockRowsHisto[0]);
1,632✔
6566
  int32_t bucketRange = ceil(((double)(pData->defMaxRows - pData->defMinRows)) / numOfBuckets);
1,632✔
6567

6568
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
34,272✔
6569
    len =
32,640✔
6570
        tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "%04d |", pData->defMinRows + bucketRange * (i + 1));
32,640✔
6571

6572
    int32_t num = 0;
32,640✔
6573
    if (pData->blockRowsHisto[i] > 0) {
32,640✔
6574
      num = (pData->blockRowsHisto[i]) / factor;
7✔
6575
    }
6576

6577
    for (int32_t j = 0; j < num; ++j) {
32,878✔
6578
      int32_t x = tsnprintf(varDataVal(st) + len, sizeof(st) - VARSTR_HEADER_SIZE - len, "%c", '|');
238✔
6579
      len += x;
238✔
6580
    }
6581

6582
    if (pData->blockRowsHisto[i] > 0) {
32,640✔
6583
      double v = pData->blockRowsHisto[i] * 100.0 / pData->numOfBlocks;
7✔
6584
      len += tsnprintf(varDataVal(st) + len, sizeof(st) - VARSTR_HEADER_SIZE - len, "  %d (%.2f%c)",
7✔
6585
                       pData->blockRowsHisto[i], v, '%');
6586
    }
6587

6588
    varDataSetLen(st, len);
32,640✔
6589
    code = colDataSetVal(pColInfo, row++, st, false);
32,640✔
6590
    if (TSDB_CODE_SUCCESS != code) {
32,640!
6591
      return code;
×
6592
    }
6593
  }
6594

6595
  return TSDB_CODE_SUCCESS;
1,632✔
6596
}
6597
int32_t blockDBUsageSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
4✔
6598
  if (pResultInfo->initialized) {
4!
6599
    return TSDB_CODE_SUCCESS;
×
6600
  }
6601
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
4!
6602
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6603
  }
6604

6605
  SDBBlockUsageInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
4✔
6606
  return TSDB_CODE_SUCCESS;
4✔
6607
}
6608
int32_t blockDBUsageFunction(SqlFunctionCtx* pCtx) {
8✔
6609
  const int32_t BLOCK_DISK_USAGE_RESULT_ROWS = 2;
8✔
6610

6611
  SInputColumnInfoData* pInput = &pCtx->input;
8✔
6612
  SColumnInfoData*      pInputCol = pInput->pData[0];
8✔
6613
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
8✔
6614
  SDBBlockUsageInfo*    pDistInfo = GET_ROWCELL_INTERBUF(pResInfo);
8✔
6615

6616
  SDBBlockUsageInfo p1 = {0};
8✔
6617
  if (tDeserializeBlockDbUsage(varDataVal(pInputCol->pData), varDataLen(pInputCol->pData), &p1) < 0) {
8!
6618
    qError("failed to deserialize block dist info");
×
6619
    return TSDB_CODE_FAILED;
×
6620
  }
6621

6622
  pDistInfo->dataInDiskSize += p1.dataInDiskSize;
8✔
6623
  pDistInfo->walInDiskSize += p1.walInDiskSize;
8✔
6624
  pDistInfo->rawDataSize += p1.rawDataSize;
8✔
6625
  pResInfo->numOfRes = BLOCK_DISK_USAGE_RESULT_ROWS;  // default output rows
8✔
6626
  return TSDB_CODE_SUCCESS;
8✔
6627
}
6628

6629
int32_t tSerializeBlockDbUsage(void* buf, int32_t bufLen, const SDBBlockUsageInfo* pInfo) {
16✔
6630
  SEncoder encoder = {0};
16✔
6631
  int32_t  code = 0;
16✔
6632
  int32_t  lino;
6633
  int32_t  tlen;
6634
  tEncoderInit(&encoder, buf, bufLen);
16✔
6635

6636
  TAOS_CHECK_EXIT(tStartEncode(&encoder));
16!
6637

6638
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->dataInDiskSize));
32!
6639
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->walInDiskSize));
32!
6640
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->rawDataSize));
32!
6641

6642
  tEndEncode(&encoder);
16✔
6643

6644
_exit:
16✔
6645
  if (code) {
16!
6646
    tlen = code;
×
6647
  } else {
6648
    tlen = encoder.pos;
16✔
6649
  }
6650
  tEncoderClear(&encoder);
16✔
6651
  return tlen;
16✔
6652
}
6653
int32_t tDeserializeBlockDbUsage(void* buf, int32_t bufLen, SDBBlockUsageInfo* pInfo) {
8✔
6654
  SDecoder decoder = {0};
8✔
6655
  int32_t  code = 0;
8✔
6656
  int32_t  lino;
6657
  tDecoderInit(&decoder, buf, bufLen);
8✔
6658

6659
  TAOS_CHECK_EXIT(tStartDecode(&decoder));
8!
6660
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->dataInDiskSize));
16!
6661
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->walInDiskSize));
16!
6662
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->rawDataSize));
16!
6663

6664
_exit:
8✔
6665
  tDecoderClear(&decoder);
8✔
6666
  return code;
8✔
6667
}
6668
int32_t blockDBUsageFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
4✔
6669
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
4✔
6670
  SDBBlockUsageInfo*   pData = GET_ROWCELL_INTERBUF(pResInfo);
4✔
6671

6672
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);
4✔
6673
  if (NULL == pColInfo) {
4!
6674
    return TSDB_CODE_OUT_OF_RANGE;
×
6675
  }
6676
  int32_t len = 0;
4✔
6677
  int32_t row = 0;
4✔
6678
  char    st[256] = {0};
4✔
6679

6680
  uint64_t totalDiskSize = pData->dataInDiskSize;
4✔
6681
  uint64_t rawDataSize = pData->rawDataSize;
4✔
6682
  double   compressRatio = 0;
4✔
6683
  if (rawDataSize != 0) {
4✔
6684
    compressRatio = totalDiskSize * 100 / (double)rawDataSize;
3✔
6685
    len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Compress_ratio=[%.2f%]", compressRatio);
3✔
6686
  } else {
6687
    len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Compress_ratio=[NULL]");
1✔
6688
  }
6689

6690
  varDataSetLen(st, len);
4✔
6691
  int32_t code = colDataSetVal(pColInfo, row++, st, false);
4✔
6692
  if (TSDB_CODE_SUCCESS != code) {
4!
6693
    return code;
×
6694
  }
6695

6696
  len =
4✔
6697
      tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Disk_occupied=[%" PRId64 "k]", pData->dataInDiskSize);
4✔
6698
  varDataSetLen(st, len);
4✔
6699
  code = colDataSetVal(pColInfo, row++, st, false);
4✔
6700
  if (TSDB_CODE_SUCCESS != code) {
4!
6701
    return code;
×
6702
  }
6703
  return code;
4✔
6704
}
6705

6706
bool getDerivativeFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
30,298✔
6707
  pEnv->calcMemSize = sizeof(SDerivInfo);
30,298✔
6708
  return true;
30,298✔
6709
}
6710

6711
int32_t derivativeFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
60,999✔
6712
  if (pResInfo->initialized) {
60,999✔
6713
    return TSDB_CODE_SUCCESS;
30,621✔
6714
  }
6715
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
30,378!
6716
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6717
  }
6718

6719
  SDerivInfo* pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
30,378✔
6720

6721
  pDerivInfo->ignoreNegative = pCtx->param[2].param.i;
30,378✔
6722
  pDerivInfo->prevTs = -1;
30,378✔
6723
  pDerivInfo->tsWindow = pCtx->param[1].param.i;
30,378✔
6724
  pDerivInfo->valueSet = false;
30,378✔
6725
  return TSDB_CODE_SUCCESS;
30,378✔
6726
}
6727

6728
int32_t derivativeFunction(SqlFunctionCtx* pCtx) {
30,701✔
6729
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
30,701✔
6730
  SDerivInfo*          pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
30,701✔
6731

6732
  SInputColumnInfoData* pInput = &pCtx->input;
30,701✔
6733
  SColumnInfoData*      pInputCol = pInput->pData[0];
30,701✔
6734

6735
  int32_t          numOfElems = 0;
30,701✔
6736
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
30,701✔
6737
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
30,701✔
6738
  int32_t          code = TSDB_CODE_SUCCESS;
30,701✔
6739

6740
  funcInputUpdate(pCtx);
30,701✔
6741

6742
  double v = 0;
30,701✔
6743
  if (pCtx->order == TSDB_ORDER_ASC) {
30,701✔
6744
    SFuncInputRow row = {0};
27,375✔
6745
    bool          result = false;
27,375✔
6746
    while (1) {
3,480,683✔
6747
      code = funcInputGetNextRow(pCtx, &row, &result);
3,508,058✔
6748
      if (TSDB_CODE_SUCCESS != code) {
3,508,058!
6749
        return code;
×
6750
      }
6751
      if (!result) {
3,508,058✔
6752
        break;
27,375✔
6753
      }
6754
      if (row.isDataNull) {
3,480,683✔
6755
        continue;
19,768✔
6756
      }
6757

6758
      char* d = row.pData;
3,460,915✔
6759
      GET_TYPED_DATA(v, double, pInputCol->info.type, d, typeGetTypeModFromColInfo(&pInputCol->info));
3,460,915!
6760

6761
      int32_t pos = pCtx->offset + numOfElems;
3,460,915✔
6762
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
3,460,915✔
6763
        pDerivInfo->valueSet = true;
26,855✔
6764
      } else {
6765
        if (row.ts == pDerivInfo->prevTs) {
3,434,060!
6766
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6767
        }
6768
        double r = ((v - pDerivInfo->prevValue) * pDerivInfo->tsWindow) / (row.ts - pDerivInfo->prevTs);
3,434,060✔
6769
        if (pDerivInfo->ignoreNegative && r < 0) {
3,434,060✔
6770
        } else {
6771
          if (isinf(r) || isnan(r)) {
1,726,399!
6772
            colDataSetNULL(pOutput, pos);
×
6773
          } else {
6774
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
1,726,399✔
6775
            if (code != TSDB_CODE_SUCCESS) {
1,726,399!
6776
              return code;
×
6777
            }
6778
          }
6779

6780
          if (pTsOutput != NULL) {
1,726,399!
6781
            colDataSetInt64(pTsOutput, pos, &row.ts);
×
6782
          }
6783

6784
          // handle selectivity
6785
          if (pCtx->subsidiaries.num > 0) {
1,726,399✔
6786
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
1,243,049✔
6787
            if (code != TSDB_CODE_SUCCESS) {
1,243,049!
6788
              return code;
×
6789
            }
6790
          }
6791

6792
          numOfElems++;
1,726,399✔
6793
        }
6794
      }
6795

6796
      pDerivInfo->prevValue = v;
3,460,915✔
6797
      pDerivInfo->prevTs = row.ts;
3,460,915✔
6798
    }
6799
  } else {
6800
    SFuncInputRow row = {0};
3,326✔
6801
    bool          result = false;
3,326✔
6802
    while (1) {
331,668✔
6803
      code = funcInputGetNextRow(pCtx, &row, &result);
334,994✔
6804
      if (TSDB_CODE_SUCCESS != code) {
334,994!
6805
        return code;
×
6806
      }
6807
      if (!result) {
334,994✔
6808
        break;
3,326✔
6809
      }
6810
      if (row.isDataNull) {
331,668✔
6811
        continue;
222✔
6812
      }
6813

6814
      char* d = row.pData;
331,446✔
6815
      GET_TYPED_DATA(v, double, pInputCol->info.type, d, typeGetTypeModFromColInfo(&pInputCol->info));
331,446!
6816

6817
      int32_t pos = pCtx->offset + numOfElems;
331,446✔
6818
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
331,446✔
6819
        pDerivInfo->valueSet = true;
3,319✔
6820
      } else {
6821
        if (row.ts == pDerivInfo->prevTs) {
328,127!
6822
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6823
        }
6824
        double r = ((pDerivInfo->prevValue - v) * pDerivInfo->tsWindow) / (pDerivInfo->prevTs - row.ts);
328,127✔
6825
        if (pDerivInfo->ignoreNegative && r < 0) {
328,127✔
6826
        } else {
6827
          if (isinf(r) || isnan(r)) {
145,854!
6828
            colDataSetNULL(pOutput, pos);
×
6829
          } else {
6830
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
145,854✔
6831
            if (code != TSDB_CODE_SUCCESS) {
145,854!
6832
              return code;
×
6833
            }
6834
          }
6835

6836
          if (pTsOutput != NULL) {
145,854!
6837
            colDataSetInt64(pTsOutput, pos, &pDerivInfo->prevTs);
×
6838
          }
6839

6840
          // handle selectivity
6841
          if (pCtx->subsidiaries.num > 0) {
145,854✔
6842
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
50,776✔
6843
            if (code != TSDB_CODE_SUCCESS) {
50,776!
6844
              return code;
×
6845
            }
6846
          }
6847
          numOfElems++;
145,854✔
6848
        }
6849
      }
6850

6851
      pDerivInfo->prevValue = v;
331,446✔
6852
      pDerivInfo->prevTs = row.ts;
331,446✔
6853
    }
6854
  }
6855

6856
  pResInfo->numOfRes = numOfElems;
30,701✔
6857

6858
  return TSDB_CODE_SUCCESS;
30,701✔
6859
}
6860

6861
int32_t getIrateInfoSize(int32_t pkBytes) { return (int32_t)sizeof(SRateInfo) + 2 * pkBytes; }
2,315,976✔
6862

6863
bool getIrateFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
124,302✔
6864
  int32_t pkBytes = (pFunc->hasPk) ? pFunc->pkBytes : 0;
124,302✔
6865
  pEnv->calcMemSize = getIrateInfoSize(pkBytes);
124,302✔
6866
  return true;
124,429✔
6867
}
6868

6869
int32_t irateFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
13,762,422✔
6870
  if (pResInfo->initialized) {
13,762,422!
6871
    return TSDB_CODE_SUCCESS;
×
6872
  }
6873
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
13,762,422!
6874
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6875
  }
6876

6877
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
13,762,518✔
6878

6879
  pInfo->firstKey = INT64_MIN;
13,762,518✔
6880
  pInfo->lastKey = INT64_MIN;
13,762,518✔
6881
  pInfo->firstValue = (double)INT64_MIN;
13,762,518✔
6882
  pInfo->lastValue = (double)INT64_MIN;
13,762,518✔
6883

6884
  pInfo->hasResult = 0;
13,762,518✔
6885
  return TSDB_CODE_SUCCESS;
13,762,518✔
6886
}
6887

6888
static void doSaveRateInfo(SRateInfo* pRateInfo, bool isFirst, int64_t ts, char* pk, double v) {
67,515,686✔
6889
  if (isFirst) {
67,515,686✔
6890
    pRateInfo->firstValue = v;
27,976,622✔
6891
    pRateInfo->firstKey = ts;
27,976,622✔
6892
    if (pRateInfo->firstPk) {
27,976,622✔
6893
      int32_t pkBytes;
6894
      if (IS_VAR_DATA_TYPE(pRateInfo->pkType)) {
35!
6895
        pkBytes = calcStrBytesByType(pRateInfo->pkType, pk);
8✔
6896
      } else {
6897
        pkBytes = pRateInfo->pkBytes;
27✔
6898
      }
6899
      (void)memcpy(pRateInfo->firstPk, pk, pkBytes);
35✔
6900
    }
6901
  } else {
6902
    pRateInfo->lastValue = v;
39,539,064✔
6903
    pRateInfo->lastKey = ts;
39,539,064✔
6904
    if (pRateInfo->lastPk) {
39,539,064✔
6905
      int32_t pkBytes;
6906
      if (IS_VAR_DATA_TYPE(pRateInfo->pkType)) {
52!
6907
        pkBytes = calcStrBytesByType(pRateInfo->pkType, pk);
12✔
6908
      } else {
6909
        pkBytes = pRateInfo->pkBytes;
40✔
6910
      }
6911
      (void)memcpy(pRateInfo->lastPk, pk, pkBytes);
52✔
6912
    }
6913
  }
6914
}
67,515,686✔
6915

6916
static void initializeRateInfo(SqlFunctionCtx* pCtx, SRateInfo* pRateInfo, bool isMerge) {
15,975,273✔
6917
  if (pCtx->hasPrimaryKey) {
15,975,273✔
6918
    if (!isMerge) {
19✔
6919
      pRateInfo->pkType = pCtx->input.pPrimaryKey->info.type;
17✔
6920
      pRateInfo->pkBytes = pCtx->input.pPrimaryKey->info.bytes;
17✔
6921
      pRateInfo->firstPk = pRateInfo->pkData;
17✔
6922
      pRateInfo->lastPk = pRateInfo->pkData + pRateInfo->pkBytes;
17✔
6923
    } else {
6924
      pRateInfo->firstPk = pRateInfo->pkData;
2✔
6925
      pRateInfo->lastPk = pRateInfo->pkData + pRateInfo->pkBytes;
2✔
6926
    }
6927
  } else {
6928
    pRateInfo->firstPk = NULL;
15,975,254✔
6929
    pRateInfo->lastPk = NULL;
15,975,254✔
6930
  }
6931
}
15,975,273✔
6932

6933
int32_t irateFunction(SqlFunctionCtx* pCtx) {
11,593,332✔
6934
  int32_t              code = TSDB_CODE_SUCCESS;
11,593,332✔
6935
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
11,593,332✔
6936
  SRateInfo*           pRateInfo = GET_ROWCELL_INTERBUF(pResInfo);
11,593,332✔
6937

6938
  SInputColumnInfoData* pInput = &pCtx->input;
11,593,332✔
6939
  SColumnInfoData*      pInputCol = pInput->pData[0];
11,593,332✔
6940

6941
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
11,593,332✔
6942

6943
  funcInputUpdate(pCtx);
11,593,332✔
6944

6945
  initializeRateInfo(pCtx, pRateInfo, false);
11,593,451✔
6946

6947
  int32_t       numOfElems = 0;
11,593,548✔
6948
  int32_t       type = pInputCol->info.type;
11,593,548✔
6949
  SFuncInputRow row = {0};
11,593,548✔
6950
  bool          result = false;
11,593,548✔
6951
  while (1) {
37,549,207✔
6952
    code = funcInputGetNextRow(pCtx, &row, &result);
49,142,755✔
6953
    if (TSDB_CODE_SUCCESS != code) {
49,141,277!
6954
      return code;
×
6955
    }
6956
    if (!result) {
49,141,277✔
6957
      break;
11,593,648✔
6958
    }
6959
    if (row.isDataNull) {
37,547,629✔
6960
      continue;
59,321✔
6961
    }
6962

6963
    char*  data = row.pData;
37,488,308✔
6964
    double v = 0;
37,488,308✔
6965
    GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
37,488,308!
6966

6967
    if (INT64_MIN == pRateInfo->lastKey) {
37,491,685✔
6968
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
11,565,777✔
6969
      pRateInfo->hasResult = 1;
11,565,733✔
6970
      continue;
11,565,733✔
6971
    }
6972

6973
    if (row.ts > pRateInfo->lastKey) {
25,925,908✔
6974
      if ((INT64_MIN == pRateInfo->firstKey) || pRateInfo->lastKey > pRateInfo->firstKey) {
25,785,156!
6975
        doSaveRateInfo(pRateInfo, true, pRateInfo->lastKey, pRateInfo->lastPk, pRateInfo->lastValue);
25,785,159✔
6976
      }
6977
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
25,785,162✔
6978
      continue;
25,784,983✔
6979
    } else if (row.ts == pRateInfo->lastKey) {
140,752!
6980
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6981
    }
6982

6983
    if ((INT64_MIN == pRateInfo->firstKey) || row.ts > pRateInfo->firstKey) {
140,752!
6984
      doSaveRateInfo(pRateInfo, true, row.ts, row.pPk, v);
273✔
6985
    } else if (row.ts == pRateInfo->firstKey) {
140,479!
6986
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6987
    }
6988
  }
6989

6990
  numOfElems++;
11,593,648✔
6991

6992
  SET_VAL(pResInfo, numOfElems, 1);
11,593,648!
6993
  return TSDB_CODE_SUCCESS;
11,593,648✔
6994
}
6995

6996
static double doCalcRate(const SRateInfo* pRateInfo, double tickPerSec) {
11,563,461✔
6997
  if ((INT64_MIN == pRateInfo->lastKey) || (INT64_MIN == pRateInfo->firstKey) ||
11,563,461✔
6998
      (pRateInfo->firstKey >= pRateInfo->lastKey)) {
4,163,846!
6999
    return 0.0;
7,399,615✔
7000
  }
7001

7002
  double diff = 0;
4,163,846✔
7003
  // If the previous value of the last is greater than the last value, only keep the last point instead of the delta
7004
  // value between two values.
7005
  diff = pRateInfo->lastValue;
4,163,846✔
7006
  if (diff >= pRateInfo->firstValue) {
4,163,846✔
7007
    diff -= pRateInfo->firstValue;
1,415,749✔
7008
  }
7009

7010
  int64_t duration = pRateInfo->lastKey - pRateInfo->firstKey;
4,163,846✔
7011
  if (duration == 0) {
4,163,846!
7012
    return 0;
×
7013
  }
7014

7015
  return (duration > 0) ? ((double)diff) / (duration / tickPerSec) : 0.0;
4,163,846!
7016
}
7017

7018
static void irateTransferInfoImpl(TSKEY inputKey, SRateInfo* pInput, SRateInfo* pOutput, bool isFirstKey) {
232✔
7019
  if (inputKey > pOutput->lastKey) {
232✔
7020
    doSaveRateInfo(pOutput, true, pOutput->lastKey, pOutput->lastPk, pOutput->lastValue);
143✔
7021
    if (isFirstKey) {
143✔
7022
      doSaveRateInfo(pOutput, false, pInput->firstKey, pInput->firstPk, pInput->firstValue);
63✔
7023
    } else {
7024
      doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
80✔
7025
    }
7026
  } else if ((inputKey < pOutput->lastKey) && (inputKey > pOutput->firstKey)) {
89!
7027
    if (isFirstKey) {
14✔
7028
      doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
7✔
7029
    } else {
7030
      doSaveRateInfo(pOutput, true, pInput->lastKey, pInput->lastPk, pInput->lastValue);
7✔
7031
    }
7032
  } else {
7033
    // inputKey < pOutput->firstKey
7034
  }
7035
}
232✔
7036

7037
static void irateCopyInfo(SRateInfo* pInput, SRateInfo* pOutput) {
2,190,850✔
7038
  doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
2,190,850✔
7039
  doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
2,190,850✔
7040
}
2,190,850✔
7041

7042
static int32_t irateTransferInfo(SRateInfo* pInput, SRateInfo* pOutput) {
2,190,966✔
7043
  if ((pInput->firstKey != INT64_MIN &&
2,190,966✔
7044
       (pInput->firstKey == pOutput->firstKey || pInput->firstKey == pOutput->lastKey)) ||
2,100,315!
7045
      (pInput->lastKey != INT64_MIN && (pInput->lastKey == pOutput->firstKey || pInput->lastKey == pOutput->lastKey))) {
2,190,966!
7046
    return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
7047
  }
7048

7049
  if (pOutput->hasResult == 0) {
2,190,966✔
7050
    irateCopyInfo(pInput, pOutput);
2,190,850✔
7051
    pOutput->hasResult = pInput->hasResult;
2,190,850✔
7052
    return TSDB_CODE_SUCCESS;
2,190,850✔
7053
  }
7054

7055
  if (pInput->firstKey != INT64_MIN) {
116!
7056
    irateTransferInfoImpl(pInput->firstKey, pInput, pOutput, true);
116✔
7057
  }
7058

7059
  if (pInput->lastKey != INT64_MIN) {
116!
7060
    irateTransferInfoImpl(pInput->lastKey, pInput, pOutput, false);
116✔
7061
  }
7062

7063
  pOutput->hasResult = pInput->hasResult;
116✔
7064
  return TSDB_CODE_SUCCESS;
116✔
7065
}
7066

7067
int32_t irateFunctionMerge(SqlFunctionCtx* pCtx) {
2,190,976✔
7068
  SInputColumnInfoData* pInput = &pCtx->input;
2,190,976✔
7069
  SColumnInfoData*      pCol = pInput->pData[0];
2,190,976✔
7070
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
2,190,976!
7071
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
7072
  }
7073

7074
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,190,976✔
7075
  initializeRateInfo(pCtx, pInfo, true);
2,190,976✔
7076

7077
  int32_t start = pInput->startRowIndex;
2,190,976✔
7078
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
4,381,952✔
7079
    char*      data = colDataGetData(pCol, i);
2,190,976!
7080
    SRateInfo* pInputInfo = (SRateInfo*)varDataVal(data);
2,190,976✔
7081
    initializeRateInfo(pCtx, pInfo, true);
2,190,976✔
7082
    if (pInputInfo->hasResult) {
2,190,976✔
7083
      int32_t code = irateTransferInfo(pInputInfo, pInfo);
2,190,966✔
7084
      if (code != TSDB_CODE_SUCCESS) {
2,190,966!
7085
        return code;
×
7086
      }
7087
    }
7088
  }
7089

7090
  if (pInfo->hasResult) {
2,190,976✔
7091
    GET_RES_INFO(pCtx)->numOfRes = 1;
2,190,966✔
7092
  }
7093

7094
  return TSDB_CODE_SUCCESS;
2,190,976✔
7095
}
7096

7097
int32_t iratePartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
2,191,528✔
7098
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,191,528✔
7099
  SRateInfo*           pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
2,191,528✔
7100
  int32_t              resultBytes = getIrateInfoSize(pInfo->pkBytes);
2,191,528✔
7101
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
2,191,528!
7102

7103
  if (NULL == res) {
2,191,528!
7104
    return terrno;
×
7105
  }
7106
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
2,191,528✔
7107
  varDataSetLen(res, resultBytes);
2,191,528✔
7108

7109
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
2,191,528✔
7110
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
2,191,528✔
7111
  if (NULL == pCol) {
2,191,528!
7112
    taosMemoryFree(res);
×
7113
    return TSDB_CODE_OUT_OF_RANGE;
×
7114
  }
7115

7116
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
2,191,528✔
7117

7118
  taosMemoryFree(res);
2,191,528!
7119
  return code;
2,191,528✔
7120
}
7121

7122
int32_t irateFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
11,564,661✔
7123
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
11,564,661✔
7124
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
11,564,661✔
7125
  if (NULL == pCol) {
11,563,456!
7126
    return TSDB_CODE_OUT_OF_RANGE;
×
7127
  }
7128

7129
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
11,563,456✔
7130
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
11,563,456✔
7131

7132
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
11,563,456✔
7133
  double     result = doCalcRate(pInfo, (double)TSDB_TICK_PER_SECOND(pCtx->param[1].param.i));
11,563,456!
7134
  int32_t    code = colDataSetVal(pCol, pBlock->info.rows, (const char*)&result, pResInfo->isNullRes);
11,563,464✔
7135

7136
  return code;
11,563,258✔
7137
}
7138

7139
int32_t groupConstValueFunction(SqlFunctionCtx* pCtx) {
94,983,275✔
7140
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
94,983,275✔
7141
  SGroupKeyInfo*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
94,983,275✔
7142

7143
  SInputColumnInfoData* pInput = &pCtx->input;
94,983,275✔
7144
  SColumnInfoData*      pInputCol = pInput->pData[0];
94,983,275✔
7145

7146
  int32_t startIndex = pInput->startRowIndex;
94,983,275✔
7147

7148
  // escape rest of data blocks to avoid first entry to be overwritten.
7149
  if (pInfo->hasResult) {
94,983,275✔
7150
    goto _group_value_over;
7,662,380✔
7151
  }
7152

7153
  if (pInputCol->pData == NULL || colDataIsNull_s(pInputCol, startIndex)) {
174,084,293✔
7154
    pInfo->isNull = true;
2,770,967✔
7155
    pInfo->hasResult = true;
2,770,967✔
7156
    goto _group_value_over;
2,770,967✔
7157
  }
7158

7159
  char* data = colDataGetData(pInputCol, startIndex);
84,549,928!
7160
  if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
84,549,928!
7161
    int32_t bytes = calcStrBytesByType(pInputCol->info.type, data);
69,106,213✔
7162
    (void)memcpy(pInfo->data, data, bytes);
69,239,195✔
7163
  } else {
7164
    (void)memcpy(pInfo->data, data, pInputCol->info.bytes);
15,443,715✔
7165
  }
7166
  pInfo->hasResult = true;
84,682,910✔
7167

7168
_group_value_over:
95,116,257✔
7169

7170
  SET_VAL(pResInfo, 1, 1);
95,116,257✔
7171
  return TSDB_CODE_SUCCESS;
95,116,257✔
7172
}
7173

7174
int32_t groupKeyFunction(SqlFunctionCtx* pCtx) { return groupConstValueFunction(pCtx); }
94,673,145✔
7175

7176
int32_t groupConstValueFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
85,885,289✔
7177
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
85,885,289✔
7178
  int32_t          code = TSDB_CODE_SUCCESS;
85,885,289✔
7179
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
85,885,289✔
7180
  if (NULL == pCol) {
85,944,380!
7181
    return TSDB_CODE_OUT_OF_RANGE;
×
7182
  }
7183

7184
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
85,944,380✔
7185

7186
  SGroupKeyInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
85,944,380✔
7187

7188
  if (pInfo->hasResult) {
85,944,380!
7189
    int32_t currentRow = pBlock->info.rows;
85,981,822✔
7190
    for (; currentRow < pBlock->info.rows + pResInfo->numOfRes; ++currentRow) {
172,556,318✔
7191
      code = colDataSetVal(pCol, currentRow, pInfo->data, pInfo->isNull ? true : false);
85,963,384✔
7192
      if (TSDB_CODE_SUCCESS != code) {
86,574,496!
7193
        return code;
×
7194
      }
7195
    }
7196
  } else {
7197
    pResInfo->numOfRes = 0;
×
7198
  }
7199

7200
  return code;
86,555,492✔
7201
}
7202

7203
int32_t groupKeyFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { return groupConstValueFinalize(pCtx, pBlock); }
85,816,404✔
7204

7205
int32_t groupKeyCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
7206
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
7207
  SGroupKeyInfo*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
7208

7209
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
7210
  SGroupKeyInfo*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
7211

7212
  // escape rest of data blocks to avoid first entry to be overwritten.
7213
  if (pDBuf->hasResult) {
×
7214
    goto _group_key_over;
×
7215
  }
7216

7217
  if (pSBuf->isNull) {
×
7218
    pDBuf->isNull = true;
×
7219
    pDBuf->hasResult = true;
×
7220
    goto _group_key_over;
×
7221
  }
7222

7223
  if (IS_VAR_DATA_TYPE(pSourceCtx->resDataInfo.type)) {
×
7224
    int32_t bytes = calcStrBytesByType(pSourceCtx->resDataInfo.type, pSBuf->data);
×
7225
    (void)memcpy(pDBuf->data, pSBuf->data, bytes);
×
7226
  } else {
7227
    (void)memcpy(pDBuf->data, pSBuf->data, pSourceCtx->resDataInfo.bytes);
×
7228
  }
7229

7230
  pDBuf->hasResult = true;
×
7231

7232
_group_key_over:
×
7233

7234
  SET_VAL(pDResInfo, 1, 1);
×
7235
  return TSDB_CODE_SUCCESS;
×
7236
}
7237

7238
int32_t cachedLastRowFunction(SqlFunctionCtx* pCtx) {
6,026✔
7239
  int32_t numOfElems = 0;
6,026✔
7240

7241
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
6,026✔
7242
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
6,026✔
7243

7244
  SInputColumnInfoData* pInput = &pCtx->input;
6,026✔
7245
  SColumnInfoData*      pInputCol = pInput->pData[0];
6,026✔
7246

7247
  int32_t bytes = pInputCol->info.bytes;
6,026✔
7248
  pInfo->bytes = bytes;
6,026✔
7249

7250
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
6,026✔
7251
  pInfo->pkType = -1;
6,026✔
7252
  __compar_fn_t pkCompareFn = NULL;
6,026✔
7253
  if (pCtx->hasPrimaryKey) {
6,026✔
7254
    pInfo->pkType = pkCol->info.type;
952✔
7255
    pInfo->pkBytes = pkCol->info.bytes;
952✔
7256
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
952✔
7257
  }
7258

7259
  // TODO it traverse the different way.
7260
  // last_row function does not ignore the null value
7261
  for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
12,064✔
7262
    numOfElems++;
6,037✔
7263

7264
    bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
6,037✔
7265
    char* data = isNull ? NULL : colDataGetData(pInputCol, i);
6,037!
7266

7267
    TSKEY cts = getRowPTs(pInput->pPTS, i);
6,037!
7268
    if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
6,037✔
7269
      int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
5,171✔
7270
      if (code != TSDB_CODE_SUCCESS) {
5,171!
7271
        return code;
×
7272
      }
7273
      pResInfo->numOfRes = 1;
5,171✔
7274
    }
7275
  }
7276

7277
  SET_VAL(pResInfo, numOfElems, 1);
6,027!
7278
  return TSDB_CODE_SUCCESS;
6,027✔
7279
}
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