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

taosdata / TDengine / #3630

06 Mar 2025 11:35AM UTC coverage: 63.629% (-0.06%) from 63.692%
#3630

push

travis-ci

web-flow
Merge pull request #30042 from taosdata/doc/internal

docs: format

149060 of 300532 branches covered (49.6%)

Branch coverage included in aggregate %.

233739 of 301077 relevant lines covered (77.63%)

17473135.72 hits per line

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

72.56
/source/libs/function/src/builtinsimpl.c
1
/*
2
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
3
 *
4
 * This program is free software: you can use, redistribute, and/or modify
5
 * it under the terms of the GNU Affero General Public License, version 3
6
 * or later ("AGPL"), as published by the Free Software Foundation.
7
 *
8
 * This program is distributed in the hope that it will be useful, but WITHOUT
9
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
10
 * FITNESS FOR A PARTICULAR PURPOSE.
11
 *
12
 * You should have received a copy of the GNU Affero General Public License
13
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
14
 */
15

16
#include "builtinsimpl.h"
17
#include "cJSON.h"
18
#include "function.h"
19
#include "functionResInfoInt.h"
20
#include "query.h"
21
#include "querynodes.h"
22
#include "tanalytics.h"
23
#include "tcompare.h"
24
#include "tdatablock.h"
25
#include "tdigest.h"
26
#include "tfunctionInt.h"
27
#include "tglobal.h"
28
#include "thistogram.h"
29
#include "tpercentile.h"
30

31
bool ignoreNegative(int8_t ignoreOption) { return (ignoreOption & 0x1) == 0x1; }
1,477,384,943✔
32
bool ignoreNull(int8_t ignoreOption) { return (ignoreOption & 0x2) == 0x2; }
1,823,302✔
33

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

193
void funcInputUpdate(SqlFunctionCtx* pCtx) {
22,912,244✔
194
  SFuncInputRowIter* pIter = &pCtx->rowIter;
22,912,244✔
195

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

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

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

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

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

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

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

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

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

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

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

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

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

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

382
bool funcInputGetNextRowNoPk(SFuncInputRowIter* pIter, SFuncInputRow* pRow) {
1,560,752,365✔
383
  if (pIter->rowIndex <= pIter->inputEndIndex) {
1,560,752,365✔
384
    setInputRowInfo(pRow, pIter, pIter->rowIndex, false);
1,538,003,345✔
385
    ++pIter->rowIndex;
1,538,059,322✔
386
    return true;
1,538,059,322✔
387
  } else {
388
    return false;
22,749,020✔
389
  }
390
}
391

392
int32_t funcInputGetNextRow(SqlFunctionCtx* pCtx, SFuncInputRow* pRow, bool* res) {
1,560,677,558✔
393
  SFuncInputRowIter* pIter = &pCtx->rowIter;
1,560,677,558✔
394
  if (pCtx->hasPrimaryKey) {
1,560,677,558✔
395
    if (pCtx->order == TSDB_ORDER_ASC) {
330!
396
      *res = funcInputGetNextRowAscPk(pIter, pRow);
330✔
397
      return TSDB_CODE_SUCCESS;
330✔
398
    } else {
399
      return funcInputGetNextRowDescPk(pIter, pRow, res);
×
400
    }
401
  } else {
402
    *res = funcInputGetNextRowNoPk(pIter, pRow);
1,560,677,228✔
403
    return TSDB_CODE_SUCCESS;
1,560,642,778✔
404
  }
405
  return TSDB_CODE_SUCCESS;
406
}
407

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

415
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
66,818,322✔
416
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
33,409,161✔
417

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

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

427
    char* pData = colDataGetData(pSrcCol, rowIndex);
33,409,161!
428

429
    // append to dest col
430
    int32_t dstSlotId = pc->pExpr->base.resSchema.slotId;
33,409,161✔
431

432
    SColumnInfoData* pDstCol = taosArrayGet(pCtx->pDstBlock->pDataBlock, dstSlotId);
33,409,161✔
433
    if (NULL == pDstCol) {
33,409,161!
434
      return TSDB_CODE_OUT_OF_RANGE;
×
435
    }
436
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
66,818,322✔
437
      colDataSetNULL(pDstCol, pos);
20!
438
    } else {
439
      int32_t code = colDataSetVal(pDstCol, pos, pData, false);
33,409,141✔
440
      if (TSDB_CODE_SUCCESS != code) {
33,409,141!
441
        return code;
×
442
      }
443
    }
444
  }
445
  return TSDB_CODE_SUCCESS;
33,409,161✔
446
}
447

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

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

453
int32_t functionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
778,471,428✔
454
  if (pResultInfo->initialized) {
778,471,428✔
455
    return TSDB_CODE_SUCCESS;  // already initialized
165,238✔
456
  }
457

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

462
  initResultRowEntry(pResultInfo, pCtx->resDataInfo.interBufSize);
778,306,190✔
463
  return TSDB_CODE_SUCCESS;
778,306,190✔
464
}
465

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

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

479
  return code;
195,483,000✔
480
}
481

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

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

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

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

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

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

509
  return code;
39✔
510
}
511

512
EFuncDataRequired countDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
199,435✔
513
  SNode* pParam = nodesListGetNode(pFunc->pParameterList, 0);
199,435✔
514
  if (QUERY_NODE_COLUMN == nodeType(pParam) && PRIMARYKEY_TIMESTAMP_COL_ID == ((SColumnNode*)pParam)->colId) {
199,457!
515
    return FUNC_DATA_REQUIRED_NOT_LOAD;
139,700✔
516
  }
517
  return FUNC_DATA_REQUIRED_SMA_LOAD;
59,757✔
518
}
519

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

525
static int64_t getNumOfElems(SqlFunctionCtx* pCtx) {
113,220,572✔
526
  int64_t numOfElem = 0;
113,220,572✔
527

528
  /*
529
   * 1. column data missing (schema modified) causes pInputCol->hasNull == true. pInput->colDataSMAIsSet == true;
530
   * 2. for general non-primary key columns, pInputCol->hasNull may be true or false, pInput->colDataSMAIsSet == true;
531
   * 3. for primary key column, pInputCol->hasNull always be false, pInput->colDataSMAIsSet == false;
532
   */
533
  SInputColumnInfoData* pInput = &pCtx->input;
113,220,572✔
534
  SColumnInfoData*      pInputCol = pInput->pData[0];
113,220,572✔
535
  if (1 == pInput->numOfRows && pInput->blankFill) {
113,220,572✔
536
    return 0;
443,280✔
537
  }
538
  if (pInput->colDataSMAIsSet && pInput->totalRows == pInput->numOfRows) {
112,777,292!
539
    numOfElem = pInput->numOfRows - pInput->pColumnDataAgg[0]->numOfNull;
3,739✔
540
  } else {
541
    if (pInputCol->hasNull) {
112,773,553✔
542
      for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
396,336,674✔
543
        if (colDataIsNull(pInputCol, pInput->totalRows, i, NULL)) {
736,581,560!
544
          continue;
2,351,772✔
545
        }
546
        numOfElem += 1;
365,939,008✔
547
      }
548
    } else {
549
      // when counting on the primary time stamp column and no statistics data is presented, use the size value
550
      // directly.
551
      numOfElem = pInput->numOfRows;
84,727,659✔
552
    }
553
  }
554
  return numOfElem;
112,777,292✔
555
}
556

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

564
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
113,429,826✔
565
  SInputColumnInfoData* pInput = &pCtx->input;
113,429,826✔
566

567
  int32_t type = pInput->pData[0]->info.type;
113,429,826✔
568

569
  char* buf = GET_ROWCELL_INTERBUF(pResInfo);
113,429,826✔
570
  if (IS_NULL_TYPE(type)) {
113,429,826✔
571
    // select count(NULL) returns 0
572
    numOfElem = 1;
136,448✔
573
    *((int64_t*)buf) += 0;
136,448✔
574
  } else {
575
    numOfElem = getNumOfElems(pCtx);
113,293,378✔
576
    *((int64_t*)buf) += numOfElem;
112,977,364✔
577
  }
578

579
  if (tsCountAlwaysReturnValue) {
113,113,812!
580
    pResInfo->numOfRes = 1;
113,135,356✔
581
  } else {
582
    SET_VAL(pResInfo, *((int64_t*)buf), 1);
×
583
  }
584

585
  return TSDB_CODE_SUCCESS;
113,113,812✔
586
}
587

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

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

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

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

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

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

613
int32_t sumFunction(SqlFunctionCtx* pCtx) {
92,114,316✔
614
  int32_t numOfElem = 0;
92,114,316✔
615

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

621
  SSumRes* pSumRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
92,114,316✔
622
  pSumRes->type = type;
92,114,316✔
623

624
  if (IS_NULL_TYPE(type)) {
92,114,316✔
625
    numOfElem = 0;
196✔
626
    goto _sum_over;
196✔
627
  }
628

629
  if (pInput->colDataSMAIsSet) {
92,114,120✔
630
    numOfElem = pInput->numOfRows - pAgg->numOfNull;
3,232✔
631

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

642
    int32_t start = pInput->startRowIndex;
92,110,888✔
643
    int32_t numOfRows = pInput->numOfRows;
92,110,888✔
644

645
    if (IS_SIGNED_NUMERIC_TYPE(type) || type == TSDB_DATA_TYPE_BOOL) {
92,110,888!
646
      if (type == TSDB_DATA_TYPE_TINYINT || type == TSDB_DATA_TYPE_BOOL) {
85,019,527!
647
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int8_t, numOfElem);
1,407,660✔
648
      } else if (type == TSDB_DATA_TYPE_SMALLINT) {
84,682,407✔
649
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int16_t, numOfElem);
796,359✔
650
      } else if (type == TSDB_DATA_TYPE_INT) {
84,635,615✔
651
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int32_t, numOfElem);
395,857,566✔
652
      } else if (type == TSDB_DATA_TYPE_BIGINT) {
19,020,631!
653
        LIST_ADD_N(pSumRes->isum, pCol, start, numOfRows, int64_t, numOfElem);
73,626,650✔
654
      }
655
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
7,091,361!
656
      if (type == TSDB_DATA_TYPE_UTINYINT) {
202✔
657
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint8_t, numOfElem);
130,039!
658
      } else if (type == TSDB_DATA_TYPE_USMALLINT) {
163✔
659
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint16_t, numOfElem);
130,047✔
660
      } else if (type == TSDB_DATA_TYPE_UINT) {
123✔
661
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint32_t, numOfElem);
130,039!
662
      } else if (type == TSDB_DATA_TYPE_UBIGINT) {
84!
663
        LIST_ADD_N(pSumRes->usum, pCol, start, numOfRows, uint64_t, numOfElem);
130,624✔
664
      }
665
    } else if (type == TSDB_DATA_TYPE_DOUBLE) {
7,091,159✔
666
      LIST_ADD_N(pSumRes->dsum, pCol, start, numOfRows, double, numOfElem);
4,524,013✔
667
    } else if (type == TSDB_DATA_TYPE_FLOAT) {
5,830,659✔
668
      LIST_ADD_N(pSumRes->dsum, pCol, start, numOfRows, float, numOfElem);
18,211,433✔
669
    }
670
  }
671

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

677
_sum_over:
92,387,593✔
678
  if (numOfElem == 0) {
92,114,316✔
679
    if (tsCountAlwaysReturnValue && pCtx->pExpr->pExpr->_function.pFunctNode->hasOriginalFunc &&
89,112✔
680
        fmIsCountLikeFunc(pCtx->pExpr->pExpr->_function.pFunctNode->originalFuncId)) {
11,533✔
681
      numOfElem = 1;
23✔
682
    }
683
  }
684
  // data in the check operation are all null, not output
685
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
92,114,316✔
686
  return TSDB_CODE_SUCCESS;
92,114,316✔
687
}
688

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

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

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

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

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

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

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

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

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

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

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

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

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

799
EFuncDataRequired statisDataRequired(SFunctionNode* pFunc, STimeWindow* pTimeWindow) {
190,676✔
800
  if(funcNotSupportStringSma(pFunc)) {
190,676✔
801
    return FUNC_DATA_REQUIRED_DATA_LOAD;
126✔
802
  }
803
  return FUNC_DATA_REQUIRED_SMA_LOAD;
190,550✔
804
}
805

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

814
  SMinmaxResInfo* buf = GET_ROWCELL_INTERBUF(pResultInfo);
55,508,140✔
815
  buf->assign = false;
55,508,140✔
816
  buf->tuplePos.pageId = -1;
55,508,140✔
817

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

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

829
int32_t minFunction(SqlFunctionCtx* pCtx) {
22,992,332✔
830
  int32_t numOfElems = 0;
22,992,332✔
831
  int32_t code = doMinMaxHelper(pCtx, 1, &numOfElems);
22,992,332✔
832
  if (code != TSDB_CODE_SUCCESS) {
23,070,933!
833
    return code;
×
834
  }
835
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
23,070,933✔
836
  return TSDB_CODE_SUCCESS;
23,070,933✔
837
}
838

839
int32_t maxFunction(SqlFunctionCtx* pCtx) {
40,836,907✔
840
  int32_t numOfElems = 0;
40,836,907✔
841
  int32_t code = doMinMaxHelper(pCtx, 0, &numOfElems);
40,836,907✔
842
  if (code != TSDB_CODE_SUCCESS) {
40,881,424!
843
    return code;
×
844
  }
845
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
40,881,424✔
846
  return TSDB_CODE_SUCCESS;
40,881,424✔
847
}
848

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

853
int32_t minmaxFunctionFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
53,758,905✔
854
  int32_t code = TSDB_CODE_SUCCESS;
53,758,905✔
855

856
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
53,758,905✔
857
  SMinmaxResInfo*      pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
53,758,905✔
858

859
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
53,758,905✔
860
  int32_t currentRow = pBlock->info.rows;
53,758,905✔
861

862
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
53,758,905✔
863
  if (NULL == pCol) {
53,759,784!
864
    return TSDB_CODE_OUT_OF_RANGE;
×
865
  }
866
  pEntryInfo->isNullRes = (pEntryInfo->numOfRes == 0) ? 1 : 0;
53,759,784✔
867

868
  // NOTE: do nothing change it, for performance issue
869
  if (!pEntryInfo->isNullRes) {
53,759,784✔
870
    switch (pCol->info.type) {
47,451,290!
871
      case TSDB_DATA_TYPE_UBIGINT:
8,984,680✔
872
      case TSDB_DATA_TYPE_BIGINT:
873
        ((int64_t*)pCol->pData)[currentRow] = pRes->v;
8,984,680✔
874
        break;
8,984,680✔
875
      case TSDB_DATA_TYPE_UINT:
15,362,196✔
876
      case TSDB_DATA_TYPE_INT:
877
        colDataSetInt32(pCol, currentRow, (int32_t*)&pRes->v);
15,362,196✔
878
        break;
15,362,196✔
879
      case TSDB_DATA_TYPE_USMALLINT:
9,286,541✔
880
      case TSDB_DATA_TYPE_SMALLINT:
881
        colDataSetInt16(pCol, currentRow, (int16_t*)&pRes->v);
9,286,541✔
882
        break;
9,286,541✔
883
      case TSDB_DATA_TYPE_BOOL:
203,795✔
884
      case TSDB_DATA_TYPE_UTINYINT:
885
      case TSDB_DATA_TYPE_TINYINT:
886
        colDataSetInt8(pCol, currentRow, (int8_t*)&pRes->v);
203,795✔
887
        break;
203,795✔
888
      case TSDB_DATA_TYPE_DOUBLE:
5,088✔
889
        colDataSetDouble(pCol, currentRow, (double*)&pRes->v);
5,088✔
890
        break;
5,088✔
891
      case TSDB_DATA_TYPE_FLOAT: {
9,007,710✔
892
        float v = GET_FLOAT_VAL(&pRes->v);
9,007,710✔
893
        colDataSetFloat(pCol, currentRow, &v);
9,007,710✔
894
        break;
9,007,710✔
895
      }
896
      case TSDB_DATA_TYPE_VARBINARY:
4,607,879✔
897
      case TSDB_DATA_TYPE_VARCHAR:
898
      case TSDB_DATA_TYPE_NCHAR: {
899
        code = colDataSetVal(pCol, currentRow, pRes->str, false);
4,607,879✔
900
        if (TSDB_CODE_SUCCESS != code) {
4,607,879!
901
          return code;
×
902
        }
903
        break;
4,607,879✔
904
      }
905
    }
906
  } else {
907
    colDataSetNULL(pCol, currentRow);
6,308,494!
908
  }
909

910
  taosMemoryFreeClear(pRes->str);
53,759,784!
911
  if (pCtx->subsidiaries.num > 0) {
53,759,784✔
912
    if (pEntryInfo->numOfRes > 0) {
18,329,431✔
913
      code = setSelectivityValue(pCtx, pBlock, &pRes->tuplePos, currentRow);
18,327,289✔
914
    } else {
915
      code = setNullSelectivityValue(pCtx, pBlock, currentRow);
2,142✔
916
    }
917
  }
918

919
  return code;
53,760,833✔
920
}
921

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

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

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

938
  return TSDB_CODE_SUCCESS;
2,136✔
939
}
940

941
int32_t setSelectivityValue(SqlFunctionCtx* pCtx, SSDataBlock* pBlock, const STuplePos* pTuplePos, int32_t rowIndex) {
302,474,668✔
942
  if (pCtx->subsidiaries.num <= 0) {
302,474,668✔
943
    return TSDB_CODE_SUCCESS;
127,972,572✔
944
  }
945

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

957
    bool* nullList = (bool*)p;
175,705,239✔
958
    char* pStart = (char*)(nullList + numOfCols * sizeof(bool));
175,705,239✔
959

960
    // todo set the offset value to optimize the performance.
961
    for (int32_t j = 0; j < numOfCols; ++j) {
350,688,256✔
962
      SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
175,711,596✔
963
      int32_t         dstSlotId = pc->pExpr->base.resSchema.slotId;
175,711,596✔
964

965
      SColumnInfoData* pDstCol = taosArrayGet(pBlock->pDataBlock, dstSlotId);
175,711,596✔
966
      if (NULL == pDstCol) {
175,479,466!
967
        return terrno;
×
968
      }
969
      if (nullList[j]) {
175,487,791✔
970
        colDataSetNULL(pDstCol, rowIndex);
144!
971
      } else {
972
        code = colDataSetValOrCover(pDstCol, rowIndex, pStart, false);
175,487,647✔
973
        if (TSDB_CODE_SUCCESS != code) {
174,982,873!
974
          return code;
×
975
        }
976
      }
977
      pStart += pDstCol->info.bytes;
174,983,017✔
978
    }
979
  }
980

981
  return TSDB_CODE_SUCCESS;
174,960,544✔
982
}
983

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

991
  int32_t code = TSDB_CODE_SUCCESS;
55,516,031✔
992
  for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
111,019,180✔
993
    SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
55,518,367✔
994

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

999
    SColumnInfoData* pSrcCol = taosArrayGet(pCtx->pSrcBlock->pDataBlock, srcSlotId);
55,518,367✔
1000
    if (NULL == pSrcCol) {
55,511,693!
1001
      return TSDB_CODE_OUT_OF_RANGE;
×
1002
    }
1003

1004
    char* pData = colDataGetData(pSrcCol, rowIndex);
55,511,693!
1005

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

1009
    SColumnInfoData* pDstCol = taosArrayGet(pCtx->pDstBlock->pDataBlock, dstSlotId);
55,511,693✔
1010
    if (NULL == pDstCol) {
55,501,932!
1011
      return TSDB_CODE_OUT_OF_RANGE;
×
1012
    }
1013

1014
    if (colDataIsNull_s(pSrcCol, rowIndex) == true) {
111,003,864✔
1015
      colDataSetNULL(pDstCol, pos);
400✔
1016
    } else {
1017
      code = colDataSetVal(pDstCol, pos, pData, false);
55,501,532✔
1018
      if (TSDB_CODE_SUCCESS != code) {
55,502,749!
1019
        return code;
×
1020
      }
1021
    }
1022
  }
1023
  return code;
55,500,813✔
1024
}
1025

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

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

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

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

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

1100
int32_t getStdInfoSize() { return (int32_t)sizeof(SStdRes); }
1,259,362✔
1101

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

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

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

1120
int32_t stdFunction(SqlFunctionCtx* pCtx) {
6,186,541✔
1121
  int32_t numOfElem = 0;
6,186,541✔
1122

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

1127
  SStdRes* pStdRes = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
6,186,541✔
1128
  pStdRes->type = type;
6,186,541✔
1129

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

1133
  int32_t start = pInput->startRowIndex;
6,186,541✔
1134
  int32_t numOfRows = pInput->numOfRows;
6,186,541✔
1135

1136
  if (IS_NULL_TYPE(type)) {
6,186,541✔
1137
    numOfElem = 0;
134✔
1138
    goto _stddev_over;
134✔
1139
  }
1140

1141
  switch (type) {
6,186,407!
1142
    case TSDB_DATA_TYPE_TINYINT: {
10,288✔
1143
      int8_t* plist = (int8_t*)pCol->pData;
10,288✔
1144
      for (int32_t i = start; i < numOfRows + start; ++i) {
130,909✔
1145
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
120,621✔
1146
          continue;
18,165✔
1147
        }
1148

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

1155
      break;
10,288✔
1156
    }
1157

1158
    case TSDB_DATA_TYPE_SMALLINT: {
216,260✔
1159
      int16_t* plist = (int16_t*)pCol->pData;
216,260✔
1160
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
980,627✔
1161
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
764,367✔
1162
          continue;
52,498✔
1163
        }
1164

1165
        numOfElem += 1;
711,869✔
1166
        pStdRes->count += 1;
711,869✔
1167
        pStdRes->isum += plist[i];
711,869✔
1168
        pStdRes->quadraticISum += plist[i] * plist[i];
711,869✔
1169
      }
1170
      break;
216,260✔
1171
    }
1172

1173
    case TSDB_DATA_TYPE_INT: {
19,290✔
1174
      int32_t* plist = (int32_t*)pCol->pData;
19,290✔
1175
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
388,705✔
1176
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
369,415✔
1177
          continue;
29,959✔
1178
        }
1179

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

1186
      break;
19,290✔
1187
    }
1188

1189
    case TSDB_DATA_TYPE_BIGINT: {
32,081✔
1190
      int64_t* plist = (int64_t*)pCol->pData;
32,081✔
1191
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
1,682,536✔
1192
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
1,650,455✔
1193
          continue;
98,976✔
1194
        }
1195

1196
        numOfElem += 1;
1,551,479✔
1197
        pStdRes->count += 1;
1,551,479✔
1198
        pStdRes->isum += plist[i];
1,551,479✔
1199
        pStdRes->quadraticISum += plist[i] * plist[i];
1,551,479✔
1200
      }
1201
      break;
32,081✔
1202
    }
1203

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

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

1217
      break;
25✔
1218
    }
1219

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

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

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

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

1248
      break;
25✔
1249
    }
1250

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

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

1266
    case TSDB_DATA_TYPE_FLOAT: {
5,854,245✔
1267
      float* plist = (float*)pCol->pData;
5,854,245✔
1268
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
23,085,373✔
1269
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
17,231,128✔
1270
          continue;
98,282✔
1271
        }
1272

1273
        numOfElem += 1;
17,132,846✔
1274
        pStdRes->count += 1;
17,132,846✔
1275
        pStdRes->dsum += plist[i];
17,132,846✔
1276
        pStdRes->quadraticDSum += plist[i] * plist[i];
17,132,846✔
1277
      }
1278
      break;
5,854,245✔
1279
    }
1280

1281
    case TSDB_DATA_TYPE_DOUBLE: {
54,163✔
1282
      double* plist = (double*)pCol->pData;
54,163✔
1283
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
3,197,468✔
1284
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
3,143,305✔
1285
          continue;
527,901✔
1286
        }
1287

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

1296
    default:
×
1297
      break;
×
1298
  }
1299

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

1306
static void stdTransferInfo(SStdRes* pInput, SStdRes* pOutput) {
1,257,309✔
1307
  if (IS_NULL_TYPE(pInput->type)) {
1,257,309✔
1308
    return;
80✔
1309
  }
1310
  pOutput->type = pInput->type;
1,257,229✔
1311
  if (IS_SIGNED_NUMERIC_TYPE(pOutput->type)) {
1,257,229!
1312
    pOutput->quadraticISum += pInput->quadraticISum;
7,658✔
1313
    pOutput->isum += pInput->isum;
7,658✔
1314
  } else if (IS_UNSIGNED_NUMERIC_TYPE(pOutput->type)) {
1,249,571!
1315
    pOutput->quadraticUSum += pInput->quadraticUSum;
1✔
1316
    pOutput->usum += pInput->usum;
1✔
1317
  } else {
1318
    pOutput->quadraticDSum += pInput->quadraticDSum;
1,249,570✔
1319
    pOutput->dsum += pInput->dsum;
1,249,570✔
1320
  }
1321

1322
  pOutput->count += pInput->count;
1,257,229✔
1323
}
1324

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

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

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

1338
  SStdRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,257,218✔
1339

1340
  for (int32_t i = pInput->startRowIndex; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
2,514,524✔
1341
    if (colDataIsNull_s(pCol, i)) continue;
2,514,612!
1342
    char*    data = colDataGetData(pCol, i);
1,257,306!
1343
    SStdRes* pInputInfo = (SStdRes*)varDataVal(data);
1,257,306✔
1344
    stdTransferInfo(pInputInfo, pInfo);
1,257,306✔
1345
  }
1346

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

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

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

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

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

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

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

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

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

