executil.c 21.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * 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"
H
Hongze Cheng 已提交
17
#include "tmsg.h"
18
#include "thash.h"
19

20 21 22
#include "executil.h"
#include "executorimpl.h"
//#include "queryLog.h"
23
#include "tbuffer.h"
H
Haojun Liao 已提交
24
#include "tcompression.h"
H
Haojun Liao 已提交
25 26 27 28 29 30 31
#include "tlosertree.h"

typedef struct SCompSupporter {
  STableQueryInfo **pTableQueryInfo;
  int32_t          *rowIndex;
  int32_t           order;
} SCompSupporter;
32

H
Haojun Liao 已提交
33
int32_t getRowNumForMultioutput(STaskAttr* pQueryAttr, bool topBottomQuery, bool stable) {
W
wpan 已提交
34 35
  if (pQueryAttr && (!stable)) {
    for (int16_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
36 37 38
//      if (pQueryAttr->pExpr1[i].base. == FUNCTION_TOP || pQueryAttr->pExpr1[i].base.functionId == FUNCTION_BOTTOM) {
//        return (int32_t)pQueryAttr->pExpr1[i].base.param[0].i;
//      }
W
wpan 已提交
39 40 41 42 43 44
    }
  }

  return 1;
}

H
Haojun Liao 已提交
45
int32_t getOutputInterResultBufSize(STaskAttr* pQueryAttr) {
H
Haojun Liao 已提交
46 47
  int32_t size = 0;

H
Haojun Liao 已提交
48 49
  for (int32_t i = 0; i < pQueryAttr->numOfOutput; ++i) {
    size += pQueryAttr->pExpr1[i].base.interBytes;
H
Haojun Liao 已提交
50 51
  }

H
Haojun Liao 已提交
52
  assert(size >= 0);
H
Haojun Liao 已提交
53 54 55
  return size;
}

H
Haojun Liao 已提交
56
int32_t initResultRowInfo(SResultRowInfo *pResultRowInfo, int32_t size, int16_t type) {
57
  pResultRowInfo->type     = type;
H
Haojun Liao 已提交
58
  pResultRowInfo->size     = 0;
59
  pResultRowInfo->curPos  = -1;
60
  pResultRowInfo->capacity = size;
61

H
Haojun Liao 已提交
62 63
  pResultRowInfo->pResult = calloc(pResultRowInfo->capacity, POINTER_BYTES);
  if (pResultRowInfo->pResult == NULL) {
B
Bomin Zhang 已提交
64 65
    return TSDB_CODE_QRY_OUT_OF_MEMORY;
  }
H
Haojun Liao 已提交
66

67 68 69
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
70
void cleanupResultRowInfo(SResultRowInfo *pResultRowInfo) {
H
Haojun Liao 已提交
71
  if (pResultRowInfo == NULL) {
72 73
    return;
  }
H
Haojun Liao 已提交
74

H
Haojun Liao 已提交
75 76
  if (pResultRowInfo->capacity == 0) {
    assert(pResultRowInfo->pResult == NULL);
77 78
    return;
  }
79

D
dapan1121 已提交
80
  for(int32_t i = 0; i < pResultRowInfo->size; ++i) {
D
dapan1121 已提交
81
    if (pResultRowInfo->pResult[i]) {
H
Haojun Liao 已提交
82
      tfree(pResultRowInfo->pResult[i]->key);
83 84
    }
  }
85
  
H
Haojun Liao 已提交
86
  tfree(pResultRowInfo->pResult);
87 88
}

H
Haojun Liao 已提交
89
void resetResultRowInfo(STaskRuntimeEnv *pRuntimeEnv, SResultRowInfo *pResultRowInfo) {
H
Haojun Liao 已提交
90
  if (pResultRowInfo == NULL || pResultRowInfo->capacity == 0) {
91 92
    return;
  }
H
Haojun Liao 已提交
93

H
Haojun Liao 已提交
94 95 96
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
    SResultRow *pWindowRes = pResultRowInfo->pResult[i];
    clearResultRow(pRuntimeEnv, pWindowRes, pResultRowInfo->type);
H
Haojun Liao 已提交
97 98 99 100 101 102

    int32_t groupIndex = 0;
    int64_t uid = 0;

    SET_RES_WINDOW_KEY(pRuntimeEnv->keyBuf, &groupIndex, sizeof(groupIndex), uid);
    taosHashRemove(pRuntimeEnv->pResultRowHashTable, (const char *)pRuntimeEnv->keyBuf, GET_RES_WINDOW_KEY_LEN(sizeof(groupIndex)));
103
  }
104 105

  pResultRowInfo->size     = 0;
106
  pResultRowInfo->curPos  = -1;
107 108
}

