groupoperator.c 27.9 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
static int32_t  setGroupResultOutputBuf(SOperatorInfo* pOperator, SOptrBasicInfo* binfo, int32_t numOfCols, char* pData, int16_t bytes,
32
                                        uint64_t groupId, SDiskbasedBuf* pBuf, SAggSupporter* pAggSup);
H
Haojun Liao 已提交
33

H
Haojun Liao 已提交
34 35 36 37 38
static void freeGroupKey(void* param) {
  SGroupKeys* pKey = (SGroupKeys*) param;
  taosMemoryFree(pKey->pData);
}

39
static void destroyGroupOperatorInfo(void* param) {
H
Haojun Liao 已提交
40
  SGroupbyOperatorInfo* pInfo = (SGroupbyOperatorInfo*)param;
41 42 43 44
  if (pInfo == NULL) {
    return;
  }

45
  cleanupBasicInfo(&pInfo->binfo);
H
Haojun Liao 已提交
46 47
  taosMemoryFreeClear(pInfo->keyBuf);
  taosArrayDestroy(pInfo->pGroupCols);
H
Haojun Liao 已提交
48
  taosArrayDestroyEx(pInfo->pGroupColVals, freeGroupKey);
49
  cleanupExprSupp(&pInfo->scalarSup);
H
Haojun Liao 已提交
50 51 52

  cleanupGroupResInfo(&pInfo->groupResInfo);
  cleanupAggSup(&pInfo->aggSup);
D
dapan1121 已提交
53
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
54 55
}

wmmhello's avatar
wmmhello 已提交
56
static int32_t initGroupOptrInfo(SArray** pGroupColVals, int32_t* keyLen, char** keyBuf, const SArray* pGroupColList) {
H
Haojun Liao 已提交
57 58
  *pGroupColVals = taosArrayInit(4, sizeof(SGroupKeys));
  if ((*pGroupColVals) == NULL) {
H
Haojun Liao 已提交
59 60 61 62 63 64
    return TSDB_CODE_OUT_OF_MEMORY;
  }

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

67
    SGroupKeys key = {0};
H
Haojun Liao 已提交
68 69
    key.bytes  = pCol->bytes;
    key.type   = pCol->type;
H
Haojun Liao 已提交
70
    key.isNull = false;
H
Haojun Liao 已提交
71
    key.pData  = taosMemoryCalloc(1, pCol->bytes);
H
Haojun Liao 已提交
72 73 74 75
    if (key.pData == NULL) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }

H
Haojun Liao 已提交
76
    taosArrayPush((*pGroupColVals), &key);
H
Haojun Liao 已提交
77 78 79
  }

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

82
  (*keyBuf) = taosMemoryCalloc(1, (*keyLen));