1424
  if (pStddevRes->count == 0) {
4,929,453✔
1425
    GET_RES_INFO(pCtx)->numOfRes = 0;
53,086✔
1426
    return functionFinalize(pCtx, pBlock);
53,086✔
1427
  }
1428

1429
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
4,876,367!
1430
    avg = pStddevRes->isum / ((double)pStddevRes->count);
208,238✔
1431
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticISum / ((double)pStddevRes->count) - avg * avg));
208,238✔
1432
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
4,668,129!
1433
    avg = pStddevRes->usum / ((double)pStddevRes->count);
10✔
1434
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticUSum / ((double)pStddevRes->count) - avg * avg));
10✔
1435
  } else {
1436
    avg = pStddevRes->dsum / ((double)pStddevRes->count);
4,668,119✔
1437
    pStddevRes->result = sqrt(fabs(pStddevRes->quadraticDSum / ((double)pStddevRes->count) - avg * avg));
4,668,119✔
1438
  }
1439

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

1445
  return functionFinalize(pCtx, pBlock);
4,876,367✔
1446
}
1447

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

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

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

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

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

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

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

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

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

1499
  taosMemoryFree(res);
1,257,740!
1500
  return code;
1,257,742✔
1501
}
1502

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

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

1511
  stdTransferInfo(pSBuf, pDBuf);
3✔
1512

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

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

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

1531
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
4,330,790✔
1532

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

1538
int32_t leastSQRFunction(SqlFunctionCtx* pCtx) {
4,362,347✔
1539
  int32_t numOfElem = 0;
4,362,347✔
1540

1541
  SInputColumnInfoData* pInput = &pCtx->input;
4,362,347✔
1542
  int32_t               type = pInput->pData[0]->info.type;
4,362,347✔
1543

1544
  SLeastSQRInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
4,362,347✔
1545

1546
  SColumnInfoData* pCol = pInput->pData[0];
4,362,347✔
1547

1548
  double(*param)[3] = pInfo->matrix;
4,362,347✔
1549
  double x = pInfo->startVal;
4,362,347✔
1550

1551
  int32_t start = pInput->startRowIndex;
4,362,347✔
1552
  int32_t numOfRows = pInput->numOfRows;
4,362,347✔
1553

1554
  switch (type) {
4,362,347!
1555
    case TSDB_DATA_TYPE_TINYINT: {
5,738✔
1556
      int8_t* plist = (int8_t*)pCol->pData;
5,738✔
1557
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
276,966✔
1558
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
271,228✔
1559
          continue;
3,236✔
1560
        }
1561
        numOfElem++;
267,992✔
1562
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
267,992✔
1563
      }
1564
      break;
5,738✔
1565
    }
1566
    case TSDB_DATA_TYPE_SMALLINT: {
5,287✔
1567
      int16_t* plist = (int16_t*)pCol->pData;
5,287✔
1568
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
307,940✔
1569
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
302,653✔
1570
          continue;
2,436✔
1571
        }
1572

1573
        numOfElem++;
300,217✔
1574
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
300,217✔
1575
      }
1576
      break;
5,287✔
1577
    }
1578

1579
    case TSDB_DATA_TYPE_INT: {
2,156,625✔
1580
      int32_t* plist = (int32_t*)pCol->pData;
2,156,625✔
1581
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
6,474,766✔
1582
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
4,318,141✔
1583
          continue;
2,016✔
1584
        }
1585

1586
        numOfElem++;
4,316,125✔
1587
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
4,316,125✔
1588
      }
1589
      break;
2,156,625✔
1590
    }
1591

1592
    case TSDB_DATA_TYPE_BIGINT: {
10,817✔
1593
      int64_t* plist = (int64_t*)pCol->pData;
10,817✔
1594
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
369,707✔
1595
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
358,890✔
1596
          continue;
149,692✔
1597
        }
1598

1599
        numOfElem++;
209,198✔
1600
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
209,198✔
1601
      }
1602
      break;
10,817✔
1603
    }
1604

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

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

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

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

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

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

1655
    case TSDB_DATA_TYPE_FLOAT: {
12,585✔
1656
      float* plist = (float*)pCol->pData;
12,585✔
1657
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
584,776✔
1658
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
572,191✔
1659
          continue;
140,236✔
1660
        }
1661

1662
        numOfElem++;
431,955✔
1663
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
431,955✔
1664
      }
1665
      break;
12,585✔
1666
    }
1667

1668
    case TSDB_DATA_TYPE_DOUBLE: {
2,170,889✔
1669
      double* plist = (double*)pCol->pData;
2,170,889✔
1670
      for (int32_t i = start; i < numOfRows + pInput->startRowIndex; ++i) {
6,132,839✔
1671
        if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
3,961,950✔
1672
          continue;
150,912✔
1673
        }
1674

1675
        numOfElem++;
3,811,038✔
1676
        LEASTSQR_CAL(param, x, plist, i, pInfo->stepVal);
3,811,038✔
1677
      }
1678
      break;
2,170,889✔
1679
    }
1680
    case TSDB_DATA_TYPE_NULL: {
×
1681
      GET_RES_INFO(pCtx)->isNullRes = 1;
×
1682
      numOfElem = 1;
×
1683
      break;
×
1684
    }
1685

1686
    default:
×
1687
      break;
×
1688
  }
1689

1690
  pInfo->startVal = x;
4,362,347✔
1691
  pInfo->num += numOfElem;
4,362,347✔
1692

1693
  SET_VAL(GET_RES_INFO(pCtx), numOfElem, 1);
4,362,347✔
1694

1695
  return TSDB_CODE_SUCCESS;
4,362,347✔
1696
}
1697

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

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

1709
  if (0 == pInfo->num) {
4,324,737✔
1710
    colDataSetNULL(pCol, currentRow);
23,477!
1711
    return TSDB_CODE_SUCCESS;
23,477✔
1712
  }
1713

1714
  double(*param)[3] = pInfo->matrix;
4,301,260✔
1715

1716
  param[1][1] = (double)pInfo->num;
4,301,260✔
1717
  param[1][0] = param[0][1];
4,301,260✔
1718

1719
  double param00 = param[0][0] - param[1][0] * (param[0][1] / param[1][1]);
4,301,260✔
1720
  double param02 = param[0][2] - param[1][2] * (param[0][1] / param[1][1]);
4,301,260✔
1721

1722
  if (0 == param00) {
4,301,260✔
1723
    colDataSetNULL(pCol, currentRow);
3,953,522!
1724
    return TSDB_CODE_SUCCESS;
3,953,522✔
1725
  }
1726

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

1732
  param12 /= param[1][1];
347,738✔
1733

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

1749
  int32_t code = colDataSetVal(pCol, currentRow, buf, pResInfo->isNullRes);
347,746✔
1750

1751
  return code;
347,745✔
1752
}
1753

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

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

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

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

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

1795
  return TSDB_CODE_SUCCESS;
4,501✔
1796
}
1797

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

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

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

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

1820
  SPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,464,998✔
1821
  if (pCtx->scanFlag == MAIN_SCAN && pInfo->stage == 0) {
2,464,998✔
1822
    pInfo->stage += 1;
4,501✔
1823

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

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

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

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

1860
      pInfo->numOfElems += (pInput->numOfRows - pAgg->numOfNull);
1,223,950✔
1861
    } else {
1862
      // check the valid data one by one
1863
      int32_t start = pInput->startRowIndex;
8,594✔
1864
      for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
12,842,817✔
1865
        if (colDataIsNull_f(pCol->nullbitmap, i)) {
12,834,223✔
1866
          continue;
2,000✔
1867
        }
1868

1869
        char* data = colDataGetData(pCol, i);
12,832,223!
1870

1871
        double v = 0;
12,832,223✔
1872
        GET_TYPED_DATA(v, double, type, data);
12,832,223!
1873
        if (v < GET_DOUBLE_VAL(&pInfo->minval)) {
12,832,223✔
1874
          SET_DOUBLE_VAL(&pInfo->minval, v);
3,035✔
1875
        }
1876

1877
        if (v > GET_DOUBLE_VAL(&pInfo->maxval)) {
12,832,223✔
1878
          SET_DOUBLE_VAL(&pInfo->maxval, v);
410,085✔
1879
        }
1880

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

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

1901
    SET_VAL(pResInfo, numOfElems, 1);
1,230,748!
1902
  }
1903

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

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

1912
  int32_t code = 0;
4,501✔
1913
  double  v = 0;
4,501✔
1914

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

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

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

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

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

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

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

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

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

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

1966
      tMemBucketDestroy(pMemBucket);
2,761✔
1967
      return functionFinalize(pCtx, pBlock);
2,761✔
1968
    }
1969
  } else {
1970
    return functionFinalize(pCtx, pBlock);
1,706✔
1971
  }
1972

1973
_fin_error:
×
1974

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

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

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

1994
static int8_t getApercentileAlgo(char* algoStr) {
24,822✔
1995
  int8_t algoType;
1996
  if (strcasecmp(algoStr, "default") == 0) {
24,822✔
1997
    algoType = APERCT_ALGO_DEFAULT;
11,149✔
1998
  } else if (strcasecmp(algoStr, "t-digest") == 0) {
13,673✔
1999
    algoType = APERCT_ALGO_TDIGEST;
13,668✔
2000
  } else {
2001
    algoType = APERCT_ALGO_UNKNOWN;
5✔
2002
  }
2003

2004
  return algoType;
24,822✔
2005
}
2006

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

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

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

2024
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
16,070,048✔
2025

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

2030
  if (pCtx->numOfParams == 2) {
16,070,048✔
2031
    pInfo->algo = APERCT_ALGO_DEFAULT;
16,045,235✔
2032
  } else if (pCtx->numOfParams == 3) {
24,813!
2033
    pInfo->algo = getApercentileAlgo(varDataVal(pCtx->param[2].param.pz));
24,827✔
2034
    if (pInfo->algo == APERCT_ALGO_UNKNOWN) {
24,817!
2035
      return TSDB_CODE_FUNC_FUNTION_PARA_VALUE;
×
2036
    }
2037
  }
2038

2039
  char* tmp = (char*)pInfo + sizeof(SAPercentileInfo);
16,070,038✔
2040
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
16,070,038✔
2041
    pInfo->pTDigest = tdigestNewFrom(tmp, COMPRESSION);
13,669✔
2042
  } else {
2043
    buildHistogramInfo(pInfo);
16,056,369✔
2044
    pInfo->pHisto = tHistogramCreateFrom(tmp, MAX_HISTOGRAM_BIN);
16,056,380✔
2045
    qDebug("%s set up histogram, numOfElems:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
16,056,368✔
2046
           pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2047
  }
2048

2049
  return TSDB_CODE_SUCCESS;
16,070,041✔
2050
}
2051

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

2057
  SColumnInfoData* pCol = pInput->pData[0];
14,404,800✔
2058
  int32_t          type = pCol->info.type;
14,404,800✔
2059

2060
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
14,404,800✔
2061

2062
  int32_t start = pInput->startRowIndex;
14,404,800✔
2063
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
14,404,800✔
2064
    buildTDigestInfo(pInfo);
17,293✔
2065
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
17,294✔
2066
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
1,114,221✔
2067
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
1,096,931✔
2068
        continue;
215,701✔
2069
      }
2070
      numOfElems += 1;
881,230✔
2071
      char* data = colDataGetData(pCol, i);
881,230!
2072

2073
      double  v = 0;  // value
881,230✔
2074
      int64_t w = 1;  // weigth
881,230✔
2075
      GET_TYPED_DATA(v, double, type, data);
881,230✔
2076
      int32_t code = tdigestAdd(pInfo->pTDigest, v, w);
881,230✔
2077
      if (code != TSDB_CODE_SUCCESS) {
881,227!
2078
        return code;
×
2079
      }
2080
    }
2081
  } else {
2082
    // might be a race condition here that pHisto can be overwritten or setup function
2083
    // has not been called, need to relink the buffer pHisto points to.
2084
    buildHistogramInfo(pInfo);
14,387,507✔
2085
    qDebug("%s before add %d elements into histogram, total:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems: %p",
14,387,504✔
2086
           __FUNCTION__, numOfElems, pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto,
2087
           pInfo->pHisto->elems);
2088
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
55,954,868✔
2089
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
41,567,230✔
2090
        continue;
729,143✔
2091
      }
2092
      numOfElems += 1;
40,838,087✔
2093
      char* data = colDataGetData(pCol, i);
40,838,087!
2094

2095
      double v = 0;
40,838,087✔
2096
      GET_TYPED_DATA(v, double, type, data);
40,838,087!
2097
      int32_t code = tHistogramAdd(&pInfo->pHisto, v);
40,838,087✔
2098
      if (code != TSDB_CODE_SUCCESS) {
40,838,221!
2099
        return code;
×
2100
      }
2101
    }
2102

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

2108
  SET_VAL(pResInfo, numOfElems, 1);
14,404,814✔
2109
  return TSDB_CODE_SUCCESS;
14,404,814✔
2110
}
2111

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

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

2123
    if (hasRes) {
845✔
2124
      *hasRes = true;
843✔
2125
    }
2126

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

2131
    if (pTDigest->num_centroids <= 0 && pTDigest->num_buffered_pts == 0) {
845!
2132
      (void)memcpy(pTDigest, pInput->pTDigest, (size_t)TDIGEST_SIZE(COMPRESSION));
843✔
2133
      tdigestAutoFill(pTDigest, COMPRESSION);
843✔
2134
    } else {
2135
      int32_t code = tdigestMerge(pTDigest, pInput->pTDigest);
2✔
2136
      if (TSDB_CODE_SUCCESS != code) {
2!
2137
        return code;
×
2138
      }
2139
    }
2140
  } else {
2141
    buildHistogramInfo(pInput);
1,835,040✔
2142
    if (pInput->pHisto->numOfElems <= 0) {
1,835,040✔
2143
      return TSDB_CODE_SUCCESS;
208✔
2144
    }
2145

2146
    if (hasRes) {
1,834,832✔
2147
      *hasRes = true;
1,834,830✔
2148
    }
2149

2150
    buildHistogramInfo(pOutput);
1,834,832✔
2151
    SHistogramInfo* pHisto = pOutput->pHisto;
1,834,832✔
2152

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

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

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

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

2181
int32_t apercentileFunctionMerge(SqlFunctionCtx* pCtx) {
1,835,800✔
2182
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,835,800✔
2183

2184
  SInputColumnInfoData* pInput = &pCtx->input;
1,835,800✔
2185

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

2191
  SAPercentileInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
1,835,800✔
2192

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

2195
  bool    hasRes = false;
1,835,800✔
2196
  int32_t start = pInput->startRowIndex;
1,835,800✔
2197
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
3,671,682✔
2198
    char* data = colDataGetData(pCol, i);
1,835,882!
2199

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

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

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

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

2221
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
14,200,907✔
2222
    buildTDigestInfo(pInfo);
12,830✔
2223
    tdigestAutoFill(pInfo->pTDigest, COMPRESSION);
12,829✔
2224
    if (pInfo->pTDigest->size > 0) {
12,829!
2225
      pInfo->result = tdigestQuantile(pInfo->pTDigest, pInfo->percent / 100);
12,829✔
2226
    } else {  // no need to free
2227
      // setNull(pCtx->pOutput, pCtx->outputType, pCtx->outputBytes);
2228
      return TSDB_CODE_SUCCESS;
×
2229
    }
2230
  } else {
2231
    buildHistogramInfo(pInfo);
14,188,077✔
2232
    if (pInfo->pHisto->numOfElems > 0) {
14,188,073✔
2233
      qDebug("%s get the final res, elements:%" PRId64 ", numOfEntry:%d, pHisto:%p, elems:%p", __FUNCTION__,
14,136,839✔
2234
             pInfo->pHisto->numOfElems, pInfo->pHisto->numOfEntries, pInfo->pHisto, pInfo->pHisto->elems);
2235

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

2254
  return functionFinalize(pCtx, pBlock);
14,200,894✔
2255
}
2256

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

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

2267
  if (pInfo->algo == APERCT_ALGO_TDIGEST) {
1,835,555✔
2268
    (void)memcpy(varDataVal(res), pInfo, resultBytes);
844✔
2269
    varDataSetLen(res, resultBytes);
844✔
2270
  } else {
2271
    (void)memcpy(varDataVal(res), pInfo, resultBytes);
1,834,711✔
2272
    varDataSetLen(res, resultBytes);
1,834,711✔
2273
  }
2274

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

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

2284
  taosMemoryFree(res);
1,835,555!
2285
  return code;
1,835,554✔
2286
}
2287

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

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

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

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

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

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

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

2338
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
5,958✔
2339
  if (pResult->hasResult) {
5,958✔
2340
    if (pResult->pkBytes > 0) {
5,886✔
2341
      pResult->pkData = pResult->buf + pResult->bytes;
6✔
2342
    } else {
2343
      pResult->pkData = NULL;
5,880✔
2344
    }
2345
    if (pResult->ts < pBlockInfo->window.skey) {
5,886✔
2346
      return FUNC_DATA_REQUIRED_NOT_LOAD;
4,162✔
2347
    } else if (pResult->ts == pBlockInfo->window.skey) {
1,724✔
2348
      if (NULL == pResult->pkData) {
250✔
2349
        return FUNC_DATA_REQUIRED_NOT_LOAD;
244✔
2350
      }
2351
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 0, TSDB_ORDER_ASC) < 0) {
6!
2352
        return FUNC_DATA_REQUIRED_NOT_LOAD;
6✔
2353
      }
2354
    }
2355
    return FUNC_DATA_REQUIRED_DATA_LOAD;
1,474✔
2356
  } else {
2357
    return FUNC_DATA_REQUIRED_DATA_LOAD;
72✔
2358
  }
2359
}
2360

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

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

2369
  SFirstLastRes* pResult = GET_ROWCELL_INTERBUF(pEntry);
30,460✔
2370
  if (pResult->hasResult) {
30,460✔
2371
    if (pResult->pkBytes > 0) {
30,398✔
2372
      pResult->pkData = pResult->buf + pResult->bytes;
5✔
2373
    } else {
2374
      pResult->pkData = NULL;
30,393✔
2375
    }
2376
    if (pResult->ts > pBlockInfo->window.ekey) {
30,398✔
2377
      return FUNC_DATA_REQUIRED_NOT_LOAD;
28,440✔
2378
    } else if (pResult->ts == pBlockInfo->window.ekey && pResult->pkData) {
1,958✔
2379
      if (comparePkDataWithSValue(pResult->pkType, pResult->pkData, pBlockInfo->pks + 1, TSDB_ORDER_DESC) < 0) {
5!
2380
        return FUNC_DATA_REQUIRED_NOT_LOAD;
×
2381
      }
2382
    }
2383
    return FUNC_DATA_REQUIRED_DATA_LOAD;
1,958✔
2384
  } else {
2385
    return FUNC_DATA_REQUIRED_DATA_LOAD;
62✔
2386
  }
2387
}
2388

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

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

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

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

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

2417
  return *(TSKEY*)colDataGetData(pTsColInfo, rowIndex);
404,965,720!
2418
}
2419

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

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

2434
static int32_t prepareBuf(SqlFunctionCtx* pCtx) {
288,051,709✔
2435
  if (pCtx->subsidiaries.rowLen == 0) {
288,051,709✔
2436
    int32_t rowLen = 0;
655,324✔
2437
    for (int32_t j = 0; j < pCtx->subsidiaries.num; ++j) {
1,316,575✔
2438
      SqlFunctionCtx* pc = pCtx->subsidiaries.pCtx[j];
661,251✔
2439
      rowLen += pc->pExpr->base.resSchema.bytes;
661,251✔
2440
    }
2441

2442
    pCtx->subsidiaries.rowLen = rowLen + pCtx->subsidiaries.num * sizeof(bool);
655,324✔
2443
    pCtx->subsidiaries.buf = taosMemoryMalloc(pCtx->subsidiaries.rowLen);
655,324!
2444
    if (NULL == pCtx->subsidiaries.buf) {
654,412!
2445
      return terrno;
×
2446
    }
2447
  }
2448
  return TSDB_CODE_SUCCESS;
288,050,797✔
2449
}
2450

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

2455
  if (pCtx->subsidiaries.num <= 0) {
235,846,878✔
2456
    return TSDB_CODE_SUCCESS;
109,627,830✔
2457
  }
2458

2459
  if (!pInfo->hasResult) {
126,219,048✔
2460
    code = saveTupleData(pCtx, rowIndex, pSrcBlock, &pInfo->pos);
104,301,891✔
2461
  } else if (!noElements) {
21,917,157!
2462
    code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pInfo->pos);
22,011,088✔
2463
  } else { } // dothing
2464

2465
  return code;
125,891,982✔
2466
}
2467

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

2473
  if (IS_VAR_DATA_TYPE(type)) {
97,166,098!
2474
    if (type == TSDB_DATA_TYPE_JSON) {
15,224,258!
2475
      pInfo->bytes = getJsonValueLen(pData);
×
2476
    } else {
2477
      pInfo->bytes = varDataTLen(pData);
15,224,258✔
2478
    }
2479
  }
2480

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

2494
  pInfo->ts = currentTs;
97,166,098✔
2495
  int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pInfo, false);
97,166,098✔
2496
  if (code != TSDB_CODE_SUCCESS) {
97,216,438!
2497
    return code;
×
2498
  }
2499

2500
  pInfo->hasResult = true;
97,216,438✔
2501
  return TSDB_CODE_SUCCESS;
97,216,438✔
2502
}
2503

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

2509
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
52,975,615✔
2510
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
52,975,615✔
2511

2512
  SInputColumnInfoData* pInput = &pCtx->input;
52,975,615✔
2513
  SColumnInfoData*      pInputCol = pInput->pData[0];
52,975,615✔
2514

2515
  pInfo->bytes = pInputCol->info.bytes;
52,975,615✔
2516

2517
  if (IS_NULL_TYPE(pInputCol->info.type)) {
52,975,615✔
2518
    return TSDB_CODE_SUCCESS;
5,009✔
2519
  }
2520

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

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

2542
  SColumnDataAgg* pColAgg = (pInput->colDataSMAIsSet) ? pInput->pColumnDataAgg[0] : NULL;
53,005,768!
2543

2544
  TSKEY startKey = getRowPTs(pInput->pPTS, 0);
53,005,768!
2545
  TSKEY endKey = getRowPTs(pInput->pPTS, pInput->totalRows - 1);
53,005,768!
2546

2547
  int32_t blockDataOrder = (startKey <= endKey) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
53,005,768✔
2548

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

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

2565
      numOfElems++;
2566

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

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

2588
      numOfElems++;
2589

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

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

2602
  int     from = -1;
53,005,768✔
2603
  int32_t i = -1;
53,005,768✔
2604
  while (funcInputGetNextRowIndex(pInput, from, true, &i, &from)) {
166,929,407✔
2605
    if (pInputCol->hasNull && colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
152,203,729!
2606
      continue;
85,523✔
2607
    }
2608

2609
    numOfElems++;
113,808,469✔
2610
    char* data = colDataGetData(pInputCol, i);
113,808,469!
2611
    char* pkData = NULL;
113,808,469✔
2612
    if (pCtx->hasPrimaryKey) {
113,808,469✔
2613
      pkData = colDataGetData(pkCol, i);
153!
2614
    }
2615
    TSKEY cts = pts[i];
113,808,469✔
2616
    if (pResInfo->numOfRes == 0 || pInfo->ts > cts ||
113,808,469✔
2617
        (pInfo->ts == cts && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
69,837,108!
2618
      int32_t code = doSaveCurrentVal(pCtx, i, cts, pkData, pInputCol->info.type, data);
43,971,361✔
2619
      if (code != TSDB_CODE_SUCCESS) {
44,001,008!
2620
        return code;
×
2621
      }
2622
      pResInfo->numOfRes = 1;
44,001,008✔
2623
    }
2624
  }
2625
#endif
2626

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

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

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

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

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

2651
  if (IS_NULL_TYPE(type)) {
46,434,787✔
2652
    return TSDB_CODE_SUCCESS;
5,013✔
2653
  }
2654
  pInfo->bytes = bytes;
46,429,774✔
2655

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

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

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

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

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

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

2692
      numOfElems++;
2693

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

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

2708
      numOfElems++;
2709

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

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

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

2736
  // todo refactor
2737
  if (!pInputCol->hasNull && !pCtx->hasPrimaryKey) {
75,985,529✔
2738
    numOfElems = 1;
29,548,002✔
2739

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

2743
    for (int32_t i = pInput->startRowIndex, tick = 0; tick < round; i += 4, tick += 1) {
45,032,960✔
2744
      int64_t cts = pts[i];
15,487,510✔
2745
      int32_t chosen = i;
15,487,510✔
2746

2747
      if (cts < pts[i + 1]) {
15,487,510✔
2748
        cts = pts[i + 1];
4,867,211✔
2749
        chosen = i + 1;
4,867,211✔
2750
      }
2751

2752
      if (cts < pts[i + 2]) {
15,487,510✔
2753
        cts = pts[i + 2];
4,868,332✔
2754
        chosen = i + 2;
4,868,332✔
2755
      }
2756

2757
      if (cts < pts[i + 3]) {
15,487,510✔
2758
        cts = pts[i + 3];
4,868,482✔
2759
        chosen = i + 3;
4,868,482✔
2760
      }
2761

2762
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
15,487,510✔
2763
        char*   data = colDataGetData(pInputCol, chosen);
4,691,150!
2764
        int32_t code = doSaveCurrentVal(pCtx, chosen, cts, NULL, type, data);
4,691,150✔
2765
        if (code != TSDB_CODE_SUCCESS) {
4,688,598!
2766
          return code;
×
2767
        }
2768
        pResInfo->numOfRes = 1;
4,688,598✔
2769
      }
2770
    }
2771

2772
    for (int32_t i = pInput->startRowIndex + round * 4; i < pInput->startRowIndex + pInput->numOfRows; ++i) {
66,046,985✔
2773
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i]) {
36,578,892✔
2774
        char*   data = colDataGetData(pInputCol, i);
21,471,236!
2775
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], NULL, type, data);
21,471,236✔
2776
        if (code != TSDB_CODE_SUCCESS) {
21,393,879!
2777
          return code;
×
2778
        }
