groupoperator.c 26.0 KB
Newer Older
H
Haojun Liao 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "os.h"
#include "function.h"
#include "tname.h"

#include "tdatablock.h"
#include "tmsg.h"

#include "executorimpl.h"
#include "tcompare.h"
#include "thash.h"
#include "ttypes.h"
wmmhello's avatar
wmmhello 已提交
27
#include "executorInt.h"
H
Haojun Liao 已提交
28

29
static void*    getCurrentDataGroupInfo(const SPartitionOperatorInfo* pInfo, SDataGroupInfo** pGroupInfo, int32_t len);
H
Haojun Liao 已提交
30
static int32_t* setupColumnOffset(const SSDataBlock* pBlock, int32_t rowCapacity);
31 32
static int32_t  setGroupResultOutputBuf(SOperatorInfo* pOperator, SOptrBasicInfo* binfo, int32_t numOfCols, char* pData, int16_t bytes,
                                        int32_t groupId, SDiskbasedBuf* pBuf, SAggSupporter* pAggSup);
H
Haojun Liao 已提交
33

H
Haojun Liao 已提交
34
static void destroyGroupOperatorInfo(void* param, int32_t numOfOutput) {
H
Haojun Liao 已提交
35
  SGroupbyOperatorInfo* pInfo = (SGroupbyOperatorInfo*)param;
36
  cleanupBasicInfo(&pInfo->binfo);
H
Haojun Liao 已提交
37 38 39
  taosMemoryFreeClear(pInfo->keyBuf);
  taosArrayDestroy(pInfo->pGroupCols);
  taosArrayDestroy(pInfo->pGroupColVals);
40
  cleanupExecSupp(&pInfo->scalarSup);
H
Haojun Liao 已提交
41 42
}