H
Haojun Liao 已提交
83
  if ((*keyBuf) == NULL) {
H
Haojun Liao 已提交
84 85 86 87 88 89
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
90
static bool groupKeyCompare(SArray* pGroupCols, SArray* pGroupColVals, SSDataBlock* pBlock, int32_t rowIndex, int32_t numOfGroupCols) {
H
Haojun Liao 已提交
91 92
  SColumnDataAgg* pColAgg = NULL;
  for (int32_t i = 0; i < numOfGroupCols; ++i) {
H
Haojun Liao 已提交
93
    SColumn*         pCol = taosArrayGet(pGroupCols, i);
H
Haojun Liao 已提交
94 95
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pCol->slotId);
    if (pBlock->pBlockAgg != NULL) {
96
      pColAgg = pBlock->pBlockAgg[pCol->slotId];  // TODO is agg data matched?
H
Haojun Liao 已提交
97 98 99 100
    }

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

H
Haojun Liao 已提交
101
    SGroupKeys* pkey = taosArrayGet(pGroupColVals, i);
H
Haojun Liao 已提交
102 103 104 105 106 107 108 109 110 111
    if (pkey->isNull && isNull) {
      continue;
    }

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

    char* val = colDataGetData(pColInfoData, rowIndex);

wmmhello's avatar
wmmhello 已提交
112 113 114 115 116 117 118 119 120
    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 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
      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 已提交
137
static void recordNewGroupKeys(SArray* pGroupCols, SArray* pGroupColVals, SSDataBlock* pBlock, int32_t rowIndex) {
H
Haojun Liao 已提交
138 139
  SColumnDataAgg* pColAgg = NULL;

140 141
  size_t numOfGroupCols = taosArrayGetSize(pGroupCols);

H
Haojun Liao 已提交
142
  for (int32_t i = 0; i < numOfGroupCols; ++i) {
H
Haojun Liao 已提交
143
    SColumn*         pCol = taosArrayGet(pGroupCols, i);
H
Haojun Liao 已提交
144 145 146
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pCol->slotId);

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

H
Haojun Liao 已提交
150
    SGroupKeys* pkey = taosArrayGet(pGroupColVals, i);
H
Haojun Liao 已提交
151 152 153
    if (colDataIsNull(pColInfoData, pBlock->info.rows, rowIndex, pColAgg)) {
      pkey->isNull = true;
    } else {
154
      pkey->isNull = false;
H
Haojun Liao 已提交
155
      char* val = colDataGetData(pColInfoData, rowIndex);
wmmhello's avatar
wmmhello 已提交
156
      if (pkey->type == TSDB_DATA_TYPE_JSON) {
wmmhello's avatar
wmmhello 已提交
157 158 159 160
        if(tTagIsJson(val)){
          terrno = TSDB_CODE_QRY_JSON_IN_GROUP_ERROR;
          return;
        }
wmmhello's avatar
wmmhello 已提交
161 162 163
        int32_t dataLen = getJsonValueLen(val);
        memcpy(pkey->pData, val, dataLen);
      } else if (IS_VAR_DATA_TYPE(pkey->type)) {
H
Haojun Liao 已提交
164
        memcpy(pkey->pData, val, varDataTLen(val));
165
        ASSERT(varDataTLen(val) <= pkey->bytes);
H
Haojun Liao 已提交
166 167 168 169 170 171 172
      } else {
        memcpy(pkey->pData, val, pkey->bytes);
      }
    }
  }
}

wmmhello's avatar
wmmhello 已提交
173
static int32_t buildGroupKeys(void* pKey, const SArray* pGroupColVals) {
H
Haojun Liao 已提交
174 175 176 177 178 179 180 181 182 183 184 185 186
  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 已提交
187 188 189 190 191
    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 已提交
192 193 194 195 196 197 198 199 200
      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 已提交
201
  return (int32_t) (pStart - (char*)pKey);
H
Haojun Liao 已提交
202 203 204 205 206
}

// 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) {
207
    if (pCtx[i].functionId == -1) {       // select count(*),key from t group by key.
H
Haojun Liao 已提交
208 209 210
      SResultRowEntryInfo* pEntryInfo = GET_RES_INFO(&pCtx[i]);

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

wmmhello's avatar
wmmhello 已提交
216 217 218 219
        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)) {
220 221 222 223
          varDataCopy(dest, data);
        } else {
          memcpy(dest, data, pColInfoData->info.bytes);
        }
H
Haojun Liao 已提交
224 225
      } else { // it is a NULL value
        pEntryInfo->isNullRes = 1;
H
Haojun Liao 已提交
226
      }
H
Haojun Liao 已提交
227 228

      pEntryInfo->numOfRes = 1;
H
Haojun Liao 已提交
229 230 231 232 233 234 235 236
    }
  }
}

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

237
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
H
Haojun Liao 已提交
238 239 240 241 242 243 244 245 246
  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;

wmmhello's avatar
wmmhello 已提交
247
  terrno = TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
248 249 250 251
  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) {
252
      recordNewGroupKeys(pInfo->pGroupCols, pInfo->pGroupColVals, pBlock, j);
wmmhello's avatar
wmmhello 已提交
253
      if (terrno != TSDB_CODE_SUCCESS) {  // group by json error
254
        T_LONG_JMP(pTaskInfo->env, terrno);
wmmhello's avatar
wmmhello 已提交
255
      }
H
Haojun Liao 已提交
256 257 258 259 260
      pInfo->isInit = true;
      num++;
      continue;
    }

H
Haojun Liao 已提交
261
    bool equal = groupKeyCompare(pInfo->pGroupCols, pInfo->pGroupColVals, pBlock, j, numOfGroupCols);
H
Haojun Liao 已提交
262 263 264 265 266
    if (equal) {
      num++;
      continue;
    }