H
Haojun Liao 已提交
109
int32_t numOfClosedResultRows(SResultRowInfo *pResultRowInfo) {
110
  int32_t i = 0;
H
Haojun Liao 已提交
111
  while (i < pResultRowInfo->size && pResultRowInfo->pResult[i]->closed) {
112 113 114 115 116 117
    ++i;
  }
  
  return i;
}

H
Haojun Liao 已提交
118
void closeAllResultRows(SResultRowInfo *pResultRowInfo) {
H
Haojun Liao 已提交
119
  assert(pResultRowInfo->size >= 0 && pResultRowInfo->capacity >= pResultRowInfo->size);
120
  
H
Haojun Liao 已提交
121
  for (int32_t i = 0; i < pResultRowInfo->size; ++i) {
122 123
    SResultRow* pRow = pResultRowInfo->pResult[i];
    if (pRow->closed) {
124 125 126
      continue;
    }
    
127
    pRow->closed = true;
128 129 130
  }
}

H
Haojun Liao 已提交
131
bool isResultRowClosed(SResultRowInfo *pResultRowInfo, int32_t slot) {
H
Haojun Liao 已提交
132
  return (getResultRow(pResultRowInfo, slot)->closed == true);
133 134
}

H
Haojun Liao 已提交
135
void closeResultRow(SResultRowInfo *pResultRowInfo, int32_t slot) {
H
Haojun Liao 已提交
136
  getResultRow(pResultRowInfo, slot)->closed = true;
137 138
}

H
Haojun Liao 已提交
139
void clearResultRow(STaskRuntimeEnv *pRuntimeEnv, SResultRow *pResultRow, int16_t type) {
H
Haojun Liao 已提交
140
  if (pResultRow == NULL) {
141 142
    return;
  }
H
Haojun Liao 已提交
143

144
  // the result does not put into the SDiskbasedBuf, ignore it.
H
Haojun Liao 已提交
145
  if (pResultRow->pageId >= 0) {
146
    SFilePage *page = getResBufPage(pRuntimeEnv->pResultBuf, pResultRow->pageId);
H
Haojun Liao 已提交
147

H
Haojun Liao 已提交
148
    int16_t offset = 0;
H
Haojun Liao 已提交
149
    for (int32_t i = 0; i < pRuntimeEnv->pQueryAttr->numOfOutput; ++i) {
150
      struct SResultRowEntryInfo *pEntryInfo = NULL;//pResultRow->pEntryInfo[i];
151

152
      int16_t size = pRuntimeEnv->pQueryAttr->pExpr1[i].base.resSchema.bytes;
H
Haojun Liao 已提交
153
      char * s = getPosInResultPage(pRuntimeEnv->pQueryAttr, page, pResultRow->offset, offset);
154 155
      memset(s, 0, size);

H
Haojun Liao 已提交
156
      offset += size;
157
      cleanupResultRowEntry(pEntryInfo);
158
    }
159
  }
160

H
Haojun Liao 已提交
161 162
  pResultRow->numOfRows = 0;
  pResultRow->pageId = -1;
H
Haojun Liao 已提交
163
  pResultRow->offset = -1;
H
Haojun Liao 已提交
164
  pResultRow->closed = false;
165

D
dapan1121 已提交
166 167
  tfree(pResultRow->key);
  pResultRow->win = TSWINDOW_INITIALIZER;
168 169
}

H
Haojun Liao 已提交
170
// TODO refactor: use macro
H
Haojun Liao 已提交
171
SResultRowEntryInfo* getResultCell(const SResultRow* pRow, int32_t index, int32_t* offset) {
H
Haojun Liao 已提交
172
  assert(index >= 0 && offset != NULL);
H
Haojun Liao 已提交
173
  return (SResultRowEntryInfo*)((char*) pRow->pEntryInfo + offset[index]);
H
Haojun Liao 已提交
174 175
}