wmmhello's avatar
wmmhello 已提交
43
static int32_t initGroupOptrInfo(SArray** pGroupColVals, int32_t* keyLen, char** keyBuf, const SArray* pGroupColList) {
H
Haojun Liao 已提交
44 45
  *pGroupColVals = taosArrayInit(4, sizeof(SGroupKeys));
  if ((*pGroupColVals) == NULL) {
H
Haojun Liao 已提交
46 47 48 49 50 51
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  int32_t numOfGroupCols = taosArrayGetSize(pGroupColList);
  for (int32_t i = 0; i < numOfGroupCols; ++i) {
    SColumn* pCol = taosArrayGet(pGroupColList, i);
52
    (*keyLen) += pCol->bytes; // actual data + null_flag
H
Haojun Liao 已提交
53

54
    SGroupKeys key = {0};
H
Haojun Liao 已提交
55 56
    key.bytes  = pCol->bytes;
    key.type   = pCol->type;
H
Haojun Liao 已提交
57
    key.isNull = false;
H
Haojun Liao 已提交
58
    key.pData  = taosMemoryCalloc(1, pCol->bytes);
H
Haojun Liao 已提交
59 60 61 62
    if (key.pData == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }

H
Haojun Liao 已提交
63
    taosArrayPush((*pGroupColVals), &key);
H
Haojun Liao 已提交
64 65 66
  }

  int32_t nullFlagSize = sizeof(int8_t) * numOfGroupCols;
67
  (*keyLen) += nullFlagSize;
H
Haojun Liao 已提交
68

69
  (*keyBuf) = taosMemoryCalloc(1, (*keyLen));
H
Haojun Liao 已提交
70
  if ((*keyBuf) == NULL) {
H
Haojun Liao 已提交
71 72 73 74 75 76
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
77
static bool groupKeyCompare(SArray* pGroupCols, SArray* pGroupColVals, SSDataBlock* pBlock, int32_t rowIndex, int32_t numOfGroupCols) {
H
Haojun Liao 已提交
78 79
  SColumnDataAgg* pColAgg = NULL;
  for (int32_t i = 0; i < numOfGroupCols; ++i) {
H
Haojun Liao 已提交
80
    SColumn*         pCol = taosArrayGet(pGroupCols, i);
H
Haojun Liao 已提交
81 82
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pCol->slotId);
    if (pBlock->pBlockAgg != NULL) {
83
      pColAgg = pBlock->pBlockAgg[pCol->slotId];  // TODO is agg data matched?
H
Haojun Liao 已提交
84 85 86 87
    }

    bool isNull = colDataIsNull(pColInfoData, pBlock->info.rows, rowIndex, pColAgg);

H
Haojun Liao 已提交
88
    SGroupKeys* pkey = taosArrayGet(pGroupColVals, i);
H
Haojun Liao 已提交
89 90 91 92 93 94 95 96 97 98
    if (pkey->isNull && isNull) {
      continue;
    }

    if (isNull || pkey->isNull) {
      return false;
    }

    char* val = colDataGetData(pColInfoData, rowIndex);

wmmhello's avatar
wmmhello 已提交
99 100 101 102 103 104 105 106 107
    if (pkey->type == TSDB_DATA_TYPE_JSON) {
      int32_t dataLen = getJsonValueLen(val);

      if (memcmp(pkey->pData, val, dataLen) == 0){
        continue;
      } else {
        return false;
      }
    } else if (IS_VAR_DATA_TYPE(pkey->type)) {
H
Haojun Liao 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
      int32_t len = varDataLen(val);
      if (len == varDataLen(pkey->pData) && memcmp(varDataVal(pkey->pData), varDataVal(val), len) == 0) {
        continue;
      } else {
        return false;
      }
    } else {
      if (memcmp(pkey->pData, val, pkey->bytes) != 0) {
        return false;
      }
    }
  }

  return true;
}

wmmhello's avatar
wmmhello 已提交
124
static void recordNewGroupKeys(SArray* pGroupCols, SArray* pGroupColVals, SSDataBlock* pBlock, int32_t rowIndex) {
H
Haojun Liao 已提交
125 126
  SColumnDataAgg* pColAgg = NULL;

127 128
  size_t numOfGroupCols = taosArrayGetSize(pGroupCols);

H
Haojun Liao 已提交
129
  for (int32_t i = 0; i < numOfGroupCols; ++i) {
H
Haojun Liao 已提交
130
    SColumn*         pCol = taosArrayGet(pGroupCols, i);
H
Haojun Liao 已提交
131 132 133
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pCol->slotId);

    if (pBlock->pBlockAgg != NULL) {
134
      pColAgg = pBlock->pBlockAgg[pCol->slotId];  // TODO is agg data matched?
H
Haojun Liao 已提交
135 136
    }

H
Haojun Liao 已提交
137
    SGroupKeys* pkey = taosArrayGet(pGroupColVals, i);
H
Haojun Liao 已提交
138 139 140
    if (colDataIsNull(pColInfoData, pBlock->info.rows, rowIndex, pColAgg)) {
      pkey->isNull = true;
    } else {
141
      pkey->isNull = false;
H
Haojun Liao 已提交
142
      char* val = colDataGetData(pColInfoData, rowIndex);
wmmhello's avatar
wmmhello 已提交
143 144 145 146
      if (pkey->type == TSDB_DATA_TYPE_JSON) {
        int32_t dataLen = getJsonValueLen(val);
        memcpy(pkey->pData, val, dataLen);
      } else if (IS_VAR_DATA_TYPE(pkey->type)) {
H
Haojun Liao 已提交
147
        memcpy(pkey->pData, val, varDataTLen(val));
148
        ASSERT(varDataTLen(val) <= pkey->bytes);
H
Haojun Liao 已提交
149 150 151 152 153 154 155
      } else {
        memcpy(pkey->pData, val, pkey->bytes);
      }
    }
  }
}

wmmhello's avatar
wmmhello 已提交
156
static int32_t buildGroupKeys(void* pKey, const SArray* pGroupColVals) {
H
Haojun Liao 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169
  ASSERT(pKey != NULL);
  size_t numOfGroupCols = taosArrayGetSize(pGroupColVals);

  char* isNull = (char*)pKey;
  char* pStart = (char*)pKey + sizeof(int8_t) * numOfGroupCols;
  for (int32_t i = 0; i < numOfGroupCols; ++i) {
    SGroupKeys* pkey = taosArrayGet(pGroupColVals, i);
    if (pkey->isNull) {
      isNull[i] = 1;
      continue;
    }

    isNull[i] = 0;
wmmhello's avatar
wmmhello 已提交
170 171 172 173 174
    if (pkey->type == TSDB_DATA_TYPE_JSON) {
      int32_t dataLen = getJsonValueLen(pkey->pData);
      memcpy(pStart, (pkey->pData), dataLen);
      pStart += dataLen;
    } else if (IS_VAR_DATA_TYPE(pkey->type)) {
H
Haojun Liao 已提交
175 176 177 178 179 180 181 182 183
      varDataCopy(pStart, pkey->pData);
      pStart += varDataTLen(pkey->pData);
      ASSERT(varDataTLen(pkey->pData) <= pkey->bytes);
    } else {
      memcpy(pStart, pkey->pData, pkey->bytes);
      pStart += pkey->bytes;
    }
  }

H
Haojun Liao 已提交
184
  return (int32_t) (pStart - (char*)pKey);
H
Haojun Liao 已提交
185 186 187 188 189
}

// assign the group keys or user input constant values if required
static void doAssignGroupKeys(SqlFunctionCtx* pCtx, int32_t numOfOutput, int32_t totalRows, int32_t rowIndex) {
  for (int32_t i = 0; i < numOfOutput; ++i) {
190
    if (pCtx[i].functionId == -1) {       // select count(*),key from t group by key.
H
Haojun Liao 已提交
191 192 193
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[i]);

      SColumnInfoData* pColInfoData = pCtx[i].input.pData[0];
194
      // todo OPT all/all not NULL
H
Haojun Liao 已提交
195 196 197 198
      if (!colDataIsNull(pColInfoData, totalRows, rowIndex, NULL)) {
        char* dest = GET_ROWCELL_INTERBUF(pEntryInfo);
        char* data = colDataGetData(pColInfoData, rowIndex);

wmmhello's avatar
wmmhello 已提交
199 200 201 202
        if (pColInfoData->info.type == TSDB_DATA_TYPE_JSON) {
          int32_t dataLen = getJsonValueLen(data);
          memcpy(dest, data, dataLen);
        } else if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
203 204 205 206
          varDataCopy(dest, data);
        } else {
          memcpy(dest, data, pColInfoData->info.bytes);
        }
H
Haojun Liao 已提交
207 208
      } else { // it is a NULL value
        pEntryInfo->isNullRes = 1;
H
Haojun Liao 已提交
209
      }
H
Haojun Liao 已提交
210 211

      pEntryInfo->numOfRes = 1;
H
Haojun Liao 已提交
212 213 214 215 216 217 218 219
    }
  }
}