H
Haojun Liao 已提交
267
    // The first row of a new block does not belongs to the previous existed group
268
    if (j == 0) {
H
Haojun Liao 已提交
269
      num++;
270
      recordNewGroupKeys(pInfo->pGroupCols, pInfo->pGroupColVals, pBlock, j);
wmmhello's avatar
wmmhello 已提交
271
      if (terrno != TSDB_CODE_SUCCESS) {  // group by json error
272
        T_LONG_JMP(pTaskInfo->env, terrno);
wmmhello's avatar
wmmhello 已提交
273
      }
H
Haojun Liao 已提交
274 275 276
      continue;
    }

H
Haojun Liao 已提交
277
    len = buildGroupKeys(pInfo->keyBuf, pInfo->pGroupColVals);
278
    int32_t ret = setGroupResultOutputBuf(pOperator, &(pInfo->binfo), pOperator->exprSupp.numOfExprs, pInfo->keyBuf, len, pBlock->info.groupId, pInfo->aggSup.pResultBuf, &pInfo->aggSup);
H
Haojun Liao 已提交
279
    if (ret != TSDB_CODE_SUCCESS) {  // null data, too many state code
280
      T_LONG_JMP(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
H
Haojun Liao 已提交
281 282 283
    }

    int32_t rowIndex = j - num;
284
    doApplyFunctions(pTaskInfo, pCtx, NULL, rowIndex, num, pBlock->info.rows, pOperator->exprSupp.numOfExprs);
H
Haojun Liao 已提交
285 286

    // assign the group keys or user input constant values if required
287
    doAssignGroupKeys(pCtx, pOperator->exprSupp.numOfExprs, pBlock->info.rows, rowIndex);
288
    recordNewGroupKeys(pInfo->pGroupCols, pInfo->pGroupColVals, pBlock, j);
H
Haojun Liao 已提交
289 290 291 292
    num = 1;
  }

  if (num > 0) {
H
Haojun Liao 已提交
293
    len = buildGroupKeys(pInfo->keyBuf, pInfo->pGroupColVals);
H
Haojun Liao 已提交
294
    int32_t ret =
295
        setGroupResultOutputBuf(pOperator, &(pInfo->binfo), pOperator->exprSupp.numOfExprs, pInfo->keyBuf, len,
296
                                pBlock->info.groupId, pInfo->aggSup.pResultBuf, &pInfo->aggSup);
H
Haojun Liao 已提交
297
    if (ret != TSDB_CODE_SUCCESS) {
298
      T_LONG_JMP(pTaskInfo->env, TSDB_CODE_QRY_APP_ERROR);
H
Haojun Liao 已提交
299 300 301
    }

    int32_t rowIndex = pBlock->info.rows - num;
302
    doApplyFunctions(pTaskInfo, pCtx, NULL, rowIndex, num, pBlock->info.rows, pOperator->exprSupp.numOfExprs);
303
    doAssignGroupKeys(pCtx, pOperator->exprSupp.numOfExprs, pBlock->info.rows, rowIndex);
H
Haojun Liao 已提交
304 305 306
  }
}

307 308 309 310 311 312
static SSDataBlock* buildGroupResultDataBlock(SOperatorInfo* pOperator) {
  SGroupbyOperatorInfo* pInfo = pOperator->info;

  SSDataBlock* pRes = pInfo->binfo.pRes;
  while(1) {
    doBuildResultDatablock(pOperator, &pInfo->binfo, &pInfo->groupResInfo, pInfo->aggSup.pResultBuf);
313
    doFilter(pInfo->pCondition, pRes, NULL);
314

315
    if (!hasRemainResults(&pInfo->groupResInfo)) {
316 317 318 319 320 321 322 323 324 325 326 327 328
      doSetOperatorCompleted(pOperator);
      break;
    }

    if (pRes->info.rows > 0) {
      break;
    }
  }

  pOperator->resultInfo.totalRows += pRes->info.rows;
  return (pRes->info.rows == 0)? NULL:pRes;
}

329
static SSDataBlock* hashGroupbyAggregate(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
330 331 332 333
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
  }

334 335
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

H
Haojun Liao 已提交
336
  SGroupbyOperatorInfo* pInfo = pOperator->info;
337 338
  SSDataBlock* pRes = pInfo->binfo.pRes;

