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

taosdata / TDengine / #4513

17 Jul 2025 02:02AM UTC coverage: 31.359% (-31.1%) from 62.446%
#4513

push

travis-ci

web-flow
Merge pull request #31914 from taosdata/fix/3.0/compare-ans-failed

fix:Convert line endings from LF to CRLF for ans file

68541 of 301034 branches covered (22.77%)

Branch coverage included in aggregate %.

117356 of 291771 relevant lines covered (40.22%)

602262.98 hits per line

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

51.44
/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
static int32_t resetAggregateOperatorState(SOperatorInfo* pOper);
75

76
int32_t createAggregateOperatorInfo(SOperatorInfo* downstream, SAggPhysiNode* pAggNode, SExecTaskInfo* pTaskInfo,
393✔
77
                                    SOperatorInfo** pOptrInfo) {
78
  QRY_PARAM_CHECK(pOptrInfo);
393!
79

80
  int32_t    lino = 0;
393✔
81
  int32_t    code = 0;
393✔
82
  int32_t    num = 0;
393✔
83
  SExprInfo* pExprInfo = NULL;
393✔
84
  int32_t    numOfScalarExpr = 0;
393✔
85
  SExprInfo* pScalarExprInfo = NULL;
393✔
86

87
  SAggOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SAggOperatorInfo));
393!
88
  SOperatorInfo*    pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
393!
89
  if (pInfo == NULL || pOperator == NULL) {
393!
90
    code = terrno;
×
91
    goto _error;
×
92
  }
93

94
  pOperator->exprSupp.hasWindowOrGroup = false;
393✔
95

96
  SSDataBlock* pResBlock = createDataBlockFromDescNode(pAggNode->node.pOutputDataBlockDesc);
393✔
97
  QUERY_CHECK_NULL(pResBlock, code, lino, _error, terrno);
393!
98
  initBasicInfo(&pInfo->binfo, pResBlock);
393✔
99

100
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
393✔
101
  initResultSizeInfo(&pOperator->resultInfo, 4096);
393✔
102

103

104
  code = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &pExprInfo, &num);
393✔
105
  TSDB_CHECK_CODE(code, lino, _error);
393!
106

107
  code = initAggSup(&pOperator->exprSupp, &pInfo->aggSup, pExprInfo, num, keyBufSize, pTaskInfo->id.str,
393✔
108
                               pTaskInfo->streamInfo.pState, &pTaskInfo->storageAPI.functionStore);
393✔
109
  TSDB_CHECK_CODE(code, lino, _error);
393!
110

111
  if (pAggNode->pExprs != NULL) {
393✔
112
    code = createExprInfo(pAggNode->pExprs, NULL, &pScalarExprInfo, &numOfScalarExpr);
2✔
113
    TSDB_CHECK_CODE(code, lino, _error);
2!
114
  }
115

116
  code = initExprSupp(&pInfo->scalarExprSup, pScalarExprInfo, numOfScalarExpr, &pTaskInfo->storageAPI.functionStore);
393✔
117
  TSDB_CHECK_CODE(code, lino, _error);
393!
118

119
  code = filterInitFromNode((SNode*)pAggNode->node.pConditions, &pOperator->exprSupp.pFilterInfo, 0,
393✔
120
                            GET_STM_RTINFO(pTaskInfo));
393!
121
  TSDB_CHECK_CODE(code, lino, _error);
393!
122

123
  pInfo->binfo.mergeResultBlock = pAggNode->mergeDataBlock;
393✔
124
  pInfo->groupKeyOptimized = pAggNode->groupKeyOptimized;
393✔
125
  pInfo->groupId = UINT64_MAX;
393✔
126
  pInfo->binfo.inputTsOrder = pAggNode->node.inputTsOrder;
393✔
127
  pInfo->binfo.outputTsOrder = pAggNode->node.outputTsOrder;
393✔
128
  pInfo->hasCountFunc = pAggNode->hasCountLikeFunc;
393✔
129
  pInfo->pOperator = pOperator;
393✔
130
  pInfo->cleanGroupResInfo = false;
393✔
131

132
  setOperatorInfo(pOperator, "TableAggregate", QUERY_NODE_PHYSICAL_PLAN_HASH_AGG,
393✔
133
                  !pAggNode->node.forceCreateNonBlockingOptr, OP_NOT_OPENED, pInfo, pTaskInfo);
393✔
134
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, getAggregateResultNext, NULL, destroyAggOperatorInfo,
393✔
135
                                         optrDefaultBufFn, NULL, optrDefaultGetNextExtFn, NULL);
136
  setOperatorResetStateFn(pOperator, resetAggregateOperatorState);
393✔
137

138
  pOperator->pPhyNode = pAggNode;
393✔
139

140
  if (downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN) {
393✔
141
    STableScanInfo* pTableScanInfo = downstream->info;
9✔
142
    pTableScanInfo->base.pdInfo.pExprSup = &pOperator->exprSupp;
9✔
143
    pTableScanInfo->base.pdInfo.pAggSup = &pInfo->aggSup;
9✔
144
  }
145

146
  code = appendDownstream(pOperator, &downstream, 1);
393✔
147
  if (code != TSDB_CODE_SUCCESS) {
393!
148
    goto _error;
×
149
  }
150

151
  *pOptrInfo = pOperator;
393✔
152
  return TSDB_CODE_SUCCESS;
393✔
153

154
_error:
×
155
  qError("%s failed at line %d since %s", __func__, lino, tstrerror(code));