2779
        pResInfo->numOfRes = 1;
21,393,879✔
2780
      }
2781
    }
2782
  } else {
2783
    int     from = -1;
16,969,434✔
2784
    int32_t i = -1;
16,969,434✔
2785
    while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
160,397,188✔
2786
      if (colDataIsNull(pInputCol, pInput->totalRows, i, pColAgg)) {
286,871,296✔
2787
        continue;
5,585,484✔
2788
      }
2789

2790
      numOfElems++;
137,850,164✔
2791
      char* pkData = NULL;
137,850,164✔
2792
      if (pCtx->hasPrimaryKey) {
137,850,164✔
2793
        pkData = colDataGetData(pkCol, i);
100,000,193!
2794
      }
2795
      if (pResInfo->numOfRes == 0 || pInfo->ts < pts[i] ||
137,850,164✔
2796
          (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
110,870,614!
2797
        char*   data = colDataGetData(pInputCol, i);
27,040,757!
2798
        int32_t code = doSaveCurrentVal(pCtx, i, pts[i], pkData, type, data);
27,040,757✔
2799
        if (code != TSDB_CODE_SUCCESS) {
27,032,863!
2800
          return code;
×
2801
        }
2802
        pResInfo->numOfRes = 1;
27,032,863✔
2803
      }
2804
    }
2805
  }
2806
#endif
2807

2808
#endif
2809

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

2819
  return TSDB_CODE_SUCCESS;
46,562,829✔
2820
}
2821

2822
static bool firstLastTransferInfoImpl(SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst) {
71,212,650✔
2823
  if (!pInput->hasResult) {
71,212,650✔
2824
    return false;
2✔
2825
  }
2826
  __compar_fn_t pkCompareFn = NULL;
71,212,648✔
2827
  if (pInput->pkData) {
71,212,648✔
2828
    pkCompareFn = getKeyComparFunc(pInput->pkType, (isFirst) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC);
52✔
2829
  }
2830
  if (pOutput->hasResult) {
71,217,561✔
2831
    if (isFirst) {
23,821,222✔
2832
      if (pInput->ts > pOutput->ts ||
8,571,664✔
2833
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
8,571,201!
2834
        return false;
463✔
2835
      }
2836
    } else {
2837
      if (pInput->ts < pOutput->ts ||
15,249,558✔
2838
          (pInput->ts == pOutput->ts && pkCompareFn && pkCompareFn(pInput->pkData, pOutput->pkData) > 0)) {
8,770,629!
2839
        return false;
6,479,302✔
2840
      }
2841
    }
2842
  }
2843

2844
  pOutput->isNull = pInput->isNull;
64,737,796✔
2845
  pOutput->ts = pInput->ts;
64,737,796✔
2846
  pOutput->bytes = pInput->bytes;
64,737,796✔
2847
  pOutput->pkType = pInput->pkType;
64,737,796✔
2848

2849
  (void)memcpy(pOutput->buf, pInput->buf, pOutput->bytes);
64,737,796✔
2850
  if (pInput->pkData) {
64,737,796✔
2851
    pOutput->pkBytes = pInput->pkBytes;
46✔
2852
    (void)memcpy(pOutput->buf + pOutput->bytes, pInput->pkData, pOutput->pkBytes);
46✔
2853
    pOutput->pkData = pOutput->buf + pOutput->bytes;
46✔
2854
  }
2855
  return true;
64,737,796✔
2856
}
2857

2858
static int32_t firstLastTransferInfo(SqlFunctionCtx* pCtx, SFirstLastRes* pInput, SFirstLastRes* pOutput, bool isFirst,
71,212,185✔
2859
                                     int32_t rowIndex) {
2860
  if (firstLastTransferInfoImpl(pInput, pOutput, isFirst)) {
71,212,185✔
2861
    int32_t code = firstlastSaveTupleData(pCtx->pSrcBlock, rowIndex, pCtx, pOutput, false);
64,737,534✔
2862
    if (TSDB_CODE_SUCCESS != code) {
64,724,500!
2863
      return code;
×
2864
    }
2865
    pOutput->hasResult = true;
64,724,500✔
2866
  }
2867
  return TSDB_CODE_SUCCESS;
71,200,133✔
2868
}
2869

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

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

2879
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
47,410,834!
2880
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
2881
  }
2882

2883
  SFirstLastRes* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
47,410,834✔
2884

2885
  int32_t start = pInput->startRowIndex;
47,410,834✔
2886
  int32_t numOfElems = 0;
47,410,834✔
2887

2888
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
120,895,315✔
2889
    if (colDataIsNull_s(pCol, i)) {
147,010,282✔
2890
      continue;
2,285,283✔
2891
    }
2892
    char*          data = colDataGetData(pCol, i);
71,219,858!
2893
    SFirstLastRes* pInputInfo = (SFirstLastRes*)varDataVal(data);
71,219,858✔
2894
    if (pCtx->hasPrimaryKey) {
71,219,858✔
2895
      pInputInfo->pkData = pInputInfo->buf + pInputInfo->bytes;
52✔
2896
    } else {
2897
      pInputInfo->pkData = NULL;
71,219,806✔
2898
    }
2899

2900
    int32_t code = firstLastTransferInfo(pCtx, pInputInfo, pInfo, isFirstQuery, i);
71,219,858✔
2901
    if (code != TSDB_CODE_SUCCESS) {
71,199,198!
2902
      return code;
×
2903
    }
2904
    if (!numOfElems) {
71,199,198✔
2905
      numOfElems = pInputInfo->hasResult ? 1 : 0;
47,397,523✔
2906
    }
2907
  }
2908

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

2917
  SET_VAL(GET_RES_INFO(pCtx), numOfElems, 1);
47,390,174✔
2918
  return TSDB_CODE_SUCCESS;
47,390,174✔
2919
}
2920

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

2923
int32_t lastFunctionMerge(SqlFunctionCtx* pCtx) { return firstLastFunctionMergeImpl(pCtx, false); }
35,691,918✔
2924

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

2933
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
101,270,776✔
2934
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
101,270,776✔
2935

2936
  SFirstLastRes* pRes = GET_ROWCELL_INTERBUF(pResInfo);
101,270,776✔
2937

2938
  if (pResInfo->isNullRes) {
101,270,776✔
2939
    colDataSetNULL(pCol, pBlock->info.rows);
41,384✔
2940
    return setNullSelectivityValue(pCtx, pBlock, pBlock->info.rows);
41,384✔
2941
  }
2942
  code = colDataSetVal(pCol, pBlock->info.rows, pRes->buf, pRes->isNull || pResInfo->isNullRes);
101,229,392!
2943
  if (TSDB_CODE_SUCCESS != code) {
101,082,991!
2944
    return code;
×
2945
  }
2946

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

2950
  return code;
101,045,962✔
2951
}
2952

2953
int32_t firstLastPartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
75,055,338✔
2954
  int32_t code = TSDB_CODE_SUCCESS;
75,055,338✔
2955

2956
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
75,055,338✔
2957
  SFirstLastRes*       pRes = GET_ROWCELL_INTERBUF(pEntryInfo);
75,055,338✔
2958

2959
  int32_t resultBytes = getFirstLastInfoSize(pRes->bytes, pRes->pkBytes);
75,055,338✔
2960

2961
  // todo check for failure
2962
  char* res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
74,987,129!
2963
  if (NULL == res) {
75,580,233!
2964
    return terrno;
×
2965
  }
2966
  (void)memcpy(varDataVal(res), pRes, resultBytes);
75,580,233✔
2967

2968
  varDataSetLen(res, resultBytes);
75,580,233✔
2969

2970
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
75,580,233✔
2971
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
75,580,233✔
2972
  if (NULL == pCol) {
75,293,102!
2973
    taosMemoryFree(res);
×
2974
    return TSDB_CODE_OUT_OF_RANGE;
×
2975
  }
2976

2977
  if (pEntryInfo->numOfRes == 0) {
75,339,475✔
2978
    colDataSetNULL(pCol, pBlock->info.rows);
2,361,314!
2979
    code = setNullSelectivityValue(pCtx, pBlock, pBlock->info.rows);
2,361,314✔
2980
  } else {
2981
    code = colDataSetVal(pCol, pBlock->info.rows, res, false);
72,978,161✔
2982
    if (TSDB_CODE_SUCCESS != code) {
72,427,340!
2983
      taosMemoryFree(res);
×
2984
      return code;
×
2985
    }
2986
    code = setSelectivityValue(pCtx, pBlock, &pRes->pos, pBlock->info.rows);
72,427,340✔
2987
  }
2988
  taosMemoryFree(res);
74,691,167!
2989
  return code;
75,719,710✔
2990
}
2991

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

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

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

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

3011
  if (colDataIsNull_s(pInputCol, rowIndex)) {
140,000,212✔
3012
    pInfo->isNull = true;
508,731✔
3013
  } else {
3014
    pInfo->isNull = false;
69,491,375✔
3015

3016
    if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
69,491,375!
3017
      if (pInputCol->info.type == TSDB_DATA_TYPE_JSON) {
41,866,421!
3018
        pInfo->bytes = getJsonValueLen(pData);
×
3019
      } else {
3020
        pInfo->bytes = varDataTLen(pData);
41,866,421✔
3021
      }
3022
    }
3023

3024
    (void)memcpy(pInfo->buf, pData, pInfo->bytes);
69,491,375✔
3025
  }
3026

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

3045
  pInfo->hasResult = true;
69,823,514✔
3046

3047
  return TSDB_CODE_SUCCESS;
69,823,514✔
3048
}
3049

3050
int32_t lastRowFunction(SqlFunctionCtx* pCtx) {
68,433,494✔
3051
  int32_t numOfElems = 0;
68,433,494✔
3052

3053
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
68,433,494✔
3054
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
68,433,494✔
3055

3056
  SInputColumnInfoData* pInput = &pCtx->input;
68,433,494✔
3057
  SColumnInfoData*      pInputCol = pInput->pData[0];
68,433,494✔
3058

3059
  int32_t type = pInputCol->info.type;
68,433,494✔
3060
  int32_t bytes = pInputCol->info.bytes;
68,433,494✔
3061
  pInfo->bytes = bytes;
68,433,494✔
3062

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

3077
  if (pCtx->order == TSDB_ORDER_ASC && !pCtx->hasPrimaryKey) {
68,467,109!
3078
    for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
69,122,184!
3079
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
34,565,004✔
3080
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
34,565,004!
3081
      TSKEY cts = getRowPTs(pInput->pPTS, i);
34,565,004✔
3082
      numOfElems++;
34,565,004✔
3083

3084
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
34,565,004✔
3085
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
34,144,550✔
3086
        if (code != TSDB_CODE_SUCCESS) return code;
34,137,730!
3087
      }
3088

3089
      break;
34,558,184✔
3090
    }
3091
  } else if (!pCtx->hasPrimaryKey && pCtx->order == TSDB_ORDER_DESC) {
33,903,109!
3092
    // the optimized version only valid if all tuples in one block are monotonious increasing or descreasing.
3093
    // this assumption is NOT always works if project operator exists in downstream.
3094
    for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
67,792,657!
3095
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
33,982,024✔
3096
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
33,982,024!
3097
      TSKEY cts = getRowPTs(pInput->pPTS, i);
33,982,024!
3098
      numOfElems++;
33,982,024✔
3099

3100
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
33,982,024✔
3101
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
33,648,863✔
3102
        if (code != TSDB_CODE_SUCCESS) return code;
33,495,734!
3103
      }
3104
      break;
33,828,895✔
3105
    }
3106
  } else {
3107
    int64_t* pts = (int64_t*)pInput->pPTS->pData;
×
3108
    int      from = -1;
×
3109
    int32_t  i = -1;
×
3110
    while (funcInputGetNextRowIndex(pInput, from, false, &i, &from)) {
6,000,235✔
3111
      bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
6,060,681✔
3112
      char* data = isNull ? NULL : colDataGetData(pInputCol, i);
6,060,681!
3113
      TSKEY cts = pts[i];
6,060,681✔
3114

3115
      numOfElems++;
6,060,681✔
3116
      char* pkData = NULL;
6,060,681✔
3117
      if (pCtx->hasPrimaryKey) {
6,060,681✔
3118
        pkData = colDataGetData(pkCol, i);
171!
3119
      }
3120
      if (pResInfo->numOfRes == 0 || pInfo->ts < cts ||
6,060,681✔
3121
          (pInfo->ts == pts[i] && pkCompareFn && pkCompareFn(pkData, pInfo->pkData) < 0)) {
3,858,928!
3122
        int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
2,201,759✔
3123
        if (code != TSDB_CODE_SUCCESS) {
2,201,966!
3124
          return code;
×
3125
        }
3126
        pResInfo->numOfRes = 1;
2,201,966✔
3127
      }
3128
    }
3129
  }
3130

3131
  SET_VAL(pResInfo, numOfElems, 1);
68,375,477!
3132
  return TSDB_CODE_SUCCESS;
68,375,477✔
3133
}
3134

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

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

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

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

3247
  return false;
3248
}
3249

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

3265
static void tryToSetDouble(SDiffInfo* pDiffInfo, SColumnInfoData* pOutput, double v, int32_t pos) {
2,614,668✔
3266
  double delta = v - pDiffInfo->prev.d64;
2,614,668✔
3267
  if (delta < 0 && ignoreNegative(pDiffInfo->ignoreOption)) {
2,614,668✔
3268
    colDataSetNull_f_s(pOutput, pos);
658,567✔
3269
  } else {
3270
    colDataSetDouble(pOutput, pos, &delta);
1,956,101✔
3271
  }
3272
  pDiffInfo->prev.d64 = v;
2,614,668✔
3273
}
2,614,668✔
3274

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

3342
// TODO: the primary key compare can be skipped for ordered pk if knonwn before
3343
// TODO: for desc ordered, pk shall select the smallest one for one ts. if across block boundaries.
3344
bool funcInputGetNextRowIndex(SInputColumnInfoData* pInput, int32_t from, bool firstOccur, int32_t* pRowIndex,
332,601,515✔
3345
                              int32_t* nextFrom) {
3346
  if (pInput->pPrimaryKey == NULL) {
332,601,515✔
3347
    if (from == -1) {
232,648,870✔
3348
      from = pInput->startRowIndex;
70,844,538✔
3349
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
161,804,332✔
3350
      return false;
70,621,197✔
3351
    }
3352
    *pRowIndex = from;
162,027,673✔
3353
    *nextFrom = from + 1;
162,027,673✔
3354
    return true;
162,027,673✔
3355
  } else {
3356
    if (from == -1) {
99,952,645✔
3357
      from = pInput->startRowIndex;
30,175✔
3358
    } else if (from >= pInput->numOfRows + pInput->startRowIndex) {
99,922,470✔
3359
      return false;
30,175✔
3360
    }
3361
    TSKEY*           tsList = (int64_t*)pInput->pPTS->pData;
99,922,470✔
3362
    SColumnInfoData* pkCol = pInput->pPrimaryKey;
99,922,470✔
3363
    int8_t           pkType = pkCol->info.type;
99,922,470✔
3364
    int32_t          order = (firstOccur) ? TSDB_ORDER_ASC : TSDB_ORDER_DESC;
99,922,470✔
3365
    __compar_fn_t    compareFunc = getKeyComparFunc(pkType, order);
99,922,470✔
3366
    int32_t          select = from;
100,000,517✔
3367
    char*            val = colDataGetData(pkCol, select);
100,000,517!
3368
    while (from < pInput->numOfRows + pInput->startRowIndex - 1 && tsList[from + 1] == tsList[from]) {
100,001,072✔
3369
      char* val1 = colDataGetData(pkCol, from + 1);
555!
3370
      if (compareFunc(val1, val) < 0) {
555!
3371
        select = from + 1;
×
3372
        val = val1;
×
3373
      }
3374
      from = from + 1;
555✔
3375
    }
3376
    *pRowIndex = select;
100,000,517✔
3377
    *nextFrom = from + 1;
100,000,517✔
3378
    return true;
100,000,517✔
3379
  }
3380
}
3381

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

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

3391
  if (pRow->isDataNull || !pDiffInfo->hasPrev) {
1,470,229,624✔
3392
    return true;
181,096✔
3393
  } else if (ignoreNegative(pDiffInfo->ignoreOption)) {
1,470,048,528✔
3394
    return diffIsNegtive(pDiffInfo, pCtx->input.pData[0]->info.type, pRow->pData);
2,641,064✔
3395
  }
3396
  return false;
1,467,407,464✔
3397
}
3398

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

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

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

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

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

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

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

3444
  char* pv = pRow->pData;
1,469,468,517✔
3445

3446
  if (pRow->ts == pDiffInfo->prevTs) {
1,469,468,517✔
3447
    return TSDB_CODE_FUNC_DUP_TIMESTAMP;
21✔
3448
  }
3449
  code = doHandleDiff(pDiffInfo, inputType, pv, pOutput, pos, pRow->ts);
1,469,468,496✔
3450
  if (code != TSDB_CODE_SUCCESS) {
1,469,468,496!
3451
    return code;
×
3452
  }
3453
  // handle selectivity
3454
  if (pCtx->subsidiaries.num > 0) {
1,469,468,496✔
3455
    code = appendSelectivityCols(pCtx, pRow->block, pRow->rowIndex, pos);
32,348,527✔
3456
    if (code != TSDB_CODE_SUCCESS) {
32,348,527!
3457
      return code;
×
3458
    }
3459
  }
3460

3461
  return TSDB_CODE_SUCCESS;
1,469,468,496✔
3462
}
3463

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

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

3474
  SArray* pRows = taosArrayInit_s(sizeof(SFuncInputRow), diffColNum);
1,823,146✔
3475
  if (NULL == pRows) {
1,823,146!
3476
    return terrno;
×
3477
  }
3478

3479
  bool keepNull = false;
1,823,146✔
3480
  for (int i = 0; i < diffColNum; ++i) {
3,646,448✔
3481
    SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
1,823,302✔
3482
    if (NULL == pCtx) {
1,823,302!
3483
      code = terrno;
×
3484
      goto _exit;
×
3485
    }
3486
    funcInputUpdate(pCtx);
1,823,302✔
3487
    SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,823,302✔
3488
    SDiffInfo*           pDiffInfo = GET_ROWCELL_INTERBUF(pResInfo);
1,823,302✔
3489
    if (!ignoreNull(pDiffInfo->ignoreOption)) {
1,823,302✔
3490
      keepNull = true;
1,799,705✔
3491
    }
3492
  }
3493

3494
  SqlFunctionCtx* pCtx0 = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, 0);
1,823,146✔
3495
  SFuncInputRow*  pRow0 = (SFuncInputRow*)taosArrayGet(pRows, 0);
1,823,146✔
3496
  if (NULL == pCtx0 || NULL == pRow0) {
1,823,146!
3497
    code = terrno;
×
3498
    goto _exit;
×
3499
  }
3500
  int32_t startOffset = pCtx0->offset;
1,823,146✔
3501
  bool    result = false;
1,823,146✔
3502
  while (1) {
1,470,215,109✔
3503
    code = funcInputGetNextRow(pCtx0, pRow0, &result);
1,472,038,255✔
3504
    if (TSDB_CODE_SUCCESS != code) {
1,472,038,255!
3505
      goto _exit;
×
3506
    }
3507
    if (!result) {
1,472,038,255✔
3508
      break;
1,823,125✔
3509
    }
3510
    bool hasNotNullValue = !diffResultIsNull(pCtx0, pRow0);
1,470,215,130✔
3511
    for (int i = 1; i < diffColNum; ++i) {
1,470,229,624✔
3512
      SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
14,494✔
3513
      SFuncInputRow*  pRow = (SFuncInputRow*)taosArrayGet(pRows, i);
14,494✔
3514
      if (NULL == pCtx || NULL == pRow) {
14,494!
3515
        code = terrno;
×
3516
        goto _exit;
×
3517
      }
3518
      code = funcInputGetNextRow(pCtx, pRow, &result);
14,494✔
3519
      if (TSDB_CODE_SUCCESS != code) {
14,494!
3520
        goto _exit;
×
3521
      }
3522
      if (!result) {
14,494!
3523
        // rows are not equal
3524
        code = TSDB_CODE_QRY_EXECUTOR_INTERNAL_ERROR;
×
3525
        goto _exit;
×
3526
      }
3527
      if (!diffResultIsNull(pCtx, pRow)) {
14,494✔
3528
        hasNotNullValue = true;
14,052✔
3529
      }
3530
    }
3531
    int32_t pos = startOffset + numOfElems;
1,470,215,130✔
3532

3533
    bool newRow = false;
1,470,215,130✔
3534
    for (int i = 0; i < diffColNum; ++i) {
2,147,483,647✔
3535
      SqlFunctionCtx* pCtx = *(SqlFunctionCtx**)taosArrayGet(pCtxArray, i);
1,470,229,624✔
3536
      SFuncInputRow*  pRow = (SFuncInputRow*)taosArrayGet(pRows, i);
1,470,229,624✔
3537
      if (NULL == pCtx || NULL == pRow) {
1,470,229,624!
3538
        code = terrno;
×
3539
        goto _exit;
×
3540
      }
3541
      if ((keepNull || hasNotNullValue) && !isFirstRow(pCtx, pRow)) {
1,470,229,624✔
3542
        code = setDoDiffResult(pCtx, pRow, pos);
1,469,558,093✔
3543
        if (code != TSDB_CODE_SUCCESS) {
1,469,558,093✔
3544
          goto _exit;
21✔
3545
        }
3546
        newRow = true;
1,469,558,072✔
3547
      } else {
3548
        code = trySetPreVal(pCtx, pRow);
671,531✔
3549
        if (code != TSDB_CODE_SUCCESS) {
671,531!
3550
          goto _exit;
×
3551
        }
3552
      }
3553
    }
3554
    if (newRow) ++numOfElems;
1,470,215,109✔
3555
  }
3556

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

3567
_exit:
1,823,125✔
3568
  if (pRows) {
1,823,146!
3569
    taosArrayDestroy(pRows);
1,823,146✔
3570
    pRows = NULL;
1,823,146✔
3571
  }
3572
  return code;
1,823,146✔
3573
}
3574

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

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

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

3591
  STopBotRes*           pRes = GET_ROWCELL_INTERBUF(pResInfo);
45,318,779✔
3592
  SInputColumnInfoData* pInput = &pCtx->input;
45,318,779✔
3593

3594
  pRes->maxSize = pCtx->param[1].param.i;
45,318,779✔
3595

3596
  pRes->nullTupleSaved = false;
45,318,779✔
3597
  pRes->nullTuplePos.pageId = -1;
45,318,779✔
3598
  return TSDB_CODE_SUCCESS;
45,318,779✔
3599
}
3600

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

3606
  return pRes;
213,624,756✔
3607
}
3608

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

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

3614
int32_t topFunction(SqlFunctionCtx* pCtx) {
32,683,786✔
3615
  int32_t              numOfElems = 0;
32,683,786✔
3616
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
32,683,786✔
3617

3618
  SInputColumnInfoData* pInput = &pCtx->input;
32,683,786✔
3619
  SColumnInfoData*      pCol = pInput->pData[0];
32,683,786✔
3620

3621
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
32,683,786✔
3622
  pRes->type = pInput->pData[0]->info.type;
32,683,770✔
3623

3624
  int32_t start = pInput->startRowIndex;
32,683,770✔
3625
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
126,910,630✔
3626
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
94,205,429✔
3627
      continue;
38,714✔
3628
    }
3629

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

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

3648
int32_t bottomFunction(SqlFunctionCtx* pCtx) {
13,717,594✔
3649
  int32_t              numOfElems = 0;
13,717,594✔
3650
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
13,717,594✔
3651

3652
  SInputColumnInfoData* pInput = &pCtx->input;
13,717,594✔
3653
  SColumnInfoData*      pCol = pInput->pData[0];
13,717,594✔
3654

3655
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
13,717,594✔
3656
  pRes->type = pInput->pData[0]->info.type;
13,717,573✔
3657

3658
  int32_t start = pInput->startRowIndex;
13,717,573✔
3659
  for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
41,874,423✔
3660
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
28,156,740✔
3661
      continue;
30,434✔
3662
    }
3663

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

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

3680
  return TSDB_CODE_SUCCESS;
13,717,683✔
3681
}
3682