static void doHashGroupbyAgg(SOperatorInfo* pOperator, SSDataBlock* pBlock) {
  SExecTaskInfo*        pTaskInfo = pOperator->pTaskInfo;
  SGroupbyOperatorInfo* pInfo = pOperator->info;

220
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
H
Haojun Liao 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233
  int32_t         numOfGroupCols = taosArrayGetSize(pInfo->pGroupCols);
  //  if (type == TSDB_DATA_TYPE_FLOAT || type == TSDB_DATA_TYPE_DOUBLE) {
  // qError("QInfo:0x%"PRIx64" group by not supported on double/float columns, abort", GET_TASKID(pRuntimeEnv));
  //    return;
  //  }

  int32_t     len = 0;
  STimeWindow w = TSWINDOW_INITIALIZER;

  int32_t num = 0;
  for (int32_t j = 0; j < pBlock->info.rows; ++j) {
    // Compare with the previous row of this column, and do not set the output buffer again if they are identical.
    if (!pInfo->isInit) {
234
      recordNewGroupKeys(pInfo->pGroupCols, pInfo->pGroupColVals, pBlock, j);
H
Haojun Liao 已提交
235 236 237 238 239
      pInfo->isInit = true;
      num++;
      continue;
    }

H
Haojun Liao 已提交
240
    bool equal = groupKeyCompare(pInfo->pGroupCols, pInfo->pGroupColVals, pBlock, j, numOfGroupCols);
H
Haojun Liao 已提交
241 242 243 244 245
    if (equal) {
      num++;
      continue;
    }

H
Haojun Liao 已提交
246
    // The first row of a new block does not belongs to the previous existed group
247
    if (j == 0) {
H
Haojun Liao 已提交
248
      num++;
249
      recordNewGroupKeys(pInfo->pGroupCols, pInfo->pGroupColVals, pBlock, j);
H
Haojun Liao 已提交
250 251 252
      continue;
    }

H
Haojun Liao 已提交
253
    len = buildGroupKeys(pInfo->keyBuf, pInfo->pGroupColVals);
254
    int32_t ret = setGroupResultOutputBuf(pOperator, &(pInfo->binfo), pOperator->exprSupp.numOfExprs, pInfo->keyBuf, len, 0, pInfo->aggSup.pResultBuf, &pInfo->aggSup);
H
Haojun Liao 已提交
255 256 257 258 259
    if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
    }

    int32_t rowIndex = j - num;
260
    doApplyFunctions(pTaskInfo, pCtx, &w, NULL, rowIndex, num, NULL, pBlock->info.rows, pOperator->exprSupp.numOfExprs, TSDB_ORDER_ASC);
H
Haojun Liao 已提交
261 262

    // assign the group keys or user input constant values if required
263
    doAssignGroupKeys(pCtx, pOperator->exprSupp.numOfExprs, pBlock->info.rows, rowIndex);
264
    recordNewGroupKeys(pInfo->pGroupCols, pInfo->pGroupColVals, pBlock, j);
H
Haojun Liao 已提交
265 266 267 268
    num = 1;
  }

  if (num > 0) {
H
Haojun Liao 已提交
269
    len = buildGroupKeys(pInfo->keyBuf, pInfo->pGroupColVals);
H
Haojun Liao 已提交
270
    int32_t ret =
271 272
        setGroupResultOutputBuf(pOperator, &(pInfo->binfo), pOperator->exprSupp.numOfExprs, pInfo->keyBuf, len,
                                   0, pInfo->aggSup.pResultBuf, &pInfo->aggSup);
H
Haojun Liao 已提交
273 274 275 276 277
    if (ret != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
    }

    int32_t rowIndex = pBlock->info.rows - num;
278 279
    doApplyFunctions(pTaskInfo, pCtx, &w, NULL, rowIndex, num, NULL, pBlock->info.rows, pOperator->exprSupp.numOfExprs, TSDB_ORDER_ASC);
    doAssignGroupKeys(pCtx, pOperator->exprSupp.numOfExprs, pBlock->info.rows, rowIndex);
H
Haojun Liao 已提交
280 281 282
  }
}