×
156
  if (pInfo != NULL) {
×
157
    destroyAggOperatorInfo(pInfo);
×
158
  }
159
  destroyOperatorAndDownstreams(pOperator, &downstream, 1);
×
160
  pTaskInfo->code = code;
×
161
  return code;
×
162
}
163

164
void destroyAggOperatorInfo(void* param) {
393✔
165
  if (param == NULL) {
393!
166
    return;
×
167
  }
168
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
393✔
169
  cleanupBasicInfo(&pInfo->binfo);
393✔
170

171
  if (pInfo->pOperator) {
393!
172
    cleanupResultInfo(pInfo->pOperator->pTaskInfo, &pInfo->pOperator->exprSupp, &pInfo->groupResInfo, &pInfo->aggSup,
393✔
173
                      pInfo->cleanGroupResInfo);
393✔
174
    pInfo->pOperator = NULL;
393✔
175
  }
176
  cleanupAggSup(&pInfo->aggSup);
393✔
177
  cleanupExprSuppWithoutFilter(&pInfo->scalarExprSup);
393✔
178
  cleanupGroupResInfo(&pInfo->groupResInfo);
393✔
179
  taosMemoryFreeClear(param);
393!
180
}
181

182
/**
183
 * @brief get blocks from downstream and fill results into groupedRes after aggragation
184
 * @retval false if no more groups
185
 * @retval true if there could have new groups coming
186
 * @note if pOperator.blocking is true, scan all blocks from downstream, all groups are handled
187
 *       if false, fill results of ONE GROUP
188
 * */
189
static bool nextGroupedResult(SOperatorInfo* pOperator) {
1,513✔
190
  int32_t           code = TSDB_CODE_SUCCESS;
1,513✔
191
  int32_t           lino = 0;
1,513✔
192
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
1,513✔
193
  SAggOperatorInfo* pAggInfo = pOperator->info;
1,513✔
194

195
  if(!pAggInfo) {
1,513!
196
    qError("function:%s, pAggInfo is NULL", __func__);
×
197
    return false;
×
198
  }
199
  if (pOperator->blocking && pAggInfo->hasValidBlock) {
1,513✔
200
    return false;
8✔
201
  }
202

203
  SExprSupp*   pSup = &pOperator->exprSupp;
1,505✔
204
  int64_t      st = taosGetTimestampUs();
1,505✔
205
  int32_t      order = pAggInfo->binfo.inputTsOrder;
1,505✔
206
  SSDataBlock* pBlock = pAggInfo->pNewGroupBlock;
1,505✔
207

208
  pAggInfo->cleanGroupResInfo = false;
1,505✔
209
  if (pBlock) {
1,505✔
210
    pAggInfo->pNewGroupBlock = NULL;
1,112✔
211
    tSimpleHashClear(pAggInfo->aggSup.pResultRowHashTable);
1,112✔
212
    code = setExecutionContext(pOperator, pOperator->exprSupp.numOfExprs, pBlock->info.id.groupId);
1,112✔
213
    QUERY_CHECK_CODE(code, lino, _end);
1,112!
214
    code = setInputDataBlock(pSup, pBlock, order, pBlock->info.scanFlag, true);
1,112✔
215
    QUERY_CHECK_CODE(code, lino, _end);
1,112!
216

217
    code = doAggregateImpl(pOperator, pSup->pCtx);
1,112✔
218
    QUERY_CHECK_CODE(code, lino, _end);
1,112!
219
  }
220
  while (1) {
491✔
221
    bool blockAllocated = false;
1,996✔
222
    pBlock = getNextBlockFromDownstream(pOperator, 0);
1,996✔
223
    if (pBlock == NULL) {
1,996✔
224
      if (!pAggInfo->hasValidBlock) {
423✔
225
        code = createDataBlockForEmptyInput(pOperator, &pBlock);
35✔
226
        QUERY_CHECK_CODE(code, lino, _end);
35!
227

228
        if (pBlock == NULL) {
35✔
229
          break;
3✔
230
        }
231
        blockAllocated = true;
32✔
232
      } else {
233
        break;
388✔
234
      }
235
    }
236
    pAggInfo->hasValidBlock = true;
1,605✔
237
    pAggInfo->binfo.pRes->info.scanFlag = pBlock->info.scanFlag;
1,605✔
238

239
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
240
    if (pAggInfo->scalarExprSup.pExprInfo != NULL && !blockAllocated) {
1,605!
241
      SExprSupp* pSup1 = &pAggInfo->scalarExprSup;
2✔
242
      code = projectApplyFunctions(pSup1->pExprInfo, pBlock, pBlock, pSup1->pCtx, pSup1->numOfExprs, NULL, GET_STM_RTINFO(pOperator->pTaskInfo));
2!
243
      if (code != TSDB_CODE_SUCCESS) {
2!
244
        destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
×
245
        T_LONG_JMP(pTaskInfo->env, code);
×
246
      }
247
    }
248
    // if non-blocking mode and new group arrived, save the block and break
249
    if (!pOperator->blocking && pAggInfo->groupId != UINT64_MAX && pBlock->info.id.groupId != pAggInfo->groupId) {
1,605!
250
      pAggInfo->pNewGroupBlock = pBlock;
1,114✔
251
      break;
1,114✔
252
    }
253
    // the pDataBlock are always the same one, no need to call this again
254
    code = setExecutionContext(pOperator, pOperator->exprSupp.numOfExprs, pBlock->info.id.groupId);
491✔
255
    if (code != TSDB_CODE_SUCCESS) {
491!
256
      destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
×
257
      T_LONG_JMP(pTaskInfo->env, code);
×
258
    }
259
    code = setInputDataBlock(pSup, pBlock, order, pBlock->info.scanFlag, true);
491✔
260
    if (code != TSDB_CODE_SUCCESS) {
491!
261
      destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
×
262
      T_LONG_JMP(pTaskInfo->env, code);
×
263
    }
264

265
    code = doAggregateImpl(pOperator, pSup->pCtx);
491✔
266
    if (code != TSDB_CODE_SUCCESS) {
491!
267
      destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
×
268
      T_LONG_JMP(pTaskInfo->env, code);
×
269
    }
270

271
    destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
491✔
272
  }
273

274
  // the downstream operator may return with error code, so let's check the code before generating results.
275
  if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
1,505!
276
    T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
×
277
  }
