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

taosdata / TDengine / #4754

25 Sep 2025 05:58AM UTC coverage: 57.946% (-1.0%) from 58.977%
#4754

push

travis-ci

web-flow
enh: taos command line support '-uroot' on windows (#33055)

133189 of 293169 branches covered (45.43%)

Branch coverage included in aggregate %.

201677 of 284720 relevant lines covered (70.83%)

5398749.0 hits per line

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

68.38
/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; }
34,633,678✔
33
bool ignoreNull(int8_t ignoreOption) { return (ignoreOption & 0x2) == 0x2; }
304,852✔
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) {
348,468✔
210
  SFuncInputRowIter* pIter = &pCtx->rowIter;
348,468✔
211

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

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

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

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

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

398
bool funcInputGetNextRowNoPk(SFuncInputRowIter* pIter, SFuncInputRow* pRow) {
31,251,088✔
399
  if (pIter->rowIndex <= pIter->inputEndIndex) {
31,251,088✔
400
    setInputRowInfo(pRow, pIter, pIter->rowIndex, false);
30,895,883✔
401
    ++pIter->rowIndex;
30,896,700✔
402
    return true;
30,896,700✔
403
  } else {
404
    return false;
355,205✔
405
  }
406
}
407

408
int32_t funcInputGetNextRow(SqlFunctionCtx* pCtx, SFuncInputRow* pRow, bool* res) {
31,252,182✔
409
  SFuncInputRowIter* pIter = &pCtx->rowIter;
31,252,182✔
410
  if (pCtx->hasPrimaryKey) {
31,252,182✔
411
    if (pCtx->order == TSDB_ORDER_ASC) {
1,200!
412
      *res = funcInputGetNextRowAscPk(pIter, pRow);
1,200✔
413
      return TSDB_CODE_SUCCESS;
1,200✔
414
    } else {
415
      return funcInputGetNextRowDescPk(pIter, pRow, res);
×
416
    }
417
  } else {
418
    *res = funcInputGetNextRowNoPk(pIter, pRow);
31,250,982✔
419
    return TSDB_CODE_SUCCESS;
31,251,633✔
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) {
28,984,228✔
427
  if (pCtx->subsidiaries.num <= 0) {
28,984,228!
428
    return TSDB_CODE_SUCCESS;
×
429
  }
430

431
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
57,968,832✔
432
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
28,984,603✔
433

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

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

443
    char* pData = colDataGetData(pSrcCol, rowIndex);
28,984,603!
444

445
    // append to dest col
446
    int32_t dstSlotId = pc->pExpr->base.resSchema.slotId;
28,984,603✔
447

448
    SColumnInfoData* pDstCol = taosArrayGet(pCtx->pDstBlock->pDataBlock, dstSlotId);
28,984,603✔
449
    if (NULL == pDstCol) {
28,984,604!
450
      return TSDB_CODE_OUT_OF_RANGE;
×
451
    }
452
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
57,969,208✔
453
      colDataSetNULL(pDstCol, pos);
20!
454
    } else {
455
      int32_t code = colDataSetVal(pDstCol, pos, pData, false);
28,984,584✔
456
      if (TSDB_CODE_SUCCESS != code) {
28,984,584!
457
        return code;
×
458
      }
459
    }
460
  }
461
  return TSDB_CODE_SUCCESS;
28,984,229✔
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) {
176,158,735✔
470
  if (pResultInfo->initialized) {
176,158,735✔
471
    return TSDB_CODE_SUCCESS;  // already initialized
12,585✔
472
  }
473

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

478
  initResultRowEntry(pResultInfo, pCtx->resDataInfo.interBufSize);
176,146,150✔
479
  return TSDB_CODE_SUCCESS;
176,146,150✔
480
}
481

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

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

495
  return code;
76,082,677✔
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) {
4,637✔
529
  SNode* pParam = nodesListGetNode(pFunc->pParameterList, 0);
4,637✔
530
  if (QUERY_NODE_COLUMN == nodeType(pParam) && PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)pParam)->colId) {
4,637!
531
    return FUNC_DATA_REQUIRED_NOT_LOAD;
4,628✔
532
  }
533
  return FUNC_DATA_REQUIRED_SMA_LOAD;
9✔
534
}
535

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

541
static int64_t getNumOfElems(SqlFunctionCtx* pCtx) {
50,791,989✔
542
  int64_t numOfElem = 0;
50,791,989✔
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;
50,791,989✔
550
  SColumnInfoData*      pInputCol = pInput->pData[0];
50,791,989✔
551
  if (1 == pInput->numOfRows && pInput->blankFill) {
50,791,989✔
552
    return 0;
404,307✔
553
  }
554
  if (pInput->colDataSMAIsSet && pInput->totalRows == pInput->numOfRows) {
50,387,682!
555
    numOfElem = pInput->numOfRows - pInput->pColumnDataAgg[0]->numOfNull;
4,023✔
556
  } else {
557
    if (pInputCol->hasNull) {
50,383,659✔
558
      for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
200,786,337✔
559
        if (colDataIsNull(pInputCol, pInput->totalRows, i, NULL)) {
369,568,098!
560
          continue;
11,115,608✔
561
        }
562
        numOfElem += 1;
173,668,441✔
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;
34,381,371✔
568
    }
569
  }
570
  return numOfElem;
50,387,682✔
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) {
51,010,511✔
578
  int64_t numOfElem = 0;
51,010,511✔
579

580
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
51,010,511✔
581
  SInputColumnInfoData* pInput = &pCtx->input;
51,010,511✔
582

583
  int32_t type = pInput->pData[0]->info.type;
51,010,511✔
584

585
  char*   buf = GET_ROWCELL_INTERBUF(pResInfo);
51,010,511✔
586
  int64_t val = *((int64_t*)buf);
51,010,511✔
587
  if (IS_NULL_TYPE(type)) {
51,010,511✔
588
    // select count(NULL) returns 0
589
    numOfElem = 1;
274,174✔
590
    val += 0;
274,174✔
591
  } else {
592
    numOfElem = getNumOfElems(pCtx);
50,736,337✔
593
    val += numOfElem;
50,810,002✔
594
  }
595
  taosSetInt64Aligned((int64_t*)buf, val);
596

597
  if (tsCountAlwaysReturnValue) {
51,084,176✔
598
    pResInfo->numOfRes = 1;
51,057,806✔
599
  } else {
600
    SET_VAL(pResInfo, val, 1);
26,370✔
601
  }
602

603
  return TSDB_CODE_SUCCESS;
51,084,176✔
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) {
31,751,683✔
632
  int32_t numOfElem = 0;
31,751,683✔
633

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

640
  void* pSumRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
31,751,683✔
641
  SUM_RES_SET_TYPE(pSumRes, pCtx->inputType, type);
31,751,683!
642

643
  if (IS_NULL_TYPE(type)) {
31,751,683✔
644
    numOfElem = 0;
223✔
645
    goto _sum_over;
223✔
646
  }
647

648
  if (pInput->colDataSMAIsSet) {
31,751,460✔
649
    numOfElem = pInput->numOfRows - pAgg->numOfNull;
3,997✔
650

651
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
3,997!
652
      SUM_RES_INC_ISUM(pSumRes, pAgg->sum);
3,997✔
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];
31,747,463✔
668

669
    int32_t start = pInput->startRowIndex;
31,747,463✔
670
    int32_t numOfRows = pInput->numOfRows;
31,747,463✔
671

672
    if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
31,747,463✔
673
      if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
30,426,042✔
674
        LIST_ADD_N(SUM_RES_GET_ISUM(pSumRes), pCol, start, numOfRows, int8_t, numOfElem);
3,353,355!
675
      } else if (type == TSDB_DATA_TYPE_SMALLINT) {
29,484,414✔
676
        LIST_ADD_N(SUM_RES_GET_ISUM(pSumRes), pCol, start, numOfRows, int16_t, numOfElem);
427,020!
677
      } else if (type == TSDB_DATA_TYPE_INT) {
29,442,262✔
678
        LIST_ADD_N(SUM_RES_GET_ISUM(pSumRes), pCol, start, numOfRows, int32_t, numOfElem);
303,538,708!
679
      } else if (type == TSDB_DATA_TYPE_BIGINT) {
2,934,161✔
680
        LIST_ADD_N(SUM_RES_GET_ISUM(pSumRes), pCol, start, numOfRows, int64_t, numOfElem);
12,428,935✔
681
      }
682
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
1,321,421!
683
      if (type == TSDB_DATA_TYPE_UTINYINT) {
732✔
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) {
689✔
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) {
645✔
688
        LIST_ADD_N(SUM_RES_GET_USUM(pSumRes), pCol, start, numOfRows, uint32_t, numOfElem);
141,586!
689
      } else if (type == TSDB_DATA_TYPE_UBIGINT) {
178!
690
        LIST_ADD_N(SUM_RES_GET_USUM(pSumRes), pCol, start, numOfRows, uint64_t, numOfElem);
141,391!
691
      }
692
    } else if (type == TSDB_DATA_TYPE_DOUBLE) {
1,320,689✔
693
      LIST_ADD_N(SUM_RES_GET_DSUM(pSumRes), pCol, start, numOfRows, double, numOfElem);
4,197,898!
694
    } else if (type == TSDB_DATA_TYPE_FLOAT) {
714,415!
695
      LIST_ADD_N(SUM_RES_GET_DSUM(pSumRes), pCol, start, numOfRows, float, numOfElem);
2,811,393!
696
    } else if (IS_DECIMAL_TYPE(type)) {
×
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)))) {
31,751,459!
710
    numOfElem = 0;
×
711
  }
712

713
_sum_over:
31,877,200✔
714
  if (numOfElem == 0) {
31,751,682✔
715
    if (tsCountAlwaysReturnValue && pCtx->pExpr->pExpr->_function.pFunctNode->hasOriginalFunc &&
2,258,305!
716
        fmIsCountLikeFunc(pCtx->pExpr->pExpr->_function.pFunctNode->originalFuncId)) {
804,965✔
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);
31,751,697✔
722
  return TSDB_CODE_SUCCESS;
31,751,697✔
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) {
73,289✔
810
  pEnv->calcMemSize = SUM_RES_GET_SIZE(pFunc->node.resType.type);
73,289!
811
  return true;
73,289✔
812
}
813

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

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

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

854
  SMinmaxResInfo* buf = GET_ROWCELL_INTERBUF(pResultInfo);
3,971,341✔
855
  buf->assign = false;
3,971,341✔
856
  buf->tuplePos.pageId = -1;
3,971,341✔
857

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

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

870
int32_t minFunction(SqlFunctionCtx* pCtx) {
3,404,126✔
871
  int32_t numOfElems = 0;
3,404,126✔
872
  int32_t code = doMinMaxHelper(pCtx, 1, &numOfElems);
3,404,126✔
873
  if (code != TSDB_CODE_SUCCESS) {
3,433,064!
874
    return code;
×
875
  }
876
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
3,433,064✔
877
  return TSDB_CODE_SUCCESS;
3,433,064✔
878
}
879

880
int32_t maxFunction(SqlFunctionCtx* pCtx) {
3,994,276✔
881
  int32_t numOfElems = 0;
3,994,276✔
882
  int32_t code = doMinMaxHelper(pCtx, 0, &numOfElems);
3,994,276✔
883
  if (code != TSDB_CODE_SUCCESS) {
4,016,792!
884
    return code;
×
885
  }
886
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
4,016,792✔
887
  return TSDB_CODE_SUCCESS;
4,016,792✔
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) {
3,909,960✔
895
  int32_t code = TSDB_CODE_SUCCESS;
3,909,960✔
896

897
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
3,909,960✔
898
  SMinmaxResInfo*      pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
3,909,960✔
899

900
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
3,909,960✔
901
  int32_t currentRow = pBlock->info.rows;
3,909,960✔
902

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

909
  // NOTE: do nothing change it, for performance issue
910
  if (!pEntryInfo->isNullRes) {
3,909,978✔
911
    switch (pCol->info.type) {
2,276,099!
912
      case TSDB_DATA_TYPE_UBIGINT:
524,179✔
913
      case TSDB_DATA_TYPE_BIGINT:
914
        ((int64_t*)pCol->pData)[currentRow] = pRes->v;
524,179✔
915
        break;
524,179✔
916
      case TSDB_DATA_TYPE_UINT:
785,100✔
917
      case TSDB_DATA_TYPE_INT:
918
        colDataSetInt32(pCol, currentRow, (int32_t*)&pRes->v);
785,100✔
919
        break;
785,100✔
920
      case TSDB_DATA_TYPE_USMALLINT:
12,190✔
921
      case TSDB_DATA_TYPE_SMALLINT:
922
        colDataSetInt16(pCol, currentRow, (int16_t*)&pRes->v);
12,190✔
923
        break;
12,190✔
924
      case TSDB_DATA_TYPE_BOOL:
309,307✔
925
      case TSDB_DATA_TYPE_UTINYINT:
926
      case TSDB_DATA_TYPE_TINYINT:
927
        colDataSetInt8(pCol, currentRow, (int8_t*)&pRes->v);
309,307✔
928
        break;
309,307✔
929
      case TSDB_DATA_TYPE_DOUBLE:
324,658✔
930
        colDataSetDouble(pCol, currentRow, (double*)&pRes->v);
324,658✔
931
        break;
324,658✔
932
      case TSDB_DATA_TYPE_FLOAT: {
319,509✔
933
        float v = GET_FLOAT_VAL(&pRes->v);
319,509✔
934
        colDataSetFloat(pCol, currentRow, &v);
319,509✔
935
        break;
319,509✔
936
      }
937
      case TSDB_DATA_TYPE_VARBINARY:
1,954✔
938
      case TSDB_DATA_TYPE_VARCHAR:
939
      case TSDB_DATA_TYPE_NCHAR: {
940
        code = colDataSetVal(pCol, currentRow, pRes->str, false);
1,954✔
941
        if (TSDB_CODE_SUCCESS != code) {
1,954!
942
          return code;
×
943
        }
944
        break;
1,954✔
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,633,879!
955
  }
956

957
  if (IS_VAR_DATA_TYPE(pCol->info.type)) taosMemoryFreeClear(pRes->str);
3,909,978!
958
  if (pCtx->subsidiaries.num > 0) {
3,909,978✔
959
    if (pEntryInfo->numOfRes > 0) {
6,971✔
960
      code = setSelectivityValue(pCtx, pBlock, &pRes->tuplePos, currentRow);
5,515✔
961
    } else {
962
      code = setNullSelectivityValue(pCtx, pBlock, currentRow);
1,456✔
963
    }
964
  }
965

966
  return code;
3,910,804✔
967
}
968

969
int32_t setNullSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, int32_t rowIndex) {
466,875✔
970
  if (pCtx->subsidiaries.num <= 0) {
466,875✔
971
    return TSDB_CODE_SUCCESS;
465,312✔
972
  }
973

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

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

985
  return TSDB_CODE_SUCCESS;
1,563✔
986
}
987

988
int32_t setSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, const STuplePos* pTuplePos, int32_t rowIndex) {
3,807,285✔
989
  if (pCtx->subsidiaries.num <= 0) {
3,807,285✔
990
    return TSDB_CODE_SUCCESS;
3,680,891✔
991
  }
992

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

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

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

1012
      SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId);
177,818✔
1013
      if (NULL == pDstCol) {
177,817!
1014
        return terrno;
×
1015
      }
1016
      if (nullList[j]) {
177,818✔
1017
        colDataSetNULL(pDstCol, rowIndex);
29,729✔
1018
      } else {
1019
        code = colDataSetValOrCover(pDstCol, rowIndex, pStart, false);
148,089✔
1020
        if (TSDB_CODE_SUCCESS != code) {
148,094!
1021
          return code;
×
1022
        }
1023
      }
1024
      pStart += pDstCol->info.bytes;
177,823✔
1025
    }
1026
  }
1027

1028
  return TSDB_CODE_SUCCESS;
126,622✔
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) {
1,630✔
1034
  if (pCtx->subsidiaries.num <= 0) {
1,630!
1035
    return TSDB_CODE_SUCCESS;
×
1036
  }
1037

1038
  int32_t code = TSDB_CODE_SUCCESS;
1,630✔
1039
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
5,684✔
1040
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
4,054✔
1041

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

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

1051
    char* pData = colDataGetData(pSrcCol, rowIndex);
4,054!
1052

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

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

1061
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
8,108✔
1062
      colDataSetNULL(pDstCol, pos);
480✔
1063
    } else {
1064
      code = colDataSetVal(pDstCol, pos, pData, false);
3,574✔
1065
      if (TSDB_CODE_SUCCESS != code) {
3,574!
1066
        return code;
×
1067
      }
1068
    }
1069
  }
1070
  return code;
1,630✔
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); }
14,678✔
1166

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

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

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

1185
int32_t stdFunction(SqlFunctionCtx* pCtx) {
220,791✔
1186
  int32_t numOfElem = 0;
220,791✔
1187

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

1192
  SStdRes* pStdRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
220,791✔
1193
  pStdRes->type = type;
220,791✔
1194

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

1198
  int32_t start = pInput->startRowIndex;
220,791✔
1199
  int32_t numOfRows = pInput->numOfRows;
220,791✔
1200

1201
  if (IS_NULL_TYPE(type)) {
220,791✔
1202
    numOfElem = 0;
171✔
1203
    goto _stddev_over;
171✔
1204
  }
1205

1206
  switch (type) {
220,620!
1207
    case TSDB_DATA_TYPE_TINYINT: {
6,811✔
1208
      int8_t* plist = (int8_t*)pCol->pData;
6,811✔
1209
      for (int32_t i = start; i < numOfRows + start; ++i) {
181,864✔
1210
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
175,053!
1211
          continue;
12,977✔
1212
        }
1213

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

1220
      break;
6,811✔
1221
    }
1222

1223
    case TSDB_DATA_TYPE_SMALLINT: {
105,896✔
1224
      int16_t* plist = (int16_t*)pCol->pData;
105,896✔
1225
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
393,645✔
1226
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
287,749✔
1227
          continue;
80,032✔
1228
        }
1229

1230
        numOfElem += 1;
207,717✔
1231
        pStdRes->count += 1;
207,717✔
1232
        pStdRes->isum += plist[i];
207,717✔
1233
        pStdRes->quadraticISum += plist[i] * plist[i];
207,717✔
1234
      }
1235
      break;
105,896✔
1236
    }
1237

1238
    case TSDB_DATA_TYPE_INT: {
23,503✔
1239
      int32_t* plist = (int32_t*)pCol->pData;
23,503✔
1240
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
2,315,263✔
1241
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
2,291,760!
1242
          continue;
101,270✔
1243
        }
1244

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

1251
      break;
23,503✔
1252
    }
1253

1254
    case TSDB_DATA_TYPE_BIGINT: {
20,199✔
1255
      int64_t* plist = (int64_t*)pCol->pData;
20,199✔
1256
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
724,371✔
1257
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
704,172✔
1258
          continue;
13,057✔
1259
        }
1260

1261
        numOfElem += 1;
691,115✔
1262
        pStdRes->count += 1;
691,115✔
1263
        pStdRes->isum += plist[i];
691,115✔
1264
        pStdRes->quadraticISum += plist[i] * plist[i];
691,115✔
1265
      }
1266
      break;
20,199✔
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: {
18,971✔
1332
      float* plist = (float*)pCol->pData;
18,971✔
1333
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
1,817,277✔
1334
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
1,798,306!
1335
          continue;
95,800✔
1336
        }
1337

1338
        numOfElem += 1;
1,702,506✔
1339
        pStdRes->count += 1;
1,702,506✔
1340
        pStdRes->dsum += plist[i];
1,702,506✔
1341
        pStdRes->quadraticDSum += plist[i] * plist[i];
1,702,506✔
1342
      }
1343
      break;
18,971✔
1344
    }
1345

1346
    case TSDB_DATA_TYPE_DOUBLE: {
45,143✔
1347
      double* plist = (double*)pCol->pData;
45,143✔
1348
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
2,015,423✔
1349
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
1,970,280✔
1350
          continue;
441,049✔
1351
        }
1352

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

1361
    default:
×
1362
      break;
×
1363
  }
1364

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

