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

taosdata / TDengine / #3825

01 Apr 2025 11:58AM UTC coverage: 34.067% (+0.003%) from 34.064%
#3825

push

travis-ci

happyguoxy
test:alter gcda dir

148492 of 599532 branches covered (24.77%)

Branch coverage included in aggregate %.

222504 of 489471 relevant lines covered (45.46%)

762290.2 hits per line

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

54.34
/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,
519✔
75
                                    SOperatorInfo** pOptrInfo) {
76
  QRY_PARAM_CHECK(pOptrInfo);
519!
77

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

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

92
  pOperator->exprSupp.hasWindowOrGroup = false;
520✔
93

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

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

101
  code = createExprInfo(pAggNode->pAggFuncs, pAggNode->pGroupKeys, &pExprInfo, &num);
520✔
102
  TSDB_CHECK_CODE(code, lino, _error);
520!
103

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

108
  if (pAggNode->pExprs != NULL) {
520✔
109
    code = createExprInfo(pAggNode->pExprs, NULL, &pScalarExprInfo, &numOfScalarExpr);
13✔
110
    TSDB_CHECK_CODE(code, lino, _error);
13!
111
  }
112

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

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

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

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

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

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

144
  *pOptrInfo = pOperator;
520✔
145
  return TSDB_CODE_SUCCESS;
520✔
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) {
520✔
158
  if (param == NULL) {
520!
159
    return;
×
160
  }
161
  SAggOperatorInfo* pInfo = (SAggOperatorInfo*)param;
520✔
162
  cleanupBasicInfo(&pInfo->binfo);
520✔
163

164
  if (pInfo->pOperator) {
520!
165
    cleanupResultInfo(pInfo->pOperator->pTaskInfo, &pInfo->pOperator->exprSupp, &pInfo->groupResInfo, &pInfo->aggSup,
520✔
166
                      pInfo->cleanGroupResInfo);
520✔
167
    pInfo->pOperator = NULL;
520✔
168
  }
169
  cleanupAggSup(&pInfo->aggSup);
520✔
170
  cleanupExprSupp(&pInfo->scalarExprSup);
520✔
171
  cleanupGroupResInfo(&pInfo->groupResInfo);
520✔
172
  taosMemoryFreeClear(param);
520!
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) {
538✔
183
  int32_t           code = TSDB_CODE_SUCCESS;
538✔
184
  int32_t           lino = 0;
538✔
185
  SExecTaskInfo*    pTaskInfo = pOperator->pTaskInfo;
538✔
186
  SAggOperatorInfo* pAggInfo = pOperator->info;
538✔
187

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

196
  SExprSupp*   pSup = &pOperator->exprSupp;
520✔
197
  int64_t      st = taosGetTimestampUs();
519✔
198
  int32_t      order = pAggInfo->binfo.inputTsOrder;
519✔
199
  SSDataBlock* pBlock = pAggInfo->pNewGroupBlock;
519✔
200

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

210
    code = doAggregateImpl(pOperator, pSup->pCtx);
×
211
    QUERY_CHECK_CODE(code, lino, _end);
×
212
  }