3683
static int32_t topBotResComparFn(const void* p1, const void* p2, const void* param) {
422,943,256✔
3684
  uint16_t type = *(uint16_t*)param;
422,943,256✔
3685

3686
  STopBotResItem* val1 = (STopBotResItem*)p1;
422,943,256✔
3687
  STopBotResItem* val2 = (STopBotResItem*)p2;
422,943,256✔
3688

3689
  if (IS_SIGNED_NUMERIC_TYPE(type)) {
422,943,256!
3690
    if (val1->v.i == val2->v.i) {
314,893,136✔
3691
      return 0;
204,890✔
3692
    }
3693

3694
    return (val1->v.i > val2->v.i) ? 1 : -1;
314,688,246✔
3695
  } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
108,050,120!
3696
    if (val1->v.u == val2->v.u) {
654,389✔
3697
      return 0;
143,178✔
3698
    }
3699

3700
    return (val1->v.u > val2->v.u) ? 1 : -1;
511,211✔
3701
  } else if (TSDB_DATA_TYPE_FLOAT == type) {
107,395,731✔
3702
    if (val1->v.f == val2->v.f) {
48,711,768✔
3703
      return 0;
63✔
3704
    }
3705

3706
    return (val1->v.f > val2->v.f) ? 1 : -1;
48,711,705✔
3707
  }
3708

3709
  if (val1->v.d == val2->v.d) {
58,683,963✔
3710
    return 0;
11✔
3711
  }
3712

3713
  return (val1->v.d > val2->v.d) ? 1 : -1;
58,683,952✔
3714
}
3715

3716
int32_t doAddIntoResult(SqlFunctionCtx* pCtx, void* pData, int32_t rowIndex, SSDataBlock* pSrcBlock, uint16_t type,
122,288,238✔
3717
                        uint64_t uid, SResultRowEntryInfo* pEntryInfo, bool isTopQuery) {
3718
  STopBotRes* pRes = getTopBotOutputInfo(pCtx);
122,288,238✔
3719
  int32_t     code = TSDB_CODE_SUCCESS;
122,265,793✔
3720

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

3724
  STopBotResItem* pItems = pRes->pItems;
122,334,768✔
3725

3726
  // not full yet
3727
  if (pEntryInfo->numOfRes < pRes->maxSize) {
122,334,768✔
3728
    STopBotResItem* pItem = &pItems[pEntryInfo->numOfRes];
78,862,868✔
3729
    pItem->v = val;
78,862,868✔
3730
    pItem->uid = uid;
78,862,868✔
3731

3732
    // save the data of this tuple
3733
    if (pCtx->subsidiaries.num > 0) {
78,862,868✔
3734
      code = saveTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
52,252,601✔
3735
      if (code != TSDB_CODE_SUCCESS) {
52,076,372!
3736
        return code;
×
3737
      }
3738
    }
3739
#ifdef BUF_PAGE_DEBUG
3740
    qDebug("page_saveTuple i:%d, item:%p,pageId:%d, offset:%d\n", pEntryInfo->numOfRes, pItem, pItem->tuplePos.pageId,
3741
           pItem->tuplePos.offset);
3742
#endif
3743
    // allocate the buffer and keep the data of this row into the new allocated buffer
3744
    pEntryInfo->numOfRes++;
78,686,639✔
3745
    code = taosheapsort((void*)pItems, sizeof(STopBotResItem), pEntryInfo->numOfRes, (const void*)&type,
78,686,639✔
3746
                        topBotResComparFn, !isTopQuery);
78,686,639✔
3747
    if (code != TSDB_CODE_SUCCESS) {
78,888,059!
3748
      return code;
×
3749
    }
3750
  } else {  // replace the minimum value in the result
3751
    if ((isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i > pItems[0].v.i) ||
43,471,900✔
3752
                        (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u > pItems[0].v.u) ||
27,787,025!
3753
                        (TSDB_DATA_TYPE_FLOAT == type && val.f > pItems[0].v.f) ||
27,696,267✔
3754
                        (TSDB_DATA_TYPE_DOUBLE == type && val.d > pItems[0].v.d))) ||
27,358,045✔
3755
        (!isTopQuery && ((IS_SIGNED_NUMERIC_TYPE(type) && val.i < pItems[0].v.i) ||
35,734,456!
3756
                         (IS_UNSIGNED_NUMERIC_TYPE(type) && val.u < pItems[0].v.u) ||
9,204,390!
3757
                         (TSDB_DATA_TYPE_FLOAT == type && val.f < pItems[0].v.f) ||
9,203,417✔
3758
                         (TSDB_DATA_TYPE_DOUBLE == type && val.d < pItems[0].v.d)))) {
7,986,543✔
3759
      // replace the old data and the coresponding tuple data
3760
      STopBotResItem* pItem = &pItems[0];
9,842,552✔
3761
      pItem->v = val;
9,842,552✔
3762
      pItem->uid = uid;
9,842,552✔
3763

3764
      // save the data of this tuple by over writing the old data
3765
      if (pCtx->subsidiaries.num > 0) {
9,842,552✔
3766
        code = updateTupleData(pCtx, rowIndex, pSrcBlock, &pItem->tuplePos);
7,611,017✔
3767
        if (code != TSDB_CODE_SUCCESS) {
7,594,440!
3768
          return code;
×
3769
        }
3770
      }
3771
#ifdef BUF_PAGE_DEBUG
3772
      qDebug("page_copyTuple pageId:%d, offset:%d", pItem->tuplePos.pageId, pItem->tuplePos.offset);
3773
#endif
3774
      code = taosheapadjust((void*)pItems, sizeof(STopBotResItem), 0, pEntryInfo->numOfRes - 1, (const void*)&type,
9,825,975✔
3775
                            topBotResComparFn, NULL, !isTopQuery);
9,825,975✔
3776
      if (code != TSDB_CODE_SUCCESS) {
9,776,092!
3777
        return code;
×
3778
      }
3779
    }
3780
  }
3781

3782
  return TSDB_CODE_SUCCESS;
122,293,499✔
3783
}
3784

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

3796
  int32_t offset = 0;
288,014,009✔
3797
  for (int32_t i = 0; i < pSubsidiaryies->num; ++i) {
575,662,432✔
3798
    SqlFunctionCtx* pc = pSubsidiaryies->pCtx[i];
288,020,463✔
3799

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

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

3809
    SColumnInfoData* pCol = taosArrayGet(pSrcBlock->pDataBlock, srcSlotId);
287,965,209✔
3810
    if (NULL == pCol) {
287,648,423!
3811
      return TSDB_CODE_OUT_OF_RANGE;
×
3812
    }
3813
    if ((nullList[i] = colDataIsNull_s(pCol, rowIndex)) == true) {
575,296,846✔
3814
      offset += pCol->info.bytes;
694✔
3815
      continue;
694✔
3816
    }
3817

3818
    char* p = colDataGetData(pCol, rowIndex);
287,647,729!
3819
    if (IS_VAR_DATA_TYPE(pCol->info.type)) {
287,647,729!
3820
      (void)memcpy(pStart + offset, p, (pCol->info.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(p) : varDataTLen(p));
41,466!
3821
    } else {
3822
      (void)memcpy(pStart + offset, p, pCol->info.bytes);
287,606,263✔
3823
    }
3824

3825
    offset += pCol->info.bytes;
287,647,729✔
3826
  }
3827

3828
  *res = buf;
287,641,969✔
3829
  return TSDB_CODE_SUCCESS;
287,641,969✔
3830
}
3831

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

3838
    if (pHandle->currentPage == -1) {
343,661,658✔
3839
      pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
664,191✔
3840
      if (pPage == NULL) {
664,196✔
3841
        return terrno;
2✔
3842
      }
3843
      pPage->num = sizeof(SFilePage);
664,194✔
3844
    } else {
3845
      pPage = getBufPage(pHandle->pBuf, pHandle->currentPage);
342,997,467✔
3846
      if (pPage == NULL) {
342,880,826!
3847
        return terrno;
×
3848
      }
3849
      if (pPage->num + length > getBufPageSize(pHandle->pBuf)) {
342,880,826✔
3850
        // current page is all used, let's prepare a new buffer page
3851
        releaseBufPage(pHandle->pBuf, pPage);
444,657✔
3852
        pPage = getNewBufPage(pHandle->pBuf, &pHandle->currentPage);
444,657✔
3853
        if (pPage == NULL) {
444,659!
3854
          return terrno;
×
3855
        }
3856
        pPage->num = sizeof(SFilePage);
444,659✔
3857
      }
3858
    }
3859

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

3863
    pPage->num += length;
343,516,121✔
3864
    setBufPageDirty(pPage, true);
343,516,121✔
3865
    releaseBufPage(pHandle->pBuf, pPage);
343,362,962✔
3866
  } else {  // other tuple save policy
3867
    if (pStore->streamStateFuncPut(pHandle->pState, key, pBuf, length) >= 0) {
27,195!
3868
      p.streamTupleKey = *key;
46,567✔
3869
    }
3870
  }
3871

3872
  *pPos = p;
343,257,331✔
3873
  return TSDB_CODE_SUCCESS;
343,257,331✔
3874
}
3875

3876
int32_t saveTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
245,794,434✔
3877
  int32_t code = prepareBuf(pCtx);
245,794,434✔
3878
  if (TSDB_CODE_SUCCESS != code) {
245,766,172!
3879
    return code;
×
3880
  }
3881

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

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

3903
static int32_t doUpdateTupleData(SSerializeDataHandle* pHandle, const void* pBuf, size_t length, STuplePos* pPos,
42,297,900✔
3904
                                 SFunctionStateStore* pStore) {
3905
  if (pHandle->pBuf != NULL) {
42,297,900✔
3906
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
42,219,564✔
3907
    if (pPage == NULL) {
42,215,504!
3908
      return terrno;
×
3909
    }
3910
    (void)memcpy(pPage->data + pPos->offset, pBuf, length);
42,215,504✔
3911
    setBufPageDirty(pPage, true);
42,215,504✔
3912
    releaseBufPage(pHandle->pBuf, pPage);
42,208,644✔
3913
  } else {
3914
    int32_t code = pStore->streamStateFuncPut(pHandle->pState, &pPos->streamTupleKey, pBuf, length);
78,336✔
3915
    if (TSDB_CODE_SUCCESS != code) {
78,805!
3916
      return code;
×
3917
    }
3918
  }
3919

3920
  return TSDB_CODE_SUCCESS;
42,280,397✔
3921
}
3922

3923
int32_t updateTupleData(SqlFunctionCtx* pCtx, int32_t rowIndex, const SSDataBlock* pSrcBlock, STuplePos* pPos) {
42,303,761✔
3924
  int32_t code = prepareBuf(pCtx);
42,303,761✔
3925
  if (TSDB_CODE_SUCCESS != code) {
42,302,791!
3926
    return code;
×
3927
  }
3928

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

3937
static int32_t doLoadTupleData(SSerializeDataHandle* pHandle, const STuplePos* pPos, SFunctionStateStore* pStore,
175,589,316✔
3938
                               char** value) {
3939
  if (pHandle->pBuf != NULL) {
175,589,316✔
3940
    SFilePage* pPage = getBufPage(pHandle->pBuf, pPos->pageId);
175,552,053✔
3941
    if (pPage == NULL) {
175,757,085!
3942
      *value = NULL;
×
3943
      return terrno;
×
3944
    }
3945
    *value = pPage->data + pPos->offset;
175,757,085✔
3946
    releaseBufPage(pHandle->pBuf, pPage);
175,757,085✔
3947
    return TSDB_CODE_SUCCESS;
175,686,428✔
3948
  } else {
3949
    *value = NULL;
37,263✔
3950
    int32_t vLen;
3951
    int32_t code = pStore->streamStateFuncGet(pHandle->pState, &pPos->streamTupleKey, (void**)(value), &vLen);
37,263✔
3952
    if (TSDB_CODE_SUCCESS != code) {
46,234!
3953
      return code;
×
3954
    }
3955
    return TSDB_CODE_SUCCESS;
46,234✔
3956
  }
3957
}
3958

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

3963
int32_t topBotFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
45,165,975✔
3964
  int32_t code = TSDB_CODE_SUCCESS;
45,165,975✔
3965

3966
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
45,165,975✔
3967
  STopBotRes*          pRes = getTopBotOutputInfo(pCtx);
45,165,975✔
3968

3969
  int16_t type = pCtx->pExpr->base.resSchema.type;
45,164,185✔
3970
  int32_t slotId = pCtx->pExpr->base.resSchema.slotId;
45,164,185✔
3971

3972
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
45,164,185✔
3973
  if (NULL == pCol) {
45,149,118!
3974
    return TSDB_CODE_OUT_OF_RANGE;
×
3975
  }
3976

3977
  // todo assign the tag value and the corresponding row data
3978
  int32_t currentRow = pBlock->info.rows;
45,149,118✔
3979
  if (pEntryInfo->numOfRes <= 0) {
45,149,118✔
3980
    colDataSetNULL(pCol, currentRow);
653!
3981
    code = setSelectivityValue(pCtx, pBlock, &pRes->nullTuplePos, currentRow);
653✔
3982
    return code;
653✔
3983
  }
3984
  for (int32_t i = 0; i < pEntryInfo->numOfRes; ++i) {
123,577,203✔
3985
    STopBotResItem* pItem = &pRes->pItems[i];
78,499,239✔
3986
    code = colDataSetVal(pCol, currentRow, (const char*)&pItem->v.i, false);
78,499,239✔
3987
    if (TSDB_CODE_SUCCESS != code) {
78,473,708!
3988
      return code;
×
3989
    }
3990
#ifdef BUF_PAGE_DEBUG
3991
    qDebug("page_finalize i:%d,item:%p,pageId:%d, offset:%d\n", i, pItem, pItem->tuplePos.pageId,
3992
           pItem->tuplePos.offset);
3993
#endif
3994
    code = setSelectivityValue(pCtx, pBlock, &pRes->pItems[i].tuplePos, currentRow);
78,473,708✔
3995
    if (TSDB_CODE_SUCCESS != code) {
78,428,738!
3996
      return code;
×
3997
    }
3998
    currentRow += 1;
78,428,738✔
3999
  }
4000

4001
  return code;
45,077,964✔
4002
}
4003

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

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

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

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

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

4077
int32_t getSpreadInfoSize() { return (int32_t)sizeof(SSpreadInfo); }
1,229,917✔
4078

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

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

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

4099
int32_t spreadFunction(SqlFunctionCtx* pCtx) {
5,496,196✔
4100
  int32_t numOfElems = 0;
5,496,196✔
4101

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

4107
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
5,496,196✔
4108

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

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

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

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

4137
    int32_t start = pInput->startRowIndex;
5,496,196✔
4138
    // check the valid data one by one
4139
    for (int32_t i = start; i < pInput->numOfRows + start; ++i) {
27,255,297✔
4140
      if (colDataIsNull_f(pCol->nullbitmap, i)) {
21,759,101✔
4141
        continue;
1,412,279✔
4142
      }
4143

4144
      char* data = colDataGetData(pCol, i);
20,346,822!
4145

4146
      double v = 0;
20,346,822✔
4147
      GET_TYPED_DATA(v, double, type, data);
20,346,822!
4148
      if (v < GET_DOUBLE_VAL(&pInfo->min)) {
20,346,822✔
4149
        SET_DOUBLE_VAL(&pInfo->min, v);
5,433,998✔
4150
      }
4151

4152
      if (v > GET_DOUBLE_VAL(&pInfo->max)) {
20,346,822✔
4153
        SET_DOUBLE_VAL(&pInfo->max, v);
11,540,571✔
4154
      }
4155

4156
      numOfElems += 1;
20,346,822✔
4157
    }
4158
  }
4159

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

4167
  return TSDB_CODE_SUCCESS;
5,496,196✔
4168
}
4169

4170
static void spreadTransferInfo(SSpreadInfo* pInput, SSpreadInfo* pOutput) {
1,227,455✔
4171
  pOutput->hasResult = pInput->hasResult;
1,227,455✔
4172
  if (pInput->max > pOutput->max) {
1,227,455✔
4173
    pOutput->max = pInput->max;
1,222,994✔
4174
  }
4175

4176
  if (pInput->min < pOutput->min) {
1,227,455✔
4177
    pOutput->min = pInput->min;
1,223,010✔
4178
  }
4179
}
1,227,455✔
4180

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

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

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

4194
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,223,482✔
4195

4196
  int32_t start = pInput->startRowIndex;
1,223,482✔
4197
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
2,451,174✔
4198
    if (colDataIsNull_s(pCol, i)) continue;
2,455,384!
4199
    char*        data = colDataGetData(pCol, i);
1,227,692!
4200
    SSpreadInfo* pInputInfo = (SSpreadInfo*)varDataVal(data);
1,227,692✔
4201
    if (pInputInfo->hasResult) {
1,227,692✔
4202
      spreadTransferInfo(pInputInfo, pInfo);
1,227,454✔
4203
    }
4204
  }
4205

4206
  if (pInfo->hasResult) {
1,223,482✔
4207
    GET_RES_INFO(pCtx)->numOfRes = 1;
1,223,319✔
4208
  }
4209

4210
  return TSDB_CODE_SUCCESS;
1,223,482✔
4211
}
4212

4213
int32_t spreadFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
4,277,657✔
4214
  SSpreadInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
4,277,657✔
4215
  if (pInfo->hasResult == true) {
4,277,657✔
4216
    SET_DOUBLE_VAL(&pInfo->result, pInfo->max - pInfo->min);
4,247,928✔
4217
  } else {
4218
    GET_RES_INFO(pCtx)->isNullRes = 1;
29,729✔
4219
  }
4220
  return functionFinalize(pCtx, pBlock);
4,277,657✔
4221
}
4222

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

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

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

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

4248
_exit:
1,228,368✔
4249
  taosMemoryFree(res);
1,228,368!
4250
  return code;
1,228,367✔
4251
}
4252

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

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

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

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

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

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

4285
  if (pCtx->numOfParams > 1) {
8,957,563✔
4286
    pInfo->timeUnit = pCtx->param[1].param.i;
8,939,961✔
4287
  } else {
4288
    pInfo->timeUnit = 1;
17,602✔
4289
  }
4290

4291
  return TSDB_CODE_SUCCESS;
8,957,563✔
4292
}
4293

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

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

4301
  SElapsedInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
8,957,718✔
4302

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

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

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

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

4348
      if (pCtx->end.key == INT64_MIN) {
696!
4349
        pInfo->min =
696✔
4350
            (pInfo->min > ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->min;
696✔
4351
      } else {
4352
        pInfo->min = pCtx->end.key;
×
4353
      }
4354
    } else {
4355
      if (pCtx->start.key == INT64_MIN) {
8,956,970✔
4356
        pInfo->min = (pInfo->min > ptsList[start]) ? ptsList[start] : pInfo->min;
4,138,106✔
4357
      } else {
4358
        pInfo->min = pCtx->start.key;
4,818,864✔
4359
      }
4360

4361
      if (pCtx->end.key == INT64_MIN) {
8,956,970✔
4362
        pInfo->max =
3,884,522✔
4363
            (pInfo->max < ptsList[start + pInput->numOfRows - 1]) ? ptsList[start + pInput->numOfRows - 1] : pInfo->max;
3,884,522✔
4364
      } else {
4365
        pInfo->max = pCtx->end.key + 1;
5,072,448✔
4366
      }
4367
    }
4368
  }
4369

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

4374
  return TSDB_CODE_SUCCESS;
8,957,718✔
4375
}
4376

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

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

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

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

4397
  int32_t start = pInput->startRowIndex;
×
4398

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

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

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

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

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

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

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

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

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

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

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

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

4468
static int8_t getHistogramBinType(char* binTypeStr) {
8,461,561✔
4469
  int8_t binType;
4470
  if (strcasecmp(binTypeStr, "user_input") == 0) {
8,461,561✔
4471
    binType = USER_INPUT_BIN;
2,030✔
4472
  } else if (strcasecmp(binTypeStr, "linear_bin") == 0) {
8,459,531✔
4473
    binType = LINEAR_BIN;
3,254✔
4474
  } else if (strcasecmp(binTypeStr, "log_bin") == 0) {
8,456,277!
4475
    binType = LOG_BIN;
8,456,404✔
4476
  } else {
4477
    binType = UNKNOWN_BIN;
×
4478
  }
4479

4480
  return binType;
8,461,561✔
4481
}
4482

4483
static int32_t getHistogramBinDesc(SHistoFuncInfo* pInfo, char* binDescStr, int8_t binType, bool normalized) {
8,461,582✔
4484
  cJSON*  binDesc = cJSON_Parse(binDescStr);
8,461,582✔
4485
  int32_t numOfBins;
4486
  double* intervals;
4487
  if (cJSON_IsObject(binDesc)) { /* linaer/log bins */
8,461,662✔
4488
    int32_t numOfParams = cJSON_GetArraySize(binDesc);
8,459,597✔
4489
    int32_t startIndex;
4490
    if (numOfParams != 4) {
8,459,565!
4491
      cJSON_Delete(binDesc);
×
4492
      return TSDB_CODE_FAILED;
×
4493
    }
4494

4495
    cJSON* start = cJSON_GetObjectItem(binDesc, "start");
8,459,565✔
4496
    cJSON* factor = cJSON_GetObjectItem(binDesc, "factor");
8,459,651✔
4497
    cJSON* width = cJSON_GetObjectItem(binDesc, "width");
8,459,619✔
4498
    cJSON* count = cJSON_GetObjectItem(binDesc, "count");
8,458,985✔
4499
    cJSON* infinity = cJSON_GetObjectItem(binDesc, "infinity");
8,459,521✔
4500

4501
    if (!cJSON_IsNumber(start) || !cJSON_IsNumber(count) || !cJSON_IsBool(infinity)) {
8,459,633!
4502
      cJSON_Delete(binDesc);
1✔
4503
      return TSDB_CODE_FAILED;
×
4504
    }
4505

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

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

4517
    int32_t counter = (int32_t)count->valueint;
8,459,554✔
4518
    if (infinity->valueint == false) {
8,459,554✔
4519
      startIndex = 0;
5,591✔
4520
      numOfBins = counter + 1;
5,591✔
4521
    } else {
4522
      startIndex = 1;
8,453,963✔
4523
      numOfBins = counter + 3;
8,453,963✔
4524
    }
4525

4526
    intervals = taosMemoryCalloc(numOfBins, sizeof(double));
8,459,554!
4527
    if (NULL == intervals) {
8,459,675!
4528
      cJSON_Delete(binDesc);
×
4529
      qError("histogram function out of memory");
×
4530
      return terrno;
×
4531
    }
4532
    if (cJSON_IsNumber(width) && factor == NULL && binType == LINEAR_BIN) {
8,459,675!
4533
      // linear bin process
4534
      if (width->valuedouble == 0) {
3,254!
4535
        taosMemoryFree(intervals);
×
4536
        cJSON_Delete(binDesc);
×
4537
        return TSDB_CODE_FAILED;
×
4538
      }
4539
      for (int i = 0; i < counter + 1; ++i) {
20,474✔
4540
        intervals[startIndex] = start->valuedouble + i * width->valuedouble;
17,220✔
4541
        if (isinf(intervals[startIndex])) {
17,220!
4542
          taosMemoryFree(intervals);
×
4543
          cJSON_Delete(binDesc);
×
4544
          return TSDB_CODE_FAILED;
×
4545
        }
4546
        startIndex++;
17,220✔
4547
      }
4548
    } else if (cJSON_IsNumber(factor) && width == NULL && binType == LOG_BIN) {
8,456,402!
4549
      // log bin process
4550
      if (start->valuedouble == 0) {
8,456,397!
4551
        taosMemoryFree(intervals);
×
4552
        cJSON_Delete(binDesc);
×
4553
        return TSDB_CODE_FAILED;
×
4554
      }
4555
      if (factor->valuedouble < 0 || factor->valuedouble == 0 || factor->valuedouble == 1) {
8,456,397!
4556
        taosMemoryFree(intervals);
×
4557
        cJSON_Delete(binDesc);
×
4558
        return TSDB_CODE_FAILED;
×
4559
      }
4560
      for (int i = 0; i < counter + 1; ++i) {
59,187,275✔
4561
        intervals[startIndex] = start->valuedouble * pow(factor->valuedouble, i * 1.0);
50,730,875✔
4562
        if (isinf(intervals[startIndex])) {
50,730,875!
4563
          taosMemoryFree(intervals);
×
4564
          cJSON_Delete(binDesc);
×
4565
          return TSDB_CODE_FAILED;
×
4566
        }
4567
        startIndex++;
50,730,875✔
4568
      }
4569
    } else {
4570
      taosMemoryFree(intervals);
×
4571
      cJSON_Delete(binDesc);
×
4572
      return TSDB_CODE_FAILED;
×
4573
    }
4574

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

4625
  pInfo->numOfBins = numOfBins - 1;
8,461,686✔
4626
  pInfo->normalized = normalized;
8,461,686✔
4627
  for (int32_t i = 0; i < pInfo->numOfBins; ++i) {
67,665,194✔
4628
    pInfo->bins[i].lower = intervals[i] < intervals[i + 1] ? intervals[i] : intervals[i + 1];
59,203,508✔
4629
    pInfo->bins[i].upper = intervals[i + 1] > intervals[i] ? intervals[i + 1] : intervals[i];
59,203,508✔
4630
    pInfo->bins[i].count = 0;
59,203,508✔
4631
  }
4632

4633
  taosMemoryFree(intervals);
8,461,686✔
4634
  cJSON_Delete(binDesc);
8,461,610✔
4635

4636
  return TSDB_CODE_SUCCESS;
8,461,757✔
4637
}
4638

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

4647
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(pResultInfo);
8,461,606✔
4648
  pInfo->numOfBins = 0;
8,461,606✔
4649
  pInfo->totalCount = 0;
8,461,606✔
4650
  pInfo->normalized = 0;
8,461,606✔
4651

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

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

4678
  return TSDB_CODE_SUCCESS;
8,461,799✔
4679
}
4680