1371
static void stdTransferInfo(SStdRes* pInput, SStdRes* pOutput) {
14,486✔
1372
  if (IS_NULL_TYPE(pInput->type)) {
14,486✔
1373
    return;
62✔
1374
  }
1375
  pOutput->type = pInput->type;
14,424✔
1376
  if (IS_SIGNED_NUMERIC_TYPE(pOutput->type)) {
14,424!
1377
    pOutput->quadraticISum += pInput->quadraticISum;
7,396✔
1378
    pOutput->isum += pInput->isum;
7,396✔
1379
  } else if (IS_UNSIGNED_NUMERIC_TYPE(pOutput->type)) {
7,028!
1380
    pOutput->quadraticUSum += pInput->quadraticUSum;
1✔
1381
    pOutput->usum += pInput->usum;
1✔
1382
  } else {
1383
    pOutput->quadraticDSum += pInput->quadraticDSum;
7,027✔
1384
    pOutput->dsum += pInput->dsum;
7,027✔
1385
  }
1386

1387
  pOutput->count += pInput->count;
14,424✔
1388
}
1389

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

1394
  if (IS_NULL_TYPE(pCol->info.type)) {
14,484!
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) {
14,484!
1400
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
1401
  }
1402

1403
  SStdRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
14,484✔
1404

1405
  for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
28,970✔
1406
    if (colDataIsNull_s(pCol, i)) continue;
28,972!
1407
    char*    data = colDataGetData(pCol, i);
14,486!
1408
    SStdRes* pInputInfo = (SStdRes*)varDataVal(data);
14,486✔
1409
    stdTransferInfo(pInputInfo, pInfo);
14,486✔
1410
  }
1411

1412
  SET_VAL(GET_RES_INFO(pCtx), 1, 1);
14,484✔
1413
  return TSDB_CODE_SUCCESS;
14,484✔
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) {
181,693✔
1484
  SInputColumnInfoData* pInput = &pCtx->input;
181,693✔
1485
  SStdRes*              pStddevRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
181,693✔
1486
  int32_t               type = pStddevRes->type;
181,693✔
1487
  double                avg;
1488

1489
  if (pStddevRes->count == 0) {
181,693✔
1490
    GET_RES_INFO(pCtx)->numOfRes = 0;
26,965✔
1491
    return functionFinalize(pCtx, pBlock);
26,965✔
1492
  }
1493

1494
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
154,728!
1495
    avg = pStddevRes->isum / ((double)pStddevRes->count);
115,004✔
1496
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticISum / ((double)pStddevRes->count) - avg * avg));
115,004✔
1497
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
39,724!
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);
39,714✔
1502
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticDSum / ((double)pStddevRes->count) - avg * avg));
39,714✔
1503
  }
1504

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

1510
  return functionFinalize(pCtx, pBlock);
154,728✔
1511
}
1512

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

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

1524
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
6,975!
1525
    avg = pStdvarRes->isum / ((double)pStdvarRes->count);
3,495✔
1526
    pStdvarRes->result = fabs(pStdvarRes->quadraticISum / ((double)pStdvarRes->count) - avg * avg);
3,495✔
1527
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
3,480!
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);
3,480✔
1532
    pStdvarRes->result = fabs(pStdvarRes->quadraticDSum / ((double)pStdvarRes->count) - avg * avg);
3,480✔
1533
  }
1534

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

1540
  return functionFinalize(pCtx, pBlock);
6,975✔
1541
}
1542

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

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

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

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

1564
  taosMemoryFree(res);
14,606!
1565
  return code;
14,606✔
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) {
8,191✔
1584
  pEnv->calcMemSize = sizeof(SLeastSQRInfo);
8,191✔
1585
  return true;
8,191✔
1586
}
1587

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

1596
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
33,068✔
1597

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

1605
int32_t leastSQRFunction(SqlFunctionCtx* pCtx) {
36,835✔
1606
  int32_t numOfElem = 0;
36,835✔
1607

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

1611
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
36,835✔
1612

1613
  SColumnInfoData* pCol = pInput->pData[0];
36,835✔
1614

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

1618
  int32_t start = pInput->startRowIndex;
36,835✔
1619
  int32_t numOfRows = pInput->numOfRows;
36,835✔
1620

1621
  switch (type) {
36,835!
1622
    case TSDB_DATA_TYPE_TINYINT: {
3,045✔
1623
      int8_t* plist = (int8_t*)pCol->pData;
3,045✔
1624
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
222,733✔
1625
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
219,688!
1626
          continue;
1,148✔
1627
        }
1628
        numOfElem++;
218,540✔
1629
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
218,540✔
1630
      }
1631
      break;
3,045✔
1632
    }
1633
    case TSDB_DATA_TYPE_SMALLINT: {
2,647✔
1634
      int16_t* plist = (int16_t*)pCol->pData;
2,647✔
1635
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
222,083✔
1636
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
219,436!
1637
          continue;
138,048✔
1638
        }
1639

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

1646
    case TSDB_DATA_TYPE_INT: {
8,057✔
1647
      int32_t* plist = (int32_t*)pCol->pData;
8,057✔
1648
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
431,324✔
1649
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
423,267!
1650
          continue;
138,411✔
1651
        }
1652

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

1659
    case TSDB_DATA_TYPE_BIGINT: {
1,634✔
1660
      int64_t* plist = (int64_t*)pCol->pData;
1,634✔
1661
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
84,222✔
1662
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
82,588!
1663
          continue;
948✔
1664
        }
1665

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

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

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

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

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

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

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

1722
    case TSDB_DATA_TYPE_FLOAT: {
9,077✔
1723
      float* plist = (float*)pCol->pData;
9,077✔
1724
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
377,097✔
1725
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
368,020!
1726
          continue;
148,211✔
1727
        }
1728

1729
        numOfElem++;
219,809✔
1730
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
219,809✔
1731
      }
1732
      break;
9,077✔
1733
    }
1734

1735
    case TSDB_DATA_TYPE_DOUBLE: {
11,862✔
1736
      double* plist = (double*)pCol->pData;
11,862✔
1737
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
394,590✔
1738
        if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
382,728!
1739
          continue;
1,148✔
1740
        }
1741

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

1753
    default:
1✔
1754
      break;
1✔
1755
  }
1756

1757
  pInfo->startVal = x;
36,835✔
1758
  pInfo->num += numOfElem;
36,835✔
1759

1760
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
36,835✔
1761

1762
  return TSDB_CODE_SUCCESS;
36,835✔
1763
}
1764

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

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

1776
  if (0 == pInfo->num) {
33,059✔
1777
    colDataSetNULL(pCol, currentRow);
11,278!
1778
    return TSDB_CODE_SUCCESS;
11,278✔
1779
  }
1780

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

1783
  param[1][1] = (double)pInfo->num;
21,781✔
1784
  param[1][0] = param[0][1];
21,781✔
1785

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

1789
  if (0 == param00) {
21,781✔
1790
    colDataSetNULL(pCol, currentRow);
16,427!
1791
    return TSDB_CODE_SUCCESS;
16,427✔
1792
  }
1793

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

1799
  param12 /= param[1][1];
5,354✔
1800

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

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

1818
  return code;
5,358✔
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) {
914✔
1844
  pEnv->calcMemSize = sizeof(SPercentileInfo);
914✔
1845
  return true;
914✔
1846
}
1847

1848
int32_t percentileFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
3,031✔
1849
  if (pResultInfo->initialized) {
3,031!
1850
    return TSDB_CODE_SUCCESS;
×
1851
  }
1852
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
3,031!
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,031✔
1858
  SET_DOUBLE_VAL(&pInfo->minval, DBL_MAX);
3,031✔
1859
  SET_DOUBLE_VAL(&pInfo->maxval, -DBL_MAX);
3,031✔
1860
  pInfo->numOfElems = 0;
3,031✔
1861

1862
  return TSDB_CODE_SUCCESS;
3,031✔
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) {
8,178✔
1877
  int32_t              code = TSDB_CODE_SUCCESS;
8,178✔
1878
  int32_t              numOfElems = 0;
8,178✔
1879
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
8,178✔
1880

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

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

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

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

1904
  // the first stage, only acquire the min/max value
1905
  if (pInfo->stage == 0) {
7,115✔
1906
    if (pCtx->input.colDataSMAIsSet) {
4,108!
1907
      double tmin = 0.0, tmax = 0.0;
×
1908
      if (IS_SIGNED_NUMERIC_TYPE(type)) {
×
1909
        tmin = (double)GET_INT64_VAL(&pAgg->min);
×
1910
        tmax = (double)GET_INT64_VAL(&pAgg->max);
×
1911
      } else if (IS_FLOAT_TYPE(type)) {
×
1912
        tmin = GET_DOUBLE_VAL(&pAgg->min);
×
1913
        tmax = GET_DOUBLE_VAL(&pAgg->max);
×
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) {
×
1920
        SET_DOUBLE_VAL(&pInfo->minval, tmin);
×
1921
      }
1922

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

1927
      pInfo->numOfElems += (pInput->numOfRows - pAgg->numOfNull);
×
1928
    } else {
1929
      // check the valid data one by one
1930
      int32_t start = pInput->startRowIndex;
4,108✔
1931
      for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
516,907✔
1932
        if (colDataIsNull_f(pCol, i)) {
512,799!
1933
          continue;
1,432✔
1934
        }
1935

1936
        char* data = colDataGetData(pCol, i);
511,367!
1937

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

1944
        if (v > GET_DOUBLE_VAL(&pInfo->maxval)) {
511,367✔
1945
          SET_DOUBLE_VAL(&pInfo->maxval, v);
409,284✔
1946
        }
1947

1948
        pInfo->numOfElems += 1;
511,367✔
1949
      }
1950
    }
1951
  } else {
1952
    // the second stage, calculate the true percentile value
1953
    int32_t start = pInput->startRowIndex;
3,007✔
1954
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
514,254✔
1955
      if (colDataIsNull_f(pCol, i)) {
511,249!
1956
        continue;
×
1957
      }
1958

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

1968
    SET_VAL(pResInfo, numOfElems, 1);
3,005!
1969
  }
1970

1971
  pCtx->needCleanup = true;
7,113✔
1972
  return TSDB_CODE_SUCCESS;
7,113✔
1973
}
1974

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

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

1982
  tMemBucket** pMemBucket = &ppInfo->pMemBucket;
3,027✔
1983
  if ((*pMemBucket) != NULL && (*pMemBucket)->total > 0) {  // check for null
3,027!
1984
    if (pCtx->numOfParams > 2) {
1,964✔
1985
      char buf[3200] = {0};
30✔
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;
30✔
1989

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

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

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

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

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

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

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

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

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

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

2040
_fin_error:
×
2041

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

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

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

2061
static int8_t getApercentileAlgo(char* algoStr) {
22,856✔
2062
  int8_t algoType;
2063
  if (strcasecmp(algoStr, "default") == 0) {
22,856✔
2064
    algoType = APERCT_ALGO_DEFAULT;
11,421✔
2065
  } else if (strcasecmp(algoStr, "t-digest") == 0) {
11,435✔
2066
    algoType = APERCT_ALGO_TDIGEST;
11,431✔
2067
  } else {
2068
    algoType = APERCT_ALGO_UNKNOWN;
4✔
2069
  }
2070

2071
  return algoType;
22,856✔
2072
}
2073

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

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

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

2091
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
88,784✔
2092

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

2097
  if (pCtx->numOfParams == 2) {
88,788✔
2098
    pInfo->algo = APERCT_ALGO_DEFAULT;
65,932✔
2099
  } else if (pCtx->numOfParams == 3) {
22,856!
2100
    pInfo->algo = getApercentileAlgo(varDataVal(pCtx->param[2].param.pz));
22,857✔
2101
    if (pInfo->algo == APERCT_ALGO_UNKNOWN) {
22,849!
2102
      return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
2103
    }
2104
  }
2105

2106
  char* tmp = (char*)pInfo + sizeof(SAPercentileInfo);
88,780✔
2107
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
88,780✔
2108
    pInfo->pTDigest = tdigestNewFrom(tmp, COMPRESSION);
11,430✔
2109
  } else {
2110
    buildHistogramInfo(pInfo);
77,350✔
2111
    pInfo->pHisto = tHistogramCreateFrom(tmp, MAX_HISTOGRAM_BIN);
77,351✔
2112
    qDebug("%s set up histogram, numOfElems:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
77,348!
2113
           pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2114
  }
2115

2116
  return TSDB_CODE_SUCCESS;
88,789✔
2117
}
2118

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

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

2127
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
89,627✔
2128

2129
  int32_t start = pInput->startRowIndex;
89,627✔
2130
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
89,627✔
2131
    buildTDigestInfo(pInfo);
11,455✔
2132
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
11,456✔
2133
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
586,491✔
2134
      if (colDataIsNull_f(pCol, i)) {
575,021!
2135
        continue;
210,544✔
2136
      }
2137
      numOfElems += 1;
364,477✔
2138
      char* data = colDataGetData(pCol, i);
364,477!
2139

2140
      double  v = 0;  // value
364,477✔
2141
      int64_t w = 1;  // weigth
364,477✔
2142
      GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pCol->info));
364,477!
2143
      int32_t code = tdigestAdd(pInfo->pTDigest, v, w);
364,477✔
2144
      if (code != TSDB_CODE_SUCCESS) {
364,489!
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);
78,172✔
2152
    qDebug("%s before add %d elements into histogram, total:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems: %p",
78,173!
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) {
1,674,827✔
2156
      if (colDataIsNull_f(pCol, i)) {
1,596,662✔
2157
        continue;
570,917✔
2158
      }
2159
      numOfElems += 1;
1,025,745✔
2160
      char* data = colDataGetData(pCol, i);
1,025,745!
2161

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

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

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

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

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

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

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

2198
    if (pTDigest->num_centroids <= 0 && pTDigest->num_buffered_pts == 0) {
120!
2199
      (void)memcpy(pTDigest, pInput->pTDigest, (size_t)TDIGEST_SIZE(COMPRESSION));
120✔
2200
      tdigestAutoFill(pTDigest, COMPRESSION);
120✔
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);
345✔
2209
    if (pInput->pHisto->numOfElems <= 0) {
345✔
2210
      return TSDB_CODE_SUCCESS;
50✔
2211
    }
2212

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

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

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

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

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

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

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

2251
  SInputColumnInfoData* pInput = &pCtx->input;
462✔
2252

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

2258
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
462✔
2259

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

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

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

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

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

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

2288
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
73,174✔
2289
    buildTDigestInfo(pInfo);
11,272✔
2290
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
11,273✔
2291
    if (pInfo->pTDigest->size > 0) {
11,273!
2292
      pInfo->result = tdigestQuantile(pInfo->pTDigest, pInfo->percent / 100);
11,273✔
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);
61,902✔
2299
    if (pInfo->pHisto->numOfElems > 0) {
61,901✔
2300
      qDebug("%s get the final res, elements:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
36,860!
2301
             pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2302

2303
      double  ratio[] = {pInfo->percent};
36,864✔
2304
      double* res = NULL;
36,864✔
2305
      int32_t code = tHistogramUniform(pInfo->pHisto, ratio, 1, &res);
36,864✔
2306
      if (TSDB_CODE_SUCCESS != code) {
36,865!
2307
        taosMemoryFree(res);
×
2308
        return code;
×
2309
      }
2310
      pInfo->result = *res;
36,865✔
2311
      // memcpy(pCtx->pOutput, res, sizeof(double));
2312
      taosMemoryFree(res);
36,865!
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__,
25,041!
2317
             pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries);
2318
    }
2319
  }
2320

2321
  return functionFinalize(pCtx, pBlock);
73,189✔
2322
}
2323

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

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

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

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

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

2351
  taosMemoryFree(res);
567!
2352
  return code;
567✔
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) {
1,501✔
2375
  char numVal[8] = {0};
1,501✔
2376
  switch (pkType) {
1,501✔
2377
    case TSDB_DATA_TYPE_INT:
265✔
2378
      *(int32_t*)numVal = (int32_t)VALUE_GET_TRIVIAL_DATUM(pVal);
265✔
2379
      break;
265✔
2380
    case TSDB_DATA_TYPE_UINT:
255✔
2381
      *(uint32_t*)numVal = (uint32_t)VALUE_GET_TRIVIAL_DATUM(pVal);
255✔
2382
      break;
255✔
2383
    case TSDB_DATA_TYPE_BIGINT:
256✔
2384
      *(int64_t*)numVal = (int64_t)VALUE_GET_TRIVIAL_DATUM(pVal);
256✔
2385
      break;
256✔
2386
    case TSDB_DATA_TYPE_UBIGINT:
292✔
2387
      *(uint64_t*)numVal = (uint64_t)VALUE_GET_TRIVIAL_DATUM(pVal);
292✔
2388
      break;
292✔
2389
    default:
433✔
2390
      break;
433✔
2391
  }
2392
  char*         blockData = (IS_NUMERIC_TYPE(pkType)) ? (char*)numVal : (char*)pVal->pData;
1,501!
2393
  __compar_fn_t fn = getKeyComparFunc(pkType, order);
1,501✔
2394
  return fn(pkData, blockData);
1,504✔
2395
}
2396

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

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

2405
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
3,030✔
2406
  if (pResult->hasResult) {
3,030✔
2407
    if (pResult->pkBytes > 0) {
2,991✔
2408
      pResult->pkData = pResult->buf + pResult->bytes;
1,437✔
2409
    } else {
2410
      pResult->pkData = NULL;
1,554✔
2411
    }
2412
    if (pResult->ts < pBlockInfo->window.skey) {
2,991✔
2413
      return FUNC_DATA_REQUIRED_NOT_LOAD;
1,116✔
2414
    } else if (pResult->ts == pBlockInfo->window.skey) {
1,875✔
2415
      if (NULL == pResult->pkData) {
842✔
2416
        return FUNC_DATA_REQUIRED_NOT_LOAD;
315✔
2417
      }
2418
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 0, TSDB_ORDER_ASC) < 0) {
527✔
2419
        return FUNC_DATA_REQUIRED_NOT_LOAD;
96✔
2420
      }
2421
    }
2422
    return FUNC_DATA_REQUIRED_DATA_LOAD;
1,465✔
2423
  } else {
2424
    return FUNC_DATA_REQUIRED_DATA_LOAD;
39✔
2425
  }
2426
}
2427

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

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

2436
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
8,316✔
2437
  if (pResult->hasResult) {
8,316✔
2438
    if (pResult->pkBytes > 0) {
8,263✔
2439
      pResult->pkData = pResult->buf + pResult->bytes;
2,634✔
2440
    } else {
2441
      pResult->pkData = NULL;
5,629✔
2442
    }
2443
    if (pResult->ts > pBlockInfo->window.ekey) {
8,263✔
2444
      return FUNC_DATA_REQUIRED_NOT_LOAD;
2,136✔
2445
    } else if (pResult->ts == pBlockInfo->window.ekey && pResult->pkData) {
6,127✔
2446
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 1, TSDB_ORDER_DESC) < 0) {
974✔
2447
        return FUNC_DATA_REQUIRED_NOT_LOAD;
294✔
2448
      }
2449
    }
2450
    return FUNC_DATA_REQUIRED_DATA_LOAD;
5,835✔
2451
  } else {
2452
    return FUNC_DATA_REQUIRED_DATA_LOAD;
53✔
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; }
1,152,655✔
2458

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

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

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

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

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

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

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

2501
static int32_t prepareBuf(SqlFunctionCtx* pCtx) {
335,659✔
2502
  if (pCtx->subsidiaries.rowLen == 0) {
335,659✔
2503
    int32_t rowLen = 0;
23,319✔
2504
    for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
51,222✔
2505
      SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
27,903✔
2506
      rowLen += pc->pExpr->base.resSchema.bytes;
27,903✔
2507
    }
2508

2509
    pCtx->subsidiaries.rowLen = rowLen + pCtx->subsidiaries.num * sizeof(bool);
23,319✔
2510
    pCtx->subsidiaries.buf = taosMemoryMalloc(pCtx->subsidiaries.rowLen);
23,319!
2511
    if (NULL == pCtx->subsidiaries.buf) {
23,340!
2512
      return terrno;
×
2513
    }
2514
  }
2515
  return TSDB_CODE_SUCCESS;
335,680✔
2516
}
2517

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

2522
  if (pCtx->subsidiaries.num <= 0) {
12,516,468✔
2523
    return TSDB_CODE_SUCCESS;
12,470,069✔
2524
  }
2525

2526
  if (!pInfo->hasResult) {
46,399✔
2527
    code = saveTupleData(pCtx, rowIndex, pSrcBlock, &pInfo->pos);
44,276✔
2528
  } else if (!noElements) {
2,123!
2529
    code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pInfo->pos);
3,646✔
2530
  } else {
2531
  }  // dothing
2532

2533
  return code;
47,935✔
2534
}
2535

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