278

279
  code = initGroupedResultInfo(&pAggInfo->groupResInfo, pAggInfo->aggSup.pResultRowHashTable, 0);
1,505✔
280
  QUERY_CHECK_CODE(code, lino, _end);
1,505!
281
  pAggInfo->cleanGroupResInfo = true;
1,505✔
282

283
_end:
1,505✔
284
  if (code != TSDB_CODE_SUCCESS) {
1,505!
285
    qError("%s failed at line %d since %s", __func__, lino, tstrerror(code));
×
286
    pTaskInfo->code = code;
×
287
    T_LONG_JMP(pTaskInfo->env, code);
×
288
  }
289
  return pBlock != NULL;
1,505✔
290
}
291

292
int32_t getAggregateResultNext(SOperatorInfo* pOperator, SSDataBlock** ppRes) {
1,873✔
293
  int32_t           code = TSDB_CODE_SUCCESS;
1,873✔
294
  int32_t           lino = 0;
1,873✔
295
  SAggOperatorInfo* pAggInfo = pOperator->info;
1,873✔
296
  SOptrBasicInfo*   pInfo = &pAggInfo->binfo;
1,873✔
297

298
  if (pOperator->status == OP_EXEC_DONE) {
1,873✔
299
    (*ppRes) = NULL;
388✔
300
    return code;
388✔
301
  }
302

303
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
1,485✔
304
  bool           hasNewGroups = false;
1,485✔
305
  do {
306
    hasNewGroups = nextGroupedResult(pOperator);
1,513✔
307
    code = blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
1,513✔
308
    QUERY_CHECK_CODE(code, lino, _end);
1,513!
309

310
    while (1) {
311
      doBuildResultDatablock(pOperator, pInfo, &pAggInfo->groupResInfo, pAggInfo->aggSup.pResultBuf);
1,513✔
312
      code = doFilter(pInfo->pRes, pOperator->exprSupp.pFilterInfo, NULL);
1,513✔
313
      QUERY_CHECK_CODE(code, lino, _end);
1,513!
314

315
      if (!hasRemainResults(&pAggInfo->groupResInfo)) {
1,513✔
316
        if (!hasNewGroups) setOperatorCompleted(pOperator);
1,505✔
317
        break;
1,505✔
318
      }
319

320
      if (pInfo->pRes->info.rows > 0) {
8!
321
        break;
8✔
322
      }
323
    }
324
  } while (pInfo->pRes->info.rows == 0 && hasNewGroups);
1,513✔
325

326
  size_t rows = blockDataGetNumOfRows(pInfo->pRes);
1,485✔
327
  pOperator->resultInfo.totalRows += rows;
1,485✔
328

329
_end:
1,485✔
330
  if (code != TSDB_CODE_SUCCESS) {
1,485!
331
    qError("%s failed at line %d since %s", __func__, lino, tstrerror(code));
×
332
    pTaskInfo->code = code;
×
333
    T_LONG_JMP(pTaskInfo->env, code);
×
334
  }
335

336
  (*ppRes) = (rows == 0) ? NULL : pInfo->pRes;
1,485✔
337
  return code;
1,485✔
338
}
339

340
static SSDataBlock* getAggregateResult(SOperatorInfo* pOperator) {
×
341
  SSDataBlock* pRes = NULL;
×
342
  int32_t code = getAggregateResultNext(pOperator, &pRes);
×
343
  return pRes;
×
344
}
345

346
int32_t doAggregateImpl(SOperatorInfo* pOperator, SqlFunctionCtx* pCtx) {
1,603✔
347
  int32_t code = TSDB_CODE_SUCCESS;
1,603✔
348
  if (!pOperator || (pOperator->exprSupp.numOfExprs > 0 && pCtx == NULL)) {
1,603!
349
    qError("%s failed at line %d since pCtx is NULL.", __func__, __LINE__);
×
350
    return TSDB_CODE_QRY_EXECUTOR_INTERNAL_ERROR;
×
351
  }
352
  for (int32_t k = 0; k < pOperator->exprSupp.numOfExprs; ++k) {
4,164✔
353
    if (functionNeedToExecute(&pCtx[k])) {
2,561!
354
      // todo add a dummy function to avoid process check
355
      if (pCtx[k].fpSet.process == NULL) {
2,561!
356
        continue;
×
357
      }
358

359
      if ((&pCtx[k])->input.pData[0] == NULL) {
2,561!
360
        code = TSDB_CODE_QRY_EXECUTOR_INTERNAL_ERROR;
×
361
        qError("%s aggregate function error happens, input data is NULL.", GET_TASKID(pOperator->pTaskInfo));
×
362
      } else {
363
        code = pCtx[k].fpSet.process(&pCtx[k]);
2,561✔
364
      }
365

366
      if (code != TSDB_CODE_SUCCESS) {
2,561!
367
        if (pCtx[k].fpSet.cleanup != NULL) {
×
368
          pCtx[k].fpSet.cleanup(&pCtx[k]);
×
369
        }
370
        qError("%s aggregate function error happens, code:%s", GET_TASKID(pOperator->pTaskInfo), tstrerror(code));
×
371
        return code;
×
372
      }
373
    }
374
  }
375

376
  return TSDB_CODE_SUCCESS;
1,603✔
377
}
378