283
static SSDataBlock* hashGroupbyAggregate(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
284 285 286 287
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

288 289
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

H
Haojun Liao 已提交
290
  SGroupbyOperatorInfo* pInfo = pOperator->info;
291 292
  SSDataBlock* pRes = pInfo->binfo.pRes;

H
Haojun Liao 已提交
293
  if (pOperator->status == OP_RES_TO_RETURN) {
294
    doBuildResultDatablock(pOperator, &pInfo->binfo, &pInfo->groupResInfo, pInfo->aggSup.pResultBuf);
295 296

    size_t rows = pRes->info.rows;
297
    if (rows == 0 || !hasDataInGroupInfo(&pInfo->groupResInfo)) {
298
      doSetOperatorCompleted(pOperator);
H
Haojun Liao 已提交
299
    }
300 301

    pOperator->resultInfo.totalRows += rows;
H
Haojun Liao 已提交
302
    return (pRes->info.rows == 0)? NULL:pRes;
H
Haojun Liao 已提交
303 304
  }

305 306 307
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;

308
  int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
309 310 311
  SOperatorInfo* downstream = pOperator->pDownstream[0];

  while (1) {
312
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
H
Haojun Liao 已提交
313 314 315 316
    if (pBlock == NULL) {
      break;
    }

317 318 319 320 321
    int32_t code = getTableScanInfo(pOperator, &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
      longjmp(pTaskInfo->env, code);
    }

H
Haojun Liao 已提交
322
    // the pDataBlock are always the same one, no need to call this again
323
    setInputDataBlock(pOperator, pOperator->exprSupp.pCtx, pBlock, order, scanFlag, true);
324

325
    // there is an scalar expression that needs to be calculated right before apply the group aggregation.
326 327
    if (pInfo->scalarSup.pExprInfo != NULL) {
      pTaskInfo->code = projectApplyFunctions(pInfo->scalarSup.pExprInfo, pBlock, pBlock, pInfo->scalarSup.pCtx, pInfo->scalarSup.numOfExprs, NULL);
328 329 330
      if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
        longjmp(pTaskInfo->env, pTaskInfo->code);
      }
331 332
    }

H
Haojun Liao 已提交
333 334 335 336
    doHashGroupbyAgg(pOperator, pBlock);
  }

  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
337

338 339 340 341 342 343 344 345 346 347 348 349 350 351
#if 0
  if(pOperator->fpSet.encodeResultRow){
    char *result = NULL;
    int32_t length = 0;
    pOperator->fpSet.encodeResultRow(pOperator, &result, &length);
    SAggSupporter* pSup = &pInfo->aggSup;
    taosHashClear(pSup->pResultRowHashTable);
    pInfo->binfo.resultRowInfo.size = 0;
    pOperator->fpSet.decodeResultRow(pOperator, result);
    if(result){
      taosMemoryFree(result);
    }
  }
#endif
352
  blockDataEnsureCapacity(pRes, pOperator->resultInfo.capacity);
353
  initGroupedResultInfo(&pInfo->groupResInfo, pInfo->aggSup.pResultRowHashTable, 0);
354

355 356
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;

357
  while(1) {
358
    doBuildResultDatablock(pOperator, &pInfo->binfo, &pInfo->groupResInfo, pInfo->aggSup.pResultBuf);
359
    doFilter(pInfo->pCondition, pRes);
360

361
    bool hasRemain = hasDataInGroupInfo(&pInfo->groupResInfo);
362
    if (!hasRemain) {
363
      doSetOperatorCompleted(pOperator);
364 365 366 367 368 369
      break;
    }

    if (pRes->info.rows > 0) {
      break;
    }
H
Haojun Liao 已提交
370 371
  }

372 373 374 375
  size_t rows = pRes->info.rows;
  pOperator->resultInfo.totalRows += rows;

  return (rows == 0)? NULL:pRes;
H
Haojun Liao 已提交
376 377
}

H
Haojun Liao 已提交
378 379 380
SOperatorInfo* createGroupOperatorInfo(SOperatorInfo* downstream, SExprInfo* pExprInfo, int32_t numOfCols,
                                       SSDataBlock* pResultBlock, SArray* pGroupColList, SNode* pCondition,
                                       SExprInfo* pScalarExprInfo, int32_t numOfScalarExpr, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
381 382 383 384 385 386
  SGroupbyOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SGroupbyOperatorInfo));
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

387 388 389
  pInfo->pGroupCols      = pGroupColList;
  pInfo->pCondition      = pCondition;

390 391 392
  pInfo->scalarSup.pExprInfo = pScalarExprInfo;
  pInfo->scalarSup.numOfExprs = numOfScalarExpr;
  pInfo->scalarSup.pCtx  = createSqlFunctionCtx(pScalarExprInfo, numOfScalarExpr, &pInfo->scalarSup.rowEntryInfoOffset);
393

H
Haojun Liao 已提交
394
  int32_t code = initGroupOptrInfo(&pInfo->pGroupColVals, &pInfo->groupKeyLen, &pInfo->keyBuf, pGroupColList);
H
Haojun Liao 已提交
395 396 397 398
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

399
  initResultSizeInfo(pOperator, 4096);
400 401
  initAggInfo(&pOperator->exprSupp, &pInfo->aggSup, pExprInfo, numOfCols, pInfo->groupKeyLen, pTaskInfo->id.str);
  initBasicInfo(&pInfo->binfo, pResultBlock);
402
  initResultRowInfo(&pInfo->binfo.resultRowInfo);
403

H
Haojun Liao 已提交
404
  pOperator->name         = "GroupbyAggOperator";
405
  pOperator->blocking     = true;
H
Haojun Liao 已提交
406
  pOperator->status       = OP_NOT_OPENED;
407
  // pOperator->operatorType = OP_Groupby;
408 409
  pOperator->exprSupp.pExprInfo    = pExprInfo;
  pOperator->exprSupp.numOfExprs   = numOfCols;
H
Haojun Liao 已提交
410
  pOperator->info         = pInfo;
411
  pOperator->pTaskInfo    = pTaskInfo;
H
Haojun Liao 已提交
412

413
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, hashGroupbyAggregate, NULL, NULL, destroyGroupOperatorInfo, aggEncodeResultRow, aggDecodeResultRow, NULL);
H
Haojun Liao 已提交
414 415 416 417
  code = appendDownstream(pOperator, &downstream, 1);
  return pOperator;

  _error:
H
Haojun Liao 已提交
418
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
419 420 421
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
  return NULL;
422 423
}

H
Haojun Liao 已提交
424
static void doHashPartition(SOperatorInfo* pOperator, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
425
//  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
426 427 428 429

  SPartitionOperatorInfo* pInfo = pOperator->info;

  for (int32_t j = 0; j < pBlock->info.rows; ++j) {
430
    recordNewGroupKeys(pInfo->pGroupCols, pInfo->pGroupColVals, pBlock, j);
H
Haojun Liao 已提交
431 432
    int32_t len = buildGroupKeys(pInfo->keyBuf, pInfo->pGroupColVals);

H
Haojun Liao 已提交
433 434
    SDataGroupInfo* pGInfo = NULL;
    void *pPage = getCurrentDataGroupInfo(pInfo, &pGInfo, len);
H
Haojun Liao 已提交
435

H
Haojun Liao 已提交
436 437 438
    pGInfo->numOfRows += 1;
    if (pGInfo->groupId == 0) {
      pGInfo->groupId = calcGroupId(pInfo->keyBuf, len);
H
Haojun Liao 已提交
439 440
    }

441
    // number of rows
H
Haojun Liao 已提交
442
    int32_t* rows = (int32_t*) pPage;
H
Haojun Liao 已提交
443

444 445
    // group id

446
    size_t numOfCols = pOperator->exprSupp.numOfExprs;
H
Haojun Liao 已提交
447
    for(int32_t i = 0; i < numOfCols; ++i) {
448
      SExprInfo* pExpr = &pOperator->exprSupp.pExprInfo[i];
449 450 451
      int32_t slotId = pExpr->base.pParam[0].pCol->slotId;

      SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, slotId);
H
Haojun Liao 已提交
452

H
Haojun Liao 已提交
453 454
      int32_t bytes = pColInfoData->info.bytes;
      int32_t startOffset = pInfo->columnOffset[i];
H
Haojun Liao 已提交
455

456 457
      int32_t* columnLen  = NULL;
      int32_t  contentLen = 0;
H
Haojun Liao 已提交
458 459

      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
wafwerar's avatar
wafwerar 已提交
460
        int32_t* offset = (int32_t*)((char*)pPage + startOffset);
461 462
        columnLen       = (int32_t*) ((char*)pPage + startOffset + sizeof(int32_t) * pInfo->rowCapacity);
        char*    data   = (char*)((char*) columnLen + sizeof(int32_t));
H
Haojun Liao 已提交
463 464 465 466

        if (colDataIsNull_s(pColInfoData, j)) {
          offset[(*rows)] = -1;
          contentLen = 0;
wmmhello's avatar
wmmhello 已提交
467 468 469 470 471 472 473 474 475 476
        } else if(pColInfoData->info.type == TSDB_DATA_TYPE_JSON){
          offset[*rows] = (*columnLen);
          char* src = colDataGetData(pColInfoData, j);
          int32_t dataLen = getJsonValueLen(src);

          memcpy(data + (*columnLen), src, dataLen);
          int32_t v = (data + (*columnLen) + dataLen - (char*)pPage);
          ASSERT(v > 0);

          contentLen = dataLen;
H
Haojun Liao 已提交
477 478 479 480
        } else {
          offset[*rows] = (*columnLen);
          char* src = colDataGetData(pColInfoData, j);
          memcpy(data + (*columnLen), src, varDataTLen(src));
481 482 483
          int32_t v = (data + (*columnLen) + varDataTLen(src) - (char*)pPage);
          ASSERT(v > 0);

H
Haojun Liao 已提交
484 485
          contentLen = varDataTLen(src);
        }
H
Haojun Liao 已提交
486
      } else {
wafwerar's avatar
wafwerar 已提交
487
        char* bitmap = (char*)pPage + startOffset;
488
        columnLen    = (int32_t*) ((char*)pPage + startOffset + BitmapLen(pInfo->rowCapacity));
H
Haojun Liao 已提交
489
        char* data   = (char*) columnLen + sizeof(int32_t);
H
Haojun Liao 已提交
490 491 492

        bool isNull = colDataIsNull_f(pColInfoData->nullbitmap, j);
        if (isNull) {
H
Haojun Liao 已提交
493
          colDataSetNull_f(bitmap, (*rows));
H
Haojun Liao 已提交
494
        } else {
H
Haojun Liao 已提交
495
          memcpy(data + (*columnLen), colDataGetData(pColInfoData, j), bytes);
H
Haojun Liao 已提交
496
        }
H
Haojun Liao 已提交
497
        contentLen = bytes;
H
Haojun Liao 已提交
498
      }
H
Haojun Liao 已提交
499 500

      (*columnLen) += contentLen;
501
      ASSERT(*columnLen >= 0);
H
Haojun Liao 已提交
502 503
    }