H
Haojun Liao 已提交
339
  if (pOperator->status == OP_RES_TO_RETURN) {
340
    return buildGroupResultDataBlock(pOperator);
H
Haojun Liao 已提交
341 342
  }

343 344 345
  int32_t order = TSDB_ORDER_ASC;
  int32_t scanFlag = MAIN_SCAN;

346
  int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
347 348 349
  SOperatorInfo* downstream = pOperator->pDownstream[0];

  while (1) {
350
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
H
Haojun Liao 已提交
351 352 353 354
    if (pBlock == NULL) {
      break;
    }

355 356
    int32_t code = getTableScanInfo(pOperator, &order, &scanFlag);
    if (code != TSDB_CODE_SUCCESS) {
357
      T_LONG_JMP(pTaskInfo->env, code);
358 359
    }

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

363
    // there is an scalar expression that needs to be calculated right before apply the group aggregation.
364 365
    if (pInfo->scalarSup.pExprInfo != NULL) {
      pTaskInfo->code = projectApplyFunctions(pInfo->scalarSup.pExprInfo, pBlock, pBlock, pInfo->scalarSup.pCtx, pInfo->scalarSup.numOfExprs, NULL);
366
      if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
367
        T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
368
      }
369 370
    }

H
Haojun Liao 已提交
371 372 373 374
    doHashGroupbyAgg(pOperator, pBlock);
  }

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

376 377 378 379 380 381 382 383 384 385 386 387 388 389
#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
390
  blockDataEnsureCapacity(pRes, pOperator->resultInfo.capacity);
391
  initGroupedResultInfo(&pInfo->groupResInfo, pInfo->aggSup.pResultRowHashTable, 0);
392

393
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;
394
  return buildGroupResultDataBlock(pOperator);
H
Haojun Liao 已提交
395 396
}

H
Haojun Liao 已提交
397 398 399
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 已提交
400 401 402 403 404 405
  SGroupbyOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SGroupbyOperatorInfo));
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
  if (pInfo == NULL || pOperator == NULL) {
    goto _error;
  }

406 407 408
  pInfo->pGroupCols      = pGroupColList;
  pInfo->pCondition      = pCondition;

409 410 411 412
  int32_t code = initExprSupp(&pInfo->scalarSup, pScalarExprInfo, numOfScalarExpr);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
413

414
  code = initGroupOptrInfo(&pInfo->pGroupColVals, &pInfo->groupKeyLen, &pInfo->keyBuf, pGroupColList);
H
Haojun Liao 已提交
415 416 417 418
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

419
  initResultSizeInfo(&pOperator->resultInfo, 4096);
420 421 422 423 424
  code = initAggInfo(&pOperator->exprSupp, &pInfo->aggSup, pExprInfo, numOfCols, pInfo->groupKeyLen, pTaskInfo->id.str);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

425
  initBasicInfo(&pInfo->binfo, pResultBlock);
426
  initResultRowInfo(&pInfo->binfo.resultRowInfo);
427

H
Haojun Liao 已提交
428
  pOperator->name         = "GroupbyAggOperator";
429
  pOperator->blocking     = true;
H
Haojun Liao 已提交
430
  pOperator->status       = OP_NOT_OPENED;
431
  // pOperator->operatorType = OP_Groupby;
H
Haojun Liao 已提交
432
  pOperator->info         = pInfo;
433
  pOperator->pTaskInfo    = pTaskInfo;
H
Haojun Liao 已提交
434

435
  pOperator->fpSet = createOperatorFpSet(operatorDummyOpenFn, hashGroupbyAggregate, NULL, NULL, destroyGroupOperatorInfo, aggEncodeResultRow, aggDecodeResultRow, NULL);
H
Haojun Liao 已提交
436
  code = appendDownstream(pOperator, &downstream, 1);
437 438 439 440
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

H
Haojun Liao 已提交
441 442 443
  return pOperator;

  _error:
H
Haojun Liao 已提交
444
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
445
  destroyGroupOperatorInfo(pInfo);
H
Haojun Liao 已提交
446 447
  taosMemoryFreeClear(pOperator);
  return NULL;
448 449
}