4681
static int32_t histogramFunctionImpl(SqlFunctionCtx* pCtx, bool isPartial) {
8,506,192✔
4682
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
8,506,192✔
4683

4684
  SInputColumnInfoData* pInput = &pCtx->input;
8,506,192✔
4685
  SColumnInfoData*      pCol = pInput->pData[0];
8,506,192✔
4686

4687
  int32_t type = pInput->pData[0]->info.type;
8,506,192✔
4688

4689
  int32_t start = pInput->startRowIndex;
8,506,192✔
4690
  int32_t numOfRows = pInput->numOfRows;
8,506,192✔
4691

4692
  int32_t numOfElems = 0;
8,506,192✔
4693
  for (int32_t i = start; i < numOfRows + start; ++i) {
28,156,844✔
4694
    if (pCol->hasNull && colDataIsNull_f(pCol->nullbitmap, i)) {
19,650,652✔
4695
      continue;
600,212✔
4696
    }
4697

4698
    numOfElems++;
19,050,440✔
4699

4700
    char*  data = colDataGetData(pCol, i);
19,050,440!
4701
    double v;
4702
    GET_TYPED_DATA(v, double, type, data);
19,050,440!
4703

4704
    for (int32_t k = 0; k < pInfo->numOfBins; ++k) {
45,817,572✔
4705
      if (v > pInfo->bins[k].lower && v <= pInfo->bins[k].upper) {
45,014,725✔
4706
        pInfo->bins[k].count++;
18,247,593✔
4707
        pInfo->totalCount++;
18,247,593✔
4708
        break;
18,247,593✔
4709
      }
4710
    }
4711
  }
4712

4713
  if (!isPartial) {
8,506,192✔
4714
    GET_RES_INFO(pCtx)->numOfRes = pInfo->numOfBins;
6,451,190✔
4715
  } else {
4716
    GET_RES_INFO(pCtx)->numOfRes = 1;
2,055,002✔
4717
  }
4718
  return TSDB_CODE_SUCCESS;
8,506,192✔
4719
}
4720

4721
int32_t histogramFunction(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, false); }
6,451,166✔
4722

4723
int32_t histogramFunctionPartial(SqlFunctionCtx* pCtx) { return histogramFunctionImpl(pCtx, true); }
2,055,194✔
4724

4725
static void histogramTransferInfo(SHistoFuncInfo* pInput, SHistoFuncInfo* pOutput) {
1,998,778✔
4726
  pOutput->normalized = pInput->normalized;
1,998,778✔
4727
  pOutput->numOfBins = pInput->numOfBins;
1,998,778✔
4728
  pOutput->totalCount += pInput->totalCount;
1,998,778✔
4729
  for (int32_t k = 0; k < pOutput->numOfBins; ++k) {
15,987,523✔
4730
    pOutput->bins[k].lower = pInput->bins[k].lower;
13,988,745✔
4731
    pOutput->bins[k].upper = pInput->bins[k].upper;
13,988,745✔
4732
    pOutput->bins[k].count += pInput->bins[k].count;
13,988,745✔
4733
  }
4734
}
1,998,778✔
4735

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

4743
  SHistoFuncInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,998,778✔
4744

4745
  int32_t start = pInput->startRowIndex;
1,998,778✔
4746

4747
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
3,997,557✔
4748
    char*           data = colDataGetData(pCol, i);
1,998,778!
4749
    SHistoFuncInfo* pInputInfo = (SHistoFuncInfo*)varDataVal(data);
1,998,778✔
4750
    histogramTransferInfo(pInputInfo, pInfo);
1,998,778✔
4751
  }
4752

4753
  SET_VAL(GET_RES_INFO(pCtx), pInfo->numOfBins, pInfo->numOfBins);
1,998,779!
4754
  return TSDB_CODE_SUCCESS;
1,998,779✔
4755
}
4756

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

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

4769
  if (pInfo->normalized) {
8,378,480✔
4770
    for (int32_t k = 0; k < pResInfo->numOfRes; ++k) {
66,964,239✔
4771
      if (pInfo->totalCount != 0) {
58,591,085✔
4772
        pInfo->bins[k].percentage = pInfo->bins[k].count / (double)pInfo->totalCount;
58,577,685✔
4773
      } else {
4774
        pInfo->bins[k].percentage = 0;
13,400✔
4775
      }
4776
    }
4777
  }
4778

4779
  for (int32_t i = 0; i < pResInfo->numOfRes; ++i) {
66,968,151✔
4780
    int32_t len;
4781
    char    buf[512] = {0};
58,620,314✔
4782
    if (!pInfo->normalized) {
58,620,314✔
4783
      len = tsnprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE,
32,027✔
4784
                      "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%" PRId64 "}", pInfo->bins[i].lower,
4785
                      pInfo->bins[i].upper, pInfo->bins[i].count);
4786
    } else {
4787
      len = tsnprintf(varDataVal(buf), sizeof(buf) - VARSTR_HEADER_SIZE,
58,588,287✔
4788
                      "{\"lower_bin\":%g, \"upper_bin\":%g, \"count\":%lf}", pInfo->bins[i].lower, pInfo->bins[i].upper,
4789
                      pInfo->bins[i].percentage);
4790
    }
4791
    varDataSetLen(buf, len);
58,621,627✔
4792
    code = colDataSetVal(pCol, currentRow, buf, false);
58,621,627✔
4793
    if (TSDB_CODE_SUCCESS != code) {
58,589,671!
4794
      return code;
×
4795
    }
4796
    currentRow++;
58,589,671✔
4797
  }
4798

4799
  return code;
8,347,837✔
4800
}
4801

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

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

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

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

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

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

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

4841
int32_t getHLLInfoSize() { return (int32_t)sizeof(SHLLInfo); }
9,991✔
4842

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

4848
static uint8_t hllCountNum(void* data, int32_t bytes, int32_t* buk) {
3,622,395✔
4849
  uint64_t hash = MurmurHash3_64(data, bytes);
3,622,395✔
4850
  int32_t  index = hash & HLL_BUCKET_MASK;
3,621,352✔
4851
  hash >>= HLL_BUCKET_BITS;
3,621,352✔
4852
  hash |= ((uint64_t)1 << HLL_DATA_BITS);
3,621,352✔
4853
  uint64_t bit = 1;
3,621,352✔
4854
  uint8_t  count = 1;
3,621,352✔
4855
  while ((hash & bit) == 0) {
8,089,626✔
4856
    count++;
4,468,274✔
4857
    bit <<= 1;
4,468,274✔
4858
  }
4859
  *buk = index;
3,621,352✔
4860
  return count;
3,621,352✔
4861
}
4862

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

4867
  for (int32_t j = 0; j < HLL_BUCKETS >> 3; j++) {
498,431,839✔
4868
    if (*word == 0) {
498,184,754✔
4869
      bucketHisto[0] += 8;
497,337,993✔
4870
    } else {
4871
      bytes = (uint8_t*)word;
846,761✔
4872
      bucketHisto[bytes[0]]++;
846,761✔
4873
      bucketHisto[bytes[1]]++;
846,761✔
4874
      bucketHisto[bytes[2]]++;
846,761✔
4875
      bucketHisto[bytes[3]]++;
846,761✔
4876
      bucketHisto[bytes[4]]++;
846,761✔
4877
      bucketHisto[bytes[5]]++;
846,761✔
4878
      bucketHisto[bytes[6]]++;
846,761✔
4879
      bucketHisto[bytes[7]]++;
846,761✔
4880
    }
4881
    word++;
498,184,754✔
4882
  }
4883
}
247,085✔
4884
static double hllTau(double x) {
247,090✔
4885
  if (x == 0. || x == 1.) return 0.;
247,090!
4886
  double zPrime;
4887
  double y = 1.0;
×
4888
  double z = 1 - x;
×
4889
  do {
4890
    x = sqrt(x);
×
4891
    zPrime = z;
×
4892
    y *= 0.5;
×
4893
    z -= pow(1 - x, 2) * y;
×
4894
  } while (zPrime != z);
×
4895
  return z / 3;
×
4896
}
4897

4898
static double hllSigma(double x) {
247,096✔
4899
  if (x == 1.0) return INFINITY;
247,096✔
4900
  double zPrime;
4901
  double y = 1;
220,203✔
4902
  double z = x;
220,203✔
4903
  do {
4904
    x *= x;
4,315,040✔
4905
    zPrime = z;
4,315,040✔
4906
    z += x * y;
4,315,040✔
4907
    y += y;
4,315,040✔
4908
  } while (zPrime != z);
4,315,040✔
4909
  return z;
220,203✔
4910
}
4911

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

4919
  double z = m * hllTau((m - buckethisto[HLL_DATA_BITS + 1]) / (double)m);
247,089✔
4920
  for (int j = HLL_DATA_BITS; j >= 1; --j) {
12,597,354✔
4921
    z += buckethisto[j];
12,350,258✔
4922
    z *= 0.5;
12,350,258✔
4923
  }
4924

4925
  z += m * hllSigma(buckethisto[0] / (double)m);
247,096✔
4926
  double E = (double)llroundl(HLL_ALPHA_INF * m * m / z);
247,099✔
4927

4928
  return (uint64_t)E;
247,099✔
4929
}
4930

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

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

4937
  int32_t type = pCol->info.type;
270,684✔
4938
  int32_t bytes = pCol->info.bytes;
270,684✔
4939

4940
  int32_t start = pInput->startRowIndex;
270,684✔
4941
  int32_t numOfRows = pInput->numOfRows;
270,684✔
4942

4943
  int32_t numOfElems = 0;
270,684✔
4944
  if (IS_NULL_TYPE(type)) {
270,684✔
4945
    goto _hll_over;
1,578✔
4946
  }
4947

4948
  for (int32_t i = start; i < numOfRows + start; ++i) {
4,863,106✔
4949
    if (pCol->hasNull && colDataIsNull_s(pCol, i)) {
6,164,030!
4950
      continue;
970,584✔
4951
    }
4952

4953
    numOfElems++;
3,623,937✔
4954

4955
    char* data = colDataGetData(pCol, i);
3,623,937!
4956
    if (IS_VAR_DATA_TYPE(type)) {
3,623,937!
4957
      bytes = varDataLen(data);
1,029,591✔
4958
      data = varDataVal(data);
1,029,591✔
4959
    }
4960

4961
    int32_t index = 0;
3,623,937✔
4962
    uint8_t count = hllCountNum(data, bytes, &index);
3,623,937✔
4963
    uint8_t oldcount = pInfo->buckets[index];
3,623,416✔
4964
    if (count > oldcount) {
3,623,416✔
4965
      pInfo->buckets[index] = count;
868,409✔
4966
    }
4967
  }
4968

4969
_hll_over:
268,585✔
4970
  pInfo->totalCount += numOfElems;
270,163✔
4971

4972
  if (pInfo->totalCount == 0 && !tsCountAlwaysReturnValue) {
270,163✔
4973
    SET_VAL(GET_RES_INFO(pCtx), 0, 1);
1,395✔
4974
  } else {
4975
    SET_VAL(GET_RES_INFO(pCtx), 1, 1);
268,768✔
4976
  }
4977

4978
  return TSDB_CODE_SUCCESS;
270,163✔
4979
}
4980

4981
static void hllTransferInfo(SHLLInfo* pInput, SHLLInfo* pOutput) {
10,276✔
4982
  for (int32_t k = 0; k < HLL_BUCKETS; ++k) {
164,183,003✔
4983
    if (pOutput->buckets[k] < pInput->buckets[k]) {
164,172,727✔
4984
      pOutput->buckets[k] = pInput->buckets[k];
91,501✔
4985
    }
4986
  }
4987
  pOutput->totalCount += pInput->totalCount;
10,276✔
4988
}
10,276✔
4989

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

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

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

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

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

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

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

5020
  return TSDB_CODE_SUCCESS;
10,198✔
5021
}
5022

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

5026
  SHLLInfo* pHllInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
247,063✔
5027
  pHllInfo->result = hllCountCnt(pHllInfo->buckets);
247,063✔
5028
  if (tsCountAlwaysReturnValue && pHllInfo->result == 0) {
247,104✔
5029
    pInfo->numOfRes = 1;
25,522✔
5030
  }
5031

5032
  return functionFinalize(pCtx, pBlock);
247,104✔
5033
}
5034

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

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

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

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

5057
_exit:
9,991✔
5058
  taosMemoryFree(res);
9,991!
5059
  return code;
9,992✔
5060
}
5061

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

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

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

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

5080
static int8_t getStateOpType(char* opStr) {
142,749✔
5081
  int8_t opType;
5082
  if (strncasecmp(opStr, "LT", 2) == 0) {
142,749✔
5083
    opType = STATE_OPER_LT;
1,927✔
5084
  } else if (strncasecmp(opStr, "GT", 2) == 0) {
140,822✔
5085
    opType = STATE_OPER_GT;
1,416✔
5086
  } else if (strncasecmp(opStr, "LE", 2) == 0) {
139,406✔
5087
    opType = STATE_OPER_LE;
984✔
5088
  } else if (strncasecmp(opStr, "GE", 2) == 0) {
138,422✔
5089
    opType = STATE_OPER_GE;
133,543✔
5090
  } else if (strncasecmp(opStr, "NE", 2) == 0) {
4,879✔
5091
    opType = STATE_OPER_NE;
3,040✔
5092
  } else if (strncasecmp(opStr, "EQ", 2) == 0) {
1,839!
5093
    opType = STATE_OPER_EQ;
1,839✔
5094
  } else {
5095
    opType = STATE_OPER_INVALID;
×
5096
  }
5097

5098
  return opType;
142,749✔
5099
}
5100

5101
static bool checkStateOp(int8_t op, SColumnInfoData* pCol, int32_t index, SVariant param) {
34,860,881✔
5102
  char* data = colDataGetData(pCol, index);
34,860,881!
5103
  switch (pCol->info.type) {
34,860,881!
5104
    case TSDB_DATA_TYPE_TINYINT: {
6,012✔
5105
      int8_t v = *(int8_t*)data;
6,012✔
5106
      STATE_COMP(op, v, param);
6,012!
5107
      break;
×
5108
    }
5109
    case TSDB_DATA_TYPE_UTINYINT: {
5,760✔
5110
      uint8_t v = *(uint8_t*)data;
5,760✔
5111
      STATE_COMP(op, v, param);
5,760!
5112
      break;
×
5113
    }
5114
    case TSDB_DATA_TYPE_SMALLINT: {
29,359,014✔
5115
      int16_t v = *(int16_t*)data;
29,359,014✔
5116
      STATE_COMP(op, v, param);
29,359,014!
5117
      break;
×
5118
    }
5119
    case TSDB_DATA_TYPE_USMALLINT: {
5,760✔
5120
      uint16_t v = *(uint16_t*)data;
5,760✔
5121
      STATE_COMP(op, v, param);
5,760!
5122
      break;
×
5123
    }
5124
    case TSDB_DATA_TYPE_INT: {
5,165,120✔
5125
      int32_t v = *(int32_t*)data;
5,165,120✔
5126
      STATE_COMP(op, v, param);
5,165,120!
5127
      break;
×
5128
    }
5129
    case TSDB_DATA_TYPE_UINT: {
5,760✔
5130
      uint32_t v = *(uint32_t*)data;
5,760✔
5131
      STATE_COMP(op, v, param);
5,760!
5132
      break;
×
5133
    }
5134
    case TSDB_DATA_TYPE_BIGINT: {
198,503✔
5135
      int64_t v = *(int64_t*)data;
198,503✔
5136
      STATE_COMP(op, v, param);
198,503!
5137
      break;
11✔
5138
    }
5139
    case TSDB_DATA_TYPE_UBIGINT: {
5,760✔
5140
      uint64_t v = *(uint64_t*)data;
5,760✔
5141
      STATE_COMP(op, v, param);
5,760!
5142
      break;
×
5143
    }
5144
    case TSDB_DATA_TYPE_FLOAT: {
14,724✔
5145
      float v = *(float*)data;
14,724✔
5146
      STATE_COMP(op, v, param);
14,724!
5147
      break;
×
5148
    }
5149
    case TSDB_DATA_TYPE_DOUBLE: {
94,666✔
5150
      double v = *(double*)data;
94,666✔
5151
      STATE_COMP(op, v, param);
94,666!
5152
      break;
×
5153
    }
5154
    default: {
×
5155
      return false;
×
5156
    }
5157
  }
5158
  return false;
11✔
5159
}
5160

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

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

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

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

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

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

5186
    pInfo->isPrevTsSet = true;
7,264,076✔
5187
    numOfElems++;
7,264,076✔
5188

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

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

5203
    int64_t output = -1;
7,143,952✔
5204
    if (ret) {
7,143,952✔
5205
      output = ++pInfo->count;
3,548,261✔
5206
    } else {
5207
      pInfo->count = 0;
3,595,691✔
5208
    }
5209
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
7,143,952✔
5210
    if (TSDB_CODE_SUCCESS != code) {
7,143,952!
5211
      return code;
×
5212
    }
5213

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

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

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

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

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

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

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

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

5251
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
28,153,569✔
5252
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
28,042,329!
5253
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5254
    } else {
5255
      pInfo->prevTs = tsList[i];
28,042,329✔
5256
    }
5257

5258
    pInfo->isPrevTsSet = true;
28,042,329✔
5259
    numOfElems++;
28,042,329✔
5260

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

5273
    bool    ret = checkStateOp(op, pInputCol, i, pCtx->param[2].param);
27,717,690✔
5274
    int64_t output = -1;
27,717,690✔
5275
    if (ret) {
27,717,690✔
5276
      if (pInfo->durationStart == 0) {
13,702,613✔
5277
        output = 0;
6,869,665✔
5278
        pInfo->durationStart = tsList[i];
6,869,665✔
5279
      } else {
5280
        output = (tsList[i] - pInfo->durationStart) / timeUnit;
6,832,948✔
5281
      }
5282
    } else {
5283
      pInfo->durationStart = 0;
14,015,077✔
5284
    }
5285
    code = colDataSetVal(pOutput, pCtx->offset + numOfElems - 1, (char*)&output, false);
27,717,690✔
5286
    if (TSDB_CODE_SUCCESS != code) {
27,717,690!
5287
      return code;
×
5288
    }
5289

5290
    // handle selectivity
5291
    if (pCtx->subsidiaries.num > 0) {
27,717,690✔
5292
      code = appendSelectivityValue(pCtx, i, pCtx->offset + numOfElems - 1);
16,343,868✔
5293
      if (TSDB_CODE_SUCCESS != code) {
16,343,868!
5294
        return code;
×
5295
      }
5296
    }
5297
  }
5298

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

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

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

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

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

5319
  int32_t numOfElems = 0;
23,622✔
5320
  int32_t type = pInputCol->info.type;
23,622✔
5321
  int32_t startOffset = pCtx->offset;
23,622✔
5322
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
4,000,529✔
5323
    if (pSumRes->isPrevTsSet == true && tsList[i] == pSumRes->prevTs) {
3,976,777✔
5324
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
18✔
5325
    } else {
5326
      pSumRes->prevTs = tsList[i];
3,976,759✔
5327
    }
5328
    pSumRes->isPrevTsSet = true;
3,976,759✔
5329

5330
    int32_t pos = startOffset + numOfElems;
3,976,759✔
5331
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
3,976,759✔
5332
      // colDataSetNULL(pOutput, i);
5333
      continue;
252,372✔
5334
    }
5335

5336
    char* data = colDataGetData(pInputCol, i);
3,724,387!
5337
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
4,207,364✔
5338
      int64_t v;
5339
      GET_TYPED_DATA(v, int64_t, type, data);
482,829!
5340
      pSumRes->isum += v;
482,829✔
5341
      code = colDataSetVal(pOutput, pos, (char*)&pSumRes->isum, false);
482,829✔
5342
      if (TSDB_CODE_SUCCESS != code) {
482,977!
5343
        return code;
×
5344
      }
5345
    } else if (IS_UNSIGNED_NUMERIC_TYPE(type)) {
3,242,238!
5346
      uint64_t v;
5347
      GET_TYPED_DATA(v, uint64_t, type, data);
680!
5348
      pSumRes->usum += v;
680✔
5349
      code = colDataSetVal(pOutput, pos, (char*)&pSumRes->usum, false);
680✔
5350
      if (TSDB_CODE_SUCCESS != code) {
680!
5351
        return code;
×
5352
      }
5353
    } else if (IS_FLOAT_TYPE(type)) {
3,240,878!
5354
      double v;
5355
      GET_TYPED_DATA(v, double, type, data);
3,241,732!
5356
      pSumRes->dsum += v;
3,241,732✔
5357
      // check for overflow
5358
      if (isinf(pSumRes->dsum) || isnan(pSumRes->dsum)) {
3,241,732!
5359
        colDataSetNULL(pOutput, pos);
8!
5360
      } else {
5361
        code = colDataSetVal(pOutput, pos, (char*)&pSumRes->dsum, false);
3,241,724✔
5362
        if (TSDB_CODE_SUCCESS != code) {
3,241,724!
5363
          return code;
×
5364
        }
5365
      }
5366
    }
5367

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

5376
    numOfElems++;
3,724,535✔
5377
  }
5378

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

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

5388
int32_t mavgFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
264,295✔
5389
  if (pResultInfo->initialized) {
264,295✔
5390
    return TSDB_CODE_SUCCESS;
249,992✔
5391
  }
5392
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
14,303!
5393
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5394
  }
5395

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

5407
  return TSDB_CODE_SUCCESS;
14,305✔
5408
}
5409

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

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

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

5422
  int32_t numOfElems = 0;
250,682✔
5423
  int32_t type = pInputCol->info.type;
250,682✔
5424
  int32_t startOffset = pCtx->offset;
250,682✔
5425
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
59,178,814✔
5426
    if (pInfo->isPrevTsSet == true && tsList[i] == pInfo->prevTs) {
58,928,122!
5427
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
5428
    } else {
5429
      pInfo->prevTs = tsList[i];
58,928,122✔
5430
    }
5431
    pInfo->isPrevTsSet = true;
58,928,122✔
5432

5433
    int32_t pos = startOffset + numOfElems;
58,928,122✔
5434
    if (colDataIsNull_f(pInputCol->nullbitmap, i)) {
58,928,122✔
5435
      // colDataSetNULL(pOutput, i);
5436
      continue;
413,706✔
5437
    }
5438

5439
    char*  data = colDataGetData(pInputCol, i);
58,514,416!
5440
    double v;
5441
    GET_TYPED_DATA(v, double, type, data);
58,514,416!
5442

5443
    if (!pInfo->pointsMeet && (pInfo->pos < pInfo->numOfPoints - 1)) {
58,514,416✔
5444
      pInfo->points[pInfo->pos] = v;
5,353,519✔
5445
      pInfo->sum += v;
5,353,519✔
5446
    } else {
5447
      if (!pInfo->pointsMeet && (pInfo->pos == pInfo->numOfPoints - 1)) {
53,160,897!
5448
        pInfo->sum += v;
11,069✔
5449
        pInfo->pointsMeet = true;
11,069✔
5450
      } else {
5451
        pInfo->sum = pInfo->sum + v - pInfo->points[pInfo->pos];
53,149,828✔
5452
      }
5453

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

5466
      // handle selectivity
5467
      if (pCtx->subsidiaries.num > 0) {
53,160,907✔
5468
        code = appendSelectivityValue(pCtx, i, pos);
33,598,970✔
5469
        if (TSDB_CODE_SUCCESS != code) {
33,598,970!
5470
          return code;
×
5471
        }
5472
      }
5473

5474
      numOfElems++;
53,160,907✔
5475
    }
5476

5477
    pInfo->pos++;
58,514,426✔
5478
    if (pInfo->pos == pInfo->numOfPoints) {
58,514,426✔
5479
      pInfo->pos = 0;
124,100✔
5480
    }
5481
  }
5482

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

5487
static SSampleInfo* getSampleOutputInfo(SqlFunctionCtx* pCtx) {
28,868,596✔
5488
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
28,868,596✔
5489
  SSampleInfo*         pInfo = GET_ROWCELL_INTERBUF(pResInfo);
28,868,596✔
5490

5491
  pInfo->data = (char*)pInfo + sizeof(SSampleInfo);
28,868,596✔
5492
  pInfo->tuplePos = (STuplePos*)((char*)pInfo + sizeof(SSampleInfo) + pInfo->samples * pInfo->colBytes);
28,868,596✔
5493

5494
  return pInfo;
28,868,596✔
5495
}
5496

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

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

5513
  taosSeedRand(taosSafeRand());
12,734,618✔
5514

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

5526
  return TSDB_CODE_SUCCESS;
12,734,620✔
5527
}
5528

5529
static void sampleAssignResult(SSampleInfo* pInfo, char* data, int32_t index) {
38,288,290✔
5530
  assignVal(pInfo->data + index * pInfo->colBytes, data, pInfo->colBytes, pInfo->colType);
38,288,290✔
5531
}
38,288,271✔
5532

5533
static int32_t doReservoirSample(SqlFunctionCtx* pCtx, SSampleInfo* pInfo, char* data, int32_t index) {
41,878,538✔
5534
  pInfo->totalPoints++;
41,878,538✔
5535
  if (pInfo->numSampled < pInfo->samples) {
41,878,538✔
5536
    sampleAssignResult(pInfo, data, pInfo->numSampled);
34,891,573✔
5537
    if (pCtx->subsidiaries.num > 0) {
34,891,599✔
5538
      int32_t code = saveTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[pInfo->numSampled]);
1,349,977✔
5539
      if (code != TSDB_CODE_SUCCESS) {
1,349,948!
5540
        return code;
×
5541
      }
5542
    }
5543
    pInfo->numSampled++;
34,891,570✔
5544
  } else {
5545
    int32_t j = taosRand() % (pInfo->totalPoints);
6,986,965✔
5546
    if (j < pInfo->samples) {
6,990,861✔
5547
      sampleAssignResult(pInfo, data, j);
3,398,560✔
5548
      if (pCtx->subsidiaries.num > 0) {
3,398,405✔
5549
        int32_t code = updateTupleData(pCtx, index, pCtx->pSrcBlock, &pInfo->tuplePos[j]);
968,279✔
5550
        if (code != TSDB_CODE_SUCCESS) {
964,693!
5551
          return code;
×
5552
        }
5553
      }
5554
    }
5555
  }