H
Haojun Liao 已提交
504 505
    (*rows) += 1;

H
Haojun Liao 已提交
506 507 508
    setBufPageDirty(pPage, true);
    releaseBufPage(pInfo->pBuf, pPage);
  }
H
Haojun Liao 已提交
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
}

void* getCurrentDataGroupInfo(const SPartitionOperatorInfo* pInfo, SDataGroupInfo** pGroupInfo, int32_t len) {
  SDataGroupInfo* p = taosHashGet(pInfo->pGroupSet, pInfo->keyBuf, len);

  void* pPage = NULL;
  if (p == NULL) { // it is a new group
    SDataGroupInfo gi = {0};
    gi.pPageList = taosArrayInit(100, sizeof(int32_t));
    taosHashPut(pInfo->pGroupSet, pInfo->keyBuf, len, &gi, sizeof(SDataGroupInfo));

    p = taosHashGet(pInfo->pGroupSet, pInfo->keyBuf, len);

    int32_t pageId = 0;
    pPage = getNewBufPage(pInfo->pBuf, 0, &pageId);
    taosArrayPush(p->pPageList, &pageId);

    *(int32_t *) pPage = 0;
  } else {
    int32_t* curId = taosArrayGetLast(p->pPageList);
    pPage = getBufPage(pInfo->pBuf, *curId);

    int32_t *rows = (int32_t*) pPage;
    if (*rows >= pInfo->rowCapacity) {
533 534 535
      // release buffer
      releaseBufPage(pInfo->pBuf, pPage);

H
Haojun Liao 已提交
536 537 538 539
      // add a new page for current group
      int32_t pageId = 0;
      pPage = getNewBufPage(pInfo->pBuf, 0, &pageId);
      taosArrayPush(p->pPageList, &pageId);
540
      memset(pPage, 0, getBufPageSize(pInfo->pBuf));
H
Haojun Liao 已提交
541 542
    }
  }
H
Haojun Liao 已提交
543

H
Haojun Liao 已提交
544 545 546 547 548 549 550 551 552 553 554 555 556 557
  *pGroupInfo = p;
  return pPage;
}

uint64_t calcGroupId(char* pData, int32_t len) {
  T_MD5_CTX context;
  tMD5Init(&context);
  tMD5Update(&context, (uint8_t*)pData, len);
  tMD5Final(&context);

  // NOTE: only extract the initial 8 bytes of the final MD5 digest
  uint64_t id = 0;
  memcpy(&id, context.digest, sizeof(uint64_t));
  return id;
H
Haojun Liao 已提交
558 559
}

H
Haojun Liao 已提交
560 561 562 563
int32_t* setupColumnOffset(const SSDataBlock* pBlock, int32_t rowCapacity) {
  size_t numOfCols = pBlock->info.numOfCols;
  int32_t* offset = taosMemoryCalloc(pBlock->info.numOfCols, sizeof(int32_t));

564
  offset[0] = sizeof(int32_t) + sizeof(uint64_t);  // the number of rows in current page, ref to SSDataBlock paged serialization format
H
Haojun Liao 已提交
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583

  for(int32_t i = 0; i < numOfCols - 1; ++i) {
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, i);

    int32_t bytes = pColInfoData->info.bytes;
    int32_t payloadLen = bytes * rowCapacity;
    
    if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
      // offset segment + content length + payload
      offset[i + 1] = rowCapacity * sizeof(int32_t) + sizeof(int32_t) + payloadLen + offset[i];
    } else {
      // bitmap + content length + payload
      offset[i + 1] = BitmapLen(rowCapacity) + sizeof(int32_t) + payloadLen + offset[i];
    }
  }

  return offset;
}

5
54liuyao 已提交
584 585 586 587 588 589 590 591 592
static void clearPartitionOperator(SPartitionOperatorInfo* pInfo) {
  void *ite = NULL;
  while( (ite = taosHashIterate(pInfo->pGroupSet, ite)) != NULL ) {
    taosArrayDestroy( ((SDataGroupInfo *)ite)->pPageList);
  }
  taosHashClear(pInfo->pGroupSet);
  clearDiskbasedBuf(pInfo->pBuf);
}

H
Haojun Liao 已提交
593 594 595 596 597 598 599 600
static SSDataBlock* buildPartitionResult(SOperatorInfo* pOperator) {
  SPartitionOperatorInfo* pInfo = pOperator->info;

  SDataGroupInfo* pGroupInfo = pInfo->pGroupIter;
  if (pInfo->pGroupIter == NULL || pInfo->pageIndex >= taosArrayGetSize(pGroupInfo->pPageList)) {
    // try next group data
    pInfo->pGroupIter = taosHashIterate(pInfo->pGroupSet, pInfo->pGroupIter);
    if (pInfo->pGroupIter == NULL) {
601
      doSetOperatorCompleted(pOperator);
5
54liuyao 已提交
602
      clearPartitionOperator(pInfo);
H
Haojun Liao 已提交
603 604 605 606 607 608 609 610 611 612
      return NULL;
    }

    pGroupInfo = pInfo->pGroupIter;
    pInfo->pageIndex = 0;
  }

  int32_t* pageId = taosArrayGet(pGroupInfo->pPageList, pInfo->pageIndex);
  void* page = getBufPage(pInfo->pBuf, *pageId);

H
Haojun Liao 已提交
613
  blockDataFromBuf1(pInfo->binfo.pRes, page, pInfo->rowCapacity);
H
Haojun Liao 已提交
614 615

  pInfo->pageIndex += 1;
616
  releaseBufPage(pInfo->pBuf, page);
H
Haojun Liao 已提交
617

618
  blockDataUpdateTsWindow(pInfo->binfo.pRes, 0);
H
Haojun Liao 已提交
619
  pInfo->binfo.pRes->info.groupId = pGroupInfo->groupId;
620 621

  pOperator->resultInfo.totalRows += pInfo->binfo.pRes->info.rows;
H
Haojun Liao 已提交
622 623 624
  return pInfo->binfo.pRes;
}

625
static SSDataBlock* hashPartition(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
626 627
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
628 629
  }

630 631 632
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

  SPartitionOperatorInfo* pInfo = pOperator->info;
H
Haojun Liao 已提交
633
  SSDataBlock* pRes = pInfo->binfo.pRes;
634

H
Haojun Liao 已提交
635
  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
636 637
    blockDataCleanup(pRes);
    return buildPartitionResult(pOperator);
H
Haojun Liao 已提交
638 639
  }

640
  int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
641
  SOperatorInfo* downstream = pOperator->pDownstream[0];
H
Haojun Liao 已提交
642

H
Haojun Liao 已提交
643
  while (1) {
644
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
H
Haojun Liao 已提交
645 646 647
    if (pBlock == NULL) {
      break;
    }
H
Haojun Liao 已提交
648

649
    // there is an scalar expression that needs to be calculated right before apply the group aggregation.
650 651
    if (pInfo->scalarSup.pExprInfo != NULL) {
      pTaskInfo->code = projectApplyFunctions(pInfo->scalarSup.pExprInfo, pBlock, pBlock, pInfo->scalarSup.pCtx, pInfo->scalarSup.numOfExprs, NULL);
652 653 654 655 656
      if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
        longjmp(pTaskInfo->env, pTaskInfo->code);
      }
    }

H
Haojun Liao 已提交
657
    doHashPartition(pOperator, pBlock);
H
Haojun Liao 已提交
658 659
  }

660 661
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;

H
Haojun Liao 已提交
662
  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
663 664 665 666 667
  blockDataEnsureCapacity(pRes, 4096);
  return buildPartitionResult(pOperator);
}

static void destroyPartitionOperatorInfo(void* param, int32_t numOfOutput) {
H
Haojun Liao 已提交
668
  SPartitionOperatorInfo* pInfo = (SPartitionOperatorInfo*)param;
669
  cleanupBasicInfo(&pInfo->binfo);
H
Haojun Liao 已提交
670
  taosArrayDestroy(pInfo->pGroupCols);
671

wmmhello's avatar
wmmhello 已提交
672 673 674 675
  for(int i = 0; i < taosArrayGetSize(pInfo->pGroupColVals); i++){
    SGroupKeys key = *(SGroupKeys*)taosArrayGet(pInfo->pGroupColVals, i);
    taosMemoryFree(key.pData);
  }
676

H
Haojun Liao 已提交
677
  taosArrayDestroy(pInfo->pGroupColVals);
H
Haojun Liao 已提交
678
  taosMemoryFree(pInfo->keyBuf);
wmmhello's avatar
wmmhello 已提交
679
  taosHashCleanup(pInfo->pGroupSet);
H
Haojun Liao 已提交
680
  taosMemoryFree(pInfo->columnOffset);
681 682

  cleanupExecSupp(&pInfo->scalarSup);
H
Haojun Liao 已提交
683 684
}

685
SOperatorInfo* createPartitionOperatorInfo(SOperatorInfo* downstream, SPartitionPhysiNode* pPartNode, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
686 687
  SPartitionOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SPartitionOperatorInfo));
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
688
  if (pInfo == NULL || pOperator == NULL) {
H
Haojun Liao 已提交
689 690
    goto _error;
  }
691

692 693 694 695 696 697 698 699
  SSDataBlock* pResBlock = createResDataBlock(pPartNode->node.pOutputDataBlockDesc);

  int32_t numOfCols = 0;
  SExprInfo* pExprInfo = createExprInfo(pPartNode->pTargets, NULL, &numOfCols);

  pInfo->pGroupCols = extractPartitionColInfo(pPartNode->pPartitionKeys);

  if (pPartNode->pExprs != NULL) {
700 701 702 703
    pInfo->scalarSup.numOfExprs = 0;
    pInfo->scalarSup.pExprInfo = createExprInfo(pPartNode->pExprs, NULL, &pInfo->scalarSup.numOfExprs);
    pInfo->scalarSup.pCtx = createSqlFunctionCtx(
        pInfo->scalarSup.pExprInfo, pInfo->scalarSup.numOfExprs, &pInfo->scalarSup.rowEntryInfoOffset);
704
  }
H
Haojun Liao 已提交
705 706 707 708 709 710 711

  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);
  pInfo->pGroupSet = taosHashInit(100, hashFn, false, HASH_NO_LOCK);
  if (pInfo->pGroupSet == NULL) {
    goto _error;
  }

712 713
  uint32_t defaultPgsz  = 0;
  uint32_t defaultBufsz = 0;
714
  getBufferPgSize(pResBlock->info.rowSize, &defaultPgsz, &defaultBufsz);
715 716

  int32_t code = createDiskbasedBuf(&pInfo->pBuf, defaultPgsz, defaultBufsz, pTaskInfo->id.str, TD_TMP_DIR_PATH);
H
Haojun Liao 已提交
717 718 719 720
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

721 722 723
  pInfo->rowCapacity = blockDataGetCapacityInRow(pResBlock, getBufPageSize(pInfo->pBuf));
  pInfo->columnOffset = setupColumnOffset(pResBlock, pInfo->rowCapacity);
  code = initGroupOptrInfo(&pInfo->pGroupColVals, &pInfo->groupKeyLen, &pInfo->keyBuf, pInfo->pGroupCols);
H
Haojun Liao 已提交
724 725 726
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
727 728

  pOperator->name         = "PartitionOperator";
729
  pOperator->blocking     = true;
730
  pOperator->status       = OP_NOT_OPENED;
H
Haojun Liao 已提交
731
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PARTITION;
732
  pInfo->binfo.pRes       = pResBlock;
733 734
  pOperator->exprSupp.numOfExprs   = numOfCols;
  pOperator->exprSupp.pExprInfo    = pExprInfo;
H
Haojun Liao 已提交
735
  pOperator->info         = pInfo;
736
  pOperator->pTaskInfo    = pTaskInfo;
737 738 739

  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, hashPartition, NULL, NULL, destroyPartitionOperatorInfo,
                                         NULL, NULL, NULL);
H
Haojun Liao 已提交
740

H
Haojun Liao 已提交
741
  code = appendDownstream(pOperator, &downstream, 1);
742 743 744
  return pOperator;

  _error:
H
Haojun Liao 已提交
745
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
746 747
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
748
  return NULL;
749 750
}

751 752 753
int32_t setGroupResultOutputBuf(SOperatorInfo* pOperator, SOptrBasicInfo* binfo, int32_t numOfCols, char* pData, int16_t bytes,
                                int32_t groupId, SDiskbasedBuf* pBuf, SAggSupporter* pAggSup) {
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
754
  SResultRowInfo* pResultRowInfo = &binfo->resultRowInfo;
755
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
756 757 758 759 760

  SResultRow* pResultRow =
      doSetResultOutBufByKey(pBuf, pResultRowInfo, (char*)pData, bytes, true, groupId, pTaskInfo, false, pAggSup);
  assert(pResultRow != NULL);

761
  setResultRowInitCtx(pResultRow, pCtx, numOfCols, pOperator->exprSupp.rowEntryInfoOffset);
762
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
763
}