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

taosdata / TDengine / #3778

28 Mar 2025 06:51AM UTC coverage: 63.374% (+0.4%) from 62.934%
#3778

push

travis-ci

web-flow
fix(tdb): disable page recycling (#30529)

155771 of 313582 branches covered (49.67%)

Branch coverage included in aggregate %.

241569 of 313390 relevant lines covered (77.08%)

20705705.27 hits per line

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

62.83
/source/libs/executor/src/aggregateoperator.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 "filter.h"
17
#include "function.h"
18
#include "nodes.h"
19
#include "os.h"
20
#include "querynodes.h"
21
#include "tfill.h"
22
#include "tname.h"
23

24
#include "executorInt.h"
25
#include "index.h"
26
#include "operator.h"
27
#include "query.h"
28
#include "querytask.h"
29
#include "tcompare.h"
30
#include "tdatablock.h"
31
#include "tglobal.h"
32
#include "thash.h"
33
#include "ttypes.h"
34

35
typedef struct {
36
  bool    hasAgg;
37
  int32_t numOfRows;
38
  int32_t startOffset;
39
} SFunctionCtxStatus;
40

41
typedef struct SAggOperatorInfo {
42
  SOptrBasicInfo   binfo;
43
  SAggSupporter    aggSup;
44
  STableQueryInfo* current;
45
  uint64_t         groupId;
46
  SGroupResInfo    groupResInfo;
47
  SExprSupp        scalarExprSup;
48
  bool             groupKeyOptimized;
49
  bool             hasValidBlock;
50
  SSDataBlock*     pNewGroupBlock;
51
  bool             hasCountFunc;
52
  SOperatorInfo*   pOperator;
53
  bool             cleanGroupResInfo;
54
} SAggOperatorInfo;
55

56
static void destroyAggOperatorInfo(void* param);
57
static int32_t setExecutionContext(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId);
58

59
static int32_t createDataBlockForEmptyInput(SOperatorInfo* pOperator, SSDataBlock** ppBlock);
60
static void    destroyDataBlockForEmptyInput(bool blockAllocated, SSDataBlock** ppBlock);
61

62
static int32_t doAggregateImpl(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx);
63
static int32_t getAggregateResultNext(SOperatorInfo* pOperator, SSDataBlock** ppRes);
64
static int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
65
                                const char* pKey);
66

67
static int32_t addNewResultRowBuf(SResultRow* pWindowRes, SDiskbasedBuf* pResultBuf, uint32_t size);
68

69
static int32_t doSetTableGroupOutputBuf(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId);
70

71
static void functionCtxSave(SqlFunctionCtx* pCtx, SFunctionCtxStatus* pStatus);
72
static void functionCtxRestore(SqlFunctionCtx* pCtx, SFunctionCtxStatus* pStatus);
73

74
int32_t createAggregateOperatorInfo(SOperatorInfo* downstream, SAggPhysiNode* pAggNode, SExecTaskInfo* pTaskInfo,
2,299,546✔
75
                                    SOperatorInfo** pOptrInfo) {
76
  QRY_PARAM_CHECK(pOptrInfo);
2,299,546!
77

78
  int32_t    lino = 0;
2,299,546✔
79
  int32_t    code = 0;
2,299,546✔
80
  int32_t    num = 0;
2,299,546✔
81
  SExprInfo* pExprInfo = NULL;
2,299,546✔
82
  int32_t    numOfScalarExpr = 0;
2,299,546✔
83
  SExprInfo* pScalarExprInfo = NULL;
2,299,546✔
84

85
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
2,299,546!
86
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
2,300,174!
87
  if (pInfo == NULL || pOperator == NULL) {
2,300,942!
88
    code = terrno;
×
89
    goto _error;
×
90
  }
91

92
  pOperator->exprSupp.hasWindowOrGroup = false;
2,301,169✔
93

94
  SSDataBlock* pResBlock = createDataBlockFromDescNode(pAggNode->node.pOutputDataBlockDesc);
2,301,169✔
95
  QUERY_CHECK_NULL(pResBlock, code, lino, _error, terrno);
2,301,985!
96
  initBasicInfo(&pInfo->binfo, pResBlock);
2,301,985✔
97

98
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
2,302,150✔
99
  initResultSizeInfo(&pOperator->resultInfo, 4096);
2,302,150✔
100

101
  code = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &pExprInfo, &num);
2,302,704✔
102
  TSDB_CHECK_CODE(code, lino, _error);
2,301,280!
103

104
  code = initAggSup(&pOperator->exprSupp, &pInfo->aggSup, pExprInfo, num, keyBufSize, pTaskInfo->id.str,
2,301,280✔
105
                               pTaskInfo->streamInfo.pState, &pTaskInfo->storageAPI.functionStore);
2,301,280✔
106
  TSDB_CHECK_CODE(code, lino, _error);
2,300,298!
107

108
  if (pAggNode->pExprs != NULL) {
2,300,298✔
109
    code = createExprInfo(pAggNode->pExprs, NULL, &pScalarExprInfo, &numOfScalarExpr);
199,434✔
110
    TSDB_CHECK_CODE(code, lino, _error);
199,512!
111
  }
112

113
  code = initExprSupp(&pInfo->scalarExprSup, pScalarExprInfo, numOfScalarExpr, &pTaskInfo->storageAPI.functionStore);
2,300,376✔
114
  TSDB_CHECK_CODE(code, lino, _error);
2,301,282!
115

116
  code = filterInitFromNode((SNode*)pAggNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0);
2,301,282✔
117
  TSDB_CHECK_CODE(code, lino, _error);
2,301,725!
118

119
  pInfo->binfo.mergeResultBlock = pAggNode->mergeDataBlock;
2,301,725✔
120
  pInfo->groupKeyOptimized = pAggNode->groupKeyOptimized;
2,301,725✔
121
  pInfo->groupId = UINT64_MAX;
2,301,725✔
122
  pInfo->binfo.inputTsOrder = pAggNode->node.inputTsOrder;
2,301,725✔
123
  pInfo->binfo.outputTsOrder = pAggNode->node.outputTsOrder;
2,301,725✔
124
  pInfo->hasCountFunc = pAggNode->hasCountLikeFunc;
2,301,725✔
125
  pInfo->pOperator = pOperator;
2,301,725✔
126
  pInfo->cleanGroupResInfo = false;
2,301,725✔
127

128
  setOperatorInfo(pOperator, "TableAggregate", QUERY_NODE_PHYSICAL_PLAN_HASH_AGG,
2,301,725✔
129
                  !pAggNode->node.forceCreateNonBlockingOptr, OP_NOT_OPENED, pInfo, pTaskInfo);
2,301,725✔
130
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, getAggregateResultNext, NULL, destroyAggOperatorInfo,
2,301,383✔
131
                                         optrDefaultBufFn, NULL, optrDefaultGetNextExtFn, NULL);
132

133
  if (downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
2,300,693✔
134
    STableScanInfo* pTableScanInfo = downstream->info;
802,186✔
135
    pTableScanInfo->base.pdInfo.pExprSup = &pOperator->exprSupp;
802,186✔
136
    pTableScanInfo->base.pdInfo.pAggSup = &pInfo->aggSup;
802,186✔
137
  }
138

139
  code = appendDownstream(pOperator, &downstream, 1);
2,300,693✔
140
  if (code != TSDB_CODE_SUCCESS) {
2,302,018!
141
    goto _error;
×
142
  }
143

144
  *pOptrInfo = pOperator;
2,302,018✔
145
  return TSDB_CODE_SUCCESS;
2,302,018✔
146

147
_error:
×
148
  qError("%s failed at line %d since %s", __func__, lino, tstrerror(code));
×
149
  if (pInfo != NULL) {
×
150
    destroyAggOperatorInfo(pInfo);
×
151
  }
152
  destroyOperatorAndDownstreams(pOperator, &downstream, 1);
×
153
  pTaskInfo->code = code;
×
154
  return code;
×
155
}
156

157
void destroyAggOperatorInfo(void* param) {
2,303,262✔
158
  if (param == NULL) {
2,303,262!
159
    return;
×
160
  }
161
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
2,303,262✔
162
  cleanupBasicInfo(&pInfo->binfo);
2,303,262✔
163

164
  if (pInfo->pOperator) {
2,304,070!
165
    cleanupResultInfo(pInfo->pOperator->pTaskInfo, &pInfo->pOperator->exprSupp, &pInfo->groupResInfo, &pInfo->aggSup,
2,304,075✔
166
                      pInfo->cleanGroupResInfo);
2,304,075✔
167
    pInfo->pOperator = NULL;
2,303,325✔
168
  }
169
  cleanupAggSup(&pInfo->aggSup);
2,303,320✔
170
  cleanupExprSupp(&pInfo->scalarExprSup);
2,304,068✔
171
  cleanupGroupResInfo(&pInfo->groupResInfo);
2,303,736✔
172
  taosMemoryFreeClear(param);
2,304,062!
173
}
174

175
/**
176
 * @brief get blocks from downstream and fill results into groupedRes after aggragation
177
 * @retval false if no more groups
178
 * @retval true if there could have new groups coming
179
 * @note if pOperator.blocking is true, scan all blocks from downstream, all groups are handled
180
 *       if false, fill results of ONE GROUP
181
 * */
182
static bool nextGroupedResult(SOperatorInfo* pOperator) {
2,422,679✔
183
  int32_t           code = TSDB_CODE_SUCCESS;
2,422,679✔
184
  int32_t           lino = 0;
2,422,679✔
185
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
2,422,679✔
186
  SAggOperatorInfo* pAggInfo = pOperator->info;
2,422,679✔
187

188
  if(!pAggInfo) {
2,422,679!
189
    qError("function:%s, pAggInfo is NULL", __func__);
×
190
    return false;
×
191
  }
192
  if (pOperator->blocking && pAggInfo->hasValidBlock) {
2,422,679✔
193
    return false;
76,031✔
194
  }
195

196
  SExprSupp*   pSup = &pOperator->exprSupp;
2,346,648✔
197
  int64_t      st = taosGetTimestampUs();
2,350,080✔
198
  int32_t      order = pAggInfo->binfo.inputTsOrder;
2,350,080✔
199
  SSDataBlock* pBlock = pAggInfo->pNewGroupBlock;
2,350,080✔
200

201
  pAggInfo->cleanGroupResInfo = false;
2,350,080✔
202
  if (pBlock) {
2,350,080✔
203
    pAggInfo->pNewGroupBlock = NULL;
49,902✔
204
    tSimpleHashClear(pAggInfo->aggSup.pResultRowHashTable);
49,902✔
205
    code = setExecutionContext(pOperator, pOperator->exprSupp.numOfExprs, pBlock->info.id.groupId);
49,902✔
206
    QUERY_CHECK_CODE(code, lino, _end);
49,902!
207
    code = setInputDataBlock(pSup, pBlock, order, pBlock->info.scanFlag, true);
49,902✔
208
    QUERY_CHECK_CODE(code, lino, _end);
49,902!
209

210
    code = doAggregateImpl(pOperator, pSup->pCtx);
49,902✔
211
    QUERY_CHECK_CODE(code, lino, _end);
49,902!
212
  }
213
  while (1) {
10,537,290✔
214
    bool blockAllocated = false;
12,887,370✔
215
    pBlock = getNextBlockFromDownstream(pOperator, 0);
12,887,370✔
216
    if (pBlock == NULL) {
12,878,158✔
217
      if (!pAggInfo->hasValidBlock) {
2,436,560✔
218
        code = createDataBlockForEmptyInput(pOperator, &pBlock);
268,203✔
219
        QUERY_CHECK_CODE(code, lino, _end);
268,152!
220

221
        if (pBlock == NULL) {
268,152✔
222
          break;
124,707✔
223
        }
224
        blockAllocated = true;
143,445✔
225
      } else {
226
        break;
2,168,357✔
227
      }
228
    }
229
    pAggInfo->hasValidBlock = true;
10,585,043✔
230
    pAggInfo->binfo.pRes->info.scanFlag = pBlock->info.scanFlag;
10,585,043✔
231

232
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
233
    if (pAggInfo->scalarExprSup.pExprInfo != NULL && !blockAllocated) {
10,585,043✔
234
      SExprSupp* pSup1 = &pAggInfo->scalarExprSup;
1,498,587✔
235
      code = projectApplyFunctions(pSup1->pExprInfo, pBlock, pBlock, pSup1->pCtx, pSup1->numOfExprs, NULL);
1,498,587✔
236
      if (code != TSDB_CODE_SUCCESS) {
1,498,596!
237
        destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
×
238
        T_LONG_JMP(pTaskInfo->env, code);
×
239
      }
240
    }
241
    // if non-blocking mode and new group arrived, save the block and break
242
    if (!pOperator->blocking && pAggInfo->groupId != UINT64_MAX && pBlock->info.id.groupId != pAggInfo->groupId) {
10,585,052✔
243
      pAggInfo->pNewGroupBlock = pBlock;
49,954✔
244
      break;
49,954✔
245
    }
246
    // the pDataBlock are always the same one, no need to call this again
247
    code = setExecutionContext(pOperator, pOperator->exprSupp.numOfExprs, pBlock->info.id.groupId);
10,535,098✔
248
    if (code != TSDB_CODE_SUCCESS) {
10,536,763✔
249
      destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
22✔
250
      T_LONG_JMP(pTaskInfo->env, code);
22!
251
    }
252
    code = setInputDataBlock(pSup, pBlock, order, pBlock->info.scanFlag, true);
10,536,741✔
253
    if (code != TSDB_CODE_SUCCESS) {
10,536,865!
254
      destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
×
255
      T_LONG_JMP(pTaskInfo->env, code);
×
256
    }
257

258
    code = doAggregateImpl(pOperator, pSup->pCtx);
10,536,865✔
259
    if (code != TSDB_CODE_SUCCESS) {
10,537,389✔
260
      destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
23✔
261
      T_LONG_JMP(pTaskInfo->env, code);
23!
262
    }
263

264
    destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
10,537,366✔
265
  }
266

267
  // the downstream operator may return with error code, so let's check the code before generating results.
268
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
2,343,018✔
269
    T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
4!
270
  }
271

272
  code = initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, 0);
2,343,014✔
273
  QUERY_CHECK_CODE(code, lino, _end);
2,342,543!
274
  pAggInfo->cleanGroupResInfo = true;
2,342,543✔
275

276
_end:
2,342,543✔
277
  if (code != TSDB_CODE_SUCCESS) {
2,342,543!
278
    qError("%s failed at line %d since %s", __func__, lino, tstrerror(code));
×
279
    pTaskInfo->code = code;
×
280
    T_LONG_JMP(pTaskInfo->env, code);
×
281
  }
282
  return pBlock != NULL;
2,342,543✔
283
}
284

285
int32_t getAggregateResultNext(SOperatorInfo* pOperator, SSDataBlock** ppRes) {
4,567,160✔
286
  int32_t           code = TSDB_CODE_SUCCESS;
4,567,160✔
287
  int32_t           lino = 0;
4,567,160✔
288
  SAggOperatorInfo* pAggInfo = pOperator->info;
4,567,160✔
289
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;
4,567,160✔
290

291
  if (pOperator->status == OP_EXEC_DONE) {
4,567,160✔
292
    (*ppRes) = NULL;
2,144,414✔
293
    return code;
2,144,414✔
294
  }
295

296
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
2,422,746✔
297
  bool           hasNewGroups = false;
2,422,746✔
298
  do {
299
    hasNewGroups = nextGroupedResult(pOperator);
2,422,774✔
300
    code = blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
2,418,229✔
301
    QUERY_CHECK_CODE(code, lino, _end);
2,419,279!
302

303
    while (1) {
304
      doBuildResultDatablock(pOperator, pInfo, &pAggInfo->groupResInfo, pAggInfo->aggSup.pResultBuf);
2,419,279✔
305
      code = doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
2,417,996✔
306
      QUERY_CHECK_CODE(code, lino, _end);
2,417,805!
307

308
      if (!hasRemainResults(&pAggInfo->groupResInfo)) {
2,417,805✔
309
        if (!hasNewGroups) setOperatorCompleted(pOperator);
2,341,732✔
310
        break;
2,342,507✔
311
      }
312

313
      if (pInfo->pRes->info.rows > 0) {
76,004!
314
        break;
76,004✔
315
      }
316
    }
317
  } while (pInfo->pRes->info.rows == 0 && hasNewGroups);
2,418,511✔
318

319
  size_t rows = blockDataGetNumOfRows(pInfo->pRes);
2,418,483✔
320
  pOperator->resultInfo.totalRows += rows;
2,418,092✔
321

322
_end:
2,418,092✔
323
  if (code != TSDB_CODE_SUCCESS) {
2,418,092!
324
    qError("%s failed at line %d since %s", __func__, lino, tstrerror(code));
×
325
    pTaskInfo->code = code;
×
326
    T_LONG_JMP(pTaskInfo->env, code);
×
327
  }
328

329
  (*ppRes) = (rows == 0) ? NULL : pInfo->pRes;
2,418,092✔
330
  return code;
2,418,092✔
331
}
332

333
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator) {
×
334
  SSDataBlock* pRes = NULL;
×
335
  int32_t code = getAggregateResultNext(pOperator, &pRes);
×
336
  return pRes;
×
337
}
338

339
int32_t doAggregateImpl(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx) {
10,585,997✔
340
  int32_t code = TSDB_CODE_SUCCESS;
10,585,997✔
341
  if (!pOperator || (pOperator->exprSupp.numOfExprs > 0 && pCtx == NULL)) {
10,585,997!
342
    qError("%s failed at line %d since pCtx is NULL.", __func__, __LINE__);
×
343
    return TSDB_CODE_QRY_EXECUTOR_INTERNAL_ERROR;
×
344
  }
345
  for (int32_t k = 0; k < pOperator->exprSupp.numOfExprs; ++k) {
24,735,483✔
346
    if (functionNeedToExecute(&pCtx[k])) {
14,147,304✔
347
      // todo add a dummy function to avoid process check
348
      if (pCtx[k].fpSet.process == NULL) {
14,146,239✔
349
        continue;
194,694✔
350
      }
351

352
      if ((&pCtx[k])->input.pData[0] == NULL) {
13,951,545!
353
        code = TSDB_CODE_QRY_EXECUTOR_INTERNAL_ERROR;
×
354
        qError("%s aggregate function error happens, input data is NULL.", GET_TASKID(pOperator->pTaskInfo));
×
355
      } else {
356
        code = pCtx[k].fpSet.process(&pCtx[k]);
13,951,545✔
357
      }
358

359
      if (code != TSDB_CODE_SUCCESS) {
13,953,234✔
360
        if (pCtx[k].fpSet.cleanup != NULL) {
23!
361
          pCtx[k].fpSet.cleanup(&pCtx[k]);
×
362
        }
363
        qError("%s aggregate function error happens, code:%s", GET_TASKID(pOperator->pTaskInfo), tstrerror(code));
23!
364
        return code;
23✔
365
      }
366
    }
367
  }
368

369
  return TSDB_CODE_SUCCESS;
10,588,179✔
370
}
371

372
static int32_t createDataBlockForEmptyInput(SOperatorInfo* pOperator, SSDataBlock** ppBlock) {
268,163✔
373
  int32_t code = TSDB_CODE_SUCCESS;
268,163✔
374
  int32_t lino = 0;
268,163✔
375
  SSDataBlock* pBlock = NULL;
268,163✔
376
  if (!tsCountAlwaysReturnValue) {
268,163✔
377
    return TSDB_CODE_SUCCESS;
48,365✔
378
  }
379

380
  SAggOperatorInfo* pAggInfo = pOperator->info;
219,798✔
381
  if (pAggInfo->groupKeyOptimized) {
219,798✔
382
    return TSDB_CODE_SUCCESS;
42,969✔
383
  }
384

385
  SOperatorInfo* downstream = pOperator->pDownstream[0];
176,829✔
386
  if (downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_PARTITION ||
176,829✔
387
      downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_SORT ||
176,543✔
388
      (downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN &&
176,270✔
389
       ((STableScanInfo*)downstream->info)->hasGroupByTag == true)) {
29,776✔
390
    return TSDB_CODE_SUCCESS;
596✔
391
  }
392

393
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
176,233✔
394

395
  if (!pAggInfo->hasCountFunc) {
176,233✔
396
    return TSDB_CODE_SUCCESS;
32,771✔
397
  }
398

399
  code = createDataBlock(&pBlock);
143,462✔
400
  if (code) {
143,483!
401
    return code;
×
402
  }
403

404
  pBlock->info.rows = 1;
143,483✔
405
  pBlock->info.capacity = 0;
143,483✔
406

407
  for (int32_t i = 0; i < pOperator->exprSupp.numOfExprs; ++i) {
298,970✔
408
    SColumnInfoData colInfo = {0};
155,513✔
409
    colInfo.hasNull = true;
155,513✔
410
    colInfo.info.type = TSDB_DATA_TYPE_NULL;
155,513✔
411
    colInfo.info.bytes = 1;
155,513✔
412

413
    SExprInfo* pOneExpr = &pOperator->exprSupp.pExprInfo[i];
155,513✔
414
    for (int32_t j = 0; j < pOneExpr->base.numOfParams; ++j) {
311,548✔
415
      SFunctParam* pFuncParam = &pOneExpr->base.pParam[j];
156,061✔
416
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
156,061✔
417
        int32_t slotId = pFuncParam->pCol->slotId;
156,002✔
418
        int32_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
156,002✔
419
        if (slotId >= numOfCols) {
155,980✔
420
          code = taosArrayEnsureCap(pBlock->pDataBlock, slotId + 1);
144,463✔
421
          QUERY_CHECK_CODE(code, lino, _end);
144,449!
422

423
          for (int32_t k = numOfCols; k < slotId + 1; ++k) {
293,672✔
424
            void* tmp = taosArrayPush(pBlock->pDataBlock, &colInfo);
149,213✔
425
            QUERY_CHECK_NULL(tmp, code, lino, _end, terrno);
149,223!
426
          }
427
        }
428
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
59✔
429
        // do nothing
430
      }
431
    }
432
  }
433

434
  code = blockDataEnsureCapacity(pBlock, pBlock->info.rows);
143,457✔
435
  QUERY_CHECK_CODE(code, lino, _end);
143,505!
436

437
  for (int32_t i = 0; i < blockDataGetNumOfCols(pBlock); ++i) {
292,689✔
438
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
149,158✔
439
    QUERY_CHECK_NULL(pColInfoData, code, lino, _end, terrno);
149,177!
440
    colDataSetNULL(pColInfoData, 0);
441
  }
442
  *ppBlock = pBlock;
143,468✔
443

444
_end:
143,468✔
445
  if (code != TSDB_CODE_SUCCESS) {
143,468!
446
    blockDataDestroy(pBlock);
×
447
    qError("%s failed at line %d since %s", __func__, __LINE__, tstrerror(code));
×
448
  }
449
  return code;
143,445✔
450
}
451

452
void destroyDataBlockForEmptyInput(bool blockAllocated, SSDataBlock** ppBlock) {
10,537,352✔
453
  if (!blockAllocated) {
10,537,352✔
454
    return;
10,394,150✔
455
  }
456

457
  blockDataDestroy(*ppBlock);
143,202✔
458
  *ppBlock = NULL;
143,516✔
459
}
460

461
int32_t setExecutionContext(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId) {
10,586,682✔
462
  int32_t           code = TSDB_CODE_SUCCESS;
10,586,682✔
463
  SAggOperatorInfo* pAggInfo = pOperator->info;
10,586,682✔
464
  if (pAggInfo->groupId != UINT64_MAX && pAggInfo->groupId == groupId) {
10,586,682✔
465
    return code;
7,692,214✔
466
  }
467

468
  code = doSetTableGroupOutputBuf(pOperator, numOfOutput, groupId);
2,894,468✔
469

470
  // record the current active group id
471
  pAggInfo->groupId = groupId;
2,894,695✔
472
  return code;
2,894,695✔
473
}
474

475
int32_t doSetTableGroupOutputBuf(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId) {
2,895,171✔
476
  // for simple group by query without interval, all the tables belong to one group result.
477
  int32_t           code = TSDB_CODE_SUCCESS;
2,895,171✔
478
  int32_t           lino = 0;
2,895,171✔
479
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
2,895,171✔
480
  SAggOperatorInfo* pAggInfo = pOperator->info;
2,895,171✔
481

482
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
2,895,171✔
483
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
2,895,171✔
484
  int32_t*        rowEntryInfoOffset = pOperator->exprSupp.rowEntryInfoOffset;
2,895,171✔
485

486
  SResultRow* pResultRow =
487
      doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId, sizeof(groupId), true,
2,895,171✔
488
                             groupId, pTaskInfo, false, &pAggInfo->aggSup, true);
489
  if (pResultRow == NULL || pTaskInfo->code != 0) {
2,895,842!
490
    code = pTaskInfo->code;
×
491
    lino = __LINE__;
×
492
    goto _end;
×
493
  }
494
  /*
495
   * not assign result buffer yet, add new result buffer
496
   * all group belong to one result set, and each group result has different group id so set the id to be one
497
   */
498
  if (pResultRow->pageId == -1) {
2,895,868!
499
    code = addNewResultRowBuf(pResultRow, pAggInfo->aggSup.pResultBuf, pAggInfo->binfo.pRes->info.rowSize);
×
500
    QUERY_CHECK_CODE(code, lino, _end);
×
501
  }
502

503
  code = setResultRowInitCtx(pResultRow, pCtx, numOfOutput, rowEntryInfoOffset);
2,895,868✔
504
  QUERY_CHECK_CODE(code, lino, _end);
2,894,621!
505

506
_end:
2,894,621✔
507
  if (code != TSDB_CODE_SUCCESS) {
2,894,595✔
508
    qError("%s failed at line %d since %s", __func__, lino, tstrerror(code));
22!
509
  }
510
  return code;
2,894,621✔
511
}
512

513
// a new buffer page for each table. Needs to opt this design
514
int32_t addNewResultRowBuf(SResultRow* pWindowRes, SDiskbasedBuf* pResultBuf, uint32_t size) {
×
515
  if (pWindowRes->pageId != -1) {
×
516
    return 0;
×
517
  }
518

519
  SFilePage* pData = NULL;
×
520

521
  // in the first scan, new space needed for results
522
  int32_t pageId = -1;
×
523
  SArray* list = getDataBufPagesIdList(pResultBuf);
×
524

525
  if (taosArrayGetSize(list) == 0) {
×
526
    pData = getNewBufPage(pResultBuf, &pageId);
×
527
    if (pData == NULL) {
×
528
      qError("failed to get buffer, code:%s", tstrerror(terrno));
×
529
      return terrno;
×
530
    }
531
    pData->num = sizeof(SFilePage);
×
532
  } else {
533
    SPageInfo* pi = getLastPageInfo(list);
×
534
    pData = getBufPage(pResultBuf, getPageId(pi));
×
535
    if (pData == NULL) {
×
536
      qError("failed to get buffer, code:%s", tstrerror(terrno));
×
537
      return terrno;
×
538
    }
539

540
    pageId = getPageId(pi);
×
541

542
    if (pData->num + size > getBufPageSize(pResultBuf)) {
×
543
      // release current page first, and prepare the next one
544
      releaseBufPageInfo(pResultBuf, pi);
×
545

546
      pData = getNewBufPage(pResultBuf, &pageId);
×
547
      if (pData == NULL) {
×
548
        qError("failed to get buffer, code:%s", tstrerror(terrno));
×
549
        return terrno;
×
550
      }
551
      pData->num = sizeof(SFilePage);
×
552
    }
553
  }
554

555
  if (pData == NULL) {
×
556
    return -1;
×
557
  }
558

559
  // set the number of rows in current disk page
560
  if (pWindowRes->pageId == -1) {  // not allocated yet, allocate new buffer
×
561
    pWindowRes->pageId = pageId;
×
562
    pWindowRes->offset = (int32_t)pData->num;
×
563

564
    pData->num += size;
×
565
  }
566

567
  return 0;
×
568
}
569

570
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
7,179,455✔
571
                         const char* pKey) {
572
  int32_t code = 0;
7,179,455✔
573
  //  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);
574

575
  pAggSup->currentPageId = -1;
7,179,455✔
576
  pAggSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
7,179,455✔
577
  pAggSup->keyBuf = taosMemoryCalloc(1, keyBufSize + POINTER_BYTES + sizeof(int64_t));
7,189,302!
578
  pAggSup->pResultRowHashTable = tSimpleHashInit(100, taosFastHash);
7,190,724✔
579

580
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
7,182,586!
581
    return terrno;
×
582
  }
583

584
  uint32_t defaultPgsz = 0;
7,183,037✔
585
  int64_t defaultBufsz = 0;
7,183,037✔
586
  code = getBufferPgSize(pAggSup->resultRowSize, &defaultPgsz, &defaultBufsz);
7,183,037✔
587
  if (code) {
7,187,544!
588
    qError("failed to get buff page size, rowSize:%d", pAggSup->resultRowSize);
×
589
    return code;
×
590
  }
591

592
  if (!osTempSpaceAvailable()) {
7,187,544!
593
    code = TSDB_CODE_NO_DISKSPACE;
×
594
    qError("Init stream agg supporter failed since %s, key:%s, tempDir:%s", tstrerror(code), pKey, tsTempDir);
×
595
    return code;
×
596
  }
597

598
  code = createDiskbasedBuf(&pAggSup->pResultBuf, defaultPgsz, defaultBufsz, pKey, tsTempDir);
7,185,648✔
599
  if (code != TSDB_CODE_SUCCESS) {
7,190,155✔
600
    qError("Create agg result buf failed since %s, %s", tstrerror(code), pKey);
1,173!
601
    return code;
×
602
  }
603

604
  return code;
7,188,982✔
605
}
606

607
void cleanupResultInfoInStream(SExecTaskInfo* pTaskInfo, void* pState, SExprSupp* pSup, SGroupResInfo* pGroupResInfo) {
2,198✔
608
  int32_t         code = TSDB_CODE_SUCCESS;
2,198✔
609
  SStorageAPI*    pAPI = &pTaskInfo->storageAPI;
2,198✔
610
  int32_t         numOfExprs = pSup->numOfExprs;
2,198✔
611
  int32_t*        rowEntryOffset = pSup->rowEntryInfoOffset;
2,198✔
612
  SqlFunctionCtx* pCtx = pSup->pCtx;
2,198✔
613
  int32_t         numOfRows = getNumOfTotalRes(pGroupResInfo);
2,198✔
614
  bool            needCleanup = false;
2,198✔
615

616
  for (int32_t j = 0; j < numOfExprs; ++j) {
31,205✔
617
    needCleanup |= pCtx[j].needCleanup;
29,007✔
618
  }
619
  if (!needCleanup) {
2,198!
620
    return;
2,198✔
621
  }
622
  
623
  for (int32_t i = pGroupResInfo->index; i < numOfRows; i += 1) {
×
624
    SResultWindowInfo* pWinInfo = taosArrayGet(pGroupResInfo->pRows, i);
×
625
    SRowBuffPos*       pPos = pWinInfo->pStatePos;
×
626
    SResultRow*        pRow = NULL;
×
627

628
    code = pAPI->stateStore.streamStateGetByPos(pState, pPos, (void**)&pRow);
×
629
    if (TSDB_CODE_SUCCESS != code) {
×
630
      qError("failed to get state by pos, code:%s, %s", tstrerror(code), GET_TASKID(pTaskInfo));
×
631
      continue;
×
632
    }
633

634
    for (int32_t j = 0; j < numOfExprs; ++j) {
×
635
      pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowEntryOffset);
×
636
      if (pCtx[j].fpSet.cleanup) {
×
637
        pCtx[j].fpSet.cleanup(&pCtx[j]);
×
638
      }
639
    }
640
  }
641
}
642

643
void cleanupResultInfoInGroupResInfo(SExecTaskInfo* pTaskInfo, SExprSupp* pSup, SDiskbasedBuf* pBuf,
3,955,125✔
644
                                  SGroupResInfo* pGroupResInfo) {
645
  int32_t         numOfExprs = pSup->numOfExprs;
3,955,125✔
646
  int32_t*        rowEntryOffset = pSup->rowEntryInfoOffset;
3,955,125✔
647
  SqlFunctionCtx* pCtx = pSup->pCtx;
3,955,125✔
648
  int32_t         numOfRows = getNumOfTotalRes(pGroupResInfo);
3,955,125✔
649
  bool            needCleanup = false;
3,955,346✔
650

651
  for (int32_t j = 0; j < numOfExprs; ++j) {
11,583,996✔
652
    needCleanup |= pCtx[j].needCleanup;
7,628,650✔
653
  }
654
  if (!needCleanup) {
3,955,346✔
655
    return;
3,935,162✔
656
  }
657

658
  for (int32_t i = pGroupResInfo->index; i < numOfRows; i += 1) {
20,184!
659
    SResultRow*        pRow = NULL;
×
660
    SResKeyPos*        pPos = taosArrayGetP(pGroupResInfo->pRows, i);
×
661
    SFilePage*         page = getBufPage(pBuf, pPos->pos.pageId);
×
662
    if (page == NULL) {
×
663
      qError("failed to get buffer, code:%s, %s", tstrerror(terrno), GET_TASKID(pTaskInfo));
×
664
      continue;
×
665
    }
666
    pRow = (SResultRow*)((char*)page + pPos->pos.offset);
×
667

668

669
    for (int32_t j = 0; j < numOfExprs; ++j) {
×
670
      pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowEntryOffset);
×
671
      if (pCtx[j].fpSet.cleanup) {
×
672
        pCtx[j].fpSet.cleanup(&pCtx[j]);
×
673
      }
674
    }
675
    releaseBufPage(pBuf, page);
×
676
  }
677
}
678

679
void cleanupResultInfoInHashMap(SExecTaskInfo* pTaskInfo, SExprSupp* pSup, SDiskbasedBuf* pBuf,
954,772✔
680
                       SGroupResInfo* pGroupResInfo, SSHashObj* pHashmap) {
681
  int32_t         numOfExprs = pSup->numOfExprs;
954,772✔
682
  int32_t*        rowEntryOffset = pSup->rowEntryInfoOffset;
954,772✔
683
  SqlFunctionCtx* pCtx = pSup->pCtx;
954,772✔
684
  bool            needCleanup = false;
954,772✔
685
  for (int32_t j = 0; j < numOfExprs; ++j) {
3,033,356✔
686
    needCleanup |= pCtx[j].needCleanup;
2,078,584✔
687
  }
688
  if (!needCleanup) {
954,772✔
689
    return;
953,428✔
690
  }
691

692
  // begin from last iter
693
  void*   pData = pGroupResInfo->dataPos;
1,344✔
694
  int32_t iter = pGroupResInfo->iter;
1,344✔
695
  while ((pData = tSimpleHashIterate(pHashmap, pData, &iter)) != NULL) {
1,344!
696
    SResultRowPosition* pos = pData;
×
697

698
    SFilePage* page = getBufPage(pBuf, pos->pageId);
×
699
    if (page == NULL) {
×
700
      qError("failed to get buffer, code:%s, %s", tstrerror(terrno), GET_TASKID(pTaskInfo));
×
701
      continue;
×
702
    }
703

704
    SResultRow* pRow = (SResultRow*)((char*)page + pos->offset);
×
705

706
    for (int32_t j = 0; j < numOfExprs; ++j) {
×
707
      pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowEntryOffset);
×
708
      if (pCtx[j].fpSet.cleanup) {
×
709
        pCtx[j].fpSet.cleanup(&pCtx[j]);
×
710
      }
711
    }
712

713
    releaseBufPage(pBuf, page);
×
714
  }
715
}
716

717
void cleanupResultInfo(SExecTaskInfo* pTaskInfo, SExprSupp* pSup, SGroupResInfo* pGroupResInfo,
4,909,825✔
718
                       SAggSupporter *pAggSup, bool cleanGroupResInfo) {
719
  if (cleanGroupResInfo) {
4,909,825✔
720
    cleanupResultInfoInGroupResInfo(pTaskInfo, pSup, pAggSup->pResultBuf, pGroupResInfo);
3,955,501✔
721
  } else {
722
    cleanupResultInfoInHashMap(pTaskInfo, pSup, pAggSup->pResultBuf, pGroupResInfo, pAggSup->pResultRowHashTable);
954,324✔
723
  }
724
}
4,910,641✔
725
void cleanupAggSup(SAggSupporter* pAggSup) {
7,193,084✔
726
  taosMemoryFreeClear(pAggSup->keyBuf);
7,193,084!
727
  tSimpleHashCleanup(pAggSup->pResultRowHashTable);
7,193,821✔
728
  destroyDiskbasedBuf(pAggSup->pResultBuf);
7,194,355✔
729
}
7,194,717✔
730

731
int32_t initAggSup(SExprSupp* pSup, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols, size_t keyBufSize,
7,184,470✔
732
                   const char* pkey, void* pState, SFunctionStateStore* pStore) {
733
  int32_t code = initExprSupp(pSup, pExprInfo, numOfCols, pStore);
7,184,470✔
734
  if (code != TSDB_CODE_SUCCESS) {
7,185,115!
735
    return code;
×
736
  }
737

738
  code = doInitAggInfoSup(pAggSup, pSup->pCtx, numOfCols, keyBufSize, pkey);
7,185,115✔
739
  if (code != TSDB_CODE_SUCCESS) {
7,189,204!
740
    return code;
×
741
  }
742

743
  for (int32_t i = 0; i < numOfCols; ++i) {
28,711,955✔
744
    pSup->pCtx[i].hasWindowOrGroup = pSup->hasWindowOrGroup;
21,522,751✔
745
    if (pState) {
21,522,751✔
746
      pSup->pCtx[i].saveHandle.pBuf = NULL;
253,417✔
747
      pSup->pCtx[i].saveHandle.pState = pState;
253,417✔
748
      pSup->pCtx[i].exprIdx = i;
253,417✔
749
    } else {
750
      pSup->pCtx[i].saveHandle.pBuf = pAggSup->pResultBuf;
21,269,334✔
751
    }
752
  }
753

754
  return TSDB_CODE_SUCCESS;
7,189,204✔
755
}
756

757
int32_t applyAggFunctionOnPartialTuples(SExecTaskInfo* taskInfo, SqlFunctionCtx* pCtx, SColumnInfoData* pTimeWindowData,
479,237,395✔
758
                                        int32_t offset, int32_t forwardStep, int32_t numOfTotal, int32_t numOfOutput) {
759
  int32_t code = TSDB_CODE_SUCCESS;
479,237,395✔
760
  for (int32_t k = 0; k < numOfOutput; ++k) {
1,777,614,066✔
761
    // keep it temporarily
762
    SFunctionCtxStatus status = {0};
1,299,841,822✔
763
    functionCtxSave(&pCtx[k], &status);
1,299,841,822✔
764

765
    pCtx[k].input.startRowIndex = offset;
1,296,568,058✔
766
    pCtx[k].input.numOfRows = forwardStep;
1,296,568,058✔
767

768
    // not a whole block involved in query processing, statistics data can not be used
769
    // NOTE: the original value of isSet have been changed here
770
    if (pCtx[k].input.colDataSMAIsSet && forwardStep < numOfTotal) {
1,296,568,058!
771
      pCtx[k].input.colDataSMAIsSet = false;
×
772
    }
773

774
    if (pCtx[k].isPseudoFunc) {
1,296,568,058✔
775
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
307,537,210✔
776

777
      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);
307,537,210✔
778

779
      SColumnInfoData idata = {0};
307,537,210✔
780
      idata.info.type = TSDB_DATA_TYPE_BIGINT;
307,537,210✔
781
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
307,537,210✔
782
      idata.pData = p;
307,537,210✔
783

784
      SScalarParam out = {.columnData = &idata};
307,537,210✔
785
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
307,537,210✔
786
      code = pCtx[k].sfp.process(&tw, 1, &out);
307,537,210✔
787
      if (code != TSDB_CODE_SUCCESS) {
312,761,309✔
788
        qError("%s failed at line %d since %s", __func__, __LINE__, tstrerror(code));
371,759!
789
        taskInfo->code = code;
×
790
        return code;
×
791
      }
792
      pEntryInfo->numOfRes = 1;
312,389,550✔
793
    } else {
794
      if (functionNeedToExecute(&pCtx[k]) && pCtx[k].fpSet.process != NULL) {
989,030,848✔
795
        if ((&pCtx[k])->input.pData[0] == NULL) {
772,957,246!
796
          code = TSDB_CODE_QRY_EXECUTOR_INTERNAL_ERROR;
×
797
          qError("%s apply functions error, input data is NULL.", GET_TASKID(taskInfo));
×
798
        } else {
799
          code = pCtx[k].fpSet.process(&pCtx[k]);
772,957,246✔
800
        }
801

802
        if (code != TSDB_CODE_SUCCESS) {
774,280,569!
803
          if (pCtx[k].fpSet.cleanup != NULL) {
×
804
            pCtx[k].fpSet.cleanup(&pCtx[k]);
×
805
          }
806
          qError("%s apply functions error, code:%s", GET_TASKID(taskInfo), tstrerror(code));
×
807
          taskInfo->code = code;
×
808
          return code;
×
809
        }
810
      }
811

812
      // restore it
813
      functionCtxRestore(&pCtx[k], &status);
1,001,853,771✔
814
    }
815
  }
816
  return code;
477,772,244✔
817
}
818

819
void functionCtxSave(SqlFunctionCtx* pCtx, SFunctionCtxStatus* pStatus) {
1,300,259,760✔
820
  pStatus->hasAgg = pCtx->input.colDataSMAIsSet;
1,300,259,760✔
821
  pStatus->numOfRows = pCtx->input.numOfRows;
1,300,259,760✔
822
  pStatus->startOffset = pCtx->input.startRowIndex;
1,300,259,760✔
823
}
1,300,259,760✔
824

825
void functionCtxRestore(SqlFunctionCtx* pCtx, SFunctionCtxStatus* pStatus) {
1,001,387,088✔
826
  pCtx->input.colDataSMAIsSet = pStatus->hasAgg;
1,001,387,088✔
827
  pCtx->input.numOfRows = pStatus->numOfRows;
1,001,387,088✔
828
  pCtx->input.startRowIndex = pStatus->startOffset;
1,001,387,088✔
829
}
1,001,387,088✔
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