5556

5557
  return TSDB_CODE_SUCCESS;
41,878,690✔
5558
}
5559

5560
int32_t sampleFunction(SqlFunctionCtx* pCtx) {
16,498,466✔
5561
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
16,498,466✔
5562
  SSampleInfo*         pInfo = getSampleOutputInfo(pCtx);
16,498,466✔
5563

5564
  SInputColumnInfoData* pInput = &pCtx->input;
16,498,459✔
5565

5566
  SColumnInfoData* pInputCol = pInput->pData[0];
16,498,459✔
5567
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; i += 1) {
58,768,390✔
5568
    if (colDataIsNull_s(pInputCol, i)) {
84,540,508✔
5569
      continue;
391,377✔
5570
    }
5571

5572
    char*   data = colDataGetData(pInputCol, i);
41,878,877!
5573
    int32_t code = doReservoirSample(pCtx, pInfo, data, i);
41,878,877✔
5574
    if (code != TSDB_CODE_SUCCESS) {
41,878,554!
5575
      return code;
×
5576
    }
5577
  }
5578

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

5587
  SET_VAL(pResInfo, pInfo->numSampled, pInfo->numSampled);
16,498,136✔
5588
  return TSDB_CODE_SUCCESS;
16,498,136✔
5589
}
5590

5591
int32_t sampleFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
12,370,135✔
5592
  int32_t              code = TSDB_CODE_SUCCESS;
12,370,135✔
5593
  SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(pCtx);
12,370,135✔
5594

5595
  SSampleInfo* pInfo = getSampleOutputInfo(pCtx);
12,370,135✔
5596
  pEntryInfo->complete = true;
12,370,135✔
5597

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

5604
  int32_t currentRow = pBlock->info.rows;
12,370,134✔
5605
  if (pInfo->numSampled == 0) {
12,370,134✔
5606
    colDataSetNULL(pCol, currentRow);
2,515✔
5607
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
2,515✔
5608
    return code;
2,515✔
5609
  }
5610
  for (int32_t i = 0; i < pInfo->numSampled; ++i) {
45,347,974✔
5611
    code = colDataSetVal(pCol, currentRow + i, pInfo->data + i * pInfo->colBytes, false);
32,980,536✔
5612
    if (TSDB_CODE_SUCCESS != code) {
32,980,728!
5613
      return code;
×
5614
    }
5615
    code = setSelectivityValue(pCtx, pBlock, &pInfo->tuplePos[i], currentRow + i);
32,980,728✔
5616
    if (TSDB_CODE_SUCCESS != code) {
32,980,355!
5617
      return code;
×
5618
    }
5619
  }
5620

5621
  return code;
12,367,438✔
5622
}
5623

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

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

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

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

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

5665
  return TSDB_CODE_SUCCESS;
×
5666
}
5667

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

5763
bool getUniqueFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
×
5764
#if 0
5765
  pEnv->calcMemSize = sizeof(SUniqueInfo) + UNIQUE_MAX_RESULT_SIZE;
5766
#endif
5767
  return true;
×
5768
}
5769

5770
int32_t uniqueFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
×
5771
#if 0
5772
  if (!functionSetup(pCtx, pResInfo)) {
5773
    return false;
5774
  }
5775

5776
  SUniqueInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5777
  pInfo->numOfPoints = 0;
5778
  pInfo->colType = pCtx->resDataInfo.type;
5779
  pInfo->colBytes = pCtx->resDataInfo.bytes;
5780
  if (pInfo->pHash != NULL) {
5781
    taosHashClear(pInfo->pHash);
5782
  } else {
5783
    pInfo->pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
5784
  }
5785
#endif
5786
  return TSDB_CODE_SUCCESS;
×
5787
}
5788

5789
#if 0
5790
static void doUniqueAdd(SUniqueInfo* pInfo, char* data, TSKEY ts, bool isNull) {
5791
  // handle null elements
5792
  if (isNull == true) {
5793
    int32_t      size = sizeof(SUniqueItem) + pInfo->colBytes;
5794
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + pInfo->numOfPoints * size);
5795
    if (pInfo->hasNull == false && pItem->isNull == false) {
5796
      pItem->timestamp = ts;
5797
      pItem->isNull = true;
5798
      pInfo->numOfPoints++;
5799
      pInfo->hasNull = true;
5800
    } else if (pItem->timestamp > ts && pItem->isNull == true) {
5801
      pItem->timestamp = ts;
5802
    }
5803
    return;
5804
  }
5805

5806
  int32_t      hashKeyBytes = IS_VAR_DATA_TYPE(pInfo->colType) ? varDataTLen(data) : pInfo->colBytes;
5807
  SUniqueItem* pHashItem = taosHashGet(pInfo->pHash, data, hashKeyBytes);
5808
  if (pHashItem == NULL) {
5809
    int32_t      size = sizeof(SUniqueItem) + pInfo->colBytes;
5810
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + pInfo->numOfPoints * size);
5811
    pItem->timestamp = ts;
5812
    memcpy(pItem->data, data, pInfo->colBytes);
5813

5814
    taosHashPut(pInfo->pHash, data, hashKeyBytes, (char*)pItem, sizeof(SUniqueItem*));
5815
    pInfo->numOfPoints++;
5816
  } else if (pHashItem->timestamp > ts) {
5817
    pHashItem->timestamp = ts;
5818
  }
5819
}
5820
#endif
5821

5822
int32_t uniqueFunction(SqlFunctionCtx* pCtx) {
×
5823
#if 0
5824
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
5825
  SUniqueInfo*         pInfo = GET_ROWCELL_INTERBUF(pResInfo);
5826

5827
  SInputColumnInfoData* pInput = &pCtx->input;
5828
  TSKEY*                tsList = (int64_t*)pInput->pPTS->pData;
5829

5830
  SColumnInfoData* pInputCol = pInput->pData[0];
5831
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
5832
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
5833

5834
  int32_t startOffset = pCtx->offset;
5835
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
5836
    char* data = colDataGetData(pInputCol, i);
5837
    doUniqueAdd(pInfo, data, tsList[i], colDataIsNull_s(pInputCol, i));
5838

5839
    if (sizeof(SUniqueInfo) + pInfo->numOfPoints * (sizeof(SUniqueItem) + pInfo->colBytes) >= UNIQUE_MAX_RESULT_SIZE) {
5840
      taosHashCleanup(pInfo->pHash);
5841
      return 0;
5842
    }
5843
  }
5844

5845
  for (int32_t i = 0; i < pInfo->numOfPoints; ++i) {
5846
    SUniqueItem* pItem = (SUniqueItem*)(pInfo->pItems + i * (sizeof(SUniqueItem) + pInfo->colBytes));
5847
    if (pItem->isNull == true) {
5848
      colDataSetNULL(pOutput, i);
5849
    } else {
5850
      colDataSetVal(pOutput, i, pItem->data, false);
5851
    }
5852
    if (pTsOutput != NULL) {
5853
      colDataSetInt64(pTsOutput, i, &pItem->timestamp);
5854
    }
5855
  }
5856

5857
  return pInfo->numOfPoints;
5858
#endif
5859
  return 0;
×
5860
}
5861

5862
bool getModeFuncEnv(SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
24,974✔
5863
  pEnv->calcMemSize = sizeof(SModeInfo);
24,974✔
5864
  return true;
24,974✔
5865
}
5866

5867
int32_t modeFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
25,824✔
5868
  if (pResInfo->initialized) {
25,824!
5869
    return TSDB_CODE_SUCCESS;
×
5870
  }
5871
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
25,824!
5872
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
5873
  }
5874

5875
  SModeInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
25,824✔
5876
  pInfo->colType = pCtx->resDataInfo.type;
25,824✔
5877
  pInfo->colBytes = pCtx->resDataInfo.bytes;
25,824✔
5878
  if (pInfo->pHash != NULL) {
25,824!
5879
    taosHashClear(pInfo->pHash);
×
5880
  } else {
5881
    pInfo->pHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
25,824✔
5882
    if (NULL == pInfo->pHash) {
25,823!
5883
      return terrno;
×
5884
    }
5885
  }
5886
  pInfo->nullTupleSaved = false;
25,823✔
5887
  pInfo->nullTuplePos.pageId = -1;
25,823✔
5888

5889
  pInfo->buf = taosMemoryMalloc(pInfo->colBytes);
25,823!
5890
  if (NULL == pInfo->buf) {
25,823!
5891
    taosHashCleanup(pInfo->pHash);
×
5892
    pInfo->pHash = NULL;
×
5893
    return terrno;
×
5894
  }
5895
  pCtx->needCleanup = true;
25,823✔
5896
  return TSDB_CODE_SUCCESS;
25,823✔
5897
}
5898

5899
static void modeFunctionCleanup(SModeInfo* pInfo) {
25,824✔
5900
  taosHashCleanup(pInfo->pHash);
25,824✔
5901
  pInfo->pHash = NULL;
25,824✔
5902
  taosMemoryFreeClear(pInfo->buf);
25,824!
5903
}
25,824✔
5904

5905
void modeFunctionCleanupExt(SqlFunctionCtx* pCtx) {
×
5906
  if (pCtx == NULL || GET_RES_INFO(pCtx) == NULL || GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)) == NULL) {
×
5907
    return;
×
5908
  }
5909
  modeFunctionCleanup(GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx)));
×
5910
}
5911

5912
static int32_t saveModeTupleData(SqlFunctionCtx* pCtx, char* data, SModeInfo* pInfo, STuplePos* pPos) {
98,083,322✔
5913
  if (IS_VAR_DATA_TYPE(pInfo->colType)) {
98,083,322!
5914
    if (pInfo->colType == TSDB_DATA_TYPE_JSON) {
63,085!
5915
      (void)memcpy(pInfo->buf, data, getJsonValueLen(data));
×
5916
    } else {
5917
      (void)memcpy(pInfo->buf, data, varDataTLen(data));
63,085✔
5918
    }
5919
  } else {
5920
    (void)memcpy(pInfo->buf, data, pInfo->colBytes);
98,020,237✔
5921
  }
5922

5923
  return doSaveTupleData(&pCtx->saveHandle, pInfo->buf, pInfo->colBytes, NULL, pPos, pCtx->pStore);
98,083,322✔
5924
}
5925

5926
static int32_t doModeAdd(SModeInfo* pInfo, int32_t rowIndex, SqlFunctionCtx* pCtx, char* data) {
123,720,646✔
5927
  int32_t code = TSDB_CODE_SUCCESS;
123,720,646✔
5928
  int32_t hashKeyBytes;
5929
  if (IS_VAR_DATA_TYPE(pInfo->colType)) {
123,720,646✔
5930
    if (pInfo->colType == TSDB_DATA_TYPE_JSON) {
63,147!
5931
      hashKeyBytes = getJsonValueLen(data);
×
5932
    } else {
5933
      hashKeyBytes = varDataTLen(data);
63,147✔
5934
    }
5935
  } else {
5936
    hashKeyBytes = pInfo->colBytes;
123,657,499✔
5937
  }
5938

5939
  SModeItem* pHashItem = (SModeItem*)taosHashGet(pInfo->pHash, data, hashKeyBytes);
123,720,639✔
5940
  if (pHashItem == NULL) {
123,720,524✔
5941
    int32_t   size = sizeof(SModeItem);
98,083,309✔
5942
    SModeItem item = {0};
98,083,309✔
5943

5944
    item.count += 1;
98,083,309✔
5945
    code = saveModeTupleData(pCtx, data, pInfo, &item.dataPos);
98,083,309✔
5946
    if (code != TSDB_CODE_SUCCESS) {
98,083,197!
5947
      return code;
×
5948
    }
5949

5950
    if (pCtx->subsidiaries.num > 0) {
98,083,197✔
5951
      code = saveTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &item.tuplePos);
66,293,969✔
5952
      if (code != TSDB_CODE_SUCCESS) {
66,293,969!
5953
        return code;
×
5954
      }
5955
    }
5956

5957
    code = taosHashPut(pInfo->pHash, data, hashKeyBytes, &item, sizeof(SModeItem));
98,083,197✔
5958
    if (code != TSDB_CODE_SUCCESS) {
98,083,454!
5959
      return code;
×
5960
    }
5961
  } else {
5962
    pHashItem->count += 1;
25,637,215✔
5963
    if (pCtx->subsidiaries.num > 0) {
25,637,215✔
5964
      code = updateTupleData(pCtx, rowIndex, pCtx->pSrcBlock, &pHashItem->tuplePos);
6,624,861✔
5965
      if (code != TSDB_CODE_SUCCESS) {
6,624,861!
5966
        return code;
×
5967
      }
5968
    }
5969
  }
5970

5971
  return code;
123,720,669✔
5972
}
5973

5974
int32_t modeFunction(SqlFunctionCtx* pCtx) {
2,507,321✔
5975
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
2,507,321✔
5976
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
2,507,321✔
5977

5978
  SInputColumnInfoData* pInput = &pCtx->input;
2,507,321✔
5979

5980
  SColumnInfoData* pInputCol = pInput->pData[0];
2,507,321✔
5981
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
2,507,321✔
5982

5983
  int32_t numOfElems = 0;
2,507,321✔
5984
  int32_t startOffset = pCtx->offset;
2,507,321✔
5985
  for (int32_t i = pInput->startRowIndex; i < pInput->numOfRows + pInput->startRowIndex; ++i) {
126,759,531✔
5986
    if (colDataIsNull_s(pInputCol, i)) {
248,504,612✔
5987
      continue;
532,611✔
5988
    }
5989
    numOfElems++;
123,719,695✔
5990

5991
    char*   data = colDataGetData(pInputCol, i);
123,719,695!
5992
    int32_t code = doModeAdd(pInfo, i, pCtx, data);
123,719,695✔
5993
    if (code != TSDB_CODE_SUCCESS) {
123,720,669✔
5994
      modeFunctionCleanup(pInfo);
1,070✔
5995
      return code;
×
5996
    }
5997
  }
5998

5999
  if (numOfElems == 0 && pCtx->subsidiaries.num > 0 && !pInfo->nullTupleSaved) {
2,507,225!
6000
    int32_t code = saveTupleData(pCtx, pInput->startRowIndex, pCtx->pSrcBlock, &pInfo->nullTuplePos);
50✔
6001
    if (code != TSDB_CODE_SUCCESS) {
50!
6002
      modeFunctionCleanup(pInfo);
×
6003
      return code;
×
6004
    }
6005
    pInfo->nullTupleSaved = true;
50✔
6006
  }
6007

6008
  SET_VAL(pResInfo, numOfElems, 1);
2,507,225✔
6009

6010
  return TSDB_CODE_SUCCESS;
2,507,225✔
6011
}
6012

6013
int32_t modeFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
25,824✔
6014
  int32_t              code = TSDB_CODE_SUCCESS;
25,824✔
6015
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
25,824✔
6016
  SModeInfo*           pInfo = GET_ROWCELL_INTERBUF(pResInfo);
25,824✔
6017
  int32_t              slotId = pCtx->pExpr->base.resSchema.slotId;
25,824✔
6018
  SColumnInfoData*     pCol = taosArrayGet(pBlock->pDataBlock, slotId);
25,824✔
6019
  int32_t              currentRow = pBlock->info.rows;
25,824✔
6020
  if (NULL == pCol) {
25,824!
6021
    modeFunctionCleanup(pInfo);
×
6022
    return TSDB_CODE_OUT_OF_RANGE;
×
6023
  }
6024

6025
  STuplePos resDataPos, resTuplePos;
6026
  int32_t   maxCount = 0;
25,824✔
6027

6028
  void* pIter = taosHashIterate(pInfo->pHash, NULL);
25,824✔
6029
  while (pIter != NULL) {
98,109,314✔
6030
    SModeItem* pItem = (SModeItem*)pIter;
98,083,490✔
6031
    if (pItem->count >= maxCount) {
98,083,490✔
6032
      maxCount = pItem->count;
47,403,168✔
6033
      resDataPos = pItem->dataPos;
47,403,168✔
6034
      resTuplePos = pItem->tuplePos;
47,403,168✔
6035
    }
6036

6037
    pIter = taosHashIterate(pInfo->pHash, pIter);
98,083,490✔
6038
  }
6039

6040
  if (maxCount != 0) {
25,824✔
6041
    char* pData = NULL;
22,781✔
6042
    code = loadTupleData(pCtx, &resDataPos, &pData);
22,781✔
6043
    if (pData == NULL || TSDB_CODE_SUCCESS != code) {
22,781!
6044
      code = terrno = TSDB_CODE_NOT_FOUND;
×
6045
      qError("Load tuple data failed since %s, groupId:%" PRIu64 ", ts:%" PRId64, terrstr(),
×
6046
             resDataPos.streamTupleKey.groupId, resDataPos.streamTupleKey.ts);
6047
      modeFunctionCleanup(pInfo);
×
6048
      return code;
×
6049
    }
6050

6051
    code = colDataSetVal(pCol, currentRow, pData, false);
22,781✔
6052
    if (TSDB_CODE_SUCCESS != code) {
22,781!
6053
      modeFunctionCleanup(pInfo);
×
6054
      return code;
×
6055
    }
6056
    code = setSelectivityValue(pCtx, pBlock, &resTuplePos, currentRow);
22,781✔
6057
  } else {
6058
    colDataSetNULL(pCol, currentRow);
3,043✔
6059
    code = setSelectivityValue(pCtx, pBlock, &pInfo->nullTuplePos, currentRow);
3,043✔
6060
  }
6061

6062
  modeFunctionCleanup(pInfo);
25,824✔
6063

6064
  return code;
25,824✔
6065
}
6066

6067
bool getTwaFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
75,379✔
6068
  pEnv->calcMemSize = sizeof(STwaInfo);
75,379✔
6069
  return true;
75,379✔
6070
}
6071

6072
int32_t twaFunctionSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
10,788,960✔
6073
  if (pResultInfo->initialized) {
10,788,960!
6074
    return TSDB_CODE_SUCCESS;
×
6075
  }
6076
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
10,788,960!
6077
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6078
  }
6079

6080
  STwaInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
10,789,004✔
6081
  pInfo->numOfElems = 0;
10,789,004✔
6082
  pInfo->p.key = INT64_MIN;
10,789,004✔
6083
  pInfo->win = TSWINDOW_INITIALIZER;
10,789,004✔
6084
  return TSDB_CODE_SUCCESS;
10,789,004✔
6085
}
6086

6087
static double twa_get_area(SPoint1 s, SPoint1 e) {
28,466,665✔
6088
  if (e.key == INT64_MAX || s.key == INT64_MIN) {
28,466,665!
6089
    return 0;
×
6090
  }
6091

6092
  if ((s.val >= 0 && e.val >= 0) || (s.val <= 0 && e.val <= 0)) {
28,466,902✔
6093
    return (s.val + e.val) * (e.key - s.key) / 2;
15,588,044✔
6094
  }
6095

6096
  double x = (s.key * e.val - e.key * s.val) / (e.val - s.val);
12,878,858✔
6097
  double val = (s.val * (x - s.key) + e.val * (e.key - x)) / 2;
12,878,858✔
6098
  return val;
12,878,858✔
6099
}
6100

6101
int32_t twaFunction(SqlFunctionCtx* pCtx) {
10,795,217✔
6102
  int32_t               code = TSDB_CODE_SUCCESS;
10,795,217✔
6103
  SInputColumnInfoData* pInput = &pCtx->input;
10,795,217✔
6104
  SColumnInfoData*      pInputCol = pInput->pData[0];
10,795,217✔
6105

6106
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
10,795,217✔
6107
  STwaInfo*            pInfo = GET_ROWCELL_INTERBUF(pResInfo);
10,795,217✔
6108
  SPoint1*             last = &pInfo->p;
10,795,217✔
6109

6110
  if (IS_NULL_TYPE(pInputCol->info.type)) {
10,795,217!
6111
    pInfo->numOfElems = 0;
×
6112
    goto _twa_over;
×
6113
  }
6114

6115
  funcInputUpdate(pCtx);
10,795,217✔
6116
  SFuncInputRow row = {0};
10,795,294✔
6117
  bool          result = false;
10,795,294✔
6118
  if (pCtx->start.key != INT64_MIN && last->key == INT64_MIN) {
10,795,294!
6119
    while (1) {
6120
      code = funcInputGetNextRow(pCtx, &row, &result);
3,564,936✔
6121
      if (TSDB_CODE_SUCCESS != code) {
3,564,941!
6122
        return code;
×
6123
      }
6124
      if (!result) {
3,564,941✔
6125
        break;
2✔
6126
      }
6127
      if (row.isDataNull) {
3,564,939✔
6128
        continue;
2✔
6129
      }
6130

6131
      last->key = row.ts;
3,564,937✔
6132

6133
      GET_TYPED_DATA(last->val, double, pInputCol->info.type, row.pData);
3,564,937!
6134

6135
      pInfo->dOutput += twa_get_area(pCtx->start, *last);
3,564,937✔
6136
      pInfo->win.skey = pCtx->start.key;
3,564,935✔
6137
      pInfo->numOfElems++;
3,564,935✔
6138
      break;
3,564,935✔
6139
    }
6140
  } else if (pInfo->p.key == INT64_MIN) {
7,230,360✔
6141
    while (1) {
6142
      code = funcInputGetNextRow(pCtx, &row, &result);
7,353,617✔
6143
      if (TSDB_CODE_SUCCESS != code) {
7,353,461!
6144
        return code;
×
6145
      }
6146
      if (!result) {
7,353,461✔
6147
        break;
12,665✔
6148
      }
6149
      if (row.isDataNull) {
7,340,796✔
6150
        continue;
129,060✔
6151
      }
6152

6153
      last->key = row.ts;
7,211,736✔
6154

6155
      GET_TYPED_DATA(last->val, double, pInputCol->info.type, row.pData);
7,211,736!
6156

6157
      pInfo->win.skey = last->key;
7,211,736✔
6158
      pInfo->numOfElems++;
7,211,736✔
6159
      break;
7,211,736✔
6160
    }
6161
  }
6162

6163
  SPoint1 st = {0};
10,795,141✔
6164

6165
  // calculate the value of
6166
  while (1) {
6167
    code = funcInputGetNextRow(pCtx, &row, &result);
31,992,389✔
6168
    if (TSDB_CODE_SUCCESS != code) {
31,992,301!
6169
      return code;
×
6170
    }
6171
    if (!result) {
31,992,301✔
6172
      break;
10,795,138✔
6173
    }
6174
    if (row.isDataNull) {
21,197,163✔
6175
      continue;
630✔
6176
    }
6177
    pInfo->numOfElems++;
21,196,533✔
6178
    switch (pInputCol->info.type) {
21,196,533!
6179
      case TSDB_DATA_TYPE_TINYINT: {
83,367✔
6180
        INIT_INTP_POINT(st, row.ts, *(int8_t*)row.pData);
83,367✔
6181
        break;
83,367✔
6182
      }
6183
      case TSDB_DATA_TYPE_SMALLINT: {
361,933✔
6184
        INIT_INTP_POINT(st, row.ts, *(int16_t*)row.pData);
361,933✔
6185
        break;
361,933✔
6186
      }
6187
      case TSDB_DATA_TYPE_INT: {
19,401,689✔
6188
        INIT_INTP_POINT(st, row.ts, *(int32_t*)row.pData);
19,401,689✔
6189
        break;
19,401,689✔
6190
      }
6191
      case TSDB_DATA_TYPE_BIGINT: {
98,262✔
6192
        INIT_INTP_POINT(st, row.ts, *(int64_t*)row.pData);
98,262✔
6193
        break;
98,262✔
6194
      }
6195
      case TSDB_DATA_TYPE_FLOAT: {
891,413✔
6196
        INIT_INTP_POINT(st, row.ts, *(float_t*)row.pData);
891,413✔
6197
        break;
891,413✔
6198
      }
6199
      case TSDB_DATA_TYPE_DOUBLE: {
94,515✔
6200
        INIT_INTP_POINT(st, row.ts, *(double*)row.pData);
94,515✔
6201
        break;
94,515✔
6202
      }
6203
      case TSDB_DATA_TYPE_UTINYINT: {
68,357✔
6204
        INIT_INTP_POINT(st, row.ts, *(uint8_t*)row.pData);
68,357✔
6205
        break;
68,357✔
6206
      }
6207
      case TSDB_DATA_TYPE_USMALLINT: {
68,150✔
6208
        INIT_INTP_POINT(st, row.ts, *(uint16_t*)row.pData);
68,150✔
6209
        break;
68,150✔
6210
      }
6211
      case TSDB_DATA_TYPE_UINT: {
70,651✔
6212
        INIT_INTP_POINT(st, row.ts, *(uint32_t*)row.pData);
70,651✔
6213
        break;
70,651✔
6214
      }
6215
      case TSDB_DATA_TYPE_UBIGINT: {
58,337✔
6216
        INIT_INTP_POINT(st, row.ts, *(uint64_t*)row.pData);
58,337✔
6217
        break;
58,337✔
6218
      }
6219
      default: {
×
6220
        return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
6221
      }
6222
    }
6223
    if (pInfo->p.key == st.key) {
21,196,674!
6224
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6225
    }
6226

6227
    pInfo->dOutput += twa_get_area(pInfo->p, st);
21,196,674✔
6228
    pInfo->p = st;
21,196,618✔
6229
  }
6230

6231
  // the last interpolated time window value
6232
  if (pCtx->end.key != INT64_MIN) {
10,795,138✔
6233
    pInfo->dOutput += twa_get_area(pInfo->p, pCtx->end);
3,706,104✔
6234
    pInfo->p = pCtx->end;
3,706,106✔
6235
    pInfo->numOfElems += 1;
3,706,106✔
6236
  }
6237

6238
  pInfo->win.ekey = pInfo->p.key;
10,795,140✔
6239

6240
_twa_over:
10,795,140✔
6241
  SET_VAL(pResInfo, 1, 1);
10,795,140✔
6242
  return TSDB_CODE_SUCCESS;
10,795,140✔
6243
}
6244

6245
/*
6246
 * To copy the input to interResBuf to avoid the input buffer space be over writen
6247
 * by next input data. The TWA function only applies to each table, so no merge procedure
6248
 * is required, we simply copy to the resut ot interResBuffer.
6249
 */
6250
// void twa_function_copy(SQLFunctionCtx *pCtx) {
6251
//   SResultRowEntryInfo *pResInfo = GET_RES_INFO(pCtx);
6252
//
6253
//   memcpy(GET_ROWCELL_INTERBUF(pResInfo), pCtx->pInput, (size_t)pCtx->inputBytes);
6254
//   pResInfo->hasResult = ((STwaInfo *)pCtx->pInput)->hasResult;
6255
// }
6256

6257
int32_t twaFinalize(struct SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
10,782,585✔
6258
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
10,782,585✔
6259

6260
  STwaInfo* pInfo = (STwaInfo*)GET_ROWCELL_INTERBUF(pResInfo);
10,782,585✔
6261
  if (pInfo->numOfElems == 0) {
10,782,585✔
6262
    pResInfo->numOfRes = 0;
12,551✔
6263
  } else {
6264
    if (pInfo->win.ekey == pInfo->win.skey) {
10,770,034✔
6265
      pInfo->dTwaRes = pInfo->p.val;
5,704,276✔
6266
    } else if (pInfo->win.ekey == INT64_MAX || pInfo->win.skey == INT64_MIN) {  // no data in timewindow
5,065,758!
6267
      pInfo->dTwaRes = 0;
×
6268
    } else {
6269
      pInfo->dTwaRes = pInfo->dOutput / (pInfo->win.ekey - pInfo->win.skey);
5,066,229✔
6270
    }
6271

6272
    pResInfo->numOfRes = 1;
10,770,034✔
6273
  }
6274

6275
  return functionFinalize(pCtx, pBlock);
10,782,585✔
6276
}
6277

6278
int32_t blockDistSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
1,628✔
6279
  if (pResultInfo->initialized) {
1,628!
6280
    return TSDB_CODE_SUCCESS;
×
6281
  }
6282
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
1,628!
6283
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6284
  }
6285

6286
  STableBlockDistInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,628✔
6287
  pInfo->minRows = INT32_MAX;
1,628✔
6288
  return TSDB_CODE_SUCCESS;
1,628✔
6289
}
6290

6291
int32_t blockDistFunction(SqlFunctionCtx* pCtx) {
3,253✔
6292
  const int32_t BLOCK_DIST_RESULT_ROWS = 25;
3,253✔
6293

6294
  SInputColumnInfoData* pInput = &pCtx->input;
3,253✔
6295
  SColumnInfoData*      pInputCol = pInput->pData[0];
3,253✔
6296
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
3,253✔
6297
  STableBlockDistInfo*  pDistInfo = GET_ROWCELL_INTERBUF(pResInfo);
3,253✔
6298

6299
  STableBlockDistInfo p1 = {0};
3,253✔
6300
  if (tDeserializeBlockDistInfo(varDataVal(pInputCol->pData), varDataLen(pInputCol->pData), &p1) < 0) {
3,253!
6301
    qError("failed to deserialize block dist info");
×
6302
    return TSDB_CODE_FAILED;
×
6303
  }
6304

6305
  pDistInfo->numOfBlocks += p1.numOfBlocks;
3,253✔
6306
  pDistInfo->numOfTables += p1.numOfTables;
3,253✔
6307
  pDistInfo->numOfInmemRows += p1.numOfInmemRows;
3,253✔
6308
  pDistInfo->numOfSttRows += p1.numOfSttRows;
3,253✔
6309
  pDistInfo->totalSize += p1.totalSize;
3,253✔
6310
  pDistInfo->totalRows += p1.totalRows;
3,253✔
6311
  pDistInfo->numOfFiles += p1.numOfFiles;
3,253✔
6312

6313
  pDistInfo->defMinRows = p1.defMinRows;
3,253✔
6314
  pDistInfo->defMaxRows = p1.defMaxRows;
3,253✔
6315
  pDistInfo->rowSize = p1.rowSize;
3,253✔
6316

6317
  if (pDistInfo->minRows > p1.minRows) {
3,253✔
6318
    pDistInfo->minRows = p1.minRows;
2✔
6319
  }
6320
  if (pDistInfo->maxRows < p1.maxRows) {
3,253✔
6321
    pDistInfo->maxRows = p1.maxRows;
2✔
6322
  }
6323
  pDistInfo->numOfVgroups += (p1.numOfTables != 0 ? 1 : 0);
3,253✔
6324
  for (int32_t i = 0; i < tListLen(pDistInfo->blockRowsHisto); ++i) {
68,313✔
6325
    pDistInfo->blockRowsHisto[i] += p1.blockRowsHisto[i];
65,060✔
6326
  }
6327

6328
  pResInfo->numOfRes = BLOCK_DIST_RESULT_ROWS;  // default output rows
3,253✔
6329
  return TSDB_CODE_SUCCESS;
3,253✔
6330
}
6331

6332
int32_t tSerializeBlockDistInfo(void* buf, int32_t bufLen, const STableBlockDistInfo* pInfo) {
6,497✔
6333
  SEncoder encoder = {0};
6,497✔
6334
  int32_t  code = 0;
6,497✔
6335
  int32_t  lino;
6336
  int32_t  tlen;
6337
  tEncoderInit(&encoder, buf, bufLen);
6,497✔
6338

6339
  TAOS_CHECK_EXIT(tStartEncode(&encoder));
6,502!
6340
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->rowSize));
12,978!
6341

6342
  TAOS_CHECK_EXIT(tEncodeU16(&encoder, pInfo->numOfFiles));
12,978!
6343
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfBlocks));
12,978!
6344
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfTables));
12,978!
6345

6346
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalSize));
12,978!
6347
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->totalRows));
12,978!
6348
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->maxRows));
12,978!
6349
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->minRows));
12,978!
6350
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMaxRows));
12,978!
6351
  TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->defMinRows));
12,978!
6352
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfInmemRows));
12,978!
6353
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfSttRows));
12,978!
6354
  TAOS_CHECK_EXIT(tEncodeU32(&encoder, pInfo->numOfVgroups));
12,978!
6355

6356
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
136,117✔
6357
    TAOS_CHECK_EXIT(tEncodeI32(&encoder, pInfo->blockRowsHisto[i]));
259,256!
6358
  }
6359

6360
  tEndEncode(&encoder);
6,489✔
6361

6362
_exit:
6,494✔
6363
  if (code) {
6,494!
6364
    tlen = code;
×
6365
  } else {
6366
    tlen = encoder.pos;
6,494✔
6367
  }
6368
  tEncoderClear(&encoder);
6,494✔
6369
  return tlen;
6,490✔
6370
}
6371

6372
int32_t tDeserializeBlockDistInfo(void* buf, int32_t bufLen, STableBlockDistInfo* pInfo) {
3,253✔
6373
  SDecoder decoder = {0};
3,253✔
6374
  int32_t  code = 0;
3,253✔
6375
  int32_t  lino;
6376
  tDecoderInit(&decoder, buf, bufLen);
3,253✔
6377

6378
  TAOS_CHECK_EXIT(tStartDecode(&decoder));
3,253!
6379
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->rowSize));
6,506!
6380

6381
  TAOS_CHECK_EXIT(tDecodeU16(&decoder, &pInfo->numOfFiles));
6,506!
6382
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfBlocks));
6,506!
6383
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfTables));
6,506!
6384

6385
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->totalSize));
6,506!
6386
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->totalRows));
6,506!
6387
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->maxRows));
6,506!
6388
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->minRows));
6,506!
6389
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->defMaxRows));
6,506!
6390
  TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->defMinRows));
6,506!
6391
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfInmemRows));
6,506!
6392
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfSttRows));
6,506!
6393
  TAOS_CHECK_EXIT(tDecodeU32(&decoder, &pInfo->numOfVgroups));
6,506!
6394

6395
  for (int32_t i = 0; i < tListLen(pInfo->blockRowsHisto); ++i) {
68,313✔
6396
    TAOS_CHECK_EXIT(tDecodeI32(&decoder, &pInfo->blockRowsHisto[i]));
130,120!
6397
  }
6398

6399
_exit:
3,253✔
6400
  tDecoderClear(&decoder);
3,253✔
6401
  return code;
3,253✔
6402
}
6403

6404
int32_t blockDistFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1,628✔
6405
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,628✔
6406
  STableBlockDistInfo* pData = GET_ROWCELL_INTERBUF(pResInfo);
1,628✔
6407

6408
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);
1,628✔
6409
  if (NULL == pColInfo) {
1,628!
6410
    return TSDB_CODE_OUT_OF_RANGE;
×
6411
  }
6412

6413
  if (pData->totalRows == 0) {
1,628✔
6414
    pData->minRows = 0;
1,626✔
6415
  }
6416

6417
  int32_t row = 0;
1,628✔
6418
  char    st[256] = {0};
1,628✔
6419
  double  averageSize = 0;
1,628✔
6420
  if (pData->numOfBlocks != 0) {
1,628✔
6421
    averageSize = ((double)pData->totalSize) / pData->numOfBlocks;
2✔
6422
  }
6423
  uint64_t totalRawSize = pData->totalRows * pData->rowSize;
1,628✔
6424
  double   compRatio = 0;
1,628✔
6425
  if (totalRawSize != 0) {
1,628✔
6426
    compRatio = pData->totalSize * 100 / (double)totalRawSize;
2✔
6427
  }
6428

6429
  int32_t len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
3,256✔
6430
                          "Total_Blocks=[%d] Total_Size=[%.2f KiB] Average_size=[%.2f KiB] Compression_Ratio=[%.2f %c]",
6431
                          pData->numOfBlocks, pData->totalSize / 1024.0, averageSize / 1024.0, compRatio, '%');
1,628✔
6432

6433
  varDataSetLen(st, len);
1,628✔
6434
  int32_t code = colDataSetVal(pColInfo, row++, st, false);
1,628✔
6435
  if (TSDB_CODE_SUCCESS != code) {
1,628!
6436
    return code;
×
6437
  }
6438

6439
  int64_t avgRows = 0;
1,628✔
6440
  if (pData->numOfBlocks > 0) {
1,628✔
6441
    avgRows = pData->totalRows / pData->numOfBlocks;
2✔
6442
  }
6443

6444
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
1,628✔
6445
                  "Block_Rows=[%" PRId64 "] MinRows=[%d] MaxRows=[%d] AvgRows=[%" PRId64 "]", pData->totalRows,
6446
                  pData->minRows, pData->maxRows, avgRows);
6447
  varDataSetLen(st, len);
1,628✔
6448
  code = colDataSetVal(pColInfo, row++, st, false);
1,628✔
6449
  if (TSDB_CODE_SUCCESS != code) {
1,628!
6450
    return code;
×
6451
  }
6452

6453
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Inmem_Rows=[%u] Stt_Rows=[%u] ",
1,628✔
6454
                  pData->numOfInmemRows, pData->numOfSttRows);
6455
  varDataSetLen(st, len);
1,628✔
6456
  code = colDataSetVal(pColInfo, row++, st, false);
1,628✔
6457
  if (TSDB_CODE_SUCCESS != code) {
1,628!
6458
    return code;
×
6459
  }
6460

6461
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
3,256✔
6462
                  "Total_Tables=[%d] Total_Filesets=[%d] Total_Vgroups=[%d]", pData->numOfTables, pData->numOfFiles,
1,628✔
6463
                  pData->numOfVgroups);
6464

6465
  varDataSetLen(st, len);
1,628✔
6466
  code = colDataSetVal(pColInfo, row++, st, false);
1,628✔
6467
  if (TSDB_CODE_SUCCESS != code) {
1,628!
6468
    return code;
×
6469
  }
6470

6471
  len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE,
1,628✔
6472
                  "--------------------------------------------------------------------------------");
6473
  varDataSetLen(st, len);
1,628✔
6474
  code = colDataSetVal(pColInfo, row++, st, false);
1,628✔
6475
  if (TSDB_CODE_SUCCESS != code) {
1,628!
6476
    return code;
×
6477
  }
6478

6479
  int32_t maxVal = 0;
1,628✔
6480
  int32_t minVal = INT32_MAX;
1,628✔
6481
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
34,188✔
6482
    if (maxVal < pData->blockRowsHisto[i]) {
32,560✔
6483
      maxVal = pData->blockRowsHisto[i];
3✔
6484
    }
6485

6486
    if (minVal > pData->blockRowsHisto[i]) {
32,560✔
6487
      minVal = pData->blockRowsHisto[i];
1,629✔
6488
    }
6489
  }
6490

6491
  // maximum number of step is 80
6492
  double factor = pData->numOfBlocks / 80.0;
1,628✔
6493

6494
  int32_t numOfBuckets = sizeof(pData->blockRowsHisto) / sizeof(pData->blockRowsHisto[0]);
1,628✔
6495
  int32_t bucketRange = ceil(((double)(pData->defMaxRows - pData->defMinRows)) / numOfBuckets);
1,628✔
6496

6497
  for (int32_t i = 0; i < tListLen(pData->blockRowsHisto); ++i) {
34,188✔
6498
    len =
32,560✔
6499
        tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "%04d |", pData->defMinRows + bucketRange * (i + 1));
32,560✔
6500

6501
    int32_t num = 0;
32,560✔
6502
    if (pData->blockRowsHisto[i] > 0) {
32,560✔
6503
      num = (pData->blockRowsHisto[i]) / factor;
3✔
6504
    }
6505

6506
    for (int32_t j = 0; j < num; ++j) {
32,719✔
6507
      int32_t x = tsnprintf(varDataVal(st) + len, sizeof(st) - VARSTR_HEADER_SIZE - len, "%c", '|');
159✔
6508
      len += x;
159✔
6509
    }
6510

6511
    if (pData->blockRowsHisto[i] > 0) {
32,560✔
6512
      double v = pData->blockRowsHisto[i] * 100.0 / pData->numOfBlocks;
3✔
6513
      len += tsnprintf(varDataVal(st) + len, sizeof(st) - VARSTR_HEADER_SIZE - len, "  %d (%.2f%c)",
3✔
6514
                       pData->blockRowsHisto[i], v, '%');
6515
    }
6516

6517
    varDataSetLen(st, len);
32,560✔
6518
    code = colDataSetVal(pColInfo, row++, st, false);
32,560✔
6519
    if (TSDB_CODE_SUCCESS != code) {
32,560!
6520
      return code;
×
6521
    }
6522
  }
6523

6524
  return TSDB_CODE_SUCCESS;
1,628✔
6525
}
6526
int32_t blockDBUsageSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResultInfo) {
1✔
6527
  if (pResultInfo->initialized) {
1!
6528
    return TSDB_CODE_SUCCESS;
×
6529
  }
6530
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResultInfo)) {
1!
6531
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6532
  }
6533

6534
  SDBBlockUsageInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1✔
6535
  return TSDB_CODE_SUCCESS;
1✔
6536
}
6537
int32_t blockDBUsageFunction(SqlFunctionCtx* pCtx) {
2✔
6538
  const int32_t BLOCK_DISK_USAGE_RESULT_ROWS = 2;
2✔
6539

6540
  SInputColumnInfoData* pInput = &pCtx->input;
2✔
6541
  SColumnInfoData*      pInputCol = pInput->pData[0];
2✔
6542
  SResultRowEntryInfo*  pResInfo = GET_RES_INFO(pCtx);
2✔
6543
  SDBBlockUsageInfo*    pDistInfo = GET_ROWCELL_INTERBUF(pResInfo);
2✔
6544

6545
  SDBBlockUsageInfo p1 = {0};
2✔
6546
  if (tDeserializeBlockDbUsage(varDataVal(pInputCol->pData), varDataLen(pInputCol->pData), &p1) < 0) {
2!
6547
    qError("failed to deserialize block dist info");
×
6548
    return TSDB_CODE_FAILED;
×
6549
  }
6550

6551
  pDistInfo->dataInDiskSize += p1.dataInDiskSize;
2✔
6552
  pDistInfo->walInDiskSize += p1.walInDiskSize;
2✔
6553
  pDistInfo->rawDataSize += p1.rawDataSize;
2✔
6554
  pResInfo->numOfRes = BLOCK_DISK_USAGE_RESULT_ROWS;  // default output rows
2✔
6555
  return TSDB_CODE_SUCCESS;
2✔
6556
}
6557

6558
int32_t tSerializeBlockDbUsage(void* buf, int32_t bufLen, const SDBBlockUsageInfo* pInfo) {
4✔
6559
  SEncoder encoder = {0};
4✔
6560
  int32_t  code = 0;
4✔
6561
  int32_t  lino;
6562
  int32_t  tlen;
6563
  tEncoderInit(&encoder, buf, bufLen);
4✔
6564

6565
  TAOS_CHECK_EXIT(tStartEncode(&encoder));
4!
6566

6567
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->dataInDiskSize));
8!
6568
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->walInDiskSize));
8!
6569
  TAOS_CHECK_EXIT(tEncodeU64(&encoder, pInfo->rawDataSize));
8!
6570

6571
  tEndEncode(&encoder);
4✔
6572

6573
_exit:
4✔
6574
  if (code) {
4!
6575
    tlen = code;
×
6576
  } else {
6577
    tlen = encoder.pos;
4✔
6578
  }
6579
  tEncoderClear(&encoder);
4✔
6580
  return tlen;
4✔
6581
}
6582
int32_t tDeserializeBlockDbUsage(void* buf, int32_t bufLen, SDBBlockUsageInfo* pInfo) {
2✔
6583
  SDecoder decoder = {0};
2✔
6584
  int32_t  code = 0;
2✔
6585
  int32_t  lino;
6586
  tDecoderInit(&decoder, buf, bufLen);
2✔
6587

6588
  TAOS_CHECK_EXIT(tStartDecode(&decoder));
2!
6589
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->dataInDiskSize));
4!
6590
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->walInDiskSize));
4!
6591
  TAOS_CHECK_EXIT(tDecodeU64(&decoder, &pInfo->rawDataSize));
4!
6592

6593
_exit:
2✔
6594
  tDecoderClear(&decoder);
2✔
6595
  return code;
2✔
6596
}
6597
int32_t blockDBUsageFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1✔
6598
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1✔
6599
  SDBBlockUsageInfo*   pData = GET_ROWCELL_INTERBUF(pResInfo);
1✔
6600

6601
  SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, 0);
1✔
6602
  if (NULL == pColInfo) {
1!
6603
    return TSDB_CODE_OUT_OF_RANGE;
×
6604
  }
6605
  int32_t len = 0;
1✔
6606
  int32_t row = 0;
1✔
6607
  char    st[256] = {0};
1✔
6608

6609
  uint64_t totalDiskSize = pData->dataInDiskSize;
1✔
6610
  uint64_t rawDataSize = pData->rawDataSize;
1✔
6611
  double   compressRadio = 0;
1✔
6612
  if (rawDataSize != 0) {
1!
6613
    compressRadio = totalDiskSize * 100 / (double)rawDataSize;
1✔
6614
    len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Compress_radio=[%.2f]", compressRadio);
1✔
6615
  } else {
6616
    len = tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Compress_radio=[NULL]");
×
6617
  }
6618

6619
  varDataSetLen(st, len);
1✔
6620
  int32_t code = colDataSetVal(pColInfo, row++, st, false);
1✔
6621
  if (TSDB_CODE_SUCCESS != code) {
1!
6622
    return code;
×
6623
  }
6624

6625
  len =
1✔
6626
      tsnprintf(varDataVal(st), sizeof(st) - VARSTR_HEADER_SIZE, "Disk_occupied=[%" PRId64 "k]", pData->dataInDiskSize);
1✔
6627
  varDataSetLen(st, len);
1✔
6628
  code = colDataSetVal(pColInfo, row++, st, false);
1✔
6629
  if (TSDB_CODE_SUCCESS != code) {
1!
6630
    return code;
×
6631
  }
6632
  return code;
1✔
6633
}
6634

6635
bool getDerivativeFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
30,584✔
6636
  pEnv->calcMemSize = sizeof(SDerivInfo);
30,584✔
6637
  return true;
30,584✔
6638
}
6639

6640
int32_t derivativeFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
84,318✔
6641
  if (pResInfo->initialized) {
84,318✔
6642
    return TSDB_CODE_SUCCESS;
53,598✔
6643
  }
6644
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
30,720!
6645
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6646
  }
6647

6648
  SDerivInfo* pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
30,720✔
6649

6650
  pDerivInfo->ignoreNegative = pCtx->param[2].param.i;
30,720✔
6651
  pDerivInfo->prevTs = -1;
30,720✔
6652
  pDerivInfo->tsWindow = pCtx->param[1].param.i;
30,720✔
6653
  pDerivInfo->valueSet = false;
30,720✔
6654
  return TSDB_CODE_SUCCESS;
30,720✔
6655
}
6656

6657
int32_t derivativeFunction(SqlFunctionCtx* pCtx) {
53,734✔
6658
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
53,734✔
6659
  SDerivInfo*          pDerivInfo = GET_ROWCELL_INTERBUF(pResInfo);
53,734✔
6660

6661
  SInputColumnInfoData* pInput = &pCtx->input;
53,734✔
6662
  SColumnInfoData*      pInputCol = pInput->pData[0];
53,734✔
6663

6664
  int32_t          numOfElems = 0;
53,734✔
6665
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
53,734✔
6666
  SColumnInfoData* pTsOutput = pCtx->pTsOutput;
53,734✔
6667
  int32_t          code = TSDB_CODE_SUCCESS;
53,734✔
6668

6669
  funcInputUpdate(pCtx);
53,734✔
6670

6671
  double v = 0;
53,734✔
6672
  if (pCtx->order == TSDB_ORDER_ASC) {
53,734✔
6673
    SFuncInputRow row = {0};
50,377✔
6674
    bool          result = false;
50,377✔
6675
    while (1) {
2,739,907✔
6676
      code = funcInputGetNextRow(pCtx, &row, &result);
2,790,284✔
6677
      if (TSDB_CODE_SUCCESS != code) {
2,790,284!
6678
        return code;
×
6679
      }
6680
      if (!result) {
2,790,284✔
6681
        break;
50,377✔
6682
      }
6683
      if (row.isDataNull) {
2,739,907✔
6684
        continue;
41,315✔
6685
      }
6686

6687
      char* d = row.pData;
2,698,592✔
6688
      GET_TYPED_DATA(v, double, pInputCol->info.type, d);
2,698,592!
6689

6690
      int32_t pos = pCtx->offset + numOfElems;
2,698,592✔
6691
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
2,698,592✔
6692
        pDerivInfo->valueSet = true;
26,964✔
6693
      } else {
6694
        if (row.ts == pDerivInfo->prevTs) {
2,671,628!
6695
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6696
        }
6697
        double r = ((v - pDerivInfo->prevValue) * pDerivInfo->tsWindow) / (row.ts - pDerivInfo->prevTs);
2,671,628✔
6698
        if (pDerivInfo->ignoreNegative && r < 0) {
2,671,628✔
6699
        } else {
6700
          if (isinf(r) || isnan(r)) {
1,573,265!
6701
            colDataSetNULL(pOutput, pos);
×
6702
          } else {
6703
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
1,573,265✔
6704
            if (code != TSDB_CODE_SUCCESS) {
1,573,265!
6705
              return code;
×
6706
            }
6707
          }
6708

6709
          if (pTsOutput != NULL) {
1,573,265!
6710
            colDataSetInt64(pTsOutput, pos, &row.ts);
×
6711
          }
6712

6713
          // handle selectivity
6714
          if (pCtx->subsidiaries.num > 0) {
1,573,265✔
6715
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
1,001,223✔
6716
            if (code != TSDB_CODE_SUCCESS) {
1,001,223!
6717
              return code;
×
6718
            }
6719
          }
6720

6721
          numOfElems++;
1,573,265✔
6722
        }
6723
      }
6724

6725
      pDerivInfo->prevValue = v;
2,698,592✔
6726
      pDerivInfo->prevTs = row.ts;
2,698,592✔
6727
    }
6728
  } else {
6729
    SFuncInputRow row = {0};
3,357✔
6730
    bool          result = false;
3,357✔
6731
    while (1) {
332,858✔
6732
      code = funcInputGetNextRow(pCtx, &row, &result);
336,215✔
6733
      if (TSDB_CODE_SUCCESS != code) {
336,215!
6734
        return code;
×
6735
      }
6736
      if (!result) {
336,215✔
6737
        break;
3,357✔
6738
      }
6739
      if (row.isDataNull) {
332,858✔
6740
        continue;
20✔
6741
      }
6742

6743
      char* d = row.pData;
332,838✔
6744
      GET_TYPED_DATA(v, double, pInputCol->info.type, d);
332,838!
6745

6746
      int32_t pos = pCtx->offset + numOfElems;
332,838✔
6747
      if (!pDerivInfo->valueSet) {  // initial value is not set yet
332,838✔
6748
        pDerivInfo->valueSet = true;
3,347✔
6749
      } else {
6750
        if (row.ts == pDerivInfo->prevTs) {
329,491!
6751
          return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6752
        }
6753
        double r = ((pDerivInfo->prevValue - v) * pDerivInfo->tsWindow) / (pDerivInfo->prevTs - row.ts);
329,491✔
6754
        if (pDerivInfo->ignoreNegative && r < 0) {
329,491✔
6755
        } else {
6756
          if (isinf(r) || isnan(r)) {
169,738!
6757
            colDataSetNULL(pOutput, pos);
×
6758
          } else {
6759
            code = colDataSetVal(pOutput, pos, (const char*)&r, false);
169,738✔
6760
            if (code != TSDB_CODE_SUCCESS) {
169,738!
6761
              return code;
×
6762
            }
6763
          }
6764

6765
          if (pTsOutput != NULL) {
169,738!
6766
            colDataSetInt64(pTsOutput, pos, &pDerivInfo->prevTs);
×
6767
          }
6768

6769
          // handle selectivity
6770
          if (pCtx->subsidiaries.num > 0) {
169,738✔
6771
            code = appendSelectivityCols(pCtx, row.block, row.rowIndex, pos);
59,262✔
6772
            if (code != TSDB_CODE_SUCCESS) {
59,262!
6773
              return code;
×
6774
            }
6775
          }
6776
          numOfElems++;
169,738✔
6777
        }
6778
      }
6779

6780
      pDerivInfo->prevValue = v;
332,838✔
6781
      pDerivInfo->prevTs = row.ts;
332,838✔
6782
    }
6783
  }
6784

6785
  pResInfo->numOfRes = numOfElems;
53,734✔
6786

6787
  return TSDB_CODE_SUCCESS;
53,734✔
6788
}
6789

6790
int32_t getIrateInfoSize(int32_t pkBytes) { return (int32_t)sizeof(SRateInfo) + 2 * pkBytes; }
1,802,733✔
6791

6792
bool getIrateFuncEnv(struct SFunctionNode* pFunc, SFuncExecEnv* pEnv) {
124,171✔
6793
  int32_t pkBytes = (pFunc->hasPk) ? pFunc->pkBytes : 0;
124,171✔
6794
  pEnv->calcMemSize = getIrateInfoSize(pkBytes);
124,171✔
6795
  return true;
124,327✔
6796
}
6797

6798
int32_t irateFuncSetup(SqlFunctionCtx* pCtx, SResultRowEntryInfo* pResInfo) {
11,918,869✔
6799
  if (pResInfo->initialized) {
11,918,869!
6800
    return TSDB_CODE_SUCCESS;
×
6801
  }
6802
  if (TSDB_CODE_SUCCESS != functionSetup(pCtx, pResInfo)) {
11,918,869!
6803
    return TSDB_CODE_FUNC_SETUP_ERROR;
×
6804
  }
6805

6806
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
11,918,891✔
6807

6808
  pInfo->firstKey = INT64_MIN;
11,918,891✔
6809
  pInfo->lastKey = INT64_MIN;
11,918,891✔
6810
  pInfo->firstValue = (double)INT64_MIN;
11,918,891✔
6811
  pInfo->lastValue = (double)INT64_MIN;
11,918,891✔
6812

6813
  pInfo->hasResult = 0;
11,918,891✔
6814
  return TSDB_CODE_SUCCESS;
11,918,891✔
6815
}
6816

6817
static void doSaveRateInfo(SRateInfo* pRateInfo, bool isFirst, int64_t ts, char* pk, double v) {
58,229,670✔
6818
  if (isFirst) {
58,229,670✔
6819
    pRateInfo->firstValue = v;
24,003,834✔
6820
    pRateInfo->firstKey = ts;
24,003,834✔
6821
    if (pRateInfo->firstPk) {
24,003,834✔
6822
      int32_t pkBytes;
6823
      if (IS_VAR_DATA_TYPE(pRateInfo->pkType)) {
35!
6824
        if (pRateInfo->pkType == TSDB_DATA_TYPE_JSON) {
8!
6825
          pkBytes = getJsonValueLen(pk);
×
6826
        } else {
6827
          pkBytes = varDataTLen(pk);
8✔
6828
        }
6829
      } else {
6830
        pkBytes = pRateInfo->pkBytes;
27✔
6831
      }
6832
      (void)memcpy(pRateInfo->firstPk, pk, pkBytes);
35✔
6833
    }
6834
  } else {
6835
    pRateInfo->lastValue = v;
34,225,836✔
6836
    pRateInfo->lastKey = ts;
34,225,836✔
6837
    if (pRateInfo->lastPk) {
34,225,836✔
6838
      int32_t pkBytes;
6839
      if (IS_VAR_DATA_TYPE(pRateInfo->pkType)) {
52!
6840
        if (pRateInfo->pkType == TSDB_DATA_TYPE_JSON) {
12!
6841
          pkBytes = getJsonValueLen(pk);
×
6842
        } else {
6843
          pkBytes = varDataTLen(pk);
12✔
6844
        }
6845
      } else {
6846
        pkBytes = pRateInfo->pkBytes;
40✔
6847
      }
6848
      (void)memcpy(pRateInfo->lastPk, pk, pkBytes);
52✔
6849
    }
6850
  }
6851
}
58,229,670✔
6852

6853
static void initializeRateInfo(SqlFunctionCtx* pCtx, SRateInfo* pRateInfo, bool isMerge) {
13,598,781✔
6854
  if (pCtx->hasPrimaryKey) {
13,598,781✔
6855
    if (!isMerge) {
19✔
6856
      pRateInfo->pkType = pCtx->input.pPrimaryKey->info.type;
17✔
6857
      pRateInfo->pkBytes = pCtx->input.pPrimaryKey->info.bytes;
17✔
6858
      pRateInfo->firstPk = pRateInfo->pkData;
17✔
6859
      pRateInfo->lastPk = pRateInfo->pkData + pRateInfo->pkBytes;
17✔
6860
    } else {
6861
      pRateInfo->firstPk = pRateInfo->pkData;
2✔
6862
      pRateInfo->lastPk = pRateInfo->pkData + pRateInfo->pkBytes;
2✔
6863
    }
6864
  } else {
6865
    pRateInfo->firstPk = NULL;
13,598,762✔
6866
    pRateInfo->lastPk = NULL;
13,598,762✔
6867
  }
6868
}
13,598,781✔
6869

6870
int32_t irateFunction(SqlFunctionCtx* pCtx) {
10,242,164✔
6871
  int32_t              code = TSDB_CODE_SUCCESS;
10,242,164✔
6872
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
10,242,164✔
6873
  SRateInfo*           pRateInfo = GET_ROWCELL_INTERBUF(pResInfo);
10,242,164✔
6874

6875
  SInputColumnInfoData* pInput = &pCtx->input;
10,242,164✔
6876
  SColumnInfoData*      pInputCol = pInput->pData[0];
10,242,164✔
6877

6878
  SColumnInfoData* pOutput = (SColumnInfoData*)pCtx->pOutput;
10,242,164✔
6879

6880
  funcInputUpdate(pCtx);
10,242,164✔
6881

6882
  initializeRateInfo(pCtx, pRateInfo, false);
10,242,196✔
6883

6884
  int32_t       numOfElems = 0;
10,242,160✔
6885
  int32_t       type = pInputCol->info.type;
10,242,160✔
6886
  SFuncInputRow row = {0};
10,242,160✔
6887
  bool          result = false;
10,242,160✔
6888
  while (1) {
33,085,986✔
6889
    code = funcInputGetNextRow(pCtx, &row, &result);
43,328,146✔
6890
    if (TSDB_CODE_SUCCESS != code) {
43,327,418!
6891
      return code;
×
6892
    }
6893
    if (!result) {
43,327,418✔
6894
      break;
10,242,355✔
6895
    }
6896
    if (row.isDataNull) {
33,085,063✔
6897
      continue;
122,362✔
6898
    }
6899

6900
    char*  data = row.pData;
32,962,701✔
6901
    double v = 0;
32,962,701✔
6902
    GET_TYPED_DATA(v, double, type, data);
32,962,701!
6903

6904
    if (INT64_MIN == pRateInfo->lastKey) {
32,962,701✔
6905
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
10,224,087✔
6906
      pRateInfo->hasResult = 1;
10,224,058✔
6907
      continue;
10,224,058✔
6908
    }
6909

6910
    if (row.ts > pRateInfo->lastKey) {
22,738,614✔
6911
      if ((INT64_MIN == pRateInfo->firstKey) || pRateInfo->lastKey > pRateInfo->firstKey) {
22,324,968!
6912
        doSaveRateInfo(pRateInfo, true, pRateInfo->lastKey, pRateInfo->lastPk, pRateInfo->lastValue);
22,324,968✔
6913
      }
6914
      doSaveRateInfo(pRateInfo, false, row.ts, row.pPk, v);
22,324,915✔
6915
      continue;
22,324,871✔
6916
    } else if (row.ts == pRateInfo->lastKey) {
413,646!
6917
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6918
    }
6919

6920
    if ((INT64_MIN == pRateInfo->firstKey) || row.ts > pRateInfo->firstKey) {
413,646!
6921
      doSaveRateInfo(pRateInfo, true, row.ts, row.pPk, v);
×
6922
    } else if (row.ts == pRateInfo->firstKey) {
414,977!
6923
      return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6924
    }
6925
  }
6926

6927
  numOfElems++;
10,242,355✔
6928

6929
  SET_VAL(pResInfo, numOfElems, 1);
10,242,355!
6930
  return TSDB_CODE_SUCCESS;
10,242,355✔
6931
}
6932

6933
static double doCalcRate(const SRateInfo* pRateInfo, double tickPerSec) {
10,238,010✔
6934
  if ((INT64_MIN == pRateInfo->lastKey) || (INT64_MIN == pRateInfo->firstKey) ||
10,238,010✔
6935
      (pRateInfo->firstKey >= pRateInfo->lastKey)) {
3,372,392!
6936
    return 0.0;
6,865,618✔
6937
  }
6938

6939
  double diff = 0;
3,372,392✔
6940
  // If the previous value of the last is greater than the last value, only keep the last point instead of the delta
6941
  // value between two values.
6942
  diff = pRateInfo->lastValue;
3,372,392✔
6943
  if (diff >= pRateInfo->firstValue) {
3,372,392✔
6944
    diff -= pRateInfo->firstValue;
1,681,738✔
6945
  }
6946

6947
  int64_t duration = pRateInfo->lastKey - pRateInfo->firstKey;
3,372,392✔
6948
  if (duration == 0) {
3,372,392!
6949
    return 0;
×
6950
  }
6951

6952
  return (duration > 0) ? ((double)diff) / (duration / tickPerSec) : 0.0;
3,372,392!
6953
}
6954

6955
static void irateTransferInfoImpl(TSKEY inputKey, SRateInfo* pInput, SRateInfo* pOutput, bool isFirstKey) {
402✔
6956
  if (inputKey > pOutput->lastKey) {
402✔
6957
    doSaveRateInfo(pOutput, true, pOutput->lastKey, pOutput->lastPk, pOutput->lastValue);
173✔
6958
    if (isFirstKey) {
173✔
6959
      doSaveRateInfo(pOutput, false, pInput->firstKey, pInput->firstPk, pInput->firstValue);
39✔
6960
    } else {
6961
      doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
134✔
6962
    }
6963
  } else if ((inputKey < pOutput->lastKey) && (inputKey > pOutput->firstKey)) {
229!
6964
    if (isFirstKey) {
128✔
6965
      doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
91✔
6966
    } else {
6967
      doSaveRateInfo(pOutput, true, pInput->lastKey, pInput->lastPk, pInput->lastValue);
37✔
6968
    }
6969
  } else {
6970
    // inputKey < pOutput->firstKey
6971
  }
6972
}
402✔
6973

6974
static void irateCopyInfo(SRateInfo* pInput, SRateInfo* pOutput) {
1,678,109✔
6975
  doSaveRateInfo(pOutput, true, pInput->firstKey, pInput->firstPk, pInput->firstValue);
1,678,109✔
6976
  doSaveRateInfo(pOutput, false, pInput->lastKey, pInput->lastPk, pInput->lastValue);
1,678,109✔
6977
}
1,678,109✔
6978

6979
static int32_t irateTransferInfo(SRateInfo* pInput, SRateInfo* pOutput) {
1,678,310✔
6980
  if ((pInput->firstKey != INT64_MIN &&
1,678,310✔
6981
       (pInput->firstKey == pOutput->firstKey || pInput->firstKey == pOutput->lastKey)) ||
1,591,501!
6982
      (pInput->lastKey != INT64_MIN && (pInput->lastKey == pOutput->firstKey || pInput->lastKey == pOutput->lastKey))) {
1,678,310!
6983
    return TSDB_CODE_FUNC_DUP_TIMESTAMP;
×
6984
  }
6985

6986
  if (pOutput->hasResult == 0) {
1,678,310✔
6987
    irateCopyInfo(pInput, pOutput);
1,678,109✔
6988
    pOutput->hasResult = pInput->hasResult;
1,678,109✔
6989
    return TSDB_CODE_SUCCESS;
1,678,109✔
6990
  }
6991

6992
  if (pInput->firstKey != INT64_MIN) {
201!
6993
    irateTransferInfoImpl(pInput->firstKey, pInput, pOutput, true);
201✔
6994
  }
6995

6996
  if (pInput->lastKey != INT64_MIN) {
201!
6997
    irateTransferInfoImpl(pInput->lastKey, pInput, pOutput, false);
201✔
6998
  }
6999

7000
  pOutput->hasResult = pInput->hasResult;
201✔
7001
  return TSDB_CODE_SUCCESS;
201✔
7002
}
7003

7004
int32_t irateFunctionMerge(SqlFunctionCtx* pCtx) {
1,678,318✔
7005
  SInputColumnInfoData* pInput = &pCtx->input;
1,678,318✔
7006
  SColumnInfoData*      pCol = pInput->pData[0];
1,678,318✔
7007
  if (pCol->info.type != TSDB_DATA_TYPE_BINARY) {
1,678,318!
7008
    return TSDB_CODE_FUNC_FUNTION_PARA_TYPE;
×
7009
  }
7010

7011
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,678,318✔
7012
  initializeRateInfo(pCtx, pInfo, true);
1,678,318✔
7013

7014
  int32_t start = pInput->startRowIndex;
1,678,318✔
7015
  for (int32_t i = start; i < start + pInput->numOfRows; ++i) {
3,356,636✔
7016
    char*      data = colDataGetData(pCol, i);
1,678,318!
7017
    SRateInfo* pInputInfo = (SRateInfo*)varDataVal(data);
1,678,318✔
7018
    initializeRateInfo(pCtx, pInfo, true);
1,678,318✔
7019
    if (pInputInfo->hasResult) {
1,678,318✔
7020
      int32_t code = irateTransferInfo(pInputInfo, pInfo);
1,678,310✔
7021
      if (code != TSDB_CODE_SUCCESS) {
1,678,310!
7022
        return code;
×
7023
      }
7024
    }
7025
  }
7026

7027
  if (pInfo->hasResult) {
1,678,318✔
7028
    GET_RES_INFO(pCtx)->numOfRes = 1;
1,678,310✔
7029
  }
7030

7031
  return TSDB_CODE_SUCCESS;
1,678,318✔
7032
}
7033

7034
int32_t iratePartialFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
1,678,318✔
7035
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
1,678,318✔
7036
  SRateInfo*           pInfo = GET_ROWCELL_INTERBUF(GET_RES_INFO(pCtx));
1,678,318✔
7037
  int32_t              resultBytes = getIrateInfoSize(pInfo->pkBytes);
1,678,318✔
7038
  char*                res = taosMemoryCalloc(resultBytes + VARSTR_HEADER_SIZE, sizeof(char));
1,678,318!
7039

7040
  if (NULL == res) {
1,678,318!
7041
    return terrno;
×
7042
  }
7043
  (void)memcpy(varDataVal(res), pInfo, resultBytes);
1,678,318✔
7044
  varDataSetLen(res, resultBytes);
1,678,318✔
7045

7046
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
1,678,318✔
7047
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
1,678,318✔
7048
  if (NULL == pCol) {
1,678,318!
7049
    taosMemoryFree(res);
×
7050
    return TSDB_CODE_OUT_OF_RANGE;
×
7051
  }
7052

7053
  int32_t code = colDataSetVal(pCol, pBlock->info.rows, res, false);
1,678,318✔
7054

7055
  taosMemoryFree(res);
1,678,318!
7056
  return code;
1,678,318✔
7057
}
7058

7059
int32_t irateFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
10,238,083✔
7060
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
10,238,083✔
7061
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
10,238,083✔
7062
  if (NULL == pCol) {
10,238,002!
7063
    return TSDB_CODE_OUT_OF_RANGE;
×
7064
  }
7065

7066
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
10,238,002✔
7067
  pResInfo->isNullRes = (pResInfo->numOfRes == 0) ? 1 : 0;
10,238,002✔
7068

7069
  SRateInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
10,238,002✔
7070
  double     result = doCalcRate(pInfo, (double)TSDB_TICK_PER_SECOND(pCtx->param[1].param.i));
10,238,002!
7071
  int32_t    code = colDataSetVal(pCol, pBlock->info.rows, (const char*)&result, pResInfo->isNullRes);
10,237,993✔
7072

7073
  return code;
10,237,728✔
7074
}
7075

7076
int32_t groupConstValueFunction(SqlFunctionCtx* pCtx) {
104,715,888✔
7077
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
104,715,888✔
7078
  SGroupKeyInfo*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
104,715,888✔
7079

7080
  SInputColumnInfoData* pInput = &pCtx->input;
104,715,888✔
7081
  SColumnInfoData*      pInputCol = pInput->pData[0];
104,715,888✔
7082

7083
  int32_t startIndex = pInput->startRowIndex;
104,715,888✔
7084

7085
  // escape rest of data blocks to avoid first entry to be overwritten.
7086
  if (pInfo->hasResult) {
104,715,888✔
7087
    goto _group_value_over;
10,793,939✔
7088
  }
7089

7090
  if (pInputCol->pData == NULL || colDataIsNull_s(pInputCol, startIndex)) {
187,435,353✔
7091
    pInfo->isNull = true;
2,665,639✔
7092
    pInfo->hasResult = true;
2,665,639✔
7093
    goto _group_value_over;
2,665,639✔
7094
  }
7095

7096
  char* data = colDataGetData(pInputCol, startIndex);
91,256,310!
7097
  if (IS_VAR_DATA_TYPE(pInputCol->info.type)) {
91,256,310!
7098
    (void)memcpy(pInfo->data, data,
72,082,030✔
7099
                 (pInputCol->info.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(data) : varDataTLen(data));
72,082,030✔
7100
  } else {
7101
    (void)memcpy(pInfo->data, data, pInputCol->info.bytes);
19,174,280✔
7102
  }
7103
  pInfo->hasResult = true;
91,256,310✔
7104

7105
_group_value_over:
104,715,888✔
7106

7107
  SET_VAL(pResInfo, 1, 1);
104,715,888✔
7108
  return TSDB_CODE_SUCCESS;
104,715,888✔
7109
}
7110

7111
int32_t groupKeyFunction(SqlFunctionCtx* pCtx) { return groupConstValueFunction(pCtx); }
104,707,104✔
7112

7113
int32_t groupConstValueFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) {
92,518,923✔
7114
  int32_t          slotId = pCtx->pExpr->base.resSchema.slotId;
92,518,923✔
7115
  int32_t          code = TSDB_CODE_SUCCESS;
92,518,923✔
7116
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, slotId);
92,518,923✔
7117
  if (NULL == pCol) {
92,443,262!
7118
    return TSDB_CODE_OUT_OF_RANGE;
×
7119
  }
7120

7121
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
92,443,262✔
7122

7123
  SGroupKeyInfo* pInfo = GET_ROWCELL_INTERBUF(pResInfo);
92,443,262✔
7124

7125
  if (pInfo->hasResult) {
92,443,262!
7126
    int32_t currentRow = pBlock->info.rows;
92,467,447✔
7127
    for (; currentRow < pBlock->info.rows + pResInfo->numOfRes; ++currentRow) {
185,701,331✔
7128
      code = colDataSetVal(pCol, currentRow, pInfo->data, pInfo->isNull ? true : false);
92,481,372✔
7129
      if (TSDB_CODE_SUCCESS != code) {
93,233,884!
7130
        return code;
×
7131
      }
7132
    }
7133
  } else {
7134
    pResInfo->numOfRes = 0;
×
7135
  }
7136

7137
  return code;
93,195,774✔
7138
}
7139

7140
int32_t groupKeyFinalize(SqlFunctionCtx* pCtx, SSDataBlock* pBlock) { return groupConstValueFinalize(pCtx, pBlock); }
92,562,268✔
7141

7142
int32_t groupKeyCombine(SqlFunctionCtx* pDestCtx, SqlFunctionCtx* pSourceCtx) {
×
7143
  SResultRowEntryInfo* pDResInfo = GET_RES_INFO(pDestCtx);
×
7144
  SGroupKeyInfo*       pDBuf = GET_ROWCELL_INTERBUF(pDResInfo);
×
7145

7146
  SResultRowEntryInfo* pSResInfo = GET_RES_INFO(pSourceCtx);
×
7147
  SGroupKeyInfo*       pSBuf = GET_ROWCELL_INTERBUF(pSResInfo);
×
7148

7149
  // escape rest of data blocks to avoid first entry to be overwritten.
7150
  if (pDBuf->hasResult) {
×
7151
    goto _group_key_over;
×
7152
  }
7153

7154
  if (pSBuf->isNull) {
×
7155
    pDBuf->isNull = true;
×
7156
    pDBuf->hasResult = true;
×
7157
    goto _group_key_over;
×
7158
  }
7159

7160
  if (IS_VAR_DATA_TYPE(pSourceCtx->resDataInfo.type)) {
×
7161
    (void)memcpy(pDBuf->data, pSBuf->data,
×
7162
                 (pSourceCtx->resDataInfo.type == TSDB_DATA_TYPE_JSON) ? getJsonValueLen(pSBuf->data)
×
7163
                                                                       : varDataTLen(pSBuf->data));
×
7164
  } else {
7165
    (void)memcpy(pDBuf->data, pSBuf->data, pSourceCtx->resDataInfo.bytes);
×
7166
  }
7167

7168
  pDBuf->hasResult = true;
×
7169

7170
_group_key_over:
×
7171

7172
  SET_VAL(pDResInfo, 1, 1);
×
7173
  return TSDB_CODE_SUCCESS;
×
7174
}
7175

7176
int32_t cachedLastRowFunction(SqlFunctionCtx* pCtx) {
9,430✔
7177
  int32_t numOfElems = 0;
9,430✔
7178

7179
  SResultRowEntryInfo* pResInfo = GET_RES_INFO(pCtx);
9,430✔
7180
  SFirstLastRes*       pInfo = GET_ROWCELL_INTERBUF(pResInfo);
9,430✔
7181

7182
  SInputColumnInfoData* pInput = &pCtx->input;
9,430✔
7183
  SColumnInfoData*      pInputCol = pInput->pData[0];
9,430✔
7184

7185
  int32_t bytes = pInputCol->info.bytes;
9,430✔
7186
  pInfo->bytes = bytes;
9,430✔
7187

7188
  SColumnInfoData* pkCol = pInput->pPrimaryKey;
9,430✔
7189
  pInfo->pkType = -1;
9,430✔
7190
  __compar_fn_t pkCompareFn = NULL;
9,430✔
7191
  if (pCtx->hasPrimaryKey) {
9,430✔
7192
    pInfo->pkType = pkCol->info.type;
20✔
7193
    pInfo->pkBytes = pkCol->info.bytes;
20✔
7194
    pkCompareFn = getKeyComparFunc(pInfo->pkType, TSDB_ORDER_DESC);
20✔
7195
  }
7196

7197
  // TODO it traverse the different way.
7198
  // last_row function does not ignore the null value
7199
  for (int32_t i = pInput->numOfRows + pInput->startRowIndex - 1; i >= pInput->startRowIndex; --i) {
18,872✔
7200
    numOfElems++;
9,441✔
7201

7202
    bool  isNull = colDataIsNull(pInputCol, pInput->numOfRows, i, NULL);
9,441✔
7203
    char* data = isNull ? NULL : colDataGetData(pInputCol, i);
9,441!
7204

7205
    TSKEY cts = getRowPTs(pInput->pPTS, i);
9,441!
7206
    if (pResInfo->numOfRes == 0 || pInfo->ts < cts) {
9,441✔
7207
      int32_t code = doSaveLastrow(pCtx, data, i, cts, pInfo);
9,139✔
7208
      if (code != TSDB_CODE_SUCCESS) {
9,139!
7209
        return code;
×
7210
      }
7211
      pResInfo->numOfRes = 1;
9,139✔
7212
    }
7213
  }
7214

7215
  SET_VAL(pResInfo, numOfElems, 1);
9,431!
7216
  return TSDB_CODE_SUCCESS;
9,431✔
7217
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc