executil.c 21.0 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;
}

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

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

66 67 68
  return TSDB_CODE_SUCCESS;
}

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

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

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

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

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

    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)));
102
  }
103 104

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  p->numOfElemPerBlock = 128;

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

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

H
Haojun Liao 已提交
196
SResultRow* getNewResultRow(SResultRowPool* p) {
197 198 199 200 201 202 203 204 205 206 207 208 209
  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 已提交
210
    ptr = ((char*) (*pBlock)) + p->elemSize * p->position.pos;
211 212 213
  }

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

216 217 218
  return ptr;
}

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

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

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

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

H
Haojun Liao 已提交
235
void* destroyResultRowPool(SResultRowPool* p) {
236 237 238 239 240 241 242
  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 已提交
243
    tfree(*ptr);
244 245 246 247
  }

  taosArrayDestroy(p->pData);

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

void interResToBinary(SBufferWriter* bw, SArray* pRes, int32_t tagLen) {
H
Haojun Liao 已提交
253
  uint32_t numOfGroup = (uint32_t) taosArrayGetSize(pRes);
254 255 256 257 258 259 260 261 262
  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 已提交
263
    uint32_t numOfCols = (uint32_t) taosArrayGetSize(pOne->pResult);
264 265 266
    tbufWriteUint32(bw, numOfCols);
    for(int32_t j = 0; j < numOfCols; ++j) {
      SStddevInterResult* p = taosArrayGet(pOne->pResult, j);
H
Haojun Liao 已提交
267
      uint32_t numOfRows = (uint32_t) taosArrayGetSize(p->pResult);
268 269 270 271 272

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

      for(int32_t k = 0; k < numOfRows; ++k) {
273 274 275
//        SResPair v = *(SResPair*) taosArrayGet(p->pResult, k);
//        tbufWriteDouble(bw, v.avg);
//        tbufWriteInt64(bw, v.key);
276 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
      }
    }
  }
}

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) {
303
//      int16_t colId = tbufReadUint16(&br);
304 305
      int32_t numOfRows = tbufReadUint32(&br);

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

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

    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 已提交
336
  int32_t numOfCols = (int32_t) taosArrayGetSize(pResult->pResult);
337 338 339 340 341 342
  for(int32_t i = 0; i < numOfCols; ++i) {
    SStddevInterResult *p = taosArrayGet(pResult->pResult, i);
    taosArrayDestroy(p->pResult);
  }

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

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

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

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

  pGroupResInfo->pRows = taosArrayFromList(pResultInfo->pResult, pResultInfo->size, POINTER_BYTES);
H
Haojun Liao 已提交
359
  pGroupResInfo->index = 0;
H
Haojun Liao 已提交
360 361 362
  assert(pGroupResInfo->index <= getNumOfTotalRes(pGroupResInfo));
}

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

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

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

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

H
Haojun Liao 已提交
379 380 381 382 383 384 385 386 387 388
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 已提交
389
  return (int32_t) taosArrayGetSize(pGroupResInfo->pRows);
H
Haojun Liao 已提交
390 391
}

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

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

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

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

  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 已提交
437 438
  SResultRow* pWindowRes1 = pList[left]->resInfo.pResult[leftPos];
//  SResultRow * pWindowRes1 = getResultRow(&(pList[left]->resInfo), leftPos);
H
Haojun Liao 已提交
439 440
  TSKEY leftTimestamp = pWindowRes1->win.skey;

H
Haojun Liao 已提交
441 442 443
//  SResultRowInfo *pWindowResInfo2 = &(pList[right]->resInfo);
//  SResultRow * pWindowRes2 = getResultRow(pWindowResInfo2, rightPos);
  SResultRow* pWindowRes2 = pList[right]->resInfo.pResult[rightPos];
H
Haojun Liao 已提交
444 445 446 447 448 449 450 451 452 453 454 455 456
  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;
  }
}

457 458 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
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 已提交
487
void orderTheResultRows(STaskRuntimeEnv* pRuntimeEnv) {
488 489 490 491 492 493 494 495 496 497
  __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 已提交
498
static int32_t mergeIntoGroupResultImplRv(STaskRuntimeEnv *pRuntimeEnv, SGroupResInfo* pGroupResInfo, uint64_t groupId, int32_t* rowCellInfoOffset) {
499 500 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
  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 已提交
527
static UNUSED_FUNC int32_t mergeIntoGroupResultImpl(STaskRuntimeEnv *pRuntimeEnv, SGroupResInfo* pGroupResInfo, SArray *pTableList,
H
Haojun Liao 已提交
528
    int32_t* rowCellInfoOffset) {
H
Haojun Liao 已提交
529
  bool ascQuery = QUERY_IS_ASC_QUERY(pRuntimeEnv->pQueryAttr);
H
Haojun Liao 已提交
530 531 532 533

  int32_t code = TSDB_CODE_SUCCESS;

  int32_t *posList = NULL;
534
  SMultiwayMergeTreeInfo *pTree = NULL;
H
Haojun Liao 已提交
535 536 537 538 539 540 541 542 543 544 545
  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) {
546
//    qError("QInfo:%"PRIu64" failed alloc memory", GET_TASKID(pRuntimeEnv));
H
Haojun Liao 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
    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 已提交
565
  SCompSupporter cs = {pTableQueryInfoList, posList, pRuntimeEnv->pQueryAttr->order.order};
H
Haojun Liao 已提交
566

567
  int32_t ret = tMergeTreeCreate(&pTree, numOfTables, &cs, tableResultComparFn);
H
Haojun Liao 已提交
568 569 570 571 572 573 574 575 576
  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) {
577
    int32_t tableIndex = tMergeTreeGetChosenIndex(pTree);
H
Haojun Liao 已提交
578 579 580 581

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

H
Haojun Liao 已提交
582
    int64_t num = getNumOfResultWindowRes(pRuntimeEnv, pWindowRes, rowCellInfoOffset);
H
Haojun Liao 已提交
583 584 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
    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 已提交
613
    tMergeTreeAdjust(pTree, tMergeTreeGetAdjustIndex(pTree));
H
Haojun Liao 已提交
614 615 616 617
  }

  int64_t endt = taosGetTimestampMs();

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

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

  return code;
}

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

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

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

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

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

  return TSDB_CODE_SUCCESS;
}
H
Haojun Liao 已提交
651

652 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
//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 已提交
726