H
Haojun Liao 已提交
450
static void doHashPartition(SOperatorInfo* pOperator, SSDataBlock* pBlock) {
H
Haojun Liao 已提交
451
//  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
H
Haojun Liao 已提交
452 453 454 455

  SPartitionOperatorInfo* pInfo = pOperator->info;

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

459 460
    SDataGroupInfo* pGroupInfo = NULL;
    void *pPage = getCurrentDataGroupInfo(pInfo, &pGroupInfo, len);
H
Haojun Liao 已提交
461

462 463 464 465 466
    pGroupInfo->numOfRows += 1;

    // group id
    if (pGroupInfo->groupId == 0) {
      pGroupInfo->groupId = calcGroupId(pInfo->keyBuf, len);
H
Haojun Liao 已提交
467 468
    }

469
    // number of rows
H
Haojun Liao 已提交
470
    int32_t* rows = (int32_t*) pPage;
H
Haojun Liao 已提交
471

472
    size_t numOfCols = pOperator->exprSupp.numOfExprs;
H
Haojun Liao 已提交
473
    for(int32_t i = 0; i < numOfCols; ++i) {
474
      SExprInfo* pExpr = &pOperator->exprSupp.pExprInfo[i];
475 476 477
      int32_t slotId = pExpr->base.pParam[0].pCol->slotId;

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

H
Haojun Liao 已提交
479 480
      int32_t bytes = pColInfoData->info.bytes;
      int32_t startOffset = pInfo->columnOffset[i];
H
Haojun Liao 已提交
481

482 483
      int32_t* columnLen  = NULL;
      int32_t  contentLen = 0;
H
Haojun Liao 已提交
484 485

      if (IS_VAR_DATA_TYPE(pColInfoData->info.type)) {
wafwerar's avatar
wafwerar 已提交
486
        int32_t* offset = (int32_t*)((char*)pPage + startOffset);
487 488
        columnLen       = (int32_t*) ((char*)pPage + startOffset + sizeof(int32_t) * pInfo->rowCapacity);
        char*    data   = (char*)((char*) columnLen + sizeof(int32_t));
H
Haojun Liao 已提交
489 490 491 492

        if (colDataIsNull_s(pColInfoData, j)) {
          offset[(*rows)] = -1;
          contentLen = 0;
wmmhello's avatar
wmmhello 已提交
493 494 495 496 497 498 499 500 501 502
        } 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 已提交
503 504 505 506
        } else {
          offset[*rows] = (*columnLen);
          char* src = colDataGetData(pColInfoData, j);
          memcpy(data + (*columnLen), src, varDataTLen(src));
507 508 509
          int32_t v = (data + (*columnLen) + varDataTLen(src) - (char*)pPage);
          ASSERT(v > 0);

H
Haojun Liao 已提交
510 511
          contentLen = varDataTLen(src);
        }
H
Haojun Liao 已提交
512
      } else {
wafwerar's avatar
wafwerar 已提交
513
        char* bitmap = (char*)pPage + startOffset;
514
        columnLen    = (int32_t*) ((char*)pPage + startOffset + BitmapLen(pInfo->rowCapacity));
H
Haojun Liao 已提交
515
        char* data   = (char*) columnLen + sizeof(int32_t);
H
Haojun Liao 已提交
516 517 518

        bool isNull = colDataIsNull_f(pColInfoData->nullbitmap, j);
        if (isNull) {
H
Haojun Liao 已提交
519
          colDataSetNull_f(bitmap, (*rows));
H
Haojun Liao 已提交
520
        } else {
H
Haojun Liao 已提交
521
          memcpy(data + (*columnLen), colDataGetData(pColInfoData, j), bytes);
H
Haojun Liao 已提交
522
          ASSERT((data + (*columnLen) + bytes - (char*)pPage) <= getBufPageSize(pInfo->pBuf));
H
Haojun Liao 已提交
523
        }
H
Haojun Liao 已提交
524
        contentLen = bytes;
H
Haojun Liao 已提交
525
      }
H
Haojun Liao 已提交
526 527

      (*columnLen) += contentLen;
528
      ASSERT(*columnLen >= 0);
H
Haojun Liao 已提交
529 530
    }

H
Haojun Liao 已提交
531 532
    (*rows) += 1;

H
Haojun Liao 已提交
533 534 535
    setBufPageDirty(pPage, true);
    releaseBufPage(pInfo->pBuf, pPage);
  }
H
Haojun Liao 已提交
536 537 538 539 540 541 542 543 544 545 546 547 548 549
}

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;
550
    pPage = getNewBufPage(pInfo->pBuf, &pageId);
H
Haojun Liao 已提交
551 552 553 554 555 556 557 558 559
    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) {
560 561 562
      // release buffer
      releaseBufPage(pInfo->pBuf, pPage);

H
Haojun Liao 已提交
563 564
      // add a new page for current group
      int32_t pageId = 0;
565
      pPage = getNewBufPage(pInfo->pBuf, &pageId);
H
Haojun Liao 已提交
566
      taosArrayPush(p->pPageList, &pageId);
567
      memset(pPage, 0, getBufPageSize(pInfo->pBuf));
H
Haojun Liao 已提交
568 569
    }
  }
H
Haojun Liao 已提交
570

H
Haojun Liao 已提交
571 572 573 574 575 576 577 578 579 580 581 582 583 584
  *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 已提交
585 586
}

H
Haojun Liao 已提交
587
int32_t* setupColumnOffset(const SSDataBlock* pBlock, int32_t rowCapacity) {
588 589
  size_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
  int32_t* offset = taosMemoryCalloc(numOfCols, sizeof(int32_t));
H
Haojun Liao 已提交
590

591
  offset[0] = sizeof(int32_t) + sizeof(uint64_t);  // the number of rows in current page, ref to SSDataBlock paged serialization format
H
Haojun Liao 已提交
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610

  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 已提交
611 612 613 614 615
static void clearPartitionOperator(SPartitionOperatorInfo* pInfo) {
  void *ite = NULL;
  while( (ite = taosHashIterate(pInfo->pGroupSet, ite)) != NULL ) {
    taosArrayDestroy( ((SDataGroupInfo *)ite)->pPageList);
  }
616
  taosArrayClear(pInfo->sortedGroupArray);
5
54liuyao 已提交
617 618 619
  clearDiskbasedBuf(pInfo->pBuf);
}

620 621 622
static int compareDataGroupInfo(const void* group1, const void* group2) {
  const SDataGroupInfo* pGroupInfo1 = group1;
  const SDataGroupInfo* pGroupInfo2 = group2;
623 624 625 626 627 628 629

  if (pGroupInfo1->groupId == pGroupInfo2->groupId) {
    ASSERT(0);
    return 0;
  }

  return (pGroupInfo1->groupId < pGroupInfo2->groupId)? -1:1;
630 631
}

H
Haojun Liao 已提交
632 633 634
static SSDataBlock* buildPartitionResult(SOperatorInfo* pOperator) {
  SPartitionOperatorInfo* pInfo = pOperator->info;

635 636
  SDataGroupInfo* pGroupInfo = (pInfo->groupIndex != -1) ? taosArrayGet(pInfo->sortedGroupArray, pInfo->groupIndex) : NULL;
  if (pInfo->groupIndex == -1 || pInfo->pageIndex >= taosArrayGetSize(pGroupInfo->pPageList)) {
H
Haojun Liao 已提交
637
    // try next group data
638 639
    ++pInfo->groupIndex;
    if (pInfo->groupIndex >= taosArrayGetSize(pInfo->sortedGroupArray)) {
640
      doSetOperatorCompleted(pOperator);
5
54liuyao 已提交
641
      clearPartitionOperator(pInfo);
H
Haojun Liao 已提交
642 643 644
      return NULL;
    }

645
    pGroupInfo = taosArrayGet(pInfo->sortedGroupArray, pInfo->groupIndex);
H
Haojun Liao 已提交
646 647 648 649 650 651
    pInfo->pageIndex = 0;
  }

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

652
  blockDataEnsureCapacity(pInfo->binfo.pRes, pInfo->rowCapacity);
H
Haojun Liao 已提交
653
  blockDataFromBuf1(pInfo->binfo.pRes, page, pInfo->rowCapacity);
H
Haojun Liao 已提交
654 655

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

658
  blockDataUpdateTsWindow(pInfo->binfo.pRes, 0);
H
Haojun Liao 已提交
659
  pInfo->binfo.pRes->info.groupId = pGroupInfo->groupId;
660 661

  pOperator->resultInfo.totalRows += pInfo->binfo.pRes->info.rows;
H
Haojun Liao 已提交
662 663 664
  return pInfo->binfo.pRes;
}

665
static SSDataBlock* hashPartition(SOperatorInfo* pOperator) {
H
Haojun Liao 已提交
666 667
  if (pOperator->status == OP_EXEC_DONE) {
    return NULL;
668 669
  }

670 671 672
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;

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

H
Haojun Liao 已提交
675
  if (pOperator->status == OP_RES_TO_RETURN) {
H
Haojun Liao 已提交
676 677
    blockDataCleanup(pRes);
    return buildPartitionResult(pOperator);
H
Haojun Liao 已提交
678 679
  }

680
  int64_t st = taosGetTimestampUs();
H
Haojun Liao 已提交
681
  SOperatorInfo* downstream = pOperator->pDownstream[0];
H
Haojun Liao 已提交
682

H
Haojun Liao 已提交
683
  while (1) {
684
    SSDataBlock* pBlock = downstream->fpSet.getNextFn(downstream);
H
Haojun Liao 已提交
685 686 687
    if (pBlock == NULL) {
      break;
    }
H
Haojun Liao 已提交
688

689
    // there is an scalar expression that needs to be calculated right before apply the group aggregation.
690 691
    if (pInfo->scalarSup.pExprInfo != NULL) {
      pTaskInfo->code = projectApplyFunctions(pInfo->scalarSup.pExprInfo, pBlock, pBlock, pInfo->scalarSup.pCtx, pInfo->scalarSup.numOfExprs, NULL);
692
      if (pTaskInfo->code != TSDB_CODE_SUCCESS) {
693
        T_LONG_JMP(pTaskInfo->env, pTaskInfo->code);
694 695 696
      }
    }

wmmhello's avatar
wmmhello 已提交
697
    terrno = TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
698
    doHashPartition(pOperator, pBlock);
wmmhello's avatar
wmmhello 已提交
699
    if (terrno != TSDB_CODE_SUCCESS) {  // group by json error
700
      T_LONG_JMP(pTaskInfo->env, terrno);
wmmhello's avatar
wmmhello 已提交
701
    }
H
Haojun Liao 已提交
702 703
  }

704
  SArray* groupArray = taosArrayInit(taosHashGetSize(pInfo->pGroupSet), sizeof(SDataGroupInfo));
705 706

  void* pGroupIter = taosHashIterate(pInfo->pGroupSet, NULL);
707 708 709 710 711 712 713 714 715 716 717
  while (pGroupIter != NULL) {
    SDataGroupInfo* pGroupInfo = pGroupIter;
    taosArrayPush(groupArray, pGroupInfo);
    pGroupIter = taosHashIterate(pInfo->pGroupSet, pGroupIter);
  }

  taosArraySort(groupArray, compareDataGroupInfo);
  pInfo->sortedGroupArray = groupArray;
  pInfo->groupIndex = -1;
  taosHashClear(pInfo->pGroupSet);

718 719
  pOperator->cost.openCost = (taosGetTimestampUs() - st) / 1000.0;

H
Haojun Liao 已提交
720
  pOperator->status = OP_RES_TO_RETURN;
H
Haojun Liao 已提交
721 722 723 724
  blockDataEnsureCapacity(pRes, 4096);
  return buildPartitionResult(pOperator);
}

725
static void destroyPartitionOperatorInfo(void* param) {
H
Haojun Liao 已提交
726
  SPartitionOperatorInfo* pInfo = (SPartitionOperatorInfo*)param;
727
  cleanupBasicInfo(&pInfo->binfo);
H
Haojun Liao 已提交
728
  taosArrayDestroy(pInfo->pGroupCols);
729

wmmhello's avatar
wmmhello 已提交
730 731 732 733
  for(int i = 0; i < taosArrayGetSize(pInfo->pGroupColVals); i++){
    SGroupKeys key = *(SGroupKeys*)taosArrayGet(pInfo->pGroupColVals, i);
    taosMemoryFree(key.pData);
  }
734

H
Haojun Liao 已提交
735
  taosArrayDestroy(pInfo->pGroupColVals);
H
Haojun Liao 已提交
736
  taosMemoryFree(pInfo->keyBuf);
737
  taosArrayDestroy(pInfo->sortedGroupArray);
wmmhello's avatar
wmmhello 已提交
738
  taosHashCleanup(pInfo->pGroupSet);
H
Haojun Liao 已提交
739
  taosMemoryFree(pInfo->columnOffset);
740

741
  cleanupExprSupp(&pInfo->scalarSup);
H
Haojun Liao 已提交
742
  destroyDiskbasedBuf(pInfo->pBuf);
D
dapan1121 已提交
743
  taosMemoryFreeClear(param);
H
Haojun Liao 已提交
744 745
}

746
SOperatorInfo* createPartitionOperatorInfo(SOperatorInfo* downstream, SPartitionPhysiNode* pPartNode, SExecTaskInfo* pTaskInfo) {
H
Haojun Liao 已提交
747 748
  SPartitionOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SPartitionOperatorInfo));
  SOperatorInfo*        pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
749
  if (pInfo == NULL || pOperator == NULL) {
H
Haojun Liao 已提交
750 751
    goto _error;
  }
752

753 754 755 756 757 758 759 760
  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) {
761 762 763 764 765 766
    int32_t num = 0;
    SExprInfo* pExprInfo1 = createExprInfo(pPartNode->pExprs, NULL, &num);
    int32_t code = initExprSupp(&pInfo->scalarSup, pExprInfo1, num);
    if (code != TSDB_CODE_SUCCESS) {
      goto _error;
    }
767
  }
H
Haojun Liao 已提交
768 769 770 771 772 773 774

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

775 776
  uint32_t defaultPgsz  = 0;
  uint32_t defaultBufsz = 0;
777
  getBufferPgSize(pResBlock->info.rowSize, &defaultPgsz, &defaultBufsz);
778

wafwerar's avatar
wafwerar 已提交
779 780 781 782 783 784 785
  if (!osTempSpaceAvailable()) {
    terrno = TSDB_CODE_NO_AVAIL_DISK;
    pTaskInfo->code = terrno;
    qError("Create partition operator info failed since %s", terrstr(terrno));
    goto _error;
  }
  int32_t code = createDiskbasedBuf(&pInfo->pBuf, defaultPgsz, defaultBufsz, pTaskInfo->id.str, tsTempDir);
H
Haojun Liao 已提交
786 787 788 789
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

790 791 792
  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 已提交
793 794 795
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }
H
Haojun Liao 已提交
796 797

  pOperator->name         = "PartitionOperator";
798
  pOperator->blocking     = true;
799
  pOperator->status       = OP_NOT_OPENED;
H
Haojun Liao 已提交
800
  pOperator->operatorType = QUERY_NODE_PHYSICAL_PLAN_PARTITION;
801
  pInfo->binfo.pRes       = pResBlock;
802 803
  pOperator->exprSupp.numOfExprs   = numOfCols;
  pOperator->exprSupp.pExprInfo    = pExprInfo;
H
Haojun Liao 已提交
804
  pOperator->info         = pInfo;
805
  pOperator->pTaskInfo    = pTaskInfo;
806 807 808

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

H
Haojun Liao 已提交
810
  code = appendDownstream(pOperator, &downstream, 1);
811 812 813
  return pOperator;

  _error:
H
Haojun Liao 已提交
814
  pTaskInfo->code = TSDB_CODE_OUT_OF_MEMORY;
H
Haojun Liao 已提交
815 816
  taosMemoryFreeClear(pInfo);
  taosMemoryFreeClear(pOperator);
817
  return NULL;
818 819
}

820
int32_t setGroupResultOutputBuf(SOperatorInfo* pOperator, SOptrBasicInfo* binfo, int32_t numOfCols, char* pData, int16_t bytes,
821
                                uint64_t groupId, SDiskbasedBuf* pBuf, SAggSupporter* pAggSup) {
822
  SExecTaskInfo* pTaskInfo = pOperator->pTaskInfo;
823
  SResultRowInfo* pResultRowInfo = &binfo->resultRowInfo;
824
  SqlFunctionCtx* pCtx = pOperator->exprSupp.pCtx;
825 826 827 828 829

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

830
  setResultRowInitCtx(pResultRow, pCtx, numOfCols, pOperator->exprSupp.rowEntryInfoOffset);
831
  return TSDB_CODE_SUCCESS;
D
dapan1121 已提交
832
}