2541
  if (IS_VAR_DATA_TYPE(type)) {
9,580,199!
2542
    pInfo->bytes = calcStrBytesByType(type, pData);
1,920,654✔
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);
9,595,742✔
2551
  if (pkData != NULL) {
9,595,742✔
2552
    if (IS_VAR_DATA_TYPE(pInfo->pkType)) {
6,224!
2553
      pInfo->pkBytes = calcStrBytesByType(pInfo->pkType, pkData);
2,072✔
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);
6,224✔
2561
    pInfo->pkData = pInfo->buf + pInfo->bytes;
6,224✔
2562
  }
2563

2564
  pInfo->ts = currentTs;
9,595,742✔
2565
  int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pInfo, false);
9,595,742✔
2566
  if (code != TSDB_CODE_SUCCESS) {
9,582,158!
2567
    return code;
×
2568
  }
2569

2570
  pInfo->hasResult = true;
9,582,158✔
2571
  return TSDB_CODE_SUCCESS;
9,582,158✔
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) {
3,734,953✔
2577
  int32_t numOfElems = 0;
3,734,953✔
2578

2579
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
3,734,953✔
2580
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
3,734,953✔
2581

2582
  SInputColumnInfoData* pInput = &pCtx->input;
3,734,953✔
2583
  SColumnInfoData*      pInputCol = pInput->pData[0];
3,734,953✔
2584

2585
  pInfo->bytes = pInputCol->info.bytes;
3,734,953✔
2586

2587
  if (IS_NULL_TYPE(pInputCol->info.type)) {
3,734,953✔
2588
    return TSDB_CODE_SUCCESS;
1,155✔
2589
  }
2590

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

2600
  // All null data column, return directly.
2601
  if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) &&
3,733,782!
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;
3,733,782!
2613

2614
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
3,733,782✔
2615
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
3,733,782!
2616

2617
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
3,733,782✔
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;
3,733,782✔
2671

2672
  int     from = -1;
3,733,782✔
2673
  int32_t i = -1;
3,733,782✔
2674
  while (funcInputGetNextRowIndex(pInput, from, true, &i, &from)) {
18,357,476✔
2675
    if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
27,034,261!
2676
      continue;
4,859,468✔
2677
    }
2678

2679
    numOfElems++;
9,767,118✔
2680
    char* data = colDataGetData(pInputCol, i);
9,767,118!
2681
    char* pkData = NULL;
9,767,118✔
2682
    if (pCtx->hasPrimaryKey) {
9,767,118✔
2683
      pkData = colDataGetData(pkCol, i);
9,088!
2684
    }
2685
    TSKEY cts = pts[i];
9,767,118✔
2686
    if (pResInfo->numOfRes == 0 || pInfo->ts > cts ||
9,767,118✔
2687
        (pInfo->ts == cts && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
7,661,341!
2688
      int32_t code = doSaveCurrentVal(pCtx, i, cts, pkData, pInputCol->info.type, data);
2,105,777✔
2689
      if (code != TSDB_CODE_SUCCESS) {
2,102,885!
2690
        return code;
×
2691
      }
2692
      pResInfo->numOfRes = 1;
2,102,885✔
2693
    }
2694
  }
2695
#endif
2696

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

2709
int32_t lastFunction(SqlFunctionCtx* pCtx) {
5,456,098✔
2710
  int32_t numOfElems = 0;
5,456,098✔
2711

2712
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5,456,098✔
2713
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5,456,098✔
2714

2715
  SInputColumnInfoData* pInput = &pCtx->input;
5,456,098✔
2716
  SColumnInfoData*      pInputCol = pInput->pData[0];
5,456,098✔
2717

2718
  int32_t type = pInputCol->info.type;
5,456,098✔
2719
  int32_t bytes = pInputCol->info.bytes;
5,456,098✔
2720

2721
  if (IS_NULL_TYPE(type)) {
5,456,098✔
2722
    return TSDB_CODE_SUCCESS;
1,137✔
2723
  }
2724
  pInfo->bytes = bytes;
5,454,961✔
2725

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

2735
  // All null data column, return directly.
2736
  if (pInput->colDataSMAIsSet && (pInput->pColumnDataAgg[0]->numOfNull == pInput->totalRows) &&
5,454,357!
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;
5,454,357!
2748

2749
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
5,454,357!
2750
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
5,454,357!
2751

2752
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
5,454,357✔
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;
5,454,357✔
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) {
7,226,841✔
2808
    numOfElems = 1;
1,805,516✔
2809

2810
    int32_t round = pInput->numOfRows >> 2;
1,805,516✔
2811
    int32_t reminder = pInput->numOfRows & 0x03;
1,805,516✔
2812

2813
    for (int32_t i = pInput->startRowIndex, tick = 0; tick < round; i += 4, tick += 1) {
5,786,840✔
2814
      int64_t cts = pts[i];
4,014,339✔
2815
      int32_t chosen = i;
4,014,339✔
2816

2817
      if (cts < pts[i + 1]) {
4,014,339✔
2818
        cts = pts[i + 1];
174,729✔
2819
        chosen = i + 1;
174,729✔
2820
      }
2821

2822
      if (cts < pts[i + 2]) {
4,014,339✔
2823
        cts = pts[i + 2];
174,733✔
2824
        chosen = i + 2;
174,733✔
2825
      }
2826

2827
      if (cts < pts[i + 3]) {
4,014,339✔
2828
        cts = pts[i + 3];
174,729✔
2829
        chosen = i + 3;
174,729✔
2830
      }
2831

2832
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
4,014,339✔
2833
        char*   data = colDataGetData(pInputCol, chosen);
1,063,826!
2834
        int32_t code = doSaveCurrentVal(pCtx, chosen, cts, NULL, type, data);
1,063,826✔
2835
        if (code != TSDB_CODE_SUCCESS) {
1,030,811!
2836
          return code;
×
2837
        }
2838
        pResInfo->numOfRes = 1;
1,030,811✔
2839
      }
2840
    }
2841

2842
    for (int32_t i = pInput->startRowIndex + round * 4; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
4,532,202✔
2843
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i]) {
2,759,718✔
2844
        char*   data = colDataGetData(pInputCol, i);
255,463!
2845
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], NULL, type, data);
255,463✔
2846
        if (code != TSDB_CODE_SUCCESS) {
255,446!
2847
          return code;
×
2848
        }
2849
        pResInfo->numOfRes = 1;
255,446✔
2850
      }
2851
    }
2852
  } else {
2853
    int     from = -1;
3,648,841✔
2854
    int32_t i = -1;
3,648,841✔
2855
    while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
53,535,656✔
2856
      if (colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
99,773,612✔
2857
        continue;
8,442,441✔
2858
      }
2859

2860
      numOfElems++;
41,444,365✔
2861
      char* pkData = NULL;
41,444,365✔
2862
      if (pCtx->hasPrimaryKey) {
41,444,365✔
2863
        pkData = colDataGetData(pkCol, i);
10,541!
2864
      }
2865
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i] ||
41,444,365✔
2866
          (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
35,304,612!
2867
        char*   data = colDataGetData(pInputCol, i);
6,172,123!
2868
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], pkData, type, data);
6,172,123✔
2869
        if (code != TSDB_CODE_SUCCESS) {
6,172,131!
2870
          return code;
×
2871
        }
2872
        pResInfo->numOfRes = 1;
6,172,131✔
2873
      }
2874
    }
2875
  }
2876
#endif
2877

2878
#endif
2879

2880
  // save selectivity value for column consisted of all null values
2881
  if (numOfElems == 0) {
5,461,364✔
2882
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, pInput->startRowIndex, pCtx, pInfo, true);
1,319,896✔
2883
    if (code != TSDB_CODE_SUCCESS) {
1,319,897!
2884
      return code;
×
2885
    }
2886
    pInfo->nullTupleSaved = true;
1,319,897✔
2887
  }
2888

2889
  return TSDB_CODE_SUCCESS;
5,461,365✔
2890
}
2891

2892
static bool firstLastTransferInfoImpl(SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst) {
1,045,237✔
2893
  if (!pInput->hasResult) {
1,045,237!
2894
    return false;
×
2895
  }
2896
  __compar_fn_t pkCompareFn = NULL;
1,045,237✔
2897
  if (pInput->pkData) {
1,045,237✔
2898
    pkCompareFn = getKeyComparFunc(pInput->pkType, (isFirst) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC);
4,055✔
2899
  }
2900
  if (pOutput->hasResult) {
1,045,237✔
2901
    if (isFirst) {
800,846✔
2902
      if (pInput->ts > pOutput->ts ||
11,718✔
2903
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
11,492✔
2904
        return false;
251✔
2905
      }
2906
    } else {
2907
      if (pInput->ts < pOutput->ts ||
789,128✔
2908
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
760,497✔
2909
        return false;
28,703✔
2910
      }
2911
    }
2912
  }
2913

2914
  pOutput->isNull = pInput->isNull;
1,016,283✔
2915
  pOutput->ts = pInput->ts;
1,016,283✔
2916
  pOutput->bytes = pInput->bytes;
1,016,283✔
2917
  pOutput->pkType = pInput->pkType;
1,016,283✔
2918

2919
  (void)memcpy(pOutput->buf, pInput->buf, pOutput->bytes);
1,016,283✔
2920
  if (pInput->pkData) {
1,016,283✔
2921
    pOutput->pkBytes = pInput->pkBytes;
3,809✔
2922
    (void)memcpy(pOutput->buf + pOutput->bytes, pInput->pkData, pOutput->pkBytes);
3,809✔
2923
    pOutput->pkData = pOutput->buf + pOutput->bytes;
3,809✔
2924
  }
2925
  return true;
1,016,283✔
2926
}
2927

2928
static int32_t firstLastTransferInfo(SqlFunctionCtx* pCtx, SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst,
1,045,237✔
2929
                                     int32_t rowIndex) {
2930
  if (firstLastTransferInfoImpl(pInput, pOutput, isFirst)) {
1,045,237✔
2931
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pOutput, false);
1,016,283✔
2932
    if (TSDB_CODE_SUCCESS != code) {
1,016,283!
2933
      return code;
×
2934
    }
2935
    pOutput->hasResult = true;
1,016,283✔
2936
  }
2937
  return TSDB_CODE_SUCCESS;
1,045,237✔
2938
}
2939

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

2944
  if (IS_NULL_TYPE(pCol->info.type)) {
255,124!
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) {
255,124!
2950
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
2951
  }
2952

2953
  SFirstLastRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
255,124✔
2954

2955
  int32_t start = pInput->startRowIndex;
255,124✔
2956
  int32_t numOfElems = 0;
255,124✔
2957

2958
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
1,301,389✔
2959
    if (colDataIsNull_s(pCol, i)) {
2,092,530✔
2960
      continue;
1,028✔
2961
    }
2962
    char*          data = colDataGetData(pCol, i);
1,045,237!
2963
    SFirstLastRes* pInputInfo = (SFirstLastRes*)varDataVal(data);
1,045,237✔
2964
    if (pCtx->hasPrimaryKey) {
1,045,237✔
2965
      pInputInfo->pkData = pInputInfo->buf + pInputInfo->bytes;
4,055✔
2966
    } else {
2967
      pInputInfo->pkData = NULL;
1,041,182✔
2968
    }
2969

2970
    int32_t code = firstLastTransferInfo(pCtx, pInputInfo, pInfo, isFirstQuery, i);
1,045,237✔
2971
    if (code != TSDB_CODE_SUCCESS) {
1,045,237!
2972
      return code;
×
2973
    }
2974
    if (!numOfElems) {
1,045,237✔
2975
      numOfElems = pInputInfo->hasResult ? 1 : 0;
254,096✔
2976
    }
2977
  }
2978

2979
  if (numOfElems == 0) {
255,124✔
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);
255,124✔
2988
  return TSDB_CODE_SUCCESS;
255,124✔
2989
}
2990

2991
int32_t firstFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, true); }
41,965✔
2992

2993
int32_t lastFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, false); }
213,159✔
2994

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

3003
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,852,218✔
3004
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
2,852,218✔
3005

3006
  SFirstLastRes* pRes = GET_ROWCELL_INTERBUF(pResInfo);
2,852,218✔
3007

3008
  if (pResInfo->isNullRes) {
2,852,218✔
3009
    colDataSetNULL(pCol, pBlock->info.rows);
464,299✔
3010
    return setNullSelectivityValue(pCtx, pBlock, pBlock->info.rows);
464,299✔
3011
  }
3012
  code = colDataSetVal(pCol, pBlock->info.rows, pRes->buf, pRes->isNull || pResInfo->isNullRes);
2,387,919✔
3013
  if (TSDB_CODE_SUCCESS != code) {
2,387,919!
3014
    return code;
×
3015
  }
3016

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

3020
  return code;
2,387,918✔
3021
}
3022

3023
int32_t firstLastPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1,001,652✔
3024
  int32_t code = TSDB_CODE_SUCCESS;
1,001,652✔
3025

3026
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
1,001,652✔
3027
  SFirstLastRes*       pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
1,001,652✔
3028

3029
  int32_t resultBytes = getFirstLastInfoSize(pRes->bytes, pRes->pkBytes);
1,001,652✔
3030

3031
  // todo check for failure
3032
  char* res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
992,831!
3033
  if (NULL == res) {
1,013,302!
3034
    return terrno;
×
3035
  }
3036
  (void)memcpy(varDataVal(res), pRes, resultBytes);
1,013,302✔
3037

3038
  varDataSetLen(res, resultBytes);
1,013,302✔
3039

3040
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
1,013,302✔
3041
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
1,013,302✔
3042
  if (NULL == pCol) {
1,012,744!
3043
    taosMemoryFree(res);
×
3044
    return TSDB_CODE_OUT_OF_RANGE;
×
3045
  }
3046

3047
  if (pEntryInfo->numOfRes == 0) {
1,014,140✔
3048
    colDataSetNULL(pCol, pBlock->info.rows);
1,118!
3049
    code = setNullSelectivityValue(pCtx, pBlock, pBlock->info.rows);
1,118✔
3050
  } else {
3051
    code = colDataSetVal(pCol, pBlock->info.rows, res, false);
1,013,022✔
3052
    if (TSDB_CODE_SUCCESS != code) {
947,509!
3053
      taosMemoryFree(res);
×
3054
      return code;
×
3055
    }
3056
    code = setSelectivityValue(pCtx, pBlock, &pRes->pos, pBlock->info.rows);
947,509✔
3057
  }
3058
  taosMemoryFree(res);
950,766!
3059
  return code;
1,019,545✔
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) {
54,219✔
3077
  SInputColumnInfoData* pInput = &pCtx->input;
54,219✔
3078
  SColumnInfoData*      pInputCol = pInput->pData[0];
54,219✔
3079
  SColumnInfoData*      pkCol = pInput->pPrimaryKey;
54,219✔
3080

3081
  if (colDataIsNull_s(pInputCol, rowIndex)) {
108,438✔
3082
    pInfo->isNull = true;
3,583✔
3083
  } else {
3084
    pInfo->isNull = false;
50,636✔
3085

3086
    if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
50,636!
3087
      pInfo->bytes = calcStrBytesByType(pInputCol->info.type, pData);
7,428✔
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);
50,651✔
3096
  }
3097

3098
  if (pCtx->hasPrimaryKey && !colDataIsNull_s(pkCol, rowIndex)) {
57,275!
3099
    char* pkData = colDataGetData(pkCol, rowIndex);
3,041!
3100
    if (IS_VAR_DATA_TYPE(pInfo->pkType)) {
3,041!
3101
      pInfo->pkBytes = calcStrBytesByType(pInfo->pkType, pkData);
1,011✔
3102
    }
3103
    (void)memcpy(pInfo->buf + pInfo->bytes, pkData, pInfo->pkBytes);
3,040✔
3104
    pInfo->pkData = pInfo->buf + pInfo->bytes;
3,040✔
3105
  }
3106
  pInfo->ts = cts;
54,233✔
3107
  int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pInfo, false);
54,233✔
3108
  if (code != TSDB_CODE_SUCCESS) {
54,228!
3109
    return code;
×
3110
  }
3111

3112
  pInfo->hasResult = true;
54,228✔
3113

3114
  return TSDB_CODE_SUCCESS;
54,228✔
3115
}
3116

3117
int32_t lastRowFunction(SqlFunctionCtx* pCtx) {
81,162✔
3118
  int32_t numOfElems = 0;
81,162✔
3119

3120
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
81,162✔
3121
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
81,162✔
3122

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

3126
  int32_t type = pInputCol->info.type;
81,162✔
3127
  int32_t bytes = pInputCol->info.bytes;
81,162✔
3128
  pInfo->bytes = bytes;
81,162✔
3129

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

3144
  if (pCtx->order == TSDB_ORDER_ASC && !pCtx->hasPrimaryKey) {
81,088✔
3145
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
48,610!
3146
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
24,303✔
3147
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
24,303!
3148
      TSKEY cts = getRowPTs(pInput->pPTS, i);
24,303!
3149
      numOfElems++;
24,303✔
3150

3151
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
24,303✔
3152
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
7,035✔
3153
        if (code != TSDB_CODE_SUCCESS) return code;
7,044!
3154
      }
3155

3156
      break;
24,312✔
3157
    }
3158
  } else if (!pCtx->hasPrimaryKey && pCtx->order == TSDB_ORDER_DESC) {
56,790✔
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) {
98,256!
3162
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
49,138✔
3163
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
49,138!
3164
      TSKEY cts = getRowPTs(pInput->pPTS, i);
49,138✔
3165
      numOfElems++;
49,138✔
3166

3167
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
49,138✔
3168
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
35,671✔
3169
        if (code != TSDB_CODE_SUCCESS) return code;
35,661!
3170
      }
3171
      break;
49,128✔
3172
    }
3173
  } else {
3174
    int64_t* pts = (int64_t*)pInput->pPTS->pData;
7,662✔
3175
    int      from = -1;
7,662✔
3176
    int32_t  i = -1;
7,662✔
3177
    while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
37,316✔
3178
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
29,655✔
3179
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
29,655!
3180
      TSKEY cts = pts[i];
29,655✔
3181

3182
      numOfElems++;
29,655✔
3183
      char* pkData = NULL;
29,655✔
3184
      if (pCtx->hasPrimaryKey) {
29,655✔
3185
        pkData = colDataGetData(pkCol, i);
10,881!
3186
      }
3187
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts ||
29,655✔
3188
          (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
20,847✔
3189
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
8,814✔
3190
        if (code != TSDB_CODE_SUCCESS) {
8,812!
3191
          return code;
×
3192
        }
3193
        pResInfo->numOfRes = 1;
8,812✔
3194
      }
3195
    }
3196
  }
3197

3198
  SET_VAL(pResInfo, numOfElems, 1);
81,177!
3199
  return TSDB_CODE_SUCCESS;
81,177✔
3200
}
3201

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

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

3227
static int32_t doSetPrevVal(SDiffInfo* pDiffInfo, int32_t type, const char* pv, int64_t ts) {
44,410✔
3228
  switch (type) {
44,410!
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:
253✔
3233
    case TSDB_DATA_TYPE_TINYINT:
3234
      pDiffInfo->prev.i64 = *(int8_t*)pv;
253✔
3235
      break;
253✔
3236
    case TSDB_DATA_TYPE_UINT:
42,755✔
3237
    case TSDB_DATA_TYPE_INT:
3238
      pDiffInfo->prev.i64 = *(int32_t*)pv;
42,755✔
3239
      break;
42,755✔
3240
    case TSDB_DATA_TYPE_USMALLINT:
277✔
3241
    case TSDB_DATA_TYPE_SMALLINT:
3242
      pDiffInfo->prev.i64 = *(int16_t*)pv;
277✔
3243
      break;
277✔
3244
    case TSDB_DATA_TYPE_TIMESTAMP:
539✔
3245
    case TSDB_DATA_TYPE_UBIGINT:
3246
    case TSDB_DATA_TYPE_BIGINT:
3247
      pDiffInfo->prev.i64 = *(int64_t*)pv;
539✔
3248
      break;
539✔
3249
    case TSDB_DATA_TYPE_FLOAT:
178✔
3250
      pDiffInfo->prev.d64 = *(float*)pv;
178✔
3251
      break;
178✔
3252
    case TSDB_DATA_TYPE_DOUBLE:
372✔
3253
      pDiffInfo->prev.d64 = *(double*)pv;
372✔
3254
      break;
372✔
3255
    default:
×
3256
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
3257
  }
3258
  pDiffInfo->prevTs = ts;
44,411✔
3259
  pDiffInfo->hasPrev = true;
44,411✔
3260
  return TSDB_CODE_SUCCESS;
44,411✔
3261
}
3262

3263
static bool diffIsNegtive(SDiffInfo* pDiffInfo, int32_t type, const char* pv) {
15,403✔
3264
  switch (type) {
15,403!
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,044✔
3270
      int64_t v = *(int32_t*)pv;
2,044✔
3271
      return v < pDiffInfo->prev.i64;
2,044✔
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,996✔
3282
      int64_t v = *(int8_t*)pv;
1,996✔
3283
      return v < pDiffInfo->prev.i64;
1,996✔
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: {
1,768✔
3290
      int64_t v = *(int16_t*)pv;
1,768✔
3291
      return v < pDiffInfo->prev.i64;
1,768✔
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:
1,932✔
3298
    case TSDB_DATA_TYPE_BIGINT: {
3299
      int64_t v = *(int64_t*)pv;
1,932✔
3300
      return v < pDiffInfo->prev.i64;
1,932✔
3301
    }
3302
    case TSDB_DATA_TYPE_FLOAT: {
3,009✔
3303
      float v = *(float*)pv;
3,009✔
3304
      return v < pDiffInfo->prev.d64;
3,009✔
3305
    }
3306
    case TSDB_DATA_TYPE_DOUBLE: {
4,614✔
3307
      double v = *(double*)pv;
4,614✔
3308
      return v < pDiffInfo->prev.d64;
4,614✔
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) {
29,657,455✔
3318
  bool isNegative = v < pDiffInfo->prev.i64;
29,657,455✔
3319
  if (type == TSDB_DATA_TYPE_UBIGINT) {
29,657,455✔
3320
    isNegative = (uint64_t)v < (uint64_t)pDiffInfo->prev.i64;
893✔
3321
  }
3322
  int64_t delta = v - pDiffInfo->prev.i64;
29,657,455✔
3323
  if (isNegative && ignoreNegative(pDiffInfo->ignoreOption)) {
29,657,455✔
3324
    colDataSetNull_f_s(pOutput, pos);
3,710✔
3325
    pOutput->hasNull = true;
3,710✔
3326
  } else {
3327
    colDataSetInt64(pOutput, pos, &delta);
29,653,745✔
3328
  }
3329
  pDiffInfo->prev.i64 = v;
29,657,455✔
3330
}
29,657,455✔
3331

3332
static void tryToSetDouble(SDiffInfo* pDiffInfo, SColumnInfoData* pOutput, double v, int32_t pos) {
23,858✔
3333
  double delta = v - pDiffInfo->prev.d64;
23,858✔
3334
  if (delta < 0 && ignoreNegative(pDiffInfo->ignoreOption)) {
23,858✔
3335
    colDataSetNull_f_s(pOutput, pos);
3,751✔
3336
  } else {
3337
    colDataSetDouble(pOutput, pos, &delta);
20,107✔
3338
  }
3339
  pDiffInfo->prev.d64 = v;
23,858✔
3340
}
23,858✔
3341

3342
static int32_t doHandleDiff(SDiffInfo* pDiffInfo, int32_t type, const char* pv, SColumnInfoData* pOutput, int32_t pos,
29,681,813✔
3343
                            int64_t ts) {
3344
  if (!pDiffInfo->hasPrev) {
29,681,813✔
3345
    colDataSetNull_f_s(pOutput, pos);
500✔
3346
    return doSetPrevVal(pDiffInfo, type, pv, ts);
500✔
3347
  }
3348
  pDiffInfo->prevTs = ts;
29,681,313✔
3349
  switch (type) {
29,681,313✔
3350
    case TSDB_DATA_TYPE_UINT: {
823✔
3351
      int64_t v = *(uint32_t*)pv;
823✔
3352
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
823✔
3353
      break;
823✔
3354
    }
3355
    case TSDB_DATA_TYPE_INT: {
20,970,137✔
3356
      int64_t v = *(int32_t*)pv;
20,970,137✔
3357
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
20,970,137✔
3358
      break;
20,970,137✔
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: {
8,425✔
3371
      int64_t v = *(int8_t*)pv;
8,425✔
3372
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
8,425✔
3373
      break;
8,425✔
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: {
8,114✔
3381
      int64_t v = *(int16_t*)pv;
8,114✔
3382
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
8,114✔
3383
      break;
8,114✔
3384
    }
3385
    case TSDB_DATA_TYPE_TIMESTAMP:
8,667,728✔
3386
    case TSDB_DATA_TYPE_UBIGINT:
3387
    case TSDB_DATA_TYPE_BIGINT: {
3388
      int64_t v = *(int64_t*)pv;
8,667,728✔
3389
      tryToSetInt64(pDiffInfo, type, pOutput, v, pos);
8,667,728✔
3390
      break;
8,667,728✔
3391
    }
3392
    case TSDB_DATA_TYPE_FLOAT: {
10,078✔
3393
      double v = *(float*)pv;
10,078✔
3394
      tryToSetDouble(pDiffInfo, pOutput, v, pos);
10,078✔
3395
      break;
10,078✔
3396
    }
3397
    case TSDB_DATA_TYPE_DOUBLE: {
13,779✔
3398
      double v = *(double*)pv;
13,779✔
3399
      tryToSetDouble(pDiffInfo, pOutput, v, pos);
13,779✔
3400
      break;
13,779✔
3401
    }
3402
    default:
1✔
3403
      return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
1✔
3404
  }
3405
  pDiffInfo->hasPrev = true;
29,681,312✔
3406
  return TSDB_CODE_SUCCESS;
29,681,312✔
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,
71,966,373✔
3412
                              int32_t* nextFrom) {
3413
  if (pInput->pPrimaryKey == NULL) {
71,966,373✔
3414
    if (from == -1) {
71,924,204✔
3415
      from = pInput->startRowIndex;
7,426,066✔
3416
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
64,498,138✔
3417
      return false;
7,425,728✔
3418
    }
3419
    *pRowIndex = from;
64,498,476✔
3420
    *nextFrom = from + 1;
64,498,476✔
3421
    return true;
64,498,476✔
3422
  } else {
3423
    if (from == -1) {
42,169✔
3424
      from = pInput->startRowIndex;
15,138✔
3425
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
27,031✔
3426
      return false;
15,125✔
3427
    }
3428
    TSKEY*           tsList = (int64_t*)pInput->pPTS->pData;
27,044✔
3429
    SColumnInfoData* pkCol = pInput->pPrimaryKey;
27,044✔
3430
    int8_t           pkType = pkCol->info.type;
27,044✔
3431
    int32_t          order = (firstOccur) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
27,044✔
3432
    __compar_fn_t    compareFunc = getKeyComparFunc(pkType, order);
27,044✔
3433
    int32_t          select = from;
31,578✔
3434
    char*            val = colDataGetData(pkCol, select);
31,578!
3435
    while (from < pInput->numOfRows + pInput->startRowIndex - 1 && tsList[from + 1] == tsList[from]) {
82,494✔
3436
      char* val1 = colDataGetData(pkCol, from + 1);
50,938!
3437
      if (compareFunc(val1, val) < 0) {
50,938!
3438
        select = from + 1;
×
3439
        val = val1;
×
3440
      }
3441
      from = from + 1;
50,916✔
3442
    }
3443
    *pRowIndex = select;
31,556✔
3444
    *nextFrom = from + 1;
31,556✔
3445
    return true;
31,556✔
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) {
29,778,627✔
3455
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
29,778,627✔
3456
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
29,778,627✔
3457

3458
  if (pRow->isDataNull || !pDiffInfo->hasPrev) {
29,778,627✔
3459
    return true;
97,214✔
3460
  } else if (ignoreNegative(pDiffInfo->ignoreOption)) {
29,681,413✔
3461
    return diffIsNegtive(pDiffInfo, pCtx->input.pData[0]->info.type, pRow->pData);
15,403✔
3462
  }
3463
  return false;
29,666,010✔
3464
}
3465

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

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

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

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

3488
int32_t setDoDiffResult(SqlFunctionCtx* pCtx, SFuncInputRow* pRow, int32_t pos) {
29,733,394✔
3489
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
29,733,394✔
3490
  SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
29,733,394✔
3491

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

3501
    // handle selectivity
3502
    if (pCtx->subsidiaries.num > 0) {
51,559✔
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;
51,559✔
3509
  }
3510

3511
  char* pv = pRow->pData;
29,681,835✔
3512

3513
  if (pRow->ts == pDiffInfo->prevTs) {
29,681,835✔
3514
    return TSDB_CODE_FUNC_DUP_TIMESTAMP;
22✔
3515
  }
3516
  code = doHandleDiff(pDiffInfo, inputType, pv, pOutput, pos, pRow->ts);
29,681,813✔
3517
  if (code != TSDB_CODE_SUCCESS) {
29,681,812!
3518
    return code;
×
3519
  }
3520
  // handle selectivity
3521
  if (pCtx->subsidiaries.num > 0) {
29,681,812✔
3522
    code = appendSelectivityCols(pCtx, pRow->block, pRow->rowIndex, pos);
28,983,963✔
3523
    if (code != TSDB_CODE_SUCCESS) {
28,983,964!
3524
      return code;
×
3525
    }
3526
  }
3527

3528
  return TSDB_CODE_SUCCESS;
29,681,813✔
3529
}
3530

3531
int32_t diffFunction(SqlFunctionCtx* pCtx) { return TSDB_CODE_SUCCESS; }
304,851✔
3532

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

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

3546
  bool keepNull = false;
304,613✔
3547
  for (int i = 0; i < diffColNum; ++i) {
609,465✔
3548
    SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
304,852✔
3549
    if (NULL == pCtx) {
304,852!
3550
      code = terrno;
×
3551
      goto _exit;
×
3552
    }
3553
    funcInputUpdate(pCtx);
304,852✔
3554
    SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
304,852✔
3555
    SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
304,852✔
3556
    if (!ignoreNull(pDiffInfo->ignoreOption)) {
304,852✔
3557
      keepNull = true;
304,668✔
3558
    }
3559
  }
3560

3561
  SqlFunctionCtx* pCtx0 = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, 0);
304,613✔
3562
  SFuncInputRow*  pRow0 = (SFuncInputRow*)taosArrayGet(pRows, 0);
304,613✔
3563
  if (NULL == pCtx0 || NULL == pRow0) {
304,613!
3564
    code = terrno;
×
3565
    goto _exit;
×
3566
  }
3567
  int32_t startOffset = pCtx0->offset;
304,613✔
3568
  bool    result = false;
304,613✔
3569
  while (1) {
29,771,224✔
3570
    code = funcInputGetNextRow(pCtx0, pRow0, &result);
30,075,837✔
3571
    if (TSDB_CODE_SUCCESS != code) {
30,075,837!
3572
      goto _exit;
×
3573
    }
3574
    if (!result) {
30,075,837✔
3575
      break;
304,591✔
3576
    }
3577
    bool hasNotNullValue = !diffResultIsNull(pCtx0, pRow0);
29,771,246✔
3578
    for (int i = 1; i < diffColNum; ++i) {
29,778,628✔
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;
29,771,247✔
3599

3600
    bool newRow = false;
29,771,247✔
3601
    for (int i = 0; i < diffColNum; ++i) {
59,549,852✔
3602
      SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
29,778,628✔
3603
      SFuncInputRow*  pRow = (SFuncInputRow*)taosArrayGet(pRows, i);
29,778,627✔
3604
      if (NULL == pCtx || NULL == pRow) {
29,778,627!
3605
        code = terrno;
×
3606
        goto _exit;
×
3607
      }
3608
      if ((keepNull || hasNotNullValue) && !isFirstRow(pCtx, pRow)) {
29,778,627✔
3609
        code = setDoDiffResult(pCtx, pRow, pos);
29,733,394✔
3610
        if (code != TSDB_CODE_SUCCESS) {
29,733,394✔
3611
          goto _exit;
22✔
3612
        }
3613
        newRow = true;
29,733,372✔
3614
      } else {
3615
        code = trySetPreVal(pCtx, pRow);
45,233✔
3616
        if (code != TSDB_CODE_SUCCESS) {
45,233!
3617
          goto _exit;
×
3618
        }
3619
      }
3620
    }
3621
    if (newRow) ++numOfElems;
29,771,224✔
3622
  }
3623

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

3634
_exit:
304,591✔
3635
  if (pRows) {
304,613!
3636
    taosArrayDestroy(pRows);
304,613✔
3637
    pRows = NULL;
304,613✔
3638
  }
3639
  return code;
304,613✔
3640
}
3641

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

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

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

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

3661
  pRes->maxSize = pCtx->param[1].param.i;
34,168✔
3662

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

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

3673
  return pRes;
2,359,899✔
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) {
34,508✔
3682
  int32_t              numOfElems = 0;
34,508✔
3683
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
34,508✔
3684

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

3688
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
34,508✔
3689
  pRes->type = pInput->pData[0]->info.type;
34,508✔
3690

3691
  int32_t start = pInput->startRowIndex;
34,508✔
3692
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
1,604,908✔
3693
    if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
1,571,290!
3694
      continue;
17,332✔
3695
    }
3696

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

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

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

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

3722
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
5,178✔
3723
  pRes->type = pInput->pData[0]->info.type;
5,177✔
3724

3725
  int32_t start = pInput->startRowIndex;
5,177✔
3726
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
781,071✔
3727
    if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
775,818!
3728
      continue;
20,680✔
3729
    }
3730

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

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

3747
  return TSDB_CODE_SUCCESS;
5,253✔
3748
}
3749

3750
static int32_t topBotResComparFn(const void* p1, const void* p2, const void* param) {
1,934,972✔
3751
  uint16_t type = *(uint16_t*)param;
1,934,972✔
3752

3753
  STopBotResItem* val1 = (STopBotResItem*)p1;
1,934,972✔
3754
  STopBotResItem* val2 = (STopBotResItem*)p2;
1,934,972✔
3755

3756
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
1,934,972!
3757
    if (val1->v.i == val2->v.i) {
1,010,503✔
3758
      return 0;
201,222✔
3759
    }
3760

3761
    return (val1->v.i > val2->v.i) ? 1 : -1;
809,281✔
3762
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
924,469!
3763
    if (val1->v.u == val2->v.u) {
727,391✔
3764
      return 0;
150,844✔
3765
    }
3766

3767
    return (val1->v.u > val2->v.u) ? 1 : -1;
576,547✔
3768
  } else if (TSDB_DATA_TYPE_FLOAT == type) {
197,078✔
3769
    if (val1->v.f == val2->v.f) {
19,301✔
3770
      return 0;
63✔
3771
    }
3772

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

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

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

3783
int32_t doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, uint16_t type,
2,289,475✔
3784
                        uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery) {
3785
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
2,289,475✔
3786
  int32_t     code = TSDB_CODE_SUCCESS;
2,287,260✔
3787

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

3791
  STopBotResItem* pItems = pRes->pItems;
2,302,791✔
3792

3793
  // not full yet
3794
  if (pEntryInfo->numOfRes < pRes->maxSize) {
2,302,791✔
3795
    STopBotResItem* pItem = &pItems[pEntryInfo->numOfRes];
141,754✔
3796
    pItem->v = val;
141,754✔
3797
    pItem->uid = uid;
141,754✔
3798

3799
    // save the data of this tuple
3800
    if (pCtx->subsidiaries.num > 0) {
141,754✔
3801
      code = saveTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
68,238✔
3802
      if (code != TSDB_CODE_SUCCESS) {
68,108!
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++;
141,624✔
3812
    code = taosheapsort((void*)pItems, sizeof(STopBotResItem), pEntryInfo->numOfRes, (const void*)&type,
141,624✔
3813
                        topBotResComparFn, !isTopQuery);
141,624✔
3814
    if (code != TSDB_CODE_SUCCESS) {
142,007!
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) ||
2,161,037!
3819
                        (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u > pItems[0].v.u) ||
1,341,244!
3820
                        (TSDB_DATA_TYPE_FLOAT == type && val.f > pItems[0].v.f) ||
1,250,009✔
3821
                        (TSDB_DATA_TYPE_DOUBLE == type && val.d > pItems[0].v.d))) ||
1,248,969✔
3822
        (!isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i < pItems[0].v.i) ||
1,951,074!
3823
                         (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u < pItems[0].v.u) ||
726,068!
3824
                         (TSDB_DATA_TYPE_FLOAT == type && val.f < pItems[0].v.f) ||
724,166✔
3825
                         (TSDB_DATA_TYPE_DOUBLE == type && val.d < pItems[0].v.d)))) {
723,610!
3826
      // replace the old data and the coresponding tuple data
3827
      STopBotResItem* pItem = &pItems[0];
206,456✔
3828
      pItem->v = val;
206,456✔
3829
      pItem->uid = uid;
206,456✔
3830

3831
      // save the data of this tuple by over writing the old data
3832
      if (pCtx->subsidiaries.num > 0) {
206,456✔
3833
        code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
184,277✔
3834
        if (code != TSDB_CODE_SUCCESS) {
183,046!
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,
205,225✔
3842
                            topBotResComparFn, NULL, !isTopQuery);
205,225✔
3843
      if (code != TSDB_CODE_SUCCESS) {
219,235!
3844
        return code;
×
3845
      }
3846
    }
3847
  }
3848

3849
  return TSDB_CODE_SUCCESS;
2,315,823✔
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,
335,550✔
3859
                           char* buf, char** res) {
3860
  char* nullList = buf;
335,550✔
3861
  char* pStart = (char*)(nullList + sizeof(bool) * pSubsidiaryies->num);
335,550✔
3862

3863
  int32_t offset = 0;
335,550✔
3864
  for (int32_t i = 0; i < pSubsidiaryies->num; ++i) {
745,966✔
3865
    SqlFunctionCtx* pc = pSubsidiaryies->pCtx[i];
410,467✔
3866

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

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

3876
    SColumnInfoData* pCol = taosArrayGet(pSrcBlock->pDataBlock, srcSlotId);
410,387✔
3877
    if (NULL == pCol) {
410,322!
3878
      return TSDB_CODE_OUT_OF_RANGE;
×
3879
    }
3880
    if ((nullList[i] = colDataIsNull_s(pCol, rowIndex)) == true) {
820,644✔
3881
      offset += pCol->info.bytes;
30,218✔
3882
      continue;
30,218✔
3883
    }
3884

3885
    char* p = colDataGetData(pCol, rowIndex);
380,104!
3886
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
380,104!
3887
      int32_t bytes = calcStrBytesByType(pCol->info.type, p);
45,879✔
3888
      (void)memcpy(pStart + offset, p, bytes);
45,973✔
3889
    } else {
3890
      (void)memcpy(pStart + offset, p, pCol->info.bytes);
334,225✔
3891
    }
3892

3893
    offset += pCol->info.bytes;
380,198✔
3894
  }
3895

3896
  *res = buf;
335,499✔
3897
  return TSDB_CODE_SUCCESS;
335,499✔
3898
}
3899

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

3906
    if (pHandle->currentPage == -1) {
412,929✔
3907
      pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
24,770✔
3908
      if (pPage == NULL) {
24,772!
3909
        return terrno;
×
3910
      }
3911
      pPage->num = sizeof(SFilePage);
24,772✔
3912
    } else {
3913
      pPage = getBufPage(pHandle->pBuf, pHandle->currentPage);
388,159✔
3914
      if (pPage == NULL) {
387,907!
3915
        return terrno;
×
3916
      }
3917
      if (pPage->num + length > getBufPageSize(pHandle->pBuf)) {
387,907✔
3918
        // current page is all used, let's prepare a new buffer page
3919
        releaseBufPage(pHandle->pBuf, pPage);
4,091✔
3920
        pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
4,091✔
3921
        if (pPage == NULL) {
4,091!
3922
          return terrno;
×
3923
        }
3924
        pPage->num = sizeof(SFilePage);
4,091✔
3925
      }
3926
    }
3927

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

3931
    pPage->num += length;
412,604✔
3932
    setBufPageDirty(pPage, true);
412,604✔
3933
    releaseBufPage(pHandle->pBuf, pPage);
412,351✔
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;
411,645✔
3941
  return TSDB_CODE_SUCCESS;
411,645✔
3942
}
3943

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

3950
  SWinKey key = {0};
130,413✔
3951
  if (pCtx->saveHandle.pBuf == NULL) {
130,413!
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;
130,413✔
3965
  code = serializeTupleData(pSrcBlock, rowIndex, &pCtx->subsidiaries, pCtx->subsidiaries.buf, &buf);
130,413✔
3966
  if (TSDB_CODE_SUCCESS != code) {
130,390!
3967
    return code;
×
3968
  }
3969
  return doSaveTupleData(&pCtx->saveHandle, buf, pCtx->subsidiaries.rowLen, &key, pPos, pCtx->pStore);
130,390✔
3970
}
3971

3972
static int32_t doUpdateTupleData(SSerializeDataHandle* pHandle, const void* pBuf, size_t length, STuplePos* pPos,
205,134✔
3973
                                 SFunctionStateStore* pStore) {
3974
  if (pHandle->pBuf != NULL) {
205,134!
3975
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
205,138✔
3976
    if (pPage == NULL) {
204,820!
3977
      return terrno;
×
3978
    }
3979
    (void)memcpy(pPage->data + pPos->offset, pBuf, length);
204,820✔
3980
    setBufPageDirty(pPage, true);
204,820✔
3981
    releaseBufPage(pHandle->pBuf, pPage);
204,639✔
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;
204,199✔
3990
}
3991

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

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

4006
static int32_t doLoadTupleData(SSerializeDataHandle* pHandle, const STuplePos* pPos, SFunctionStateStore* pStore,
128,868✔
4007
                               char** value) {
4008
  if (pHandle->pBuf != NULL) {
128,868✔
4009
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
128,867✔
4010
    if (pPage == NULL) {
128,866!
4011
      *value = NULL;
×
4012
      return terrno;
×
4013
    }
4014
    *value = pPage->data + pPos->offset;
128,866✔
4015
    releaseBufPage(pHandle->pBuf, pPage);
128,866✔
4016
    return TSDB_CODE_SUCCESS;
128,865✔
4017
  } else {
4018
    *value = NULL;
1✔
4019
    int32_t vLen;
4020
    int32_t code = pStore->streamStateFuncGet(pHandle->pState, &pPos->streamTupleKey, (void**)(value), &vLen);
1✔
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) {
128,867✔
4029
  return doLoadTupleData(&pCtx->saveHandle, pPos, pCtx->pStore, value);
128,867✔
4030
}
4031

4032
int32_t topBotFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
34,182✔
4033
  int32_t code = TSDB_CODE_SUCCESS;
34,182✔
4034

4035
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
34,182✔
4036
  STopBotRes*          pRes = getTopBotOutputInfo(pCtx);
34,182✔
4037

4038
  int16_t type = pCtx->pExpr->base.resSchema.type;
34,182✔
4039
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
34,182✔
4040

4041
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
34,182✔
4042
  if (NULL == pCol) {
34,181!
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;
34,181✔
4048
  if (pEntryInfo->numOfRes <= 0) {
34,181✔
4049
    colDataSetNULL(pCol, currentRow);
342!
4050
    code = setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, currentRow);
342✔
4051
    return code;
342✔
4052
  }
4053
  for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
175,842✔
4054
    STopBotResItem* pItem = &pRes->pItems[i];
142,001✔
4055
    code = colDataSetVal(pCol, currentRow, (const char*)&pItem->v.i, false);
142,001✔
4056
    if (TSDB_CODE_SUCCESS != code) {
142,005!
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);
142,005✔
4064
    if (TSDB_CODE_SUCCESS != code) {
142,003!
4065
      return code;
×
4066
    }
4067
    currentRow += 1;
142,003✔
4068
  }
4069

4070
  return code;
33,841✔
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); }
13,774✔
4147

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

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

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

4168
int32_t spreadFunction(SqlFunctionCtx* pCtx) {
191,470✔
4169
  int32_t numOfElems = 0;
191,470✔
4170

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

4176
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
191,470✔
4177

4178
  if (pInput->colDataSMAIsSet) {
191,470!
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];
191,470✔
4205

4206
    int32_t start = pInput->startRowIndex;
191,470✔
4207
    // check the valid data one by one
4208
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
4,214,614✔
4209
      if (colDataIsNull_f(pCol, i)) {
4,023,206✔
4210
        continue;
776,012✔
4211
      }
4212

4213
      char* data = colDataGetData(pCol, i);
3,247,194!
4214

4215
      double v = 0;
3,247,194✔
4216
      GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pCol->info));
3,247,194!
4217
      if (v < GET_DOUBLE_VAL(&pInfo->min)) {
3,247,132✔
4218
        SET_DOUBLE_VAL(&pInfo->min, v);
179,229✔
4219
      }
4220

4221
      if (v > GET_DOUBLE_VAL(&pInfo->max)) {
3,247,132✔
4222
        SET_DOUBLE_VAL(&pInfo->max, v);
595,827✔
4223
      }
4224

4225
      numOfElems += 1;
3,247,132✔
4226
    }
4227
  }
4228

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

4236
  return TSDB_CODE_SUCCESS;
191,408✔
4237
}
4238

4239
static void spreadTransferInfo(SSpreadInfo* pInput, SSpreadInfo* pOutput) {
13,672✔
4240
  pOutput->hasResult = pInput->hasResult;
13,672✔
4241
  if (pInput->max > pOutput->max) {
13,672✔
4242
    pOutput->max = pInput->max;
9,512✔
4243
  }
4244

4245
  if (pInput->min < pOutput->min) {
13,672✔
4246
    pOutput->min = pInput->min;
9,504✔
4247
  }
4248
}
13,672✔
4249

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

4254
  if (IS_NULL_TYPE(pCol->info.type)) {
9,661!
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) {
9,661!
4260
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
4261
  }
4262

4263
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
9,661✔
4264

4265
  int32_t start = pInput->startRowIndex;
9,661✔
4266
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
23,363✔
4267
    if (colDataIsNull_s(pCol, i)) continue;
27,404!
4268
    char*        data = colDataGetData(pCol, i);
13,702!
4269
    SSpreadInfo* pInputInfo = (SSpreadInfo*)varDataVal(data);
13,702✔
4270
    if (pInputInfo->hasResult) {
13,702✔
4271
      spreadTransferInfo(pInputInfo, pInfo);
13,672✔
4272
    }
4273
  }
4274

4275
  if (pInfo->hasResult) {
9,661✔
4276
    GET_RES_INFO(pCtx)->numOfRes = 1;
9,631✔
4277
  }
4278

4279
  return TSDB_CODE_SUCCESS;
9,661✔
4280
}
4281

4282
int32_t spreadFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
155,593✔
4283
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
155,593✔
4284
  if (pInfo->hasResult == true) {
155,593✔
4285
    SET_DOUBLE_VAL(&pInfo->result, pInfo->max - pInfo->min);
142,368✔
4286
  } else {
4287
    GET_RES_INFO(pCtx)->isNullRes = 1;
13,225✔
4288
  }
4289
  return functionFinalize(pCtx, pBlock);
155,593✔
4290
}
4291

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

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

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

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

4317
_exit:
13,782✔
4318
  taosMemoryFree(res);
13,782!
4319
  return code;
13,782✔
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) {
17,390✔
4337
  pEnv->calcMemSize = sizeof(SElapsedInfo);
17,390✔
4338
  return true;
17,390✔
4339
}
4340

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

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

4354
  if (pCtx->numOfParams > 1) {
34,168✔
4355
    pInfo->timeUnit = pCtx->param[1].param.i;
20,399✔
4356
  } else {
4357
    pInfo->timeUnit = 1;
13,769✔
4358
  }
4359

4360
  return TSDB_CODE_SUCCESS;
34,168✔
4361
}
4362

4363
int32_t elapsedFunction(SqlFunctionCtx* pCtx) {
34,232✔
4364
  int32_t numOfElems = 0;
34,232✔
4365

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

4370
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
34,232✔
4371

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

4381
  if (pInput->colDataSMAIsSet) {
34,232!
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) {
34,232!
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];
34,232✔
4407

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

4417
      if (pCtx->end.key == INT64_MIN) {
316!
4418
        pInfo->min =
316✔
4419
            (pInfo->min > ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->min;
316✔
4420
      } else {
4421
        pInfo->min = pCtx->end.key;
×
4422
      }
4423
    } else {
4424
      if (pCtx->start.key == INT64_MIN) {
33,916!
4425
        pInfo->min = (pInfo->min > ptsList[start]) ? ptsList[start] : pInfo->min;
33,917✔
4426
      } else {
4427
        pInfo->min = pCtx->start.key;
×
4428
      }
4429

4430
      if (pCtx->end.key == INT64_MIN) {
33,916✔
4431
        pInfo->max =
33,483✔
4432
            (pInfo->max < ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->max;
33,483✔
4433
      } else {
4434
        pInfo->max = pCtx->end.key + 1;
433✔
4435
      }
4436
    }
4437
  }
4438

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

4443
  return TSDB_CODE_SUCCESS;
34,232✔
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) {
34,164✔
4479
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
34,164✔
4480
  double        result = (double)(pInfo->max - pInfo->min);
34,164✔
4481
  pInfo->result = fabs(result) / pInfo->timeUnit;
34,164✔
4482
  return functionFinalize(pCtx, pBlock);
34,164✔
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() {
3,130✔
4528
  return (int32_t)sizeof(SHistoFuncInfo) + HISTOGRAM_MAX_BINS_NUM * sizeof(SHistoFuncBin);
3,130✔
4529
}
4530

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

4536
static int8_t getHistogramBinType(char* binTypeStr) {
7,571✔
4537
  int8_t binType;
4538
  if (strcasecmp(binTypeStr, "user_input") == 0) {
7,571✔
4539
    binType = USER_INPUT_BIN;
3,093✔
4540
  } else if (strcasecmp(binTypeStr, "linear_bin") == 0) {
4,478✔
4541
    binType = LINEAR_BIN;
2,022✔
4542
  } else if (strcasecmp(binTypeStr, "log_bin") == 0) {
2,456✔
4543
    binType = LOG_BIN;
2,455✔
4544
  } else {
4545
    binType = UNKNOWN_BIN;
1✔
4546
  }
4547

4548
  return binType;
7,571✔
4549
}
4550

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

4563
    cJSON* start = cJSON_GetObjectItem(binDesc, "start");
4,478✔
4564
    cJSON* factor = cJSON_GetObjectItem(binDesc, "factor");
4,476✔
4565
    cJSON* width = cJSON_GetObjectItem(binDesc, "width");
4,477✔
4566
    cJSON* count = cJSON_GetObjectItem(binDesc, "count");
4,478✔
4567
    cJSON* infinity = cJSON_GetObjectItem(binDesc, "infinity");
4,479✔
4568

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

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

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

4585
    int32_t counter = (int32_t)count->valueint;
4,479✔
4586
    if (infinity->valueint == false) {
4,479✔
4587
      startIndex = 0;
3,080✔
4588
      numOfBins = counter + 1;
3,080✔
4589
    } else {
4590
      startIndex = 1;
1,399✔
4591
      numOfBins = counter + 3;
1,399✔
4592
    }
4593

4594
    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
4,479!
4595
    if (NULL == intervals) {
4,479!
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) {
4,479!
4601
      // linear bin process
4602
      if (width->valuedouble == 0) {
2,023!
4603
        taosMemoryFree(intervals);
×
4604
        cJSON_Delete(binDesc);
×
4605
        return TSDB_CODE_FAILED;
×
4606
      }
4607
      for (int i = 0; i < counter + 1; ++i) {
22,899✔
4608
        intervals[startIndex] = start->valuedouble + i * width->valuedouble;
20,876✔
4609
        if (isinf(intervals[startIndex])) {
20,876!
4610
          taosMemoryFree(intervals);
×
4611
          cJSON_Delete(binDesc);
×
4612
          return TSDB_CODE_FAILED;
×
4613
        }
4614
        startIndex++;
20,876✔
4615
      }
4616
    } else if (cJSON_IsNumber(factor) && width == NULL && binType == LOG_BIN) {
2,455!
4617
      // log bin process
4618
      if (start->valuedouble == 0) {
2,456!
4619
        taosMemoryFree(intervals);
×
4620
        cJSON_Delete(binDesc);
×
4621
        return TSDB_CODE_FAILED;
×
4622
      }
4623
      if (factor->valuedouble < 0 || factor->valuedouble == 0 || factor->valuedouble == 1) {
2,456!
4624
        taosMemoryFree(intervals);
×
4625
        cJSON_Delete(binDesc);
×
4626
        return TSDB_CODE_FAILED;
×
4627
      }
4628
      for (int i = 0; i < counter + 1; ++i) {
15,573✔
4629
        intervals[startIndex] = start->valuedouble * pow(factor->valuedouble, i * 1.0);
13,117✔
4630
        if (isinf(intervals[startIndex])) {
13,117!
4631
          taosMemoryFree(intervals);
×
4632
          cJSON_Delete(binDesc);
×
4633
          return TSDB_CODE_FAILED;
×
4634
        }
4635
        startIndex++;
13,117✔
4636
      }
4637
    } else {
4638
      taosMemoryFree(intervals);
×
4639
      cJSON_Delete(binDesc);
×
4640
      return TSDB_CODE_FAILED;
×
4641
    }
4642

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

4693
  pInfo->numOfBins = numOfBins - 1;
7,571✔
4694
  pInfo->normalized = normalized;
7,571✔
4695
  for (int32_t i = 0; i < pInfo->numOfBins; ++i) {
47,200✔
4696
    pInfo->bins[i].lower = intervals[i] < intervals[i + 1] ? intervals[i] : intervals[i + 1];
39,629✔
4697
    pInfo->bins[i].upper = intervals[i + 1] > intervals[i] ? intervals[i + 1] : intervals[i];
39,629✔
4698
    pInfo->bins[i].count = 0;
39,629✔
4699
  }
4700

4701
  taosMemoryFree(intervals);
7,571!
4702
  cJSON_Delete(binDesc);
7,570✔
4703

4704
  return TSDB_CODE_SUCCESS;
7,572✔
4705
}
4706

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

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

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

4727
  if (binType == UNKNOWN_BIN) {
7,570!
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));
7,570!
4731
  if (binDesc == NULL) {
7,571!
4732
    return terrno;
×
4733
  }
4734
  int64_t normalized = pCtx->param[3].param.i;
7,571✔
4735
  if (normalized != 0 && normalized != 1) {
7,571!
4736
    taosMemoryFree(binDesc);
×
4737
    return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
4738
  }
4739
  int32_t code = getHistogramBinDesc(pInfo, binDesc, binType, (bool)normalized);
7,571✔
4740
  if (TSDB_CODE_SUCCESS != code) {
7,566!
4741
    taosMemoryFree(binDesc);
×
4742
    return code;
×
4743
  }
4744
  taosMemoryFree(binDesc);
7,566!
4745

4746
  return TSDB_CODE_SUCCESS;
7,570✔
4747
}
4748

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

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

4755
  int32_t type = pInput->pData[0]->info.type;
25,318✔
4756

4757
  int32_t start = pInput->startRowIndex;
25,318✔
4758
  int32_t numOfRows = pInput->numOfRows;
25,318✔
4759

4760
  int32_t numOfElems = 0;
25,318✔
4761
  for (int32_t i = start; i < numOfRows + start; ++i) {
1,146,110✔
4762
    if (pCol->hasNull && colDataIsNull_f(pCol, i)) {
1,120,947!
4763
      continue;
228,802✔
4764
    }
4765

4766
    numOfElems++;
892,145✔
4767

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

4772
    for (int32_t k = 0; k < pInfo->numOfBins; ++k) {
2,690,797✔
4773
      if (v > pInfo->bins[k].lower && v <= pInfo->bins[k].upper) {
2,307,583✔
4774
        pInfo->bins[k].count++;
508,776✔
4775
        pInfo->totalCount++;
508,776✔
4776
        break;
508,776✔
4777
      }
4778
    }
4779
  }
4780

4781
  if (!isPartial) {
25,163✔
4782
    GET_RES_INFO(pCtx)->numOfRes = pInfo->numOfBins;
4,447✔
4783
  } else {
4784
    GET_RES_INFO(pCtx)->numOfRes = 1;
20,716✔
4785
  }
4786
  return TSDB_CODE_SUCCESS;
25,163✔
4787
}
4788

4789
int32_t histogramFunction(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, false); }
4,444✔
4790

4791
int32_t histogramFunctionPartial(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, true); }
20,872✔
4792

4793
static void histogramTransferInfo(SHistoFuncInfo* pInput, SHistoFuncInfo* pOutput) {
2,891✔
4794
  pOutput->normalized = pInput->normalized;
2,891✔
4795
  pOutput->numOfBins = pInput->numOfBins;
2,891✔
4796
  pOutput->totalCount += pInput->totalCount;
2,891✔
4797
  for (int32_t k = 0; k < pOutput->numOfBins; ++k) {
29,507✔
4798
    pOutput->bins[k].lower = pInput->bins[k].lower;
26,616✔
4799
    pOutput->bins[k].upper = pInput->bins[k].upper;
26,616✔
4800
    pOutput->bins[k].count += pInput->bins[k].count;
26,616✔
4801
  }
4802
}
2,891✔
4803

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

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

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

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

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

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

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

4837
  if (pInfo->normalized) {
6,272✔
4838
    for (int32_t k = 0; k < pResInfo->numOfRes; ++k) {
21,104✔
4839
      if (pInfo->totalCount != 0) {
17,117✔
4840
        pInfo->bins[k].percentage = pInfo->bins[k].count / (double)pInfo->totalCount;
10,814✔
4841
      } else {
4842
        pInfo->bins[k].percentage = 0;
6,303✔
4843
      }
4844
    }
4845
  }
4846

4847
  for (int32_t i = 0; i < pResInfo->numOfRes; ++i) {
33,273✔
4848
    int32_t len;
4849
    char    buf[512] = {0};
27,001✔
4850
    if (!pInfo->normalized) {
27,001✔
4851
      len = tsnprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE,
9,884✔
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,
17,117✔
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);
27,002✔
4860
    code = colDataSetVal(pCol, currentRow, buf, false);
27,002✔
4861
    if (TSDB_CODE_SUCCESS != code) {
27,001!
4862
      return code;
×
4863
    }
4864
    currentRow++;
27,001✔
4865
  }
4866

4867
  return code;
6,272✔
4868
}
4869

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

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

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

4891
_exit:
3,131✔
4892
  taosMemoryFree(res);
3,131!
4893
  return code;
3,131✔
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,165✔
4910

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

4916
static uint8_t hllCountNum(void* data, int32_t bytes, int32_t* buk) {
3,253,717✔
4917
  uint64_t hash = MurmurHash3_64(data, bytes);
3,253,717✔
4918
  int32_t  index = hash & HLL_BUCKET_MASK;
3,253,056✔
4919
  hash >>= HLL_BUCKET_BITS;
3,253,056✔
4920
  hash |= ((uint64_t)1 << HLL_DATA_BITS);
3,253,056✔
4921
  uint64_t bit = 1;
3,253,056✔
4922
  uint8_t  count = 1;
3,253,056✔
4923
  while ((hash & bit) == 0) {
6,086,014✔
4924
    count++;
2,832,958✔
4925
    bit <<= 1;
2,832,958✔
4926
  }
4927
  *buk = index;
3,253,056✔
4928
  return count;
3,253,056✔
4929
}
4930

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

4935
  for (int32_t j = 0; j < HLL_BUCKETS >> 3; j++) {
135,697,230✔
4936
    if (*word == 0) {
135,628,430✔
4937
      bucketHisto[0] += 8;
135,079,297✔
4938
    } else {
4939
      bytes = (uint8_t*)word;
549,133✔
4940
      bucketHisto[bytes[0]]++;
549,133✔
4941
      bucketHisto[bytes[1]]++;
549,133✔
4942
      bucketHisto[bytes[2]]++;
549,133✔
4943
      bucketHisto[bytes[3]]++;
549,133✔
4944
      bucketHisto[bytes[4]]++;
549,133✔
4945
      bucketHisto[bytes[5]]++;
549,133✔
4946
      bucketHisto[bytes[6]]++;
549,133✔
4947
      bucketHisto[bytes[7]]++;
549,133✔
4948
    }
4949
    word++;
135,628,430✔
4950
  }
4951
}
68,800✔
4952
static double hllTau(double x) {
68,800✔
4953
  if (x == 0. || x == 1.) return 0.;
68,800!
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) {
68,808✔
4967
  if (x == 1.0) return INFINITY;
68,808✔
4968
  double zPrime;
4969
  double y = 1;
56,868✔
4970
  double z = x;
56,868✔
4971
  do {
4972
    x *= x;
1,109,944✔
4973
    zPrime = z;
1,109,944✔
4974
    z += x * y;
1,109,944✔
4975
    y += y;
1,109,944✔
4976
  } while (zPrime != z);
1,109,944✔
4977
  return z;
56,868✔
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) {
68,780✔
4983
  double  m = HLL_BUCKETS;
68,780✔
4984
  int32_t buckethisto[64] = {0};
68,780✔
4985
  hllBucketHisto(buckets, buckethisto);
68,780✔
4986

4987
  double z = m * hllTau((m - buckethisto[HLL_DATA_BITS + 1]) / (double)m);
68,799✔
4988
  for (int j = HLL_DATA_BITS; j >= 1; --j) {
3,506,587✔
4989
    z += buckethisto[j];
3,437,780✔
4990
    z *= 0.5;
3,437,780✔
4991
  }
4992

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

4996
  return (uint64_t)E;
68,807✔
4997
}
4998

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

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

5005
  int32_t type = pCol->info.type;
71,249✔
5006
  int32_t bytes = pCol->info.bytes;
71,249✔
5007

5008
  int32_t start = pInput->startRowIndex;
71,249✔
5009
  int32_t numOfRows = pInput->numOfRows;
71,249✔
5010

5011
  int32_t numOfElems = 0;
71,249✔
5012
  if (IS_NULL_TYPE(type)) {
71,249✔
5013
    goto _hll_over;
1,245✔
5014
  }
5015

5016
  for (int32_t i = start; i < numOfRows + start; ++i) {
4,094,688✔
5017
    if (pCol->hasNull && colDataIsNull_s(pCol, i)) {
5,329,771!
5018
      continue;
771,230✔
5019
    }
5020

5021
    numOfElems++;
3,253,943✔
5022

5023
    char* data = colDataGetData(pCol, i);
3,253,943!
5024
    if (IS_VAR_DATA_TYPE(type)) {
3,253,943!
5025
      if (IS_STR_DATA_BLOB(type)) {
582,177!
5026
        bytes = blobDataLen(data);
×
5027
        data = blobDataVal(data);
×
5028
      } else {
5029
        bytes = varDataLen(data);
582,177✔
5030
        data = varDataVal(data);
582,177✔
5031
      }
5032
    }
5033

5034
    int32_t index = 0;
3,253,943✔
5035
    uint8_t count = hllCountNum(data, bytes, &index);
3,253,943✔
5036
    uint8_t oldcount = pInfo->buckets[index];
3,253,454✔
5037
    if (count > oldcount) {
3,253,454✔
5038
      pInfo->buckets[index] = count;
596,547✔
5039
    }
5040
  }
5041

5042
_hll_over:
69,515✔
5043
  pInfo->totalCount += numOfElems;
70,760✔
5044

5045
  if (pInfo->totalCount == 0 && !tsCountAlwaysReturnValue) {
70,760✔
5046
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
2,316✔
5047
  } else {
5048
    SET_VAL(GET_RES_INFO(pCtx), 1, 1);
68,444✔
5049
  }
5050

5051
  return TSDB_CODE_SUCCESS;
70,760✔
5052
}
5053

5054
static void hllTransferInfo(SHLLInfo* pInput, SHLLInfo* pOutput) {
2,462✔
5055
  for (int32_t k = 0; k < HLL_BUCKETS; ++k) {
39,653,894✔
5056
    if (pOutput->buckets[k] < pInput->buckets[k]) {
39,651,432✔
5057
      pOutput->buckets[k] = pInput->buckets[k];
114,722✔
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) {
68,779✔
5097
  SResultRowEntryInfo* pInfo = GET_RES_INFO(pCtx);
68,779✔
5098

5099
  SHLLInfo* pHllInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
68,779✔
5100
  pHllInfo->result = hllCountCnt(pHllInfo->buckets);
68,779✔
5101
  if (tsCountAlwaysReturnValue && pHllInfo->result == 0) {
68,812✔
5102
    pInfo->numOfRes = 1;
9,654✔
5103
  }
5104

5105
  return functionFinalize(pCtx, pBlock);
68,812✔
5106
}
5107

5108
int32_t hllPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
3,165✔
5109
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
3,165✔
5110
  SHLLInfo*            pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
3,165✔
5111
  int32_t              resultBytes = getHLLInfoSize();
3,165✔
5112
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
3,165!
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) {
9,324✔
5149
  pEnv->calcMemSize = sizeof(SStateInfo);
9,324✔
5150
  return true;
9,324✔
5151
}
5152

5153
static int8_t getStateOpType(char* opStr) {
9,435✔
5154
  int8_t opType;
5155
  if (strncasecmp(opStr, "LT", 2) == 0) {
9,435✔
5156
    opType = STATE_OPER_LT;
992✔
5157
  } else if (strncasecmp(opStr, "GT", 2) == 0) {
8,443✔
5158
    opType = STATE_OPER_GT;
2,738✔
5159
  } else if (strncasecmp(opStr, "LE", 2) == 0) {
5,705✔
5160
    opType = STATE_OPER_LE;
992✔
5161
  } else if (strncasecmp(opStr, "GE", 2) == 0) {
4,713✔
5162
    opType = STATE_OPER_GE;
1,570✔
5163
  } else if (strncasecmp(opStr, "NE", 2) == 0) {
3,143✔
5164
    opType = STATE_OPER_NE;
1,975✔
5165
  } else if (strncasecmp(opStr, "EQ", 2) == 0) {
1,168!
5166
    opType = STATE_OPER_EQ;
1,168✔
5167
  } else {
5168
    opType = STATE_OPER_INVALID;
×
5169
  }
5170

5171
  return opType;
9,435✔
5172
}
5173

5174
static bool checkStateOp(int8_t op, SColumnInfoData* pCol, int32_t index, SVariant param) {
233,382✔
5175
  char* data = colDataGetData(pCol, index);
233,382!
5176
  switch (pCol->info.type) {
233,382!
5177
    case TSDB_DATA_TYPE_TINYINT: {
18,596✔
5178
      int8_t v = *(int8_t*)data;
18,596✔
5179
      STATE_COMP(op, v, param);
18,596!
5180
      break;
×
5181
    }
5182
    case TSDB_DATA_TYPE_UTINYINT: {
18,048✔
5183
      uint8_t v = *(uint8_t*)data;
18,048✔
5184
      STATE_COMP(op, v, param);
18,048!
5185
      break;
×
5186
    }
5187
    case TSDB_DATA_TYPE_SMALLINT: {
69,912✔
5188
      int16_t v = *(int16_t*)data;
69,912✔
5189
      STATE_COMP(op, v, param);
69,912!
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: {
24,568✔
5198
      int32_t v = *(int32_t*)data;
24,568✔
5199
      STATE_COMP(op, v, param);
24,568!
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: {
7,568✔
5208
      int64_t v = *(int64_t*)data;
7,568✔
5209
      STATE_COMP(op, v, param);
7,568!
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: {
24,112✔
5218
      float v = *(float*)data;
24,112✔
5219
      STATE_COMP(op, v, param);
24,112!
5220
      break;
×
5221
    }
5222
    case TSDB_DATA_TYPE_DOUBLE: {
53,456✔
5223
      double v = *(double*)data;
53,456✔
5224
      STATE_COMP(op, v, param);
53,456!
5225
      break;
×
5226
    }
5227
    default: {
×
5228
      return false;
×
5229
    }
5230
  }
5231
  return false;
×
5232
}
5233

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

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

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

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

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

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

5259
    pInfo->isPrevTsSet = true;
283,341✔
5260
    numOfElems++;
283,341✔
5261

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

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

5276
    int64_t output = -1;
40,066✔
5277
    if (ret) {
40,066✔
5278
      output = ++pInfo->count;
11,148✔
5279
    } else {
5280
      pInfo->count = 0;
28,918✔
5281
    }
5282
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
40,066✔
5283
    if (TSDB_CODE_SUCCESS != code) {
40,071!
5284
      return code;
×
5285
    }
5286

5287
    // handle selectivity
5288
    if (pCtx->subsidiaries.num > 0) {
40,071✔
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;
1,887✔
5297
  return TSDB_CODE_SUCCESS;
1,887✔
5298
}
5299

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

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

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

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

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

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

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

5331
    pInfo->isPrevTsSet = true;
318,196✔
5332
    numOfElems++;
318,196✔
5333

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

5346
    bool    ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
193,312✔
5347
    int64_t output = -1;
193,312✔
5348
    if (ret) {
193,312✔
5349
      if (pInfo->durationStart == 0) {
109,660✔
5350
        output = 0;
38,339✔
5351
        pInfo->durationStart = tsList[i];
38,339✔
5352
      } else {
5353
        output = (tsList[i] - pInfo->durationStart) / timeUnit;
71,321✔
5354
      }
5355
    } else {
5356
      pInfo->durationStart = 0;
83,652✔
5357
    }
5358
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
193,312✔
5359
    if (TSDB_CODE_SUCCESS != code) {
193,312!
5360
      return code;
×
5361
    }
5362

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

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

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

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

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

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

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

5403
    int32_t pos = startOffset + numOfElems;
531,404✔
5404
    if (colDataIsNull_f(pInputCol, i)) {
531,404✔
5405
      // colDataSetNULL(pOutput, i);
5406
      continue;
292,539✔
5407
    }
5408

5409
    char* data = colDataGetData(pInputCol, i);
238,865!
5410
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
411,261!
5411
      int64_t v;
5412
      GET_TYPED_DATA(v, int64_t, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
172,396!
5413
      pSumRes->isum += v;
172,396✔
5414
      code = colDataSetVal(pOutput, pos, (char*)&pSumRes->isum, false);
172,396✔
5415
      if (TSDB_CODE_SUCCESS != code) {
172,396!
5416
        return code;
×
5417
      }
5418
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
73,173!
5419
      uint64_t v;
5420
      GET_TYPED_DATA(v, uint64_t, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
6,704!
5421
      pSumRes->usum += v;
6,704✔
5422
      code = colDataSetVal(pOutput, pos, (char*)&pSumRes->usum, false);
6,704✔
5423
      if (TSDB_CODE_SUCCESS != code) {
6,704!
5424
        return code;
×
5425
      }
5426
    } else if (IS_FLOAT_TYPE(type)) {
59,765!
5427
      double v;
5428
      GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
60,532!
5429
      pSumRes->dsum += v;
60,532✔
5430
      // check for overflow
5431
      if (isinf(pSumRes->dsum) || isnan(pSumRes->dsum)) {
60,532!
5432
        colDataSetNULL(pOutput, pos);
8!
5433
      } else {
5434
        code = colDataSetVal(pOutput, pos, (char*)&pSumRes->dsum, false);
60,524✔
5435
        if (TSDB_CODE_SUCCESS != code) {
60,524!
5436
          return code;
×
5437
        }
5438
      }
5439
    }
5440

5441
    // handle selectivity
5442
    if (pCtx->subsidiaries.num > 0) {
238,865✔
5443
      code = appendSelectivityValue(pCtx, i, pos);
206✔
5444
      if (TSDB_CODE_SUCCESS != code) {
206!
5445
        return code;
×
5446
      }
5447
    }
5448

5449
    numOfElems++;
238,865✔
5450
  }
5451

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

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

5461
int32_t mavgFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
5,558✔
5462
  if (pResultInfo->initialized) {
5,558✔
5463
    return TSDB_CODE_SUCCESS;
2,325✔
5464
  }
5465
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
3,233!
5466
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5467
  }
5468

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

5480
  return TSDB_CODE_SUCCESS;
3,234✔
5481
}
5482

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

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

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

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

5506
    int32_t pos = startOffset + numOfElems;
427,247✔
5507
    if (colDataIsNull_f(pInputCol, i)) {
427,247!
5508
      // colDataSetNULL(pOutput, i);
5509
      continue;
247,570✔
5510
    }
5511

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

5516
    if (!pInfo->pointsMeet && (pInfo->pos < pInfo->numOfPoints - 1)) {
179,676✔
5517
      pInfo->points[pInfo->pos] = v;
153,737✔
5518
      pInfo->sum += v;
153,737✔
5519
    } else {
5520
      if (!pInfo->pointsMeet && (pInfo->pos == pInfo->numOfPoints - 1)) {
25,939!
5521
        pInfo->sum += v;
977✔
5522
        pInfo->pointsMeet = true;
977✔
5523
      } else {
5524
        pInfo->sum = pInfo->sum + v - pInfo->points[pInfo->pos];
24,962✔
5525
      }
5526

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

5539
      // handle selectivity
5540
      if (pCtx->subsidiaries.num > 0) {
25,939✔
5541
        code = appendSelectivityValue(pCtx, i, pos);
280✔
5542
        if (TSDB_CODE_SUCCESS != code) {
280!
5543
          return code;
×
5544
        }
5545
      }
5546

5547
      numOfElems++;
25,939✔
5548
    }
5549

5550
    pInfo->pos++;
179,676✔
5551
    if (pInfo->pos == pInfo->numOfPoints) {
179,676✔
5552
      pInfo->pos = 0;
1,572✔
5553
    }
5554
  }
5555

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

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

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

5567
  return pInfo;
27,230✔
5568
}
5569

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

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

5586
  taosSeedRand(taosSafeRand());
12,663✔
5587

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

5599
  return TSDB_CODE_SUCCESS;
12,665✔
5600
}
5601

5602
static void sampleAssignResult(SSampleInfo* pInfo, char* data, int32_t index) {
325,792✔
5603
  assignVal(pInfo->data + index * pInfo->colBytes, data, pInfo->colBytes, pInfo->colType);
325,792✔
5604
}
325,967✔
5605

5606
static int32_t doReservoirSample(SqlFunctionCtx* pCtx, SSampleInfo* pInfo, char* data, int32_t index) {
355,409✔
5607
  pInfo->totalPoints++;
355,409✔
5608
  if (pInfo->numSampled < pInfo->samples) {
355,409✔
5609
    sampleAssignResult(pInfo, data, pInfo->numSampled);
314,182✔
5610
    if (pCtx->subsidiaries.num > 0) {
314,290✔
5611
      int32_t code = saveTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[pInfo->numSampled]);
8,413✔
5612
      if (code != TSDB_CODE_SUCCESS) {
8,437!
5613
        return code;
×
5614
      }
5615
    }
5616
    pInfo->numSampled++;
314,314✔
5617
  } else {
5618
    int32_t j = taosRand() % (pInfo->totalPoints);
41,227✔
5619
    if (j < pInfo->samples) {
41,244✔
5620
      sampleAssignResult(pInfo, data, j);
11,696✔
5621
      if (pCtx->subsidiaries.num > 0) {
11,695✔
5622
        int32_t code = updateTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[j]);
818✔
5623
        if (code != TSDB_CODE_SUCCESS) {
803!
5624
          return code;
×
5625
        }
5626
      }
5627
    }
5628
  }
5629

5630
  return TSDB_CODE_SUCCESS;
355,542✔
5631
}
5632

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

5637
  SInputColumnInfoData* pInput = &pCtx->input;
14,569✔
5638

5639
  SColumnInfoData* pInputCol = pInput->pData[0];
14,569✔
5640
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
588,592✔
5641
    if (colDataIsNull_s(pInputCol, i)) {
1,146,932✔
5642
      continue;
218,547✔
5643
    }
5644

5645
    char*   data = colDataGetData(pInputCol, i);
354,919!
5646
    int32_t code = doReservoirSample(pCtx, pInfo, data, i);
354,919✔
5647
    if (code != TSDB_CODE_SUCCESS) {
355,476!
5648
      return code;
×
5649
    }
5650
  }
5651

5652
  if (pInfo->numSampled == 0 && pCtx->subsidiaries.num > 0 && !pInfo->nullTupleSaved) {
15,126✔
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);
15,126✔
5661
  return TSDB_CODE_SUCCESS;
15,126✔
5662
}
5663

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

5668
  SSampleInfo* pInfo = getSampleOutputInfo(pCtx);
12,662✔
5669
  pEntryInfo->complete = true;
12,663✔
5670

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

5677
  int32_t currentRow = pBlock->info.rows;
12,662✔
5678
  if (pInfo->numSampled == 0) {
12,662✔
5679
    colDataSetNULL(pCol, currentRow);
1,507✔
5680
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
1,507✔
5681
    return code;
1,507✔
5682
  }
5683
  for (int32_t i = 0; i < pInfo->numSampled; ++i) {
325,066✔
5684
    code = colDataSetVal(pCol, currentRow + i, pInfo->data + i * pInfo->colBytes, false);
313,933✔
5685
    if (TSDB_CODE_SUCCESS != code) {
314,079!
5686
      return code;
×
5687
    }
5688
    code = setSelectivityValue(pCtx, pBlock, &pInfo->tuplePos[i], currentRow + i);
314,079✔
5689
    if (TSDB_CODE_SUCCESS != code) {
313,911!
5690
      return code;
×
5691
    }
5692
  }
5693

5694
  return code;
11,133✔
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) {
3,676✔
5936
  pEnv->calcMemSize = sizeof(SModeInfo);
3,676✔
5937
  return true;
3,676✔
5938
}
5939

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

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

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

5972
static void modeFunctionCleanup(SModeInfo* pInfo) {
4,264✔
5973
  taosHashCleanup(pInfo->pHash);
4,264✔
5974
  pInfo->pHash = NULL;
4,265✔
5975
  taosMemoryFreeClear(pInfo->buf);
4,265!
5976
}
4,264✔
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) {
282,490✔
5986
  if (IS_VAR_DATA_TYPE(pInfo->colType)) {
282,490!
5987
    if (pInfo->colType == TSDB_DATA_TYPE_JSON) {
43,217✔
5988
      (void)memcpy(pInfo->buf, data, getJsonValueLen(data));
1,188✔
5989
    } else if (IS_STR_DATA_BLOB(pInfo->colType)) {
42,029!
5990
      (void)memcpy(pInfo->buf, data, blobDataTLen(data));
×
5991
    } else {
5992
      (void)memcpy(pInfo->buf, data, varDataTLen(data));
42,069✔
5993
    }
5994
  } else {
5995
    (void)memcpy(pInfo->buf, data, pInfo->colBytes);
239,273✔
5996
  }
5997

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

6001
static int32_t doModeAdd(SModeInfo* pInfo, int32_t rowIndex, SqlFunctionCtx* pCtx, char* data) {
315,672✔
6002
  int32_t code = TSDB_CODE_SUCCESS;
315,672✔
6003
  int32_t hashKeyBytes;
6004
  if (IS_VAR_DATA_TYPE(pInfo->colType)) {
315,672✔
6005
    hashKeyBytes = calcStrBytesByType(pInfo->colType, data);
44,092✔
6006
  } else {
6007
    hashKeyBytes = pInfo->colBytes;
271,580✔
6008
  }
6009

6010
  SModeItem* pHashItem = (SModeItem*)taosHashGet(pInfo->pHash, data, hashKeyBytes);
315,506✔
6011
  if (pHashItem == NULL) {
314,337✔
6012
    int32_t   size = sizeof(SModeItem);
282,502✔
6013
    SModeItem item = {0};
282,502✔
6014

6015
    item.count += 1;
282,502✔
6016
    code = saveModeTupleData(pCtx, data, pInfo, &item.dataPos);
282,502✔
6017
    if (code != TSDB_CODE_SUCCESS) {
281,383!
6018
      return code;
×
6019
    }
6020

6021
    if (pCtx->subsidiaries.num > 0) {
281,383✔
6022
      code = saveTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &item.tuplePos);
568✔
6023
      if (code != TSDB_CODE_SUCCESS) {
568!
6024
        return code;
×
6025
      }
6026
    }
6027

6028
    code = taosHashPut(pInfo->pHash, data, hashKeyBytes, &item, sizeof(SModeItem));
281,383✔
6029
    if (code != TSDB_CODE_SUCCESS) {
283,957!
6030
      return code;
×
6031
    }
6032
  } else {
6033
    pHashItem->count += 1;
31,835✔
6034
    if (pCtx->subsidiaries.num > 0) {
31,835✔
6035
      code = updateTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &pHashItem->tuplePos);
5,246✔
6036
      if (code != TSDB_CODE_SUCCESS) {
5,246!
6037
        return code;
×
6038
      }
6039
    }
6040
  }
6041

6042
  return code;
315,792✔
6043
}
6044

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

6049
  SInputColumnInfoData* pInput = &pCtx->input;
6,900✔
6050

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

6054
  int32_t numOfElems = 0;
6,900✔
6055
  int32_t startOffset = pCtx->offset;
6,900✔
6056
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
637,839✔
6057
    if (colDataIsNull_s(pInputCol, i)) {
1,261,900✔
6058
      continue;
315,300✔
6059
    }
6060
    numOfElems++;
315,650✔
6061

6062
    char*   data = colDataGetData(pInputCol, i);
315,650!
6063
    int32_t code = doModeAdd(pInfo, i, pCtx, data);
315,650✔
6064
    if (code != TSDB_CODE_SUCCESS) {
315,784✔
6065
      modeFunctionCleanup(pInfo);
145✔
6066
      return code;
×
6067
    }
6068
  }
6069

6070
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pInfo->nullTupleSaved) {
6,889!
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);
6,889✔
6080

6081
  return TSDB_CODE_SUCCESS;
6,889✔
6082
}
6083

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

6096
  STuplePos resDataPos, resTuplePos;
6097
  int32_t   maxCount = 0;
4,264✔
6098

6099
  void* pIter = taosHashIterate(pInfo->pHash, NULL);
4,264✔
6100
  while (pIter != NULL) {
288,310✔
6101
    SModeItem* pItem = (SModeItem*)pIter;
284,046✔
6102
    if (pItem->count >= maxCount) {
284,046✔
6103
      maxCount = pItem->count;
283,739✔
6104
      resDataPos = pItem->dataPos;
283,739✔
6105
      resTuplePos = pItem->tuplePos;
283,739✔
6106
    }
6107

6108
    pIter = taosHashIterate(pInfo->pHash, pIter);
284,046✔
6109
  }
6110

6111
  if (maxCount != 0) {
4,264✔
6112
    char* pData = NULL;
2,245✔
6113
    code = loadTupleData(pCtx, &resDataPos, &pData);
2,245✔
6114
    if (pData == NULL || TSDB_CODE_SUCCESS != code) {
2,245!
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);
2,245✔
6123
    if (TSDB_CODE_SUCCESS != code) {
2,245!
6124
      modeFunctionCleanup(pInfo);
×
6125
      return code;
×
6126
    }
6127
    code = setSelectivityValue(pCtx, pBlock, &resTuplePos, currentRow);
2,245✔
6128
  } else {
6129
    colDataSetNULL(pCol, currentRow);
2,019✔
6130
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
2,019✔
6131
  }
6132

6133
  modeFunctionCleanup(pInfo);
4,264✔
6134

6135
  return code;
4,264✔
6136
}
6137

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

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

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

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

6163
  if ((s.val >= 0 && e.val >= 0) || (s.val <= 0 && e.val <= 0)) {
804,349✔
6164
    return (s.val + e.val) * (e.key - s.key) / 2;
758,819✔
6165
  }
6166

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

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

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

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

6186
  funcInputUpdate(pCtx);
27,772✔
6187
  SFuncInputRow row = {0};
27,772✔
6188
  bool          result = false;
27,772✔
6189
  if (pCtx->start.key != INT64_MIN && last->key == INT64_MIN) {
27,772!
6190
    while (1) {
6191
      code = funcInputGetNextRow(pCtx, &row, &result);
9,510✔
6192
      if (TSDB_CODE_SUCCESS != code) {
9,510!
6193
        return code;
×
6194
      }
6195
      if (!result) {
9,510✔
6196
        break;
2✔
6197
      }
6198
      if (row.isDataNull) {
9,508✔
6199
        continue;
2✔
6200
      }
6201

6202
      last->key = row.ts;
9,506✔
6203

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

6206
      pInfo->dOutput += twa_get_area(pCtx->start, *last);
9,506✔
6207
      pInfo->win.skey = pCtx->start.key;
9,506✔
6208
      pInfo->numOfElems++;
9,506✔
6209
      break;
9,506✔
6210
    }
6211
  } else if (pInfo->p.key == INT64_MIN) {
18,264✔
6212
    while (1) {
6213
      code = funcInputGetNextRow(pCtx, &row, &result);
78,065✔
6214
      if (TSDB_CODE_SUCCESS != code) {
78,064!
6215
        return code;
×
6216
      }
6217
      if (!result) {
78,064✔
6218
        break;
7,279✔
6219
      }
6220
      if (row.isDataNull) {
70,785✔
6221
        continue;
59,975✔
6222
      }
6223

6224
      last->key = row.ts;
10,810✔
6225

6226
      GET_TYPED_DATA(last->val, double, pInputCol->info.type, row.pData, typeGetTypeModFromColInfo(&pInputCol->info));
10,810!
6227

6228
      pInfo->win.skey = last->key;
10,811✔
6229
      pInfo->numOfElems++;
10,811✔
6230
      break;
10,811✔
6231
    }
6232
  }
6233

6234
  SPoint1 st = {0};
27,772✔
6235

6236
  // calculate the value of
6237
  while (1) {
6238
    code = funcInputGetNextRow(pCtx, &row, &result);
813,678✔
6239
    if (TSDB_CODE_SUCCESS != code) {
813,745!
6240
      return code;
×
6241
    }
6242
    if (!result) {
813,745✔
6243
      break;
27,773✔
6244
    }
6245
    if (row.isDataNull) {
785,972✔
6246
      continue;
624✔
6247
    }
6248
    pInfo->numOfElems++;
785,348✔
6249
    switch (pInputCol->info.type) {
785,348✔
6250
      case TSDB_DATA_TYPE_TINYINT: {
76,072✔
6251
        INIT_INTP_POINT(st, row.ts, *(int8_t*)row.pData);
76,072✔
6252
        break;
76,072✔
6253
      }
6254
      case TSDB_DATA_TYPE_SMALLINT: {
77,197✔
6255
        INIT_INTP_POINT(st, row.ts, *(int16_t*)row.pData);
77,197✔
6256
        break;
77,197✔
6257
      }
6258
      case TSDB_DATA_TYPE_INT: {
149,958✔
6259
        INIT_INTP_POINT(st, row.ts, *(int32_t*)row.pData);
149,958✔
6260
        break;
149,958✔
6261
      }
6262
      case TSDB_DATA_TYPE_BIGINT: {
86,739✔
6263
        INIT_INTP_POINT(st, row.ts, *(int64_t*)row.pData);
86,739✔
6264
        break;
86,739✔
6265
      }
6266
      case TSDB_DATA_TYPE_FLOAT: {
53,808✔
6267
        INIT_INTP_POINT(st, row.ts, *(float_t*)row.pData);
53,808✔
6268
        break;
53,808✔
6269
      }
6270
      case TSDB_DATA_TYPE_DOUBLE: {
76,099✔
6271
        INIT_INTP_POINT(st, row.ts, *(double*)row.pData);
76,099✔
6272
        break;
76,099✔
6273
      }
6274
      case TSDB_DATA_TYPE_UTINYINT: {
69,119✔
6275
        INIT_INTP_POINT(st, row.ts, *(uint8_t*)row.pData);
69,119✔
6276
        break;
69,119✔
6277
      }
6278
      case TSDB_DATA_TYPE_USMALLINT: {
69,098✔
6279
        INIT_INTP_POINT(st, row.ts, *(uint16_t*)row.pData);
69,098✔
6280
        break;
69,098✔
6281
      }
6282
      case TSDB_DATA_TYPE_UINT: {
67,859✔
6283
        INIT_INTP_POINT(st, row.ts, *(uint32_t*)row.pData);
67,859✔
6284
        break;
67,859✔
6285
      }
6286
      case TSDB_DATA_TYPE_UBIGINT: {
59,389✔
6287
        INIT_INTP_POINT(st, row.ts, *(uint64_t*)row.pData);
59,389✔
6288
        break;
59,389✔
6289
      }
6290
      default: {
10✔
6291
        return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
10✔
6292
      }
6293
    }
6294
    if (pInfo->p.key == st.key) {
785,338!
6295
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6296
    }
6297

6298
    pInfo->dOutput += twa_get_area(pInfo->p, st);
785,338✔
6299
    pInfo->p = st;
785,282✔
6300
  }
6301

6302
  // the last interpolated time window value
6303
  if (pCtx->end.key != INT64_MIN) {
27,773✔
6304
    pInfo->dOutput += twa_get_area(pInfo->p, pCtx->end);
9,513✔
6305
    pInfo->p = pCtx->end;
9,513✔
6306
    pInfo->numOfElems += 1;
9,513✔
6307
  }
6308

6309
  pInfo->win.ekey = pInfo->p.key;
27,773✔
6310

6311
_twa_over:
27,773✔
6312
  SET_VAL(pResInfo, 1, 1);
27,773✔
6313
  return TSDB_CODE_SUCCESS;
27,773✔
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) {
27,376✔
6329
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
27,376✔
6330

6331
  STwaInfo* pInfo = (STwaInfo*)GET_ROWCELL_INTERBUF(pResInfo);
27,376✔
6332
  if (pInfo->numOfElems == 0) {
27,376✔
6333
    pResInfo->numOfRes = 0;
7,056✔
6334
  } else {
6335
    if (pInfo->win.ekey == pInfo->win.skey) {
20,320✔
6336
      pInfo->dTwaRes = pInfo->p.val;
5,227✔
6337
    } else if (pInfo->win.ekey == INT64_MAX || pInfo->win.skey == INT64_MIN) {  // no data in timewindow
15,093!
6338
      pInfo->dTwaRes = 0;
2✔
6339
    } else {
6340
      pInfo->dTwaRes = pInfo->dOutput / (pInfo->win.ekey - pInfo->win.skey);
15,091✔
6341
    }
6342

6343
    pResInfo->numOfRes = 1;
20,320✔
6344
  }
6345

6346
  return functionFinalize(pCtx, pBlock);
27,376✔
6347
}
6348

6349
int32_t blockDistSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
11✔
6350
  if (pResultInfo->initialized) {
11!
6351
    return TSDB_CODE_SUCCESS;
×
6352
  }
6353
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
11!
6354
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6355
  }
6356

6357
  STableBlockDistInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
11✔
6358
  pInfo->minRows = INT32_MAX;
11✔
6359
  return TSDB_CODE_SUCCESS;
11✔
6360
}
6361

6362
int32_t blockDistFunction(SqlFunctionCtx* pCtx) {
20✔
6363
  const int32_t BLOCK_DIST_RESULT_ROWS = 25;
20✔
6364

6365
  SInputColumnInfoData* pInput = &pCtx->input;
20✔
6366
  SColumnInfoData*      pInputCol = pInput->pData[0];
20✔
6367
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
20✔
6368
  STableBlockDistInfo*  pDistInfo = GET_ROWCELL_INTERBUF(pResInfo);
20✔
6369

6370
  STableBlockDistInfo p1 = {0};
20✔
6371
  if (tDeserializeBlockDistInfo(varDataVal(pInputCol->pData), varDataLen(pInputCol->pData), &p1) < 0) {
20!
6372
    qError("failed to deserialize block dist info");
×
6373
    return TSDB_CODE_FAILED;
×
6374
  }
6375

6376
  pDistInfo->numOfBlocks += p1.numOfBlocks;
20✔
6377
  pDistInfo->numOfTables += p1.numOfTables;
20✔
6378
  pDistInfo->numOfInmemRows += p1.numOfInmemRows;
20✔
6379
  pDistInfo->numOfSttRows += p1.numOfSttRows;
20✔
6380
  pDistInfo->totalSize += p1.totalSize;
20✔
6381
  pDistInfo->totalRows += p1.totalRows;
20✔
6382
  pDistInfo->numOfFiles += p1.numOfFiles;
20✔
6383

6384
  pDistInfo->defMinRows = p1.defMinRows;
20✔
6385
  pDistInfo->defMaxRows = p1.defMaxRows;
20✔
6386
  pDistInfo->rowSize = p1.rowSize;
20✔
6387

6388
  if (pDistInfo->minRows > p1.minRows) {
20✔
6389
    pDistInfo->minRows = p1.minRows;
2✔
6390
  }
6391
  if (pDistInfo->maxRows < p1.maxRows) {
20✔
6392
    pDistInfo->maxRows = p1.maxRows;
2✔
6393
  }
6394
  pDistInfo->numOfVgroups += (p1.numOfTables != 0 ? 1 : 0);
20✔
6395
  for (int32_t i = 0; i < tListLen(pDistInfo->blockRowsHisto); ++i) {
420✔
6396
    pDistInfo->blockRowsHisto[i] += p1.blockRowsHisto[i];
400✔
6397
  }
6398

6399
  pResInfo->numOfRes = BLOCK_DIST_RESULT_ROWS;  // default output rows
20✔
6400
  return TSDB_CODE_SUCCESS;
20✔
6401
}
6402

6403
int32_t tSerializeBlockDistInfo(void* buf, int32_t bufLen, const STableBlockDistInfo* pInfo) {
39✔
6404
  SEncoder encoder = {0};
39✔
6405
  int32_t  code = 0;
39✔
6406
  int32_t  lino;
6407
  int32_t  tlen;
6408
  tEncoderInit(&encoder, buf, bufLen);
39✔
6409

6410
  TAOS_CHECK_EXIT(tStartEncode(&encoder));
40!
6411
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->rowSize));
80!
6412

6413
  TAOS_CHECK_EXIT(tEncodeU16(&encoder, pInfo->numOfFiles));
80!
6414
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfBlocks));
80!
6415
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfTables));
80!
6416

6417
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalSize));
80!
6418
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalRows));
80!
6419
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->maxRows));
80!
6420
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->minRows));
80!
6421
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMaxRows));
80!
6422
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMinRows));
80!
6423
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfInmemRows));
80!
6424
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfSttRows));
80!
6425
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfVgroups));
80!
6426

6427
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
840✔
6428
    TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->blockRowsHisto[i]));
1,600!
6429
  }
6430

6431
  tEndEncode(&encoder);
40✔
6432

6433
_exit:
40✔
6434
  if (code) {
40!
6435
    tlen = code;
×
6436
  } else {
6437
    tlen = encoder.pos;
40✔
6438
  }
6439
  tEncoderClear(&encoder);
40✔
6440
  return tlen;
40✔
6441
}
6442

6443
int32_t tDeserializeBlockDistInfo(void* buf, int32_t bufLen, STableBlockDistInfo* pInfo) {
20✔
6444
  SDecoder decoder = {0};
20✔
6445
  int32_t  code = 0;
20✔
6446
  int32_t  lino;
6447
  tDecoderInit(&decoder, buf, bufLen);
20✔
6448

6449
  TAOS_CHECK_EXIT(tStartDecode(&decoder));
20!
6450
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->rowSize));
40!
6451

6452
  TAOS_CHECK_EXIT(tDecodeU16(&decoder, &pInfo->numOfFiles));
40!
6453
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfBlocks));
40!
6454
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfTables));
40!
6455

6456
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->totalSize));
40!
6457
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->totalRows));
40!
6458
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->maxRows));
40!
6459
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->minRows));
40!
6460
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->defMaxRows));
40!
6461
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->defMinRows));
40!
6462
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfInmemRows));
40!
6463
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfSttRows));
40!
6464
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfVgroups));
40!
6465

6466
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
420✔
6467
    TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->blockRowsHisto[i]));
800!
6468
  }
6469

6470
_exit:
20✔
6471
  tDecoderClear(&decoder);
20✔
6472
  return code;
20✔
6473
}
6474

6475
int32_t blockDistFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
11✔
6476
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
11✔
6477
  STableBlockDistInfo* pData = GET_ROWCELL_INTERBUF(pResInfo);
11✔
6478

6479
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);
11✔
6480
  if (NULL == pColInfo) {
11!
6481
    return TSDB_CODE_OUT_OF_RANGE;
×
6482
  }
6483

6484
  if (pData->totalRows == 0) {
11✔
6485
    pData->minRows = 0;
9✔
6486
  }
6487

6488
  int32_t row = 0;
11✔
6489
  char    st[256] = {0};
11✔
6490
  double  averageSize = 0;
11✔
6491
  if (pData->numOfBlocks != 0) {
11✔
6492
    averageSize = ((double)pData->totalSize) / pData->numOfBlocks;
2✔
6493
  }
6494
  uint64_t totalRawSize = pData->totalRows * pData->rowSize;
11✔
6495
  double   compRatio = 0;
11✔
6496
  if (totalRawSize != 0) {
11✔
6497
    compRatio = pData->totalSize * 100 / (double)totalRawSize;
2✔
6498
  }
6499

6500
  int32_t len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
22✔
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, '%');
11✔
6503

6504
  varDataSetLen(st, len);
11✔
6505
  int32_t code = colDataSetVal(pColInfo, row++, st, false);
11✔
6506
  if (TSDB_CODE_SUCCESS != code) {
11!
6507
    return code;
×
6508
  }
6509

6510
  int64_t avgRows = 0;
11✔
6511
  if (pData->numOfBlocks > 0) {
11✔
6512
    avgRows = pData->totalRows / pData->numOfBlocks;
2✔
6513
  }
6514

6515
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
11✔
6516
                  "Block_Rows=[%" PRId64 "] MinRows=[%d] MaxRows=[%d] AvgRows=[%" PRId64 "]", pData->totalRows,
6517
                  pData->minRows, pData->maxRows, avgRows);
6518
  varDataSetLen(st, len);
11✔
6519
  code = colDataSetVal(pColInfo, row++, st, false);
11✔
6520
  if (TSDB_CODE_SUCCESS != code) {
11!
6521
    return code;
×
6522
  }
6523

6524
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Inmem_Rows=[%u] Stt_Rows=[%u] ",
11✔
6525
                  pData->numOfInmemRows, pData->numOfSttRows);
6526
  varDataSetLen(st, len);
11✔
6527
  code = colDataSetVal(pColInfo, row++, st, false);
11✔
6528
  if (TSDB_CODE_SUCCESS != code) {
11!
6529
    return code;
×
6530
  }
6531

6532
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
22✔
6533
                  "Total_Tables=[%d] Total_Filesets=[%d] Total_Vgroups=[%d]", pData->numOfTables, pData->numOfFiles,
11✔
6534
                  pData->numOfVgroups);
6535

6536
  varDataSetLen(st, len);
11✔
6537
  code = colDataSetVal(pColInfo, row++, st, false);
11✔
6538
  if (TSDB_CODE_SUCCESS != code) {
11!
6539
    return code;
×
6540
  }
6541

6542
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
11✔
6543
                  "--------------------------------------------------------------------------------");
6544
  varDataSetLen(st, len);
11✔
6545
  code = colDataSetVal(pColInfo, row++, st, false);
11✔
6546
  if (TSDB_CODE_SUCCESS != code) {
11!
6547
    return code;
×
6548
  }
6549

6550
  int32_t maxVal = 0;
11✔
6551
  int32_t minVal = INT32_MAX;
11✔
6552
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
231✔
6553
    if (maxVal < pData->blockRowsHisto[i]) {
220✔
6554
      maxVal = pData->blockRowsHisto[i];
3✔
6555
    }
6556

6557
    if (minVal > pData->blockRowsHisto[i]) {
220✔
6558
      minVal = pData->blockRowsHisto[i];
12✔
6559
    }
6560
  }
6561

6562
  // maximum number of step is 80
6563
  double factor = pData->numOfBlocks / 80.0;
11✔
6564

6565
  int32_t numOfBuckets = sizeof(pData->blockRowsHisto) / sizeof(pData->blockRowsHisto[0]);
11✔
6566
  int32_t bucketRange = ceil(((double)(pData->defMaxRows - pData->defMinRows)) / numOfBuckets);
11✔
6567

6568
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
231✔
6569
    len =
220✔
6570
        tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "%04d |", pData->defMinRows + bucketRange * (i + 1));
220✔
6571

6572
    int32_t num = 0;
220✔
6573
    if (pData->blockRowsHisto[i] > 0) {
220✔
6574
      num = (pData->blockRowsHisto[i]) / factor;
5✔
6575
    }
6576

6577
    for (int32_t j = 0; j < num; ++j) {
379✔
6578
      int32_t x = tsnprintf(varDataVal(st) + len, sizeof(st) - VARSTR_HEADER_SIZE - len, "%c", '|');
159✔
6579
      len += x;
159✔
6580
    }
6581

6582
    if (pData->blockRowsHisto[i] > 0) {
220✔
6583
      double v = pData->blockRowsHisto[i] * 100.0 / pData->numOfBlocks;
5✔
6584
      len += tsnprintf(varDataVal(st) + len, sizeof(st) - VARSTR_HEADER_SIZE - len, "  %d (%.2f%c)",
5✔
6585
                       pData->blockRowsHisto[i], v, '%');
6586
    }
6587

6588
    varDataSetLen(st, len);
220✔
6589
    code = colDataSetVal(pColInfo, row++, st, false);
220✔
6590
    if (TSDB_CODE_SUCCESS != code) {
220!
6591
      return code;
×
6592
    }
6593
  }
6594

6595
  return TSDB_CODE_SUCCESS;
11✔
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) {
385✔
6707
  pEnv->calcMemSize = sizeof(SDerivInfo);
385✔
6708
  return true;
385✔
6709
}
6710

6711
int32_t derivativeFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
862✔
6712
  if (pResInfo->initialized) {
862✔
6713
    return TSDB_CODE_SUCCESS;
396✔
6714
  }
6715
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
466!
6716
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6717
  }
6718

6719
  SDerivInfo* pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
466✔
6720

6721
  pDerivInfo->ignoreNegative = pCtx->param[2].param.i;
466✔
6722
  pDerivInfo->prevTs = -1;
466✔
6723
  pDerivInfo->tsWindow = pCtx->param[1].param.i;
466✔
6724
  pDerivInfo->valueSet = false;
466✔
6725
  return TSDB_CODE_SUCCESS;
466✔
6726
}
6727

6728
int32_t derivativeFunction(SqlFunctionCtx* pCtx) {
477✔
6729
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
477✔
6730
  SDerivInfo*          pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
477✔
6731

6732
  SInputColumnInfoData* pInput = &pCtx->input;
477✔
6733
  SColumnInfoData*      pInputCol = pInput->pData[0];
477✔
6734

6735
  int32_t          numOfElems = 0;
477✔
6736
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
477✔
6737
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
477✔
6738
  int32_t          code = TSDB_CODE_SUCCESS;
477✔
6739

6740
  funcInputUpdate(pCtx);
477✔
6741

6742
  double v = 0;
477✔
6743
  if (pCtx->order == TSDB_ORDER_ASC) {
477✔
6744
    SFuncInputRow row = {0};
454✔
6745
    bool          result = false;
454✔
6746
    while (1) {
60,013✔
6747
      code = funcInputGetNextRow(pCtx, &row, &result);
60,467✔
6748
      if (TSDB_CODE_SUCCESS != code) {
60,467!
6749
        return code;
×
6750
      }
6751
      if (!result) {
60,467✔
6752
        break;
454✔
6753
      }
6754
      if (row.isDataNull) {
60,013✔
6755
        continue;
17,868✔
6756
      }
6757

6758
      char* d = row.pData;
42,145✔
6759
      GET_TYPED_DATA(v, double, pInputCol->info.type, d, typeGetTypeModFromColInfo(&pInputCol->info));
42,145!
6760

6761
      int32_t pos = pCtx->offset + numOfElems;
42,145✔
6762
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
42,145✔
6763
        pDerivInfo->valueSet = true;
261✔
6764
      } else {
6765
        if (row.ts == pDerivInfo->prevTs) {
41,884!
6766
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6767
        }
6768
        double r = ((v - pDerivInfo->prevValue) * pDerivInfo->tsWindow) / (row.ts - pDerivInfo->prevTs);
41,884✔
6769
        if (pDerivInfo->ignoreNegative && r < 0) {
41,884✔
6770
        } else {
6771
          if (isinf(r) || isnan(r)) {
32,262!
6772
            colDataSetNULL(pOutput, pos);
×
6773
          } else {
6774
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
32,262✔
6775
            if (code != TSDB_CODE_SUCCESS) {
32,262!
6776
              return code;
×
6777
            }
6778
          }
6779

6780
          if (pTsOutput != NULL) {
32,262!
6781
            colDataSetInt64(pTsOutput, pos, &row.ts);
×
6782
          }
6783

6784
          // handle selectivity
6785
          if (pCtx->subsidiaries.num > 0) {
32,262✔
6786
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
62✔
6787
            if (code != TSDB_CODE_SUCCESS) {
62!
6788
              return code;
×
6789
            }
6790
          }
6791

6792
          numOfElems++;
32,262✔
6793
        }
6794
      }
6795

6796
      pDerivInfo->prevValue = v;
42,145✔
6797
      pDerivInfo->prevTs = row.ts;
42,145✔
6798
    }
6799
  } else {
6800
    SFuncInputRow row = {0};
23✔
6801
    bool          result = false;
23✔
6802
    while (1) {
46✔
6803
      code = funcInputGetNextRow(pCtx, &row, &result);
69✔
6804
      if (TSDB_CODE_SUCCESS != code) {
69!
6805
        return code;
×
6806
      }
6807
      if (!result) {
69✔
6808
        break;
23✔
6809
      }
6810
      if (row.isDataNull) {
46✔
6811
        continue;
10✔
6812
      }
6813

6814
      char* d = row.pData;
36✔
6815
      GET_TYPED_DATA(v, double, pInputCol->info.type, d, typeGetTypeModFromColInfo(&pInputCol->info));
36!
6816

6817
      int32_t pos = pCtx->offset + numOfElems;
36✔
6818
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
36✔
6819
        pDerivInfo->valueSet = true;
18✔
6820
      } else {
6821
        if (row.ts == pDerivInfo->prevTs) {
18!
6822
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6823
        }
6824
        double r = ((pDerivInfo->prevValue - v) * pDerivInfo->tsWindow) / (pDerivInfo->prevTs - row.ts);
18✔
6825
        if (pDerivInfo->ignoreNegative && r < 0) {
18!
6826
        } else {
6827
          if (isinf(r) || isnan(r)) {
18!
6828
            colDataSetNULL(pOutput, pos);
×
6829
          } else {
6830
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
18✔
6831
            if (code != TSDB_CODE_SUCCESS) {
18!
6832
              return code;
×
6833
            }
6834
          }
6835

6836
          if (pTsOutput != NULL) {
18!
6837
            colDataSetInt64(pTsOutput, pos, &pDerivInfo->prevTs);
×
6838
          }
6839

6840
          // handle selectivity
6841
          if (pCtx->subsidiaries.num > 0) {
18!
6842
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
×
6843
            if (code != TSDB_CODE_SUCCESS) {
×
6844
              return code;
×
6845
            }
6846
          }
6847
          numOfElems++;
18✔
6848
        }
6849
      }
6850

6851
      pDerivInfo->prevValue = v;
36✔
6852
      pDerivInfo->prevTs = row.ts;
36✔
6853
    }
6854
  }
6855

6856
  pResInfo->numOfRes = numOfElems;
477✔
6857

6858
  return TSDB_CODE_SUCCESS;
477✔
6859
}
6860

6861
int32_t getIrateInfoSize(int32_t pkBytes) { return (int32_t)sizeof(SRateInfo) + 2 * pkBytes; }
1,846✔
6862

6863
bool getIrateFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
1,533✔
6864
  int32_t pkBytes = (pFunc->hasPk) ? pFunc->pkBytes : 0;
1,533✔
6865
  pEnv->calcMemSize = getIrateInfoSize(pkBytes);
1,533✔
6866
  return true;
1,539✔
6867
}
6868

6869
int32_t irateFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
14,666✔
6870
  if (pResInfo->initialized) {
14,666!
6871
    return TSDB_CODE_SUCCESS;
×
6872
  }
6873
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
14,666!
6874
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6875
  }
6876

6877
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
14,666✔
6878

6879
  pInfo->firstKey = INT64_MIN;
14,666✔
6880
  pInfo->lastKey = INT64_MIN;
14,666✔
6881
  pInfo->firstValue = (double)INT64_MIN;
14,666✔
6882
  pInfo->lastValue = (double)INT64_MIN;
14,666✔
6883

6884
  pInfo->hasResult = 0;
14,666✔
6885
  return TSDB_CODE_SUCCESS;
14,666✔
6886
}
6887

6888
static void doSaveRateInfo(SRateInfo* pRateInfo, bool isFirst, int64_t ts, char* pk, double v) {
243,416✔
6889
  if (isFirst) {
243,416✔
6890
    pRateInfo->firstValue = v;
117,971✔
6891
    pRateInfo->firstKey = ts;
117,971✔
6892
    if (pRateInfo->firstPk) {
117,971✔
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;
125,445✔
6903
    pRateInfo->lastKey = ts;
125,445✔
6904
    if (pRateInfo->lastPk) {
125,445✔
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
}
243,416✔
6915

6916
static void initializeRateInfo(SqlFunctionCtx* pCtx, SRateInfo* pRateInfo, bool isMerge) {
15,865✔
6917
  if (pCtx->hasPrimaryKey) {
15,865✔
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,846✔
6929
    pRateInfo->lastPk = NULL;
15,846✔
6930
  }
6931
}
15,865✔
6932

6933
int32_t irateFunction(SqlFunctionCtx* pCtx) {
15,367✔
6934
  int32_t              code = TSDB_CODE_SUCCESS;
15,367✔
6935
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
15,367✔
6936
  SRateInfo*           pRateInfo = GET_ROWCELL_INTERBUF(pResInfo);
15,367✔
6937

6938
  SInputColumnInfoData* pInput = &pCtx->input;
15,367✔
6939
  SColumnInfoData*      pInputCol = pInput->pData[0];
15,367✔
6940

6941
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
15,367✔
6942

6943
  funcInputUpdate(pCtx);
15,367✔
6944

6945
  initializeRateInfo(pCtx, pRateInfo, false);
15,368✔
6946

6947
  int32_t       numOfElems = 0;
15,371✔
6948
  int32_t       type = pInputCol->info.type;
15,371✔
6949
  SFuncInputRow row = {0};
15,371✔
6950
  bool          result = false;
15,371✔
6951
  while (1) {
192,669✔
6952
    code = funcInputGetNextRow(pCtx, &row, &result);
208,040✔
6953
    if (TSDB_CODE_SUCCESS != code) {
208,036!
6954
      return code;
×
6955
    }
6956
    if (!result) {
208,036✔
6957
      break;
15,371✔
6958
    }
6959
    if (row.isDataNull) {
192,665✔
6960
      continue;
65,723✔
6961
    }
6962

6963
    char*  data = row.pData;
126,942✔
6964
    double v = 0;
126,942✔
6965
    GET_TYPED_DATA(v, double, type, data, typeGetTypeModFromColInfo(&pInputCol->info));
126,942!
6966

6967
    if (INT64_MIN == pRateInfo->lastKey) {
127,011✔
6968
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
7,532✔
6969
      pRateInfo->hasResult = 1;
7,532✔
6970
      continue;
7,532✔
6971
    }
6972

6973
    if (row.ts > pRateInfo->lastKey) {
119,479✔
6974
      if ((INT64_MIN == pRateInfo->firstKey) || pRateInfo->lastKey > pRateInfo->firstKey) {
117,691!
6975
        doSaveRateInfo(pRateInfo, true, pRateInfo->lastKey, pRateInfo->lastPk, pRateInfo->lastValue);
117,691✔
6976
      }
6977
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
117,690✔
6978
      continue;
117,685✔
6979
    } else if (row.ts == pRateInfo->lastKey) {
1,788!
6980
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6981
    }
6982

6983
    if ((INT64_MIN == pRateInfo->firstKey) || row.ts > pRateInfo->firstKey) {
1,788!
6984
      doSaveRateInfo(pRateInfo, true, row.ts, row.pPk, v);
12✔
6985
    } else if (row.ts == pRateInfo->firstKey) {
1,776!
6986
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6987
    }
6988
  }
6989

6990
  numOfElems++;
15,371✔
6991

6992
  SET_VAL(pResInfo, numOfElems, 1);
15,371!
6993
  return TSDB_CODE_SUCCESS;
15,371✔
6994
}
6995

6996
static double doCalcRate(const SRateInfo* pRateInfo, double tickPerSec) {
14,358✔
6997
  if ((INT64_MIN == pRateInfo->lastKey) || (INT64_MIN == pRateInfo->firstKey) ||
14,358✔
6998
      (pRateInfo->firstKey >= pRateInfo->lastKey)) {
952!
6999
    return 0.0;
13,406✔
7000
  }
7001

7002
  double diff = 0;
952✔
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;
952✔
7006
  if (diff >= pRateInfo->firstValue) {
952✔
7007
    diff -= pRateInfo->firstValue;
538✔
7008
  }
7009

7010
  int64_t duration = pRateInfo->lastKey - pRateInfo->firstKey;
952✔
7011
  if (duration == 0) {
952!
7012
    return 0;
×
7013
  }
7014

7015
  return (duration > 0) ? ((double)diff) / (duration / tickPerSec) : 0.0;
952!
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);
122✔
7021
    if (isFirstKey) {
122✔
7022
      doSaveRateInfo(pOutput, false, pInput->firstKey, pInput->firstPk, pInput->firstValue);
55✔
7023
    } else {
7024
      doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
67✔
7025
    }
7026
  } else if ((inputKey < pOutput->lastKey) && (inputKey > pOutput->firstKey)) {
110!
7027
    if (isFirstKey) {
24✔
7028
      doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
12✔
7029
    } else {
7030
      doSaveRateInfo(pOutput, true, pInput->lastKey, pInput->lastPk, pInput->lastValue);
12✔
7031
    }
7032
  } else {
7033
    // inputKey < pOutput->firstKey
7034
  }
7035
}
232✔
7036

7037
static void irateCopyInfo(SRateInfo* pInput, SRateInfo* pOutput) {
122✔
7038
  doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
122✔
7039
  doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
122✔
7040
}
122✔
7041

7042
static int32_t irateTransferInfo(SRateInfo* pInput, SRateInfo* pOutput) {
238✔
7043
  if ((pInput->firstKey != INT64_MIN &&
238✔
7044
       (pInput->firstKey == pOutput->firstKey || pInput->firstKey == pOutput->lastKey)) ||
233!
7045
      (pInput->lastKey != INT64_MIN && (pInput->lastKey == pOutput->firstKey || pInput->lastKey == pOutput->lastKey))) {
238!
7046
    return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
7047
  }
7048

7049
  if (pOutput->hasResult == 0) {
238✔
7050
    irateCopyInfo(pInput, pOutput);
122✔
7051
    pOutput->hasResult = pInput->hasResult;
122✔
7052
    return TSDB_CODE_SUCCESS;
122✔
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) {
248✔
7068
  SInputColumnInfoData* pInput = &pCtx->input;
248✔
7069
  SColumnInfoData*      pCol = pInput->pData[0];
248✔
7070
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
248!
7071
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
7072
  }
7073

7074
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
248✔
7075
  initializeRateInfo(pCtx, pInfo, true);
248✔
7076

7077
  int32_t start = pInput->startRowIndex;
248✔
7078
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
496✔
7079
    char*      data = colDataGetData(pCol, i);
248!
7080
    SRateInfo* pInputInfo = (SRateInfo*)varDataVal(data);
248✔
7081
    initializeRateInfo(pCtx, pInfo, true);
248✔
7082
    if (pInputInfo->hasResult) {
248✔
7083
      int32_t code = irateTransferInfo(pInputInfo, pInfo);
238✔
7084
      if (code != TSDB_CODE_SUCCESS) {
238!
7085
        return code;
×
7086
      }
7087
    }
7088
  }
7089

7090
  if (pInfo->hasResult) {
248✔
7091
    GET_RES_INFO(pCtx)->numOfRes = 1;
238✔
7092
  }
7093

7094
  return TSDB_CODE_SUCCESS;
248✔
7095
}
7096

7097
int32_t iratePartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
307✔
7098
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
307✔
7099
  SRateInfo*           pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
307✔
7100
  int32_t              resultBytes = getIrateInfoSize(pInfo->pkBytes);
307✔
7101
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
307!
7102

7103
  if (NULL == res) {
308!
7104
    return terrno;
×
7105
  }
7106
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
308✔
7107
  varDataSetLen(res, resultBytes);
308✔
7108

7109
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
308✔
7110
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
308✔
7111
  if (NULL == pCol) {
308!
7112
    taosMemoryFree(res);
×
7113
    return TSDB_CODE_OUT_OF_RANGE;
×
7114
  }
7115

7116
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
308✔
7117

7118
  taosMemoryFree(res);
308!
7119
  return code;
308✔
7120
}
7121

7122
int32_t irateFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
14,358✔
7123
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
14,358✔
7124
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
14,358✔
7125
  if (NULL == pCol) {
14,358!
7126
    return TSDB_CODE_OUT_OF_RANGE;
×
7127
  }
7128

7129
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
14,358✔
7130
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
14,358✔
7131

7132
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
14,358✔
7133
  double     result = doCalcRate(pInfo, (double)TSDB_TICK_PER_SECOND(pCtx->param[1].param.i));
14,358!
7134
  int32_t    code = colDataSetVal(pCol, pBlock->info.rows, (const char*)&result, pResInfo->isNullRes);
14,358✔
7135

7136
  return code;
14,358✔
7137
}
7138

7139
int32_t groupConstValueFunction(SqlFunctionCtx* pCtx) {
95,208,599✔
7140
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
95,208,599✔
7141
  SGroupKeyInfo*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
95,208,599✔
7142

7143
  SInputColumnInfoData* pInput = &pCtx->input;
95,208,599✔
7144
  SColumnInfoData*      pInputCol = pInput->pData[0];
95,208,599✔
7145

7146
  int32_t startIndex = pInput->startRowIndex;
95,208,599✔
7147

7148
  // escape rest of data blocks to avoid first entry to be overwritten.
7149
  if (pInfo->hasResult) {
95,208,599✔
7150
    goto _group_value_over;
7,364,673✔
7151
  }
7152

7153
  if (pInputCol->pData == NULL || colDataIsNull_s(pInputCol, startIndex)) {
175,190,097✔
7154
    pInfo->isNull = true;
2,738,674✔
7155
    pInfo->hasResult = true;
2,738,674✔
7156
    goto _group_value_over;
2,738,674✔
7157
  }
7158

7159
  char* data = colDataGetData(pInputCol, startIndex);
85,105,252!
7160
  if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
85,105,252!
7161
    int32_t bytes = calcStrBytesByType(pInputCol->info.type, data);
69,485,910✔
7162
    (void)memcpy(pInfo->data, data, bytes);
69,573,118✔
7163
  } else {
7164
    (void)memcpy(pInfo->data, data, pInputCol->info.bytes);
15,619,342✔
7165
  }
7166
  pInfo->hasResult = true;
85,192,460✔
7167

7168
_group_value_over:
95,295,807✔
7169

7170
  SET_VAL(pResInfo, 1, 1);
95,295,807✔
7171
  return TSDB_CODE_SUCCESS;
95,295,807✔
7172
}
7173

7174
int32_t groupKeyFunction(SqlFunctionCtx* pCtx) { return groupConstValueFunction(pCtx); }
95,201,045✔
7175

7176
int32_t groupConstValueFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
85,466,048✔
7177
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
85,466,048✔
7178
  int32_t          code = TSDB_CODE_SUCCESS;
85,466,048✔
7179
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
85,466,048✔
7180
  if (NULL == pCol) {
85,397,742!
7181
    return TSDB_CODE_OUT_OF_RANGE;
×
7182
  }
7183

7184
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
85,397,742✔
7185

7186
  SGroupKeyInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
85,397,742✔
7187

7188
  if (pInfo->hasResult) {
85,397,742!
7189
    int32_t currentRow = pBlock->info.rows;
85,424,347✔
7190
    for (; currentRow < pBlock->info.rows + pResInfo->numOfRes; ++currentRow) {
171,803,497✔
7191
      code = colDataSetVal(pCol, currentRow, pInfo->data, pInfo->isNull ? true : false);
85,452,663✔
7192
      if (TSDB_CODE_SUCCESS != code) {
86,379,150!
7193
        return code;
×
7194
      }
7195
    }
7196
  } else {
7197
    pResInfo->numOfRes = 0;
×
7198
  }
7199

7200
  return code;
86,324,229✔
7201
}
7202

7203
int32_t groupKeyFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { return groupConstValueFinalize(pCtx, pBlock); }
85,511,081✔
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) {
3,180✔
7239
  int32_t numOfElems = 0;
3,180✔
7240

7241
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
3,180✔
7242
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
3,180✔
7243

7244
  SInputColumnInfoData* pInput = &pCtx->input;
3,180✔
7245
  SColumnInfoData*      pInputCol = pInput->pData[0];
3,180✔
7246

7247
  int32_t bytes = pInputCol->info.bytes;
3,180✔
7248
  pInfo->bytes = bytes;
3,180✔
7249

7250
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
3,180✔
7251
  pInfo->pkType = -1;
3,180✔
7252
  __compar_fn_t pkCompareFn = NULL;
3,180✔
7253
  if (pCtx->hasPrimaryKey) {
3,180✔
7254
    pInfo->pkType = pkCol->info.type;
26✔
7255
    pInfo->pkBytes = pkCol->info.bytes;
26✔
7256
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
26✔
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) {
6,370✔
7262
    numOfElems++;
3,190✔
7263

7264
    bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
3,190✔
7265
    char* data = isNull ? NULL : colDataGetData(pInputCol, i);
3,190!
7266

7267
    TSKEY cts = getRowPTs(pInput->pPTS, i);
3,190!
7268
    if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
3,190✔
7269
      int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
2,711✔
7270
      if (code != TSDB_CODE_SUCCESS) {
2,711!
7271
        return code;
×
7272
      }
7273
      pResInfo->numOfRes = 1;
2,711✔
7274
    }
7275
  }
7276

7277
  SET_VAL(pResInfo, numOfElems, 1);
3,180!
7278
  return TSDB_CODE_SUCCESS;
3,180✔
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