379
static int32_t createDataBlockForEmptyInput(SOperatorInfo* pOperator, SSDataBlock** ppBlock) {
35✔
380
  int32_t code = TSDB_CODE_SUCCESS;
35✔
381
  int32_t lino = 0;
35✔
382
  SSDataBlock* pBlock = NULL;
35✔
383
  if (!tsCountAlwaysReturnValue) {
35!
384
    return TSDB_CODE_SUCCESS;
×
385
  }
386

387
  SAggOperatorInfo* pAggInfo = pOperator->info;
35✔
388
  if (pAggInfo->groupKeyOptimized) {
35!
389
    return TSDB_CODE_SUCCESS;
×
390
  }
391

392
  SOperatorInfo* downstream = pOperator->pDownstream[0];
35✔
393
  if (downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_PARTITION ||
35!
394
      downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_SORT ||
35!
395
      (downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN &&
35✔
396
       ((STableScanInfo*)downstream->info)->hasGroupByTag == true)) {
1!
397
    return TSDB_CODE_SUCCESS;
×
398
  }
399

400
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
35✔
401

402
  if (!pAggInfo->hasCountFunc) {
35✔
403
    return TSDB_CODE_SUCCESS;
3✔
404
  }
405

406
  code = createDataBlock(&pBlock);
32✔
407
  if (code) {
32!
408
    return code;
×
409
  }
410

411
  pBlock->info.rows = 1;
32✔
412
  pBlock->info.capacity = 0;
32✔
413

414
  for (int32_t i = 0; i < pOperator->exprSupp.numOfExprs; ++i) {
64✔
415
    SColumnInfoData colInfo = {0};
32✔
416
    colInfo.hasNull = true;
32✔
417
    colInfo.info.type = TSDB_DATA_TYPE_NULL;
32✔
418
    colInfo.info.bytes = 1;
32✔
419

420
    SExprInfo* pOneExpr = &pOperator->exprSupp.pExprInfo[i];
32✔
421
    for (int32_t j = 0; j < pOneExpr->base.numOfParams; ++j) {
64✔
422
      SFunctParam* pFuncParam = &pOneExpr->base.pParam[j];
32✔
423
      if (pFuncParam->type == FUNC_PARAM_TYPE_COLUMN) {
32!
424
        int32_t slotId = pFuncParam->pCol->slotId;
32✔
425
        int32_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
32✔
426
        if (slotId >= numOfCols) {
32!
427
          code = taosArrayEnsureCap(pBlock->pDataBlock, slotId + 1);
32✔
428
          QUERY_CHECK_CODE(code, lino, _end);
32!
429

430
          for (int32_t k = numOfCols; k < slotId + 1; ++k) {
64✔
431
            void* tmp = taosArrayPush(pBlock->pDataBlock, &colInfo);
32✔
432
            QUERY_CHECK_NULL(tmp, code, lino, _end, terrno);
32!
433
          }
434
        }
435
      } else if (pFuncParam->type == FUNC_PARAM_TYPE_VALUE) {
×
436
        // do nothing
437
      }
438
    }
439
  }
440

441
  code = blockDataEnsureCapacity(pBlock, pBlock->info.rows);
32✔
442
  QUERY_CHECK_CODE(code, lino, _end);
32!
443

444
  for (int32_t i = 0; i < blockDataGetNumOfCols(pBlock); ++i) {
64✔
445
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
32✔
446
    QUERY_CHECK_NULL(pColInfoData, code, lino, _end, terrno);
32!
447
    colDataSetNULL(pColInfoData, 0);
448
  }
449
  *ppBlock = pBlock;
32✔
450

451
_end:
32✔
452
  if (code != TSDB_CODE_SUCCESS) {
32!
453
    blockDataDestroy(pBlock);
×
454
    qError("%s failed at line %d since %s", __func__, __LINE__, tstrerror(code));
×
455
  }
456
  return code;
32✔
457
}
458

459
void destroyDataBlockForEmptyInput(bool blockAllocated, SSDataBlock** ppBlock) {
491✔
460
  if (!blockAllocated) {
491✔
461
    return;
459✔
462
  }
463

464
  blockDataDestroy(*ppBlock);
32✔
465
  *ppBlock = NULL;
32✔
466
}
467

468
int32_t setExecutionContext(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId) {
1,603✔
469
  int32_t           code = TSDB_CODE_SUCCESS;
1,603✔
470
  SAggOperatorInfo* pAggInfo = pOperator->info;
1,603✔
471
  if (pAggInfo->groupId != UINT64_MAX && pAggInfo->groupId == groupId) {
1,603✔
472
    return code;
84✔
473
  }
474

475
  code = doSetTableGroupOutputBuf(pOperator, numOfOutput, groupId);
1,519✔
476

477
  // record the current active group id
478
  pAggInfo->groupId = groupId;
1,519✔
479
  return code;
1,519✔
480
}
481

482
int32_t doSetTableGroupOutputBuf(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId) {
1,519✔
483
  // for simple group by query without interval, all the tables belong to one group result.
484
  int32_t           code = TSDB_CODE_SUCCESS;
1,519✔
485
  int32_t           lino = 0;
1,519✔
486
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
1,519✔
487
  SAggOperatorInfo* pAggInfo = pOperator->info;
1,519✔
488

489
  SResultRowInfo* pResultRowInfo = &pAggInfo->binfo.resultRowInfo;
1,519✔
490
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
1,519✔
491
  int32_t*        rowEntryInfoOffset = pOperator->exprSupp.rowEntryInfoOffset;
1,519✔
492

493
  SResultRow* pResultRow =
494
      doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId, sizeof(groupId), true,
1,519✔
495
                             groupId, pTaskInfo, false, &pAggInfo->aggSup, true);
496
  if (pResultRow == NULL || pTaskInfo->code != 0) {
1,519!
497
    code = pTaskInfo->code;
×
498
    lino = __LINE__;
×
499
    goto _end;
×
500
  }
501
  /*
502
   * not assign result buffer yet, add new result buffer
503
   * all group belong to one result set, and each group result has different group id so set the id to be one
504
   */
505
  if (pResultRow->pageId == -1) {
1,519!
506
    code = addNewResultRowBuf(pResultRow, pAggInfo->aggSup.pResultBuf, pAggInfo->binfo.pRes->info.rowSize);
×
507
    QUERY_CHECK_CODE(code, lino, _end);
×
508
  }
509

510
  code = setResultRowInitCtx(pResultRow, pCtx, numOfOutput, rowEntryInfoOffset);
1,519✔
511
  QUERY_CHECK_CODE(code, lino, _end);
1,519!
512

513
_end:
1,519✔
514
  if (code != TSDB_CODE_SUCCESS) {
1,519!
515
    qError("%s failed at line %d since %s", __func__, lino, tstrerror(code));
×
516
  }
517
  return code;
1,519✔
518
}
519

520
// a new buffer page for each table. Needs to opt this design
521
int32_t addNewResultRowBuf(SResultRow* pWindowRes, SDiskbasedBuf* pResultBuf, uint32_t size) {
×
522
  if (pWindowRes->pageId != -1) {
×
523
    return 0;
×
524
  }
525

526
  SFilePage* pData = NULL;
×
527

528
  // in the first scan, new space needed for results
529
  int32_t pageId = -1;
×
530
  SArray* list = getDataBufPagesIdList(pResultBuf);
×
531

532
  if (taosArrayGetSize(list) == 0) {
×
533
    pData = getNewBufPage(pResultBuf, &pageId);
×
534
    if (pData == NULL) {
×
535
      qError("failed to get buffer, code:%s", tstrerror(terrno));
×
536
      return terrno;
×
537
    }
538
    pData->num = sizeof(SFilePage);
×
539
  } else {
540
    SPageInfo* pi = getLastPageInfo(list);
×
541
    pData = getBufPage(pResultBuf, getPageId(pi));
×
542
    if (pData == NULL) {
×
543
      qError("failed to get buffer, code:%s", tstrerror(terrno));
×
544
      return terrno;
×
545
    }
546

547
    pageId = getPageId(pi);
×
548

549
    if (pData->num + size > getBufPageSize(pResultBuf)) {
×
550
      // release current page first, and prepare the next one
551
      releaseBufPageInfo(pResultBuf, pi);
×
552

553
      pData = getNewBufPage(pResultBuf, &pageId);
×
554
      if (pData == NULL) {
×
555
        qError("failed to get buffer, code:%s", tstrerror(terrno));
×
556
        return terrno;
×
557
      }
558
      pData->num = sizeof(SFilePage);
×
559
    }
560
  }
561

562
  if (pData == NULL) {
×
563
    return -1;
×
564
  }
565

566
  // set the number of rows in current disk page
567
  if (pWindowRes->pageId == -1) {  // not allocated yet, allocate new buffer
×
568
    pWindowRes->pageId = pageId;
×
569
    pWindowRes->offset = (int32_t)pData->num;
×
570

571
    pData->num += size;
×
572
  }
573

574
  return 0;
×
575
}
576

577
int32_t doInitAggInfoSup(SAggSupporter* pAggSup, SqlFunctionCtx* pCtx, int32_t numOfOutput, size_t keyBufSize,
3,125✔
578
                         const char* pKey) {
579
  int32_t code = 0;
3,125✔
580
  //  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);
581

582
  pAggSup->currentPageId = -1;
3,125✔
583
  pAggSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
3,125✔
584
  pAggSup->keyBuf = taosMemoryCalloc(1, keyBufSize + POINTER_BYTES + sizeof(int64_t));
3,126!
585
  pAggSup->pResultRowHashTable = tSimpleHashInit(100, taosFastHash);
3,127✔
586

587
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
3,127!
588
    return terrno;
×
589
  }
590

591
  uint32_t defaultPgsz = 0;
3,127✔
592
  int64_t defaultBufsz = 0;
3,127✔
593
  code = getBufferPgSize(pAggSup->resultRowSize, &defaultPgsz, &defaultBufsz);
3,127✔
594
  if (code) {
3,127!
595
    qError("failed to get buff page size, rowSize:%d", pAggSup->resultRowSize);
×
596
    return code;
×
597
  }
598

599
  if (!osTempSpaceAvailable()) {
3,127!
600
    code = TSDB_CODE_NO_DISKSPACE;
×
601
    qError("Init stream agg supporter failed since %s, key:%s, tempDir:%s", tstrerror(code), pKey, tsTempDir);
×
602
    return code;
×
603
  }
604

605
  code = createDiskbasedBuf(&pAggSup->pResultBuf, defaultPgsz, defaultBufsz, pKey, tsTempDir);
3,126✔
606
  if (code != TSDB_CODE_SUCCESS) {
3,126!
607
    qError("Create agg result buf failed since %s, %s", tstrerror(code), pKey);
×
608
    return code;
×
609
  }
610

611
  return code;
3,126✔
612
}
613

614
void cleanupResultInfoInStream(SExecTaskInfo* pTaskInfo, void* pState, SExprSupp* pSup, SGroupResInfo* pGroupResInfo) {
×
615
  int32_t         code = TSDB_CODE_SUCCESS;
×
616
  SStorageAPI*    pAPI = &pTaskInfo->storageAPI;
×
617
  int32_t         numOfExprs = pSup->numOfExprs;
×
618
  int32_t*        rowEntryOffset = pSup->rowEntryInfoOffset;
×
619
  SqlFunctionCtx* pCtx = pSup->pCtx;
×
620
  int32_t         numOfRows = getNumOfTotalRes(pGroupResInfo);
×
621
  bool            needCleanup = false;
×
622

623
  for (int32_t j = 0; j < numOfExprs; ++j) {
×
624
    needCleanup |= pCtx[j].needCleanup;
×
625
  }
626
  if (!needCleanup) {
×
627
    return;
×
628
  }
629
  
630
  for (int32_t i = pGroupResInfo->index; i < numOfRows; i += 1) {
×
631
    SResultWindowInfo* pWinInfo = taosArrayGet(pGroupResInfo->pRows, i);
×
632
    SRowBuffPos*       pPos = pWinInfo->pStatePos;
×
633
    SResultRow*        pRow = NULL;
×
634

635
    code = pAPI->stateStore.streamStateGetByPos(pState, pPos, (void**)&pRow);
×
636
    if (TSDB_CODE_SUCCESS != code) {
×
637
      qError("failed to get state by pos, code:%s, %s", tstrerror(code), GET_TASKID(pTaskInfo));
×
638
      continue;
×
639
    }
640

641
    for (int32_t j = 0; j < numOfExprs; ++j) {
×
642
      pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowEntryOffset);
×
643
      if (pCtx[j].fpSet.cleanup) {
×
644
        pCtx[j].fpSet.cleanup(&pCtx[j]);
×
645
      }
646
    }
647
  }
648
}
649

650
void cleanupResultInfoInGroupResInfo(SExecTaskInfo* pTaskInfo, SExprSupp* pSup, SDiskbasedBuf* pBuf,
524✔
651
                                  SGroupResInfo* pGroupResInfo) {
652
  int32_t         numOfExprs = pSup->numOfExprs;
524✔
653
  int32_t*        rowEntryOffset = pSup->rowEntryInfoOffset;
524✔
654
  SqlFunctionCtx* pCtx = pSup->pCtx;
524✔
655
  int32_t         numOfRows = getNumOfTotalRes(pGroupResInfo);
524✔
656
  bool            needCleanup = false;
524✔
657

658
  for (int32_t j = 0; j < numOfExprs; ++j) {
1,286✔
659
    needCleanup |= pCtx[j].needCleanup;
762✔
660
  }
661
  if (!needCleanup) {
524!
662
    return;
524✔
663
  }
664

665
  for (int32_t i = pGroupResInfo->index; i < numOfRows; i += 1) {
×
666
    SResultRow*        pRow = NULL;
×
667
    SResKeyPos*        pPos = taosArrayGetP(pGroupResInfo->pRows, i);
×
668
    SFilePage*         page = getBufPage(pBuf, pPos->pos.pageId);
×
669
    if (page == NULL) {
×
670
      qError("failed to get buffer, code:%s, %s", tstrerror(terrno), GET_TASKID(pTaskInfo));
×
671
      continue;
×
672
    }
673
    pRow = (SResultRow*)((char*)page + pPos->pos.offset);
×
674

675

676
    for (int32_t j = 0; j < numOfExprs; ++j) {
×
677
      pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowEntryOffset);
×
678
      if (pCtx[j].fpSet.cleanup) {
×
679
        pCtx[j].fpSet.cleanup(&pCtx[j]);
×
680
      }
681
    }
682
    releaseBufPage(pBuf, page);
×
683
  }
684
}
685

686
void cleanupResultInfoInHashMap(SExecTaskInfo* pTaskInfo, SExprSupp* pSup, SDiskbasedBuf* pBuf,
172✔
687
                       SGroupResInfo* pGroupResInfo, SSHashObj* pHashmap) {
688
  int32_t         numOfExprs = pSup->numOfExprs;
172✔
689
  int32_t*        rowEntryOffset = pSup->rowEntryInfoOffset;
172✔
690
  SqlFunctionCtx* pCtx = pSup->pCtx;
172✔
691
  bool            needCleanup = false;
172✔
692
  for (int32_t j = 0; j < numOfExprs; ++j) {
358✔
693
    needCleanup |= pCtx[j].needCleanup;
186✔
694
  }
695
  if (!needCleanup) {
172!
696
    return;
172✔
697
  }
698

699
  // begin from last iter
700
  void*   pData = pGroupResInfo->dataPos;
×
701
  int32_t iter = pGroupResInfo->iter;
×
702
  while ((pData = tSimpleHashIterate(pHashmap, pData, &iter)) != NULL) {
×
703
    SResultRowPosition* pos = pData;
×
704

705
    SFilePage* page = getBufPage(pBuf, pos->pageId);
×
706
    if (page == NULL) {
×
707
      qError("failed to get buffer, code:%s, %s", tstrerror(terrno), GET_TASKID(pTaskInfo));
×
708
      continue;
×
709
    }
710

711
    SResultRow* pRow = (SResultRow*)((char*)page + pos->offset);
×
712

713
    for (int32_t j = 0; j < numOfExprs; ++j) {
×
714
      pCtx[j].resultInfo = getResultEntryInfo(pRow, j, rowEntryOffset);
×
715
      if (pCtx[j].fpSet.cleanup) {
×
716
        pCtx[j].fpSet.cleanup(&pCtx[j]);
×
717
      }
718
    }
719

720
    releaseBufPage(pBuf, page);
×
721
  }
722
}
723

724
void cleanupResultInfo(SExecTaskInfo* pTaskInfo, SExprSupp* pSup, SGroupResInfo* pGroupResInfo,
696✔
725
                       SAggSupporter *pAggSup, bool cleanGroupResInfo) {
726
  if (cleanGroupResInfo) {
696✔
727
    cleanupResultInfoInGroupResInfo(pTaskInfo, pSup, pAggSup->pResultBuf, pGroupResInfo);
524✔
728
  } else {
729
    cleanupResultInfoInHashMap(pTaskInfo, pSup, pAggSup->pResultBuf, pGroupResInfo, pAggSup->pResultRowHashTable);
172✔
730
  }
731
}
696✔
732
void cleanupAggSup(SAggSupporter* pAggSup) {
3,127✔
733
  taosMemoryFreeClear(pAggSup->keyBuf);
3,127!
734
  tSimpleHashCleanup(pAggSup->pResultRowHashTable);
3,127✔
735
  destroyDiskbasedBuf(pAggSup->pResultBuf);
3,127✔
736
  memset(pAggSup, 0, sizeof(SAggSupporter));
3,127✔
737
}
3,127✔
738

739
int32_t initAggSup(SExprSupp* pSup, SAggSupporter* pAggSup, SExprInfo* pExprInfo, int32_t numOfCols, size_t keyBufSize,
3,126✔
740
                   const char* pkey, void* pState, SFunctionStateStore* pStore) {
741
  int32_t code = initExprSupp(pSup, pExprInfo, numOfCols, pStore);
3,126✔
742
  if (code != TSDB_CODE_SUCCESS) {
3,126!
743
    return code;
×
744
  }
745

746
  code = doInitAggInfoSup(pAggSup, pSup->pCtx, numOfCols, keyBufSize, pkey);
3,126✔
747
  if (code != TSDB_CODE_SUCCESS) {
3,126!
748
    return code;
×
749
  }
750

751
  for (int32_t i = 0; i < numOfCols; ++i) {
8,586✔
752
    pSup->pCtx[i].hasWindowOrGroup = pSup->hasWindowOrGroup;
5,460✔
753
    if (pState) {
5,460!
754
      pSup->pCtx[i].saveHandle.pBuf = NULL;
×
755
      pSup->pCtx[i].saveHandle.pState = pState;
×
756
      pSup->pCtx[i].exprIdx = i;
×
757
    } else {
758
      pSup->pCtx[i].saveHandle.pBuf = pAggSup->pResultBuf;
5,460✔
759
    }
760
  }
761

762
  return TSDB_CODE_SUCCESS;
3,126✔
763
}
764