213
  while (1) {
4,226✔
214
    bool blockAllocated = false;
4,745✔
215
    pBlock = getNextBlockFromDownstream(pOperator, 0);
4,745✔
216
    if (pBlock == NULL) {
4,744✔
217
      if (!pAggInfo->hasValidBlock) {
621✔
218
        code = createDataBlockForEmptyInput(pOperator, &pBlock);
145✔
219
        QUERY_CHECK_CODE(code, lino, _end);
145!
220

221
        if (pBlock == NULL) {
145✔
222
          break;
16✔
223
        }
224
        blockAllocated = true;
129✔
225
      } else {
226
        break;
476✔
227
      }
228
    }
229
    pAggInfo->hasValidBlock = true;
4,252✔
230
    pAggInfo->binfo.pRes->info.scanFlag = pBlock->info.scanFlag;
4,252✔
231

232
    // there is an scalar expression that needs to be calculated before apply the group aggregation.
233
    if (pAggInfo->scalarExprSup.pExprInfo != NULL && !blockAllocated) {
4,252!
234
      SExprSupp* pSup1 = &pAggInfo->scalarExprSup;
33✔
235
      code = projectApplyFunctions(pSup1->pExprInfo, pBlock, pBlock, pSup1->pCtx, pSup1->numOfExprs, NULL);
33✔
236
      if (code != TSDB_CODE_SUCCESS) {
33!
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) {
4,252!
243
      pAggInfo->pNewGroupBlock = pBlock;
×
244
      break;
×
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);
4,252✔
248
    if (code != TSDB_CODE_SUCCESS) {
4,252✔
249
      destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
27✔
250
      T_LONG_JMP(pTaskInfo->env, code);
27!
251
    }
252
    code = setInputDataBlock(pSup, pBlock, order, pBlock->info.scanFlag, true);
4,225✔
253
    if (code != TSDB_CODE_SUCCESS) {
4,226!
254
      destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
×
255
      T_LONG_JMP(pTaskInfo->env, code);
×
256
    }
257

258
    code = doAggregateImpl(pOperator, pSup->pCtx);
4,226✔
259
    if (code != TSDB_CODE_SUCCESS) {
4,226!
260
      destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
×
261
      T_LONG_JMP(pTaskInfo->env, code);
×
262
    }
263

264
    destroyDataBlockForEmptyInput(blockAllocated, &pBlock);
4,226✔
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) {
492!
269
    T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
×
270
  }
271

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

276
_end:
492✔
277
  if (code != TSDB_CODE_SUCCESS) {
492!
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;
492✔
283
}
284

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

291
  if (pOperator->status == OP_EXEC_DONE) {
1,000✔
292
    (*ppRes) = NULL;
462✔
293
    return code;
462✔
294
  }
295

296
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
538✔
297
  bool           hasNewGroups = false;
538✔
298
  do {
299
    hasNewGroups = nextGroupedResult(pOperator);
538✔
300
    code = blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
510✔
301
    QUERY_CHECK_CODE(code, lino, _end);
510!
302

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

308
      if (!hasRemainResults(&pAggInfo->groupResInfo)) {
510✔
309
        if (!hasNewGroups) setOperatorCompleted(pOperator);
492!
310
        break;
492✔
311
      }
312

313
      if (pInfo->pRes->info.rows > 0) {
18!
314
        break;
18✔
315
      }
316
    }
317
  } while (pInfo->pRes->info.rows == 0 && hasNewGroups);
510!
318

319
  size_t rows = blockDataGetNumOfRows(pInfo->pRes);
510✔
320
  pOperator->resultInfo.totalRows += rows;
510✔
321

322
_end:
510✔
323
  if (code != TSDB_CODE_SUCCESS) {
510!
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;
510✔
330
  return code;
510✔
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) {
4,226✔
340
  int32_t code = TSDB_CODE_SUCCESS;
4,226✔
341
  if (!pOperator || (pOperator->exprSupp.numOfExprs > 0 && pCtx == NULL)) {
4,226!
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) {
9,905✔
346
    if (functionNeedToExecute(&pCtx[k])) {
5,679!
347
      // todo add a dummy function to avoid process check
348
      if (pCtx[k].fpSet.process == NULL) {
5,679✔
349
        continue;
93✔
350
      }
351

352
      if ((&pCtx[k])->input.pData[0] == NULL) {
5,586!
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]);
5,586✔
357
      }
358

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

369
  return TSDB_CODE_SUCCESS;
4,226✔
370
}
371

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

380
  SAggOperatorInfo* pAggInfo = pOperator->info;
145✔
381
  if (pAggInfo->groupKeyOptimized) {
145!
382
    return TSDB_CODE_SUCCESS;
×
383
  }
384

385
  SOperatorInfo* downstream = pOperator->pDownstream[0];
145✔
386
  if (downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_PARTITION ||
145!
387
      downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_SORT ||
145!
388
      (downstream->operatorType == QUERY_NODE_PHYSICAL_PLAN_TABLE_SCAN &&
145✔
389
       ((STableScanInfo*)downstream->info)->hasGroupByTag == true)) {
137!
390
    return TSDB_CODE_SUCCESS;
×
391
  }
392

393
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
145✔
394

395
  if (!pAggInfo->hasCountFunc) {
145✔
396
    return TSDB_CODE_SUCCESS;
16✔
397
  }
398

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

404
  pBlock->info.rows = 1;
129✔
405
  pBlock->info.capacity = 0;
129✔
406

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

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

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

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

437
  for (int32_t i = 0; i < blockDataGetNumOfCols(pBlock); ++i) {
264✔
438
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);
135✔
439
    QUERY_CHECK_NULL(pColInfoData, code, lino, _end, terrno);
135!
440
    colDataSetNULL(pColInfoData, 0);
441
  }
442
  *ppBlock = pBlock;
129✔
443

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

452
void destroyDataBlockForEmptyInput(bool blockAllocated, SSDataBlock** ppBlock) {
4,253✔
453
  if (!blockAllocated) {
4,253✔
454
    return;
4,124✔
455
  }
456

457
  blockDataDestroy(*ppBlock);
129✔
458
  *ppBlock = NULL;
129✔
459
}
460

461
int32_t setExecutionContext(SOperatorInfo* pOperator, int32_t numOfOutput, uint64_t groupId) {
4,252✔
462
  int32_t           code = TSDB_CODE_SUCCESS;
4,252✔
463
  SAggOperatorInfo* pAggInfo = pOperator->info;
4,252✔
464
  if (pAggInfo->groupId != UINT64_MAX && pAggInfo->groupId == groupId) {
4,252✔
465
    return code;
3,401✔
466
  }
467

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

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

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

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

486
  SResultRow* pResultRow =
487
      doSetResultOutBufByKey(pAggInfo->aggSup.pResultBuf, pResultRowInfo, (char*)&groupId, sizeof(groupId), true,
851✔
488
                             groupId, pTaskInfo, false, &pAggInfo->aggSup, true);
489
  if (pResultRow == NULL || pTaskInfo->code != 0) {
851!
490
    code = pTaskInfo->code;
1✔
491
    lino = __LINE__;
1✔
492
    goto _end;
1✔
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) {
850!
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);
850✔
504
  QUERY_CHECK_CODE(code, lino, _end);
850✔
505

506
_end:
824✔
507
  if (code != TSDB_CODE_SUCCESS) {
851✔
508
    qError("%s failed at line %d since %s", __func__, lino, tstrerror(code));
27!
509
  }
510
  return code;
851✔
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,
1,470✔
571
                         const char* pKey) {
572
  int32_t code = 0;
1,470✔
573
  //  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);
574

575
  pAggSup->currentPageId = -1;
1,470✔
576
  pAggSup->resultRowSize = getResultRowSize(pCtx, numOfOutput);
1,470✔
577
  pAggSup->keyBuf = taosMemoryCalloc(1, keyBufSize + POINTER_BYTES + sizeof(int64_t));
1,470!
578
  pAggSup->pResultRowHashTable = tSimpleHashInit(100, taosFastHash);
1,471✔
579

580
  if (pAggSup->keyBuf == NULL || pAggSup->pResultRowHashTable == NULL) {
1,470!
581
    return terrno;
582
  }
583

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

592
  if (!osTempSpaceAvailable()) {
1,469!
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);
1,470✔
599
  if (code != TSDB_CODE_SUCCESS) {
1,471✔
600
    qError("Create agg result buf failed since %s, %s", tstrerror(code), pKey);
1!
601
    return code;
×
602
  }
603

604
  return code;
1,470✔
605
}
606

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

616
  for (int32_t j = 0; j < numOfExprs; ++j) {
×
617
    needCleanup |= pCtx[j].needCleanup;
×
618
  }
619
  if (!needCleanup) {
×
620
    return;
×
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,
610✔
644
                                  SGroupResInfo* pGroupResInfo) {
645
  int32_t         numOfExprs = pSup->numOfExprs;
610✔
646
  int32_t*        rowEntryOffset = pSup->rowEntryInfoOffset;
610✔
647
  SqlFunctionCtx* pCtx = pSup->pCtx;
610✔
648
  int32_t         numOfRows = getNumOfTotalRes(pGroupResInfo);
610✔
649
  bool            needCleanup = false;
610✔
650

651
  for (int32_t j = 0; j < numOfExprs; ++j) {
1,743✔
652
    needCleanup |= pCtx[j].needCleanup;
1,133✔
653
  }
654
  if (!needCleanup) {
610✔
655
    return;
607✔
656
  }
657

658
  for (int32_t i = pGroupResInfo->index; i < numOfRows; i += 1) {
3!
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,
264✔
680
                       SGroupResInfo* pGroupResInfo, SSHashObj* pHashmap) {
681
  int32_t         numOfExprs = pSup->numOfExprs;
264✔
682
  int32_t*        rowEntryOffset = pSup->rowEntryInfoOffset;
264✔
683
  SqlFunctionCtx* pCtx = pSup->pCtx;
264✔
684
  bool            needCleanup = false;
264✔
685
  for (int32_t j = 0; j < numOfExprs; ++j) {
850✔
686
    needCleanup |= pCtx[j].needCleanup;
586✔
687
  }
688
  if (!needCleanup) {
264!
689
    return;
264✔
690
  }
691

692
  // begin from last iter
693
  void*   pData = pGroupResInfo->dataPos;
×
694
  int32_t iter = pGroupResInfo->iter;
×
695
  while ((pData = tSimpleHashIterate(pHashmap, pData, &iter)) != NULL) {
×
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,
874✔
718
                       SAggSupporter *pAggSup, bool cleanGroupResInfo) {
719
  if (cleanGroupResInfo) {
874✔
720
    cleanupResultInfoInGroupResInfo(pTaskInfo, pSup, pAggSup->pResultBuf, pGroupResInfo);
610✔
721
  } else {
722
    cleanupResultInfoInHashMap(pTaskInfo, pSup, pAggSup->pResultBuf, pGroupResInfo, pAggSup->pResultRowHashTable);
264✔
723
  }
724
}
874✔
725
void cleanupAggSup(SAggSupporter* pAggSup) {
1,472✔
726
  taosMemoryFreeClear(pAggSup->keyBuf);
1,472!
727
  tSimpleHashCleanup(pAggSup->pResultRowHashTable);
1,472✔
728
  destroyDiskbasedBuf(pAggSup->pResultBuf);
1,472✔
729
}
1,472✔
730

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

738
  code = doInitAggInfoSup(pAggSup, pSup->pCtx, numOfCols, keyBufSize, pkey);
1,470✔
739
  if (code != TSDB_CODE_SUCCESS) {
1,471!
740
    return code;
×
741
  }
742

743
  for (int32_t i = 0; i < numOfCols; ++i) {
6,540✔
744
    pSup->pCtx[i].hasWindowOrGroup = pSup->hasWindowOrGroup;
5,069✔
745
    if (pState) {
5,069✔
746
      pSup->pCtx[i].saveHandle.pBuf = NULL;
56✔
747
      pSup->pCtx[i].saveHandle.pState = pState;
56✔
748
      pSup->pCtx[i].exprIdx = i;
56✔
749
    } else {
750
      pSup->pCtx[i].saveHandle.pBuf = pAggSup->pResultBuf;
5,013✔
751
    }
752
  }
753

754
  return TSDB_CODE_SUCCESS;
1,471✔
755
}
756

757
int32_t applyAggFunctionOnPartialTuples(SExecTaskInfo* taskInfo, SqlFunctionCtx* pCtx, SColumnInfoData* pTimeWindowData,
5,529✔
758
                                        int32_t offset, int32_t forwardStep, int32_t numOfTotal, int32_t numOfOutput) {
759
  int32_t code = TSDB_CODE_SUCCESS;
5,529✔
760
  for (int32_t k = 0; k < numOfOutput; ++k) {
20,153✔
761
    // keep it temporarily
762
    SFunctionCtxStatus status = {0};
14,624✔
763
    functionCtxSave(&pCtx[k], &status);
14,624✔
764

765
    pCtx[k].input.startRowIndex = offset;
14,624✔
766
    pCtx[k].input.numOfRows = forwardStep;
14,624✔
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) {
14,624!
771
      pCtx[k].input.colDataSMAIsSet = false;
×
772
    }
773

774
    if (pCtx[k].isPseudoFunc) {
14,624✔
775
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[k]);
3,348✔
776

777
      char* p = GET_ROWCELL_INTERBUF(pEntryInfo);
3,348✔
778

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

784
      SScalarParam out = {.columnData = &idata};
3,348✔
785
      SScalarParam tw = {.numOfRows = 5, .columnData = pTimeWindowData};
3,348✔
786
      code = pCtx[k].sfp.process(&tw, 1, &out);
3,348✔
787
      if (code != TSDB_CODE_SUCCESS) {
3,348!
788
        qError("%s failed at line %d since %s", __func__, __LINE__, tstrerror(code));
×
789
        taskInfo->code = code;
×
790
        return code;
×
791
      }
792
      pEntryInfo->numOfRes = 1;
3,348✔
793
    } else {
794
      if (functionNeedToExecute(&pCtx[k]) && pCtx[k].fpSet.process != NULL) {
11,276!
795
        if ((&pCtx[k])->input.pData[0] == NULL) {
8,698!
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]);
8,698✔
800
        }
801

802
        if (code != TSDB_CODE_SUCCESS) {
8,698!
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);
11,276✔
814
    }
815
  }
816
  return code;
5,529✔
817
}
818

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

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