H
Haojun Liao 已提交
176 177 178
size_t getResultRowSize(SArray* pExprInfo) {
  size_t numOfOutput = taosArrayGetSize(pExprInfo);
  return (numOfOutput * sizeof(SResultRowEntryInfo)) + /*pQueryAttr->interBufSize +*/ sizeof(SResultRow);
179 180
}

H
Haojun Liao 已提交
181 182
SResultRowPool* initResultRowPool(size_t size) {
  SResultRowPool* p = calloc(1, sizeof(SResultRowPool));
183 184 185 186 187 188
  if (p == NULL) {
    return NULL;
  }

  p->numOfElemPerBlock = 128;

H
Haojun Liao 已提交
189
  p->elemSize = (int32_t) size;
190 191 192 193 194 195 196
  p->blockSize = p->numOfElemPerBlock * p->elemSize;
  p->position.pos = 0;

  p->pData = taosArrayInit(8, POINTER_BYTES);
  return p;
}

H
Haojun Liao 已提交
197
SResultRow* getNewResultRow(SResultRowPool* p) {
198 199 200 201 202 203 204 205 206 207 208 209 210
  if (p == NULL) {
    return NULL;
  }

  void* ptr = NULL;
  if (p->position.pos == 0) {
    ptr = calloc(1, p->blockSize);
    taosArrayPush(p->pData, &ptr);

  } else {
    size_t last = taosArrayGetSize(p->pData);

    void** pBlock = taosArrayGet(p->pData, last - 1);
H
Haojun Liao 已提交
211
    ptr = ((char*) (*pBlock)) + p->elemSize * p->position.pos;
212 213 214
  }

  p->position.pos = (p->position.pos + 1)%p->numOfElemPerBlock;
215 216
  initResultRow(ptr);

217 218 219
  return ptr;
}

H
Haojun Liao 已提交
220
int64_t getResultRowPoolMemSize(SResultRowPool* p) {
221 222 223 224 225 226 227
  if (p == NULL) {
    return 0;
  }

  return taosArrayGetSize(p->pData) * p->blockSize;
}

H
Haojun Liao 已提交
228
int32_t getNumOfAllocatedResultRows(SResultRowPool* p) {
H
Haojun Liao 已提交
229
  return (int32_t) taosArrayGetSize(p->pData) * p->numOfElemPerBlock;
230 231
}

H
Haojun Liao 已提交
232 233
int32_t getNumOfUsedResultRows(SResultRowPool* p) {
  return getNumOfAllocatedResultRows(p) - p->numOfElemPerBlock + p->position.pos;
234 235
}

H
Haojun Liao 已提交
236
void* destroyResultRowPool(SResultRowPool* p) {
237 238 239 240 241 242 243
  if (p == NULL) {
    return NULL;
  }

  size_t size = taosArrayGetSize(p->pData);
  for(int32_t i = 0; i < size; ++i) {
    void** ptr = taosArrayGet(p->pData, i);
S
TD-1848  
Shengliang Guan 已提交
244
    tfree(*ptr);
245 246 247 248
  }

  taosArrayDestroy(p->pData);

S
TD-1848  
Shengliang Guan 已提交
249
  tfree(p);
250
  return NULL;
251 252 253
}

void interResToBinary(SBufferWriter* bw, SArray* pRes, int32_t tagLen) {
H
Haojun Liao 已提交
254
  uint32_t numOfGroup = (uint32_t) taosArrayGetSize(pRes);
255 256 257 258 259 260 261 262 263
  tbufWriteUint32(bw, numOfGroup);
  tbufWriteUint16(bw, tagLen);

  for(int32_t i = 0; i < numOfGroup; ++i) {
    SInterResult* pOne = taosArrayGet(pRes, i);
    if (tagLen > 0) {
      tbufWriteBinary(bw, pOne->tags, tagLen);
    }

H
Haojun Liao 已提交
264
    uint32_t numOfCols = (uint32_t) taosArrayGetSize(pOne->pResult);
265 266 267
    tbufWriteUint32(bw, numOfCols);
    for(int32_t j = 0; j < numOfCols; ++j) {
      SStddevInterResult* p = taosArrayGet(pOne->pResult, j);
H
Haojun Liao 已提交
268
      uint32_t numOfRows = (uint32_t) taosArrayGetSize(p->pResult);
269 270 271 272 273

      tbufWriteUint16(bw, p->colId);
      tbufWriteUint32(bw, numOfRows);

      for(int32_t k = 0; k < numOfRows; ++k) {
274 275 276
//        SResPair v = *(SResPair*) taosArrayGet(p->pResult, k);
//        tbufWriteDouble(bw, v.avg);
//        tbufWriteInt64(bw, v.key);
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
      }
    }
  }
}

SArray* interResFromBinary(const char* data, int32_t len) {
  SBufferReader br = tbufInitReader(data, len, false);
  uint32_t numOfGroup = tbufReadUint32(&br);
  uint16_t tagLen = tbufReadUint16(&br);

  char* tag = NULL;
  if (tagLen > 0) {
    tag = calloc(1, tagLen);
  }

  SArray* pResult = taosArrayInit(4, sizeof(SInterResult));

  for(int32_t i = 0; i < numOfGroup; ++i) {
    if (tagLen > 0) {
      memset(tag, 0, tagLen);
      tbufReadToBinary(&br, tag, tagLen);
    }

    uint32_t numOfCols = tbufReadUint32(&br);

    SArray* p = taosArrayInit(numOfCols, sizeof(SStddevInterResult));
    for(int32_t j = 0; j < numOfCols; ++j) {
304
//      int16_t colId = tbufReadUint16(&br);
305 306
      int32_t numOfRows = tbufReadUint32(&br);

307
//      SStddevInterResult interRes = {.colId = colId, .pResult = taosArrayInit(4, sizeof(struct SResPair)),};
308
      for(int32_t k = 0; k < numOfRows; ++k) {
309 310 311 312 313
//        SResPair px = {0};
//        px.avg = tbufReadDouble(&br);
//        px.key = tbufReadInt64(&br);
//
//        taosArrayPush(interRes.pResult, &px);
314 315
      }

316
//      taosArrayPush(p, &interRes);
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
    }

    char* p1 = NULL;
    if (tagLen > 0) {
      p1 = malloc(tagLen);
      memcpy(p1, tag, tagLen);
    }

    SInterResult d = {.pResult = p, .tags = p1,};
    taosArrayPush(pResult, &d);
  }

  tfree(tag);
  return pResult;
}

void freeInterResult(void* param) {
  SInterResult* pResult = (SInterResult*) param;
  tfree(pResult->tags);

H
Haojun Liao 已提交
337
  int32_t numOfCols = (int32_t) taosArrayGetSize(pResult->pResult);
338 339 340 341 342 343
  for(int32_t i = 0; i < numOfCols; ++i) {
    SStddevInterResult *p = taosArrayGet(pResult->pResult, i);
    taosArrayDestroy(p->pResult);
  }

  taosArrayDestroy(pResult->pResult);
H
Haojun Liao 已提交
344 345 346 347 348 349 350 351 352 353
}

void cleanupGroupResInfo(SGroupResInfo* pGroupResInfo) {
  assert(pGroupResInfo != NULL);

  taosArrayDestroy(pGroupResInfo->pRows);
  pGroupResInfo->pRows     = NULL;
  pGroupResInfo->index     = 0;
}

H
Haojun Liao 已提交
354
void initGroupResInfo(SGroupResInfo* pGroupResInfo, SResultRowInfo* pResultInfo) {
H
Haojun Liao 已提交
355 356 357 358 359
  if (pGroupResInfo->pRows != NULL) {
    taosArrayDestroy(pGroupResInfo->pRows);
  }

  pGroupResInfo->pRows = taosArrayFromList(pResultInfo->pResult, pResultInfo->size, POINTER_BYTES);
H
Haojun Liao 已提交
360
  pGroupResInfo->index = 0;
H
Haojun Liao 已提交
361 362 363 364

  assert(pGroupResInfo->index <= getNumOfTotalRes(pGroupResInfo));
}

H
Haojun Liao 已提交
365
bool hasRemainDataInCurrentGroup(SGroupResInfo* pGroupResInfo) {
H
Haojun Liao 已提交
366 367 368 369 370 371 372
  if (pGroupResInfo->pRows == NULL) {
    return false;
  }

  return pGroupResInfo->index < taosArrayGetSize(pGroupResInfo->pRows);
}

H
Haojun Liao 已提交
373 374 375 376 377 378 379 380
bool hasRemainData(SGroupResInfo* pGroupResInfo) {
  if (hasRemainDataInCurrentGroup(pGroupResInfo)) {
    return true;
  }

  return pGroupResInfo->currentGroup < pGroupResInfo->totalGroup;
}

H
Haojun Liao 已提交
381 382 383 384 385 386 387 388 389 390
bool incNextGroup(SGroupResInfo* pGroupResInfo) {
  return (++pGroupResInfo->currentGroup) < pGroupResInfo->totalGroup;
}

int32_t getNumOfTotalRes(SGroupResInfo* pGroupResInfo) {
  assert(pGroupResInfo != NULL);
  if (pGroupResInfo->pRows == 0) {
    return 0;
  }

H
Haojun Liao 已提交
391
  return (int32_t) taosArrayGetSize(pGroupResInfo->pRows);
H
Haojun Liao 已提交
392 393
}

H
Haojun Liao 已提交
394 395
static int64_t getNumOfResultWindowRes(STaskRuntimeEnv* pRuntimeEnv, SResultRow *pResultRow, int32_t* rowCellInfoOffset) {
  STaskAttr* pQueryAttr = pRuntimeEnv->pQueryAttr;
H
Haojun Liao 已提交
396

H
Haojun Liao 已提交
397
  for (int32_t j = 0; j < pQueryAttr->numOfOutput; ++j) {
398
    int32_t functionId = 0;//pQueryAttr->pExpr1[j].base.functionId;
H
Haojun Liao 已提交
399 400 401 402 403

    /*
     * ts, tag, tagprj function can not decide the output number of current query
     * the number of output result is decided by main output
     */
404
    if (functionId == FUNCTION_TS || functionId == FUNCTION_TAG || functionId == FUNCTION_TAGPRJ) {
H
Haojun Liao 已提交
405 406 407
      continue;
    }

408 409 410 411 412 413
//    SResultRowEntryInfo *pResultInfo = getResultCell(pResultRow, j, rowCellInfoOffset);
//    assert(pResultInfo != NULL);
//
//    if (pResultInfo->numOfRes > 0) {
//      return pResultInfo->numOfRes;
//    }
H
Haojun Liao 已提交
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
  }

  return 0;
}

static int32_t tableResultComparFn(const void *pLeft, const void *pRight, void *param) {
  int32_t left  = *(int32_t *)pLeft;
  int32_t right = *(int32_t *)pRight;

  SCompSupporter *  supporter = (SCompSupporter *)param;

  int32_t leftPos  = supporter->rowIndex[left];
  int32_t rightPos = supporter->rowIndex[right];

  /* left source is exhausted */
  if (leftPos == -1) {
    return 1;
  }

  /* right source is exhausted*/
  if (rightPos == -1) {
    return -1;
  }

  STableQueryInfo** pList = supporter->pTableQueryInfo;
H
Haojun Liao 已提交
439 440
  SResultRow* pWindowRes1 = pList[left]->resInfo.pResult[leftPos];
//  SResultRow * pWindowRes1 = getResultRow(&(pList[left]->resInfo), leftPos);
H
Haojun Liao 已提交
441 442
  TSKEY leftTimestamp = pWindowRes1->win.skey;

H
Haojun Liao 已提交
443 444 445
//  SResultRowInfo *pWindowResInfo2 = &(pList[right]->resInfo);
//  SResultRow * pWindowRes2 = getResultRow(pWindowResInfo2, rightPos);
  SResultRow* pWindowRes2 = pList[right]->resInfo.pResult[rightPos];
H
Haojun Liao 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458
  TSKEY rightTimestamp = pWindowRes2->win.skey;

  if (leftTimestamp == rightTimestamp) {
    return 0;
  }

  if (supporter->order == TSDB_ORDER_ASC) {
    return (leftTimestamp > rightTimestamp)? 1:-1;
  } else {
    return (leftTimestamp < rightTimestamp)? 1:-1;
  }
}

459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
int32_t tsAscOrder(const void* p1, const void* p2) {
  SResultRowCell* pc1 = (SResultRowCell*) p1;
  SResultRowCell* pc2 = (SResultRowCell*) p2;

  if (pc1->groupId == pc2->groupId) {
    if (pc1->pRow->win.skey == pc2->pRow->win.skey) {
      return 0;
    } else {
      return (pc1->pRow->win.skey < pc2->pRow->win.skey)? -1:1;
    }
  } else {
    return (pc1->groupId < pc2->groupId)? -1:1;
  }
}

int32_t tsDescOrder(const void* p1, const void* p2) {
  SResultRowCell* pc1 = (SResultRowCell*) p1;
  SResultRowCell* pc2 = (SResultRowCell*) p2;

  if (pc1->groupId == pc2->groupId) {
    if (pc1->pRow->win.skey == pc2->pRow->win.skey) {
      return 0;
    } else {
      return (pc1->pRow->win.skey < pc2->pRow->win.skey)? 1:-1;
    }
  } else {
    return (pc1->groupId < pc2->groupId)? -1:1;
  }
}

H
Haojun Liao 已提交
489
void orderTheResultRows(STaskRuntimeEnv* pRuntimeEnv) {
490 491 492 493 494 495 496 497 498 499
  __compar_fn_t  fn = NULL;
  if (pRuntimeEnv->pQueryAttr->order.order == TSDB_ORDER_ASC) {
    fn = tsAscOrder;
  } else {
    fn = tsDescOrder;
  }

  taosArraySort(pRuntimeEnv->pResultRowArrayList, fn);
}

H
Haojun Liao 已提交
500
static int32_t mergeIntoGroupResultImplRv(STaskRuntimeEnv *pRuntimeEnv, SGroupResInfo* pGroupResInfo, uint64_t groupId, int32_t* rowCellInfoOffset) {
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
  if (!pGroupResInfo->ordered) {
    orderTheResultRows(pRuntimeEnv);
    pGroupResInfo->ordered = true;
  }

  if (pGroupResInfo->pRows == NULL) {
    pGroupResInfo->pRows = taosArrayInit(100, POINTER_BYTES);
  }

  size_t len = taosArrayGetSize(pRuntimeEnv->pResultRowArrayList);
  for(; pGroupResInfo->position < len; ++pGroupResInfo->position) {
    SResultRowCell* pResultRowCell = taosArrayGet(pRuntimeEnv->pResultRowArrayList, pGroupResInfo->position);
    if (pResultRowCell->groupId != groupId) {
      break;
    }

    int64_t num = getNumOfResultWindowRes(pRuntimeEnv, pResultRowCell->pRow, rowCellInfoOffset);
    if (num <= 0) {
      continue;
    }

    taosArrayPush(pGroupResInfo->pRows, &pResultRowCell->pRow);
    pResultRowCell->pRow->numOfRows = (uint32_t) num;
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
529
static UNUSED_FUNC int32_t mergeIntoGroupResultImpl(STaskRuntimeEnv *pRuntimeEnv, SGroupResInfo* pGroupResInfo, SArray *pTableList,
H
Haojun Liao 已提交
530
    int32_t* rowCellInfoOffset) {
H
Haojun Liao 已提交
531
  bool ascQuery = QUERY_IS_ASC_QUERY(pRuntimeEnv->pQueryAttr);
H
Haojun Liao 已提交
532 533 534 535

  int32_t code = TSDB_CODE_SUCCESS;

  int32_t *posList = NULL;
536
  SMultiwayMergeTreeInfo *pTree = NULL;
H
Haojun Liao 已提交
537 538 539 540 541 542 543 544 545 546 547
  STableQueryInfo **pTableQueryInfoList = NULL;

  size_t size = taosArrayGetSize(pTableList);
  if (pGroupResInfo->pRows == NULL) {
    pGroupResInfo->pRows = taosArrayInit(100, POINTER_BYTES);
  }

  posList = calloc(size, sizeof(int32_t));
  pTableQueryInfoList = malloc(POINTER_BYTES * size);

  if (pTableQueryInfoList == NULL || posList == NULL || pGroupResInfo->pRows == NULL || pGroupResInfo->pRows == NULL) {
548
//    qError("QInfo:%"PRIu64" failed alloc memory", GET_TASKID(pRuntimeEnv));
H
Haojun Liao 已提交
549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _end;
  }

  int32_t numOfTables = 0;
  for (int32_t i = 0; i < size; ++i) {
    STableQueryInfo *item = taosArrayGetP(pTableList, i);
    if (item->resInfo.size > 0) {
      pTableQueryInfoList[numOfTables++] = item;
    }
  }

  // there is no data in current group
  // no need to merge results since only one table in each group
  if (numOfTables == 0) {
    goto _end;
  }

H
Haojun Liao 已提交
567
  SCompSupporter cs = {pTableQueryInfoList, posList, pRuntimeEnv->pQueryAttr->order.order};
H
Haojun Liao 已提交
568

569
  int32_t ret = tMergeTreeCreate(&pTree, numOfTables, &cs, tableResultComparFn);
H
Haojun Liao 已提交
570 571 572 573 574 575 576 577 578
  if (ret != TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_QRY_OUT_OF_MEMORY;
    goto _end;
  }

  int64_t lastTimestamp = ascQuery? INT64_MIN:INT64_MAX;
  int64_t startt = taosGetTimestampMs();

  while (1) {
579
    int32_t tableIndex = tMergeTreeGetChosenIndex(pTree);
H
Haojun Liao 已提交
580 581 582 583

    SResultRowInfo *pWindowResInfo = &pTableQueryInfoList[tableIndex]->resInfo;
    SResultRow  *pWindowRes = getResultRow(pWindowResInfo, cs.rowIndex[tableIndex]);

H
Haojun Liao 已提交
584
    int64_t num = getNumOfResultWindowRes(pRuntimeEnv, pWindowRes, rowCellInfoOffset);
H
Haojun Liao 已提交
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
    if (num <= 0) {
      cs.rowIndex[tableIndex] += 1;

      if (cs.rowIndex[tableIndex] >= pWindowResInfo->size) {
        cs.rowIndex[tableIndex] = -1;
        if (--numOfTables == 0) { // all input sources are exhausted
          break;
        }
      }
    } else {
      assert((pWindowRes->win.skey >= lastTimestamp && ascQuery) || (pWindowRes->win.skey <= lastTimestamp && !ascQuery));

      if (pWindowRes->win.skey != lastTimestamp) {
        taosArrayPush(pGroupResInfo->pRows, &pWindowRes);
        pWindowRes->numOfRows = (uint32_t) num;
      }

      lastTimestamp = pWindowRes->win.skey;

      // move to the next row of current entry
      if ((++cs.rowIndex[tableIndex]) >= pWindowResInfo->size) {
        cs.rowIndex[tableIndex] = -1;

        // all input sources are exhausted
        if ((--numOfTables) == 0) {
          break;
        }
      }
    }

H
Haojun Liao 已提交
615
    tMergeTreeAdjust(pTree, tMergeTreeGetAdjustIndex(pTree));
H
Haojun Liao 已提交
616 617 618 619
  }

  int64_t endt = taosGetTimestampMs();

620
//  qDebug("QInfo:%"PRIx64" result merge completed for group:%d, elapsed time:%" PRId64 " ms", GET_TASKID(pRuntimeEnv),
621
//         pGroupResInfo->currentGroup, endt - startt);
H
Haojun Liao 已提交
622 623 624 625 626 627 628 629 630

  _end:
  tfree(pTableQueryInfoList);
  tfree(posList);
  tfree(pTree);

  return code;
}

H
Haojun Liao 已提交
631
int32_t mergeIntoGroupResult(SGroupResInfo* pGroupResInfo, STaskRuntimeEnv* pRuntimeEnv, int32_t* offset) {
H
Haojun Liao 已提交
632 633 634
  int64_t st = taosGetTimestampUs();

  while (pGroupResInfo->currentGroup < pGroupResInfo->totalGroup) {
635
    mergeIntoGroupResultImplRv(pRuntimeEnv, pGroupResInfo, pGroupResInfo->currentGroup, offset);
H
Haojun Liao 已提交
636 637 638 639 640 641

    // this group generates at least one result, return results
    if (taosArrayGetSize(pGroupResInfo->pRows) > 0) {
      break;
    }

642
//    qDebug("QInfo:%"PRIu64" no result in group %d, continue", GET_TASKID(pRuntimeEnv), pGroupResInfo->currentGroup);
H
Haojun Liao 已提交
643 644 645 646
    cleanupGroupResInfo(pGroupResInfo);
    incNextGroup(pGroupResInfo);
  }

647
//  int64_t elapsedTime = taosGetTimestampUs() - st;
648
//  qDebug("QInfo:%"PRIu64" merge res data into group, index:%d, total group:%d, elapsed time:%" PRId64 "us", GET_TASKID(pRuntimeEnv),
649
//         pGroupResInfo->currentGroup, pGroupResInfo->totalGroup, elapsedTime);
H
Haojun Liao 已提交
650 651 652

  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
653

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
//void blockDistInfoToBinary(STableBlockDist* pDist, struct SBufferWriter* bw) {
//  tbufWriteUint32(bw, pDist->numOfTables);
//  tbufWriteUint16(bw, pDist->numOfFiles);
//  tbufWriteUint64(bw, pDist->totalSize);
//  tbufWriteUint64(bw, pDist->totalRows);
//  tbufWriteInt32(bw, pDist->maxRows);
//  tbufWriteInt32(bw, pDist->minRows);
//  tbufWriteUint32(bw, pDist->numOfRowsInMemTable);
//  tbufWriteUint32(bw, pDist->numOfSmallBlocks);
//  tbufWriteUint64(bw, taosArrayGetSize(pDist->dataBlockInfos));
//
//  // compress the binary string
//  char* p = TARRAY_GET_START(pDist->dataBlockInfos);
//
//  // compress extra bytes
//  size_t x = taosArrayGetSize(pDist->dataBlockInfos) * pDist->dataBlockInfos->elemSize;
//  char* tmp = malloc(x + 2);
//
//  bool comp = false;
//  int32_t len = tsCompressString(p, (int32_t)x, 1, tmp, (int32_t)x, ONE_STAGE_COMP, NULL, 0);
//  if (len == -1 || len >= x) { // compress failed, do not compress this binary data
//    comp = false;
//    len = (int32_t)x;
//  } else {
//    comp = true;
//  }
//
//  tbufWriteUint8(bw, comp);
//  tbufWriteUint32(bw, len);
//  if (comp) {
//    tbufWriteBinary(bw, tmp, len);
//  } else {
//    tbufWriteBinary(bw, p, len);
//  }
//  tfree(tmp);
//}

//void blockDistInfoFromBinary(const char* data, int32_t len, STableBlockDist* pDist) {
//  SBufferReader br = tbufInitReader(data, len, false);
//
//  pDist->numOfTables = tbufReadUint32(&br);
//  pDist->numOfFiles  = tbufReadUint16(&br);
//  pDist->totalSize   = tbufReadUint64(&br);
//  pDist->totalRows   = tbufReadUint64(&br);
//  pDist->maxRows     = tbufReadInt32(&br);
//  pDist->minRows     = tbufReadInt32(&br);
//  pDist->numOfRowsInMemTable = tbufReadUint32(&br);
//  pDist->numOfSmallBlocks = tbufReadUint32(&br);
//  int64_t numSteps = tbufReadUint64(&br);
//
//  bool comp = tbufReadUint8(&br);
//  uint32_t compLen = tbufReadUint32(&br);
//
//  size_t originalLen = (size_t) (numSteps *sizeof(SFileBlockInfo));
//
//  char* outputBuf = NULL;
//  if (comp) {
//    outputBuf = malloc(originalLen);
//
//    size_t actualLen = compLen;
//    const char* compStr = tbufReadBinary(&br, &actualLen);
//
//    int32_t orignalLen = tsDecompressString(compStr, compLen, 1, outputBuf,
//                                            (int32_t)originalLen , ONE_STAGE_COMP, NULL, 0);
//    assert(orignalLen == numSteps *sizeof(SFileBlockInfo));
//  } else {
//    outputBuf = (char*) tbufReadBinary(&br, &originalLen);
//  }
//
//  pDist->dataBlockInfos = taosArrayFromList(outputBuf, (uint32_t)numSteps, sizeof(SFileBlockInfo));
//  if (comp) {
//    tfree(outputBuf);
//  }
//}
H
Haojun Liao 已提交
728