765
int32_t applyAggFunctionOnPartialTuples(SExecTaskInfo* taskInfo, SqlFunctionCtx* pCtx, SColumnInfoData* pTimeWindowData,
2,622✔
766
                                        int32_t offset, int32_t forwardStep, int32_t numOfTotal, int32_t numOfOutput) {
767
  int32_t code = TSDB_CODE_SUCCESS, lino = 0;
2,622✔
768
  for (int32_t k = 0; k < numOfOutput; ++k) {
5,284✔
769
    // keep it temporarily
770
    SFunctionCtxStatus status = {0};
2,662✔
771
    functionCtxSave(&pCtx[k], &status);
2,662✔
772

773
    pCtx[k].input.startRowIndex = offset;
2,662✔
774
    pCtx[k].input.numOfRows = forwardStep;
2,662✔
775

776
    // not a whole block involved in query processing, statistics data can not be used
777
    // NOTE: the original value of isSet have been changed here
778
    if (pCtx[k].input.colDataSMAIsSet && forwardStep < numOfTotal) {
2,662!
779
      pCtx[k].input.colDataSMAIsSet = false;
×
780
    }
781

782
    if (fmIsPlaceHolderFunc(pCtx[k].functionId)) {
2,662!
783
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
×
784
      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);
×
785

786
      TAOS_CHECK_EXIT(fmSetStreamPseudoFuncParamVal(pCtx[k].functionId, pCtx[k].pExpr->base.pParamList, &taskInfo->pStreamRuntimeInfo->funcInfo));
×
787

788
      SValueNode *valueNode = (SValueNode *)nodesListGetNode(pCtx[k].pExpr->base.pParamList, 0);
×
789
      pEntryInfo->isNullRes = 0;
×
790
      if (TSDB_DATA_TYPE_NULL == valueNode->node.resType.type || valueNode->isNull) {
×
791
        pEntryInfo->isNullRes = 1;
×
792
      } else if (IS_VAR_DATA_TYPE(pCtx[k].pExpr->base.resSchema.type)){
×
793
        void* v = nodesGetValueFromNode(valueNode);
×
794
        memcpy(p, v, varDataTLen(v));
×
795
      } else {
796
        memcpy(p, nodesGetValueFromNode(valueNode), pCtx[k].pExpr->base.resSchema.bytes);
×
797
      }
798
      
799
      pEntryInfo->numOfRes = 1;
×
800
    } else if (pCtx[k].isPseudoFunc) {
2,662✔
801
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
32✔
802

803
      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);
32✔
804

805
      SColumnInfoData idata = {0};
32✔
806
      idata.info.type = TSDB_DATA_TYPE_BIGINT;
32✔
807
      idata.info.bytes = tDataTypes[TSDB_DATA_TYPE_BIGINT].bytes;
32✔
808
      idata.pData = p;
32✔
809

810
      SScalarParam out = {.columnData = &idata};
32✔
811
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
32✔
812
      TAOS_CHECK_EXIT(pCtx[k].sfp.process(&tw, 1, &out));
32!
813
      pEntryInfo->isNullRes = colDataIsNull_s(&idata, 0);
32✔
814
      pEntryInfo->numOfRes = 1;
32✔
815
    } else {
816
      if (functionNeedToExecute(&pCtx[k]) && pCtx[k].fpSet.process != NULL) {
2,630!
817
        if ((&pCtx[k])->input.pData[0] == NULL) {
342!
818
          code = TSDB_CODE_QRY_EXECUTOR_INTERNAL_ERROR;
×
819
          qError("%s apply functions error, input data is NULL.", GET_TASKID(taskInfo));
×
820
        } else {
821
          code = pCtx[k].fpSet.process(&pCtx[k]);
342✔
822
        }
823

824
        if (code != TSDB_CODE_SUCCESS) {
342!
825
          if (pCtx[k].fpSet.cleanup != NULL) {
×
826
            pCtx[k].fpSet.cleanup(&pCtx[k]);
×
827
          }
828
          TAOS_CHECK_EXIT(code);
×
829
        }
830
      }
831

832
      // restore it
833
      functionCtxRestore(&pCtx[k], &status);
2,630✔
834
    }
835
  }
836

837
_exit:
2,622✔
838

839
  if (code) {
2,622!
840
    qError("%s failed at line %d since %s", __func__, lino, tstrerror(code));
×
841
    taskInfo->code = code;
×
842
  }
843

844
  return code;
2,622✔
845
}
846

847
void functionCtxSave(SqlFunctionCtx* pCtx, SFunctionCtxStatus* pStatus) {
2,662✔
848
  pStatus->hasAgg = pCtx->input.colDataSMAIsSet;
2,662✔
849
  pStatus->numOfRows = pCtx->input.numOfRows;
2,662✔
850
  pStatus->startOffset = pCtx->input.startRowIndex;
2,662✔
851
}
2,662✔
852

853
void functionCtxRestore(SqlFunctionCtx* pCtx, SFunctionCtxStatus* pStatus) {
2,630✔
854
  pCtx->input.colDataSMAIsSet = pStatus->hasAgg;
2,630✔
855
  pCtx->input.numOfRows = pStatus->numOfRows;
2,630✔
856
  pCtx->input.startRowIndex = pStatus->startOffset;
2,630✔
857
}
2,630✔
858

859
static int32_t resetAggregateOperatorState(SOperatorInfo* pOper) {
×
860
  SAggOperatorInfo* pAgg = pOper->info;
×
861
  SAggPhysiNode*   pAggNode = (SAggPhysiNode*)pOper->pPhyNode;
×
862
  
863
  pOper->status = OP_NOT_OPENED;
×
864
  size_t keyBufSize = sizeof(int64_t) + sizeof(int64_t) + POINTER_BYTES;
×
865
  SExecTaskInfo*  pTaskInfo = pOper->pTaskInfo;
×
866
  cleanupResultInfo(pTaskInfo, &pOper->exprSupp, &pAgg->groupResInfo, &pAgg->aggSup,
×
867
                      pAgg->cleanGroupResInfo);
×
868
  cleanupGroupResInfo(&pAgg->groupResInfo);
×
869
  resetBasicOperatorState(&pAgg->binfo);
×
870
  
871
  int32_t code = resetAggSup(&pOper->exprSupp, &pAgg->aggSup, pTaskInfo, pAggNode->pAggFuncs, pAggNode->pGroupKeys,
×
872
    keyBufSize, pTaskInfo->id.str, pTaskInfo->streamInfo.pState, &pTaskInfo->storageAPI.functionStore);
×
873

874
  if (code == 0) {
×
875
    code = resetExprSupp(&pAgg->scalarExprSup, pTaskInfo, pAggNode->pExprs, NULL,
×
876
                          &pTaskInfo->storageAPI.functionStore);
877
  }
878

879
  pAgg->groupId = UINT64_MAX;
×
880
  pAgg->cleanGroupResInfo = false;
×
881
  pAgg->hasValidBlock = false;
×
882
  return 0;
×
883
}
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