tsort.c 24.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * 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/>.
 */

S
common  
Shengliang Guan 已提交
16
#include "tcommon.h"
17 18
#include "query.h"

H
Haojun Liao 已提交
19
#include "tdatablock.h"
S
Shengliang Guan 已提交
20
#include "tdef.h"
21 22
#include "tlosertree.h"
#include "tpagedbuf.h"
H
Haojun Liao 已提交
23
#include "tsort.h"
24
#include "tutil.h"
25
#include "tcompare.h"
26

27 28 29 30 31
struct STupleHandle {
  SSDataBlock* pBlock;
  int32_t      rowIndex;
};

H
Haojun Liao 已提交
32
struct SSortHandle {
33 34 35 36 37
  int32_t           type;
  int32_t           pageSize;
  int32_t           numOfPages;
  SDiskbasedBuf    *pBuf;

H
Haojun Liao 已提交
38
  SArray           *pSortInfo;
39 40
  SArray           *pOrderedSource;

41
  int32_t           loops;
42
  uint64_t          sortElapsed;
43
  int64_t           startTs;
44 45 46 47 48 49 50 51 52 53 54
  uint64_t          totalElapsed;

  int32_t           sourceId;
  SSDataBlock      *pDataBlock;
  SMsortComparParam cmpParam;
  int32_t           numOfCompletedSources;
  bool              opened;
  const char       *idStr;
  bool              inMemSort;
  bool              needAdjust;
  STupleHandle      tupleHandle;
55 56
  void             *param;
  void (*beforeFp)(SSDataBlock* pBlock, void* param);
57 58 59 60

  _sort_fetch_block_fn_t  fetchfp;
  _sort_merge_compar_fn_t comparFn;
  SMultiwayMergeTreeInfo *pMergeTree;
H
Haojun Liao 已提交
61
};
62

63 64
static int32_t msortComparFn(const void *pLeft, const void *pRight, void *param);

65 66
SSDataBlock* tsortGetSortedDataBlock(const SSortHandle* pSortHandle) {
  return createOneDataBlock(pSortHandle->pDataBlock, false);
67 68 69 70 71 72 73
}

/**
 *
 * @param type
 * @return
 */
74
SSortHandle* tsortCreateSortHandle(SArray* pSortInfo, int32_t type, int32_t pageSize, int32_t numOfPages, SSDataBlock* pBlock, const char* idstr) {
wafwerar's avatar
wafwerar 已提交
75
  SSortHandle* pSortHandle = taosMemoryCalloc(1, sizeof(SSortHandle));
76 77 78 79

  pSortHandle->type       = type;
  pSortHandle->pageSize   = pageSize;
  pSortHandle->numOfPages = numOfPages;
H
Haojun Liao 已提交
80
  pSortHandle->pSortInfo  = pSortInfo;
81
  pSortHandle->loops      = 0;
82 83 84 85

  if (pBlock != NULL) {
    pSortHandle->pDataBlock = createOneDataBlock(pBlock, false);
  }
H
Haojun Liao 已提交
86 87 88

  pSortHandle->pOrderedSource     = taosArrayInit(4, POINTER_BYTES);
  pSortHandle->cmpParam.orderInfo = pSortInfo;
89
  pSortHandle->cmpParam.cmpGroupId = false;
90

H
Haojun Liao 已提交
91
  tsortSetComparFp(pSortHandle, msortComparFn);
92 93

  if (idstr != NULL) {
94
    pSortHandle->idStr = strdup(idstr);
95 96 97 98 99
  }

  return pSortHandle;
}

100
static int32_t sortComparCleanup(SMsortComparParam* cmpParam) {
wmmhello's avatar
wmmhello 已提交
101
  for(int32_t i = 0; i < cmpParam->numOfSources; ++i) {
wmmhello's avatar
wmmhello 已提交
102
    SSortSource* pSource = cmpParam->pSources[i];    // NOTICE: pSource may be SGenericSource *, if it is SORT_MULTISOURCE_MERGE
wmmhello's avatar
wmmhello 已提交
103 104 105 106 107 108 109 110
    blockDataDestroy(pSource->src.pBlock);
    taosMemoryFreeClear(pSource);
  }

  cmpParam->numOfSources = 0;
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
111
void tsortDestroySortHandle(SSortHandle* pSortHandle) {
112 113 114 115
  if (pSortHandle == NULL) {
    return;
  }

H
Haojun Liao 已提交
116
  tsortClose(pSortHandle);
117 118 119 120
  if (pSortHandle->pMergeTree != NULL) {
    tMergeTreeDestroy(pSortHandle->pMergeTree);
  }

H
Haojun Liao 已提交
121
  destroyDiskbasedBuf(pSortHandle->pBuf);
wafwerar's avatar
wafwerar 已提交
122
  taosMemoryFreeClear(pSortHandle->idStr);
wmmhello's avatar
wmmhello 已提交
123
  blockDataDestroy(pSortHandle->pDataBlock);
wmmhello's avatar
wmmhello 已提交
124
  for (size_t i = 0; i < taosArrayGetSize(pSortHandle->pOrderedSource); i++){
wmmhello's avatar
wmmhello 已提交
125
    SSortSource** pSource = taosArrayGet(pSortHandle->pOrderedSource, i);
wmmhello's avatar
wmmhello 已提交
126
    taosMemoryFreeClear(*pSource);
wmmhello's avatar
wmmhello 已提交
127 128
  }
  taosArrayDestroy(pSortHandle->pOrderedSource);
wafwerar's avatar
wafwerar 已提交
129
  taosMemoryFreeClear(pSortHandle);
130 131
}

H
Haojun Liao 已提交
132
int32_t tsortAddSource(SSortHandle* pSortHandle, void* pSource) {
H
Haojun Liao 已提交
133
  taosArrayPush(pSortHandle->pOrderedSource, &pSource);
134
  return TSDB_CODE_SUCCESS;
135 136
}

137
static int32_t doAddNewExternalMemSource(SDiskbasedBuf *pBuf, SArray* pAllSources, SSDataBlock* pBlock, int32_t* sourceId, SArray* pPageIdList) {
wmmhello's avatar
wmmhello 已提交
138
  SSortSource* pSource = taosMemoryCalloc(1, sizeof(SSortSource));
139 140 141 142 143
  if (pSource == NULL) {
    return TSDB_CODE_QRY_OUT_OF_MEMORY;
  }

  pSource->src.pBlock = pBlock;
144
  pSource->pageIdList = pPageIdList;
145 146 147 148 149
  taosArrayPush(pAllSources, &pSource);

  (*sourceId) += 1;

  int32_t rowSize = blockDataGetSerialRowSize(pSource->src.pBlock);
150 151

  // The value of numOfRows must be greater than 0, which is guaranteed by the previous memory allocation
152
  int32_t numOfRows = (getBufPageSize(pBuf) - blockDataGetSerialMetaSize(taosArrayGetSize(pBlock->pDataBlock)))/rowSize;
wmmhello's avatar
wmmhello 已提交
153
  ASSERT(numOfRows > 0);
154 155 156 157 158 159 160
  return blockDataEnsureCapacity(pSource->src.pBlock, numOfRows);
}

static int32_t doAddToBuf(SSDataBlock* pDataBlock, SSortHandle* pHandle) {
  int32_t start = 0;

  if (pHandle->pBuf == NULL) {
wafwerar's avatar
wafwerar 已提交
161 162 163 164 165 166
    if (!osTempSpaceAvailable()) {
      terrno = TSDB_CODE_NO_AVAIL_DISK;
      qError("Add to buf failed since %s", terrstr(terrno));
      return terrno;
    }
    int32_t code = createDiskbasedBuf(&pHandle->pBuf, pHandle->pageSize, pHandle->numOfPages * pHandle->pageSize, "doAddToBuf", tsTempDir);
H
Haojun Liao 已提交
167
    dBufSetPrintInfo(pHandle->pBuf);
168 169 170 171 172
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

173
  SArray* pPageIdList = taosArrayInit(4, sizeof(int32_t));
174 175
  while(start < pDataBlock->info.rows) {
    int32_t stop = 0;
176
    blockDataSplitRows(pDataBlock, pDataBlock->info.hasVarCol, start, &stop, pHandle->pageSize);
177 178 179 180 181 182
    SSDataBlock* p = blockDataExtractBlock(pDataBlock, start, stop - start + 1);
    if (p == NULL) {
      return terrno;
    }

    int32_t pageId = -1;
183
    void* pPage = getNewBufPage(pHandle->pBuf, &pageId);
184
    if (pPage == NULL) {
wmmhello's avatar
wmmhello 已提交
185
      blockDataDestroy(p);
186 187 188
      return terrno;
    }

189 190
    taosArrayPush(pPageIdList, &pageId);

191
    int32_t size = blockDataGetSize(p) + sizeof(int32_t)  + taosArrayGetSize(p->pDataBlock) * sizeof(int32_t);
192 193
    assert(size <= getBufPageSize(pHandle->pBuf));

194
    blockDataToBuf(pPage, p);
195 196 197 198 199 200 201 202

    setBufPageDirty(pPage, true);
    releaseBufPage(pHandle->pBuf, pPage);

    blockDataDestroy(p);
    start = stop + 1;
  }

203
  blockDataCleanup(pDataBlock);
204

205
  SSDataBlock* pBlock = createOneDataBlock(pDataBlock, false);
206
  return doAddNewExternalMemSource(pHandle->pBuf, pHandle->pOrderedSource, pBlock, &pHandle->sourceId, pPageIdList);
207 208
}

209 210 211 212 213
static void setCurrentSourceIsDone(SSortSource* pSource, SSortHandle* pHandle) {
  pSource->src.rowIndex = -1;
  ++pHandle->numOfCompletedSources;
}

214 215 216 217 218 219
static int32_t sortComparInit(SMsortComparParam* cmpParam, SArray* pSources, int32_t startIndex, int32_t endIndex, SSortHandle* pHandle) {
  cmpParam->pSources  = taosArrayGet(pSources, startIndex);
  cmpParam->numOfSources = (endIndex - startIndex + 1);

  int32_t code = 0;

H
Haojun Liao 已提交
220
  if (pHandle->type == SORT_SINGLESOURCE_SORT) {
221
    for (int32_t i = 0; i < cmpParam->numOfSources; ++i) {
wmmhello's avatar
wmmhello 已提交
222
      SSortSource* pSource = cmpParam->pSources[i];
223

224
      // set current source is done
225
      if (taosArrayGetSize(pSource->pageIdList) == 0) {
226 227
        setCurrentSourceIsDone(pSource, pHandle);
        continue;
228 229 230
      }

      SPageInfo* pPgInfo = *(SPageInfo**)taosArrayGet(pSource->pageIdList, pSource->pageIndex);
231

232 233
      void* pPage = getBufPage(pHandle->pBuf, getPageId(pPgInfo));
      code = blockDataFromBuf(pSource->src.pBlock, pPage);
234 235 236 237 238 239 240 241 242
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      releaseBufPage(pHandle->pBuf, pPage);
    }
  } else {
    // multi-pass internal merge sort is required
    if (pHandle->pBuf == NULL) {
wafwerar's avatar
wafwerar 已提交
243 244 245 246 247 248 249
      if (!osTempSpaceAvailable()) {
        terrno = TSDB_CODE_NO_AVAIL_DISK;
        code = terrno;
        qError("Sort compare init failed since %s", terrstr(terrno));
        return code;
      }
      code = createDiskbasedBuf(&pHandle->pBuf, pHandle->pageSize, pHandle->numOfPages * pHandle->pageSize, "sortComparInit", tsTempDir);
H
Haojun Liao 已提交
250
      dBufSetPrintInfo(pHandle->pBuf);
251 252 253 254 255 256
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }
    }

    for (int32_t i = 0; i < cmpParam->numOfSources; ++i) {
wmmhello's avatar
wmmhello 已提交
257
      SSortSource* pSource = cmpParam->pSources[i];
258
      pSource->src.pBlock = pHandle->fetchfp(pSource->param);
259

260
      // set current source is done
261
      if (pSource->src.pBlock == NULL) {
262
        setCurrentSourceIsDone(pSource, pHandle);
263
      }
264 265 266 267 268 269 270
    }
  }

  return code;
}

static void appendOneRowToDataBlock(SSDataBlock *pBlock, const SSDataBlock* pSource, int32_t* rowIndex) {
271
  for (int32_t i = 0; i < taosArrayGetSize(pBlock->pDataBlock); ++i) {
272 273 274 275 276 277 278 279
    SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, i);

    SColumnInfoData* pSrcColInfo = taosArrayGet(pSource->pDataBlock, i);
    bool isNull = colDataIsNull(pSrcColInfo, pSource->info.rows, *rowIndex, NULL);

    if (isNull) {
      colDataAppend(pColInfo, pBlock->info.rows, NULL, true);
    } else {
280
      char* pData = colDataGetData(pSrcColInfo, *rowIndex);
281 282 283 284 285 286 287 288
      colDataAppend(pColInfo, pBlock->info.rows, pData, false);
    }
  }

  pBlock->info.rows += 1;
  *rowIndex += 1;
}

wmmhello's avatar
wmmhello 已提交
289
static int32_t adjustMergeTreeForNextTuple(SSortSource *pSource, SMultiwayMergeTreeInfo *pTree, SSortHandle *pHandle, int32_t* numOfCompleted) {
290 291 292 293 294 295 296
  /*
   * load a new SDataBlock into memory of a given intermediate data-set source,
   * since it's last record in buffer has been chosen to be processed, as the winner of loser-tree
   */
  if (pSource->src.rowIndex >= pSource->src.pBlock->info.rows) {
    pSource->src.rowIndex = 0;

297
    if (pHandle->type == SORT_SINGLESOURCE_SORT) {
wmmhello's avatar
wmmhello 已提交
298
      pSource->pageIndex ++;
299 300 301 302 303 304
      if (pSource->pageIndex >= taosArrayGetSize(pSource->pageIdList)) {
        (*numOfCompleted) += 1;
        pSource->src.rowIndex = -1;
        pSource->pageIndex = -1;
        pSource->src.pBlock = blockDataDestroy(pSource->src.pBlock);
      } else {
305 306
        SPageInfo* pPgInfo = *(SPageInfo**)taosArrayGet(pSource->pageIdList, pSource->pageIndex);

wmmhello's avatar
wmmhello 已提交
307 308
        void* pPage = getBufPage(pHandle->pBuf, getPageId(pPgInfo));
        int32_t    code = blockDataFromBuf(pSource->src.pBlock, pPage);
309 310 311 312 313
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }

        releaseBufPage(pHandle->pBuf, pPage);
314 315
      }
    } else {
wmmhello's avatar
wmmhello 已提交
316
      pSource->src.pBlock = pHandle->fetchfp(((SSortSource*)pSource)->param);
317 318 319
      if (pSource->src.pBlock == NULL) {
        (*numOfCompleted) += 1;
        pSource->src.rowIndex = -1;
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
      }
    }
  }

  /*
   * Adjust loser tree otherwise, according to new candidate data
   * if the loser tree is rebuild completed, we do not need to adjust
   */
  int32_t leafNodeIndex = tMergeTreeGetAdjustIndex(pTree);

#ifdef _DEBUG_VIEW
  printf("before adjust:\t");
  tMergeTreePrint(pTree);
#endif

  tMergeTreeAdjust(pTree, leafNodeIndex);

#ifdef _DEBUG_VIEW
  printf("\nafter adjust:\t");
  tMergeTreePrint(pTree);
#endif
341
  return TSDB_CODE_SUCCESS;
342 343
}

wmmhello's avatar
wmmhello 已提交
344
static SSDataBlock* getSortedBlockDataInner(SSortHandle* pHandle, SMsortComparParam* cmpParam, int32_t capacity) {
345
  blockDataCleanup(pHandle->pDataBlock);
346 347 348 349 350 351 352 353

  while(1) {
    if (cmpParam->numOfSources == pHandle->numOfCompletedSources) {
      break;
    }

    int32_t index = tMergeTreeGetChosenIndex(pHandle->pMergeTree);

wmmhello's avatar
wmmhello 已提交
354
    SSortSource *pSource = (*cmpParam).pSources[index];
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    appendOneRowToDataBlock(pHandle->pDataBlock, pSource->src.pBlock, &pSource->src.rowIndex);

    int32_t code = adjustMergeTreeForNextTuple(pSource, pHandle->pMergeTree, pHandle, &pHandle->numOfCompletedSources);
    if (code != TSDB_CODE_SUCCESS) {
      terrno = code;
      return NULL;
    }

    if (pHandle->pDataBlock->info.rows >= capacity) {
      return pHandle->pDataBlock;
    }
  }

  return (pHandle->pDataBlock->info.rows > 0)? pHandle->pDataBlock:NULL;
}

371
int32_t msortComparFn(const void *pLeft, const void *pRight, void *param) {
372 373 374 375 376 377 378
  int32_t pLeftIdx  = *(int32_t *)pLeft;
  int32_t pRightIdx = *(int32_t *)pRight;

  SMsortComparParam *pParam = (SMsortComparParam *)param;

  SArray *pInfo = pParam->orderInfo;

wmmhello's avatar
wmmhello 已提交
379 380
  SSortSource* pLeftSource  = pParam->pSources[pLeftIdx];
  SSortSource* pRightSource = pParam->pSources[pRightIdx];
381 382 383 384 385 386 387 388 389 390 391 392 393

  // this input is exhausted, set the special value to denote this
  if (pLeftSource->src.rowIndex == -1) {
    return 1;
  }

  if (pRightSource->src.rowIndex == -1) {
    return -1;
  }

  SSDataBlock* pLeftBlock = pLeftSource->src.pBlock;
  SSDataBlock* pRightBlock = pRightSource->src.pBlock;

394 395 396 397
  if (pParam->cmpGroupId) {
    if (pLeftBlock->info.groupId != pRightBlock->info.groupId) {
      return pLeftBlock->info.groupId < pRightBlock->info.groupId ? -1 : 1;
    }
398 399
  }

400 401
  for(int32_t i = 0; i < pInfo->size; ++i) {
    SBlockOrderInfo* pOrder = TARRAY_GET_ELEM(pInfo, i);
H
Haojun Liao 已提交
402
    SColumnInfoData* pLeftColInfoData = TARRAY_GET_ELEM(pLeftBlock->pDataBlock, pOrder->slotId);
403 404 405

    bool leftNull  = false;
    if (pLeftColInfoData->hasNull) {
406 407 408 409 410
      if (pLeftBlock->pBlockAgg == NULL) {
        leftNull = colDataIsNull_s(pLeftColInfoData, pLeftSource->src.rowIndex);
      } else {
        leftNull = colDataIsNull(pLeftColInfoData, pLeftBlock->info.rows, pLeftSource->src.rowIndex, pLeftBlock->pBlockAgg[i]);
      }
411 412
    }

H
Haojun Liao 已提交
413
    SColumnInfoData* pRightColInfoData = TARRAY_GET_ELEM(pRightBlock->pDataBlock, pOrder->slotId);
414 415
    bool rightNull = false;
    if (pRightColInfoData->hasNull) {
416 417 418 419 420
      if (pLeftBlock->pBlockAgg == NULL) {
        rightNull = colDataIsNull_s(pRightColInfoData, pRightSource->src.rowIndex);
      } else {
        rightNull = colDataIsNull(pRightColInfoData, pRightBlock->info.rows, pRightSource->src.rowIndex, pRightBlock->pBlockAgg[i]);
      }
421 422 423 424 425 426 427
    }

    if (leftNull && rightNull) {
      continue; // continue to next slot
    }

    if (rightNull) {
wmmhello's avatar
wmmhello 已提交
428
      return pOrder->nullFirst? 1:-1;
429 430 431
    }

    if (leftNull) {
wmmhello's avatar
wmmhello 已提交
432
      return pOrder->nullFirst? -1:1;
433 434
    }

435 436
    void* left1  = colDataGetData(pLeftColInfoData, pLeftSource->src.rowIndex);
    void* right1 = colDataGetData(pRightColInfoData, pRightSource->src.rowIndex);
437

438
    __compar_fn_t fn = getKeyComparFunc(pLeftColInfoData->info.type, pOrder->order);
439

440 441 442 443 444
    int ret = fn(left1, right1);
    if (ret == 0) {
      continue;
    } else {
      return ret;
445 446
    }
  }
447
  return 0;
448 449 450 451
}

static int32_t doInternalMergeSort(SSortHandle* pHandle) {
  size_t numOfSources = taosArrayGetSize(pHandle->pOrderedSource);
H
Haojun Liao 已提交
452 453 454
  if (numOfSources == 0) {
    return 0;
  }
455 456 457 458 459

  // Calculate the I/O counts to complete the data sort.
  double sortPass = floorl(log2(numOfSources) / log2(pHandle->numOfPages));

  pHandle->totalElapsed = taosGetTimestampUs() - pHandle->startTs;
460 461 462 463 464 465 466 467 468 469

  if (sortPass > 0) {
    size_t s = pHandle->pBuf ? getTotalBufSize(pHandle->pBuf) : 0;
    qDebug("%s %d rounds mergesort required to complete the sort, first-round sorted data size:%" PRIzu
           ", sort elapsed:%" PRId64 ", total elapsed:%" PRId64,
           pHandle->idStr, (int32_t)(sortPass + 1), s, pHandle->sortElapsed, pHandle->totalElapsed);
  } else {
    qDebug("%s ordered source:%"PRIzu", available buf:%d, no need internal sort", pHandle->idStr, numOfSources,
        pHandle->numOfPages);
  }
470

H
Haojun Liao 已提交
471
  int32_t numOfRows = blockDataGetCapacityInRow(pHandle->pDataBlock, pHandle->pageSize);
wmmhello's avatar
wmmhello 已提交
472
  blockDataEnsureCapacity(pHandle->pDataBlock, numOfRows);
473

474 475 476
  // the initial pass + sortPass + final mergePass
  pHandle->loops = sortPass + 2;

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
  size_t numOfSorted = taosArrayGetSize(pHandle->pOrderedSource);
  for(int32_t t = 0; t < sortPass; ++t) {
    int64_t st = taosGetTimestampUs();

    SArray* pResList = taosArrayInit(4, POINTER_BYTES);

    int32_t numOfInputSources = pHandle->numOfPages;
    int32_t sortGroup = (numOfSorted + numOfInputSources - 1) / numOfInputSources;

    // Only *numOfInputSources* can be loaded into buffer to perform the external sort.
    for(int32_t i = 0; i < sortGroup; ++i) {
      pHandle->sourceId += 1;

      int32_t end = (i + 1) * numOfInputSources - 1;
      if (end > numOfSorted - 1) {
        end = numOfSorted - 1;
      }

      pHandle->cmpParam.numOfSources = end - i * numOfInputSources + 1;

      int32_t code = sortComparInit(&pHandle->cmpParam, pHandle->pOrderedSource, i * numOfInputSources, end, pHandle);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      code = tMergeTreeCreate(&pHandle->pMergeTree, pHandle->cmpParam.numOfSources, &pHandle->cmpParam, pHandle->comparFn);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

507
      SArray* pPageIdList = taosArrayInit(4, sizeof(int32_t));
508
      while (1) {
wmmhello's avatar
wmmhello 已提交
509
        SSDataBlock* pDataBlock = getSortedBlockDataInner(pHandle, &pHandle->cmpParam, numOfRows);
510 511 512 513 514
        if (pDataBlock == NULL) {
          break;
        }

        int32_t pageId = -1;
515
        void* pPage = getNewBufPage(pHandle->pBuf, &pageId);
516 517 518 519
        if (pPage == NULL) {
          return terrno;
        }

520 521
        taosArrayPush(pPageIdList, &pageId);

522
        int32_t size = blockDataGetSize(pDataBlock) + sizeof(int32_t) + taosArrayGetSize(pDataBlock->pDataBlock) * sizeof(int32_t);
523 524
        assert(size <= getBufPageSize(pHandle->pBuf));

525
        blockDataToBuf(pPage, pDataBlock);
526 527 528 529

        setBufPageDirty(pPage, true);
        releaseBufPage(pHandle->pBuf, pPage);

530
        blockDataCleanup(pDataBlock);
531 532
      }

533
      sortComparCleanup(&pHandle->cmpParam);
534 535 536
      tMergeTreeDestroy(pHandle->pMergeTree);
      pHandle->numOfCompletedSources = 0;

537
      SSDataBlock* pBlock = createOneDataBlock(pHandle->pDataBlock, false);
538
      code = doAddNewExternalMemSource(pHandle->pBuf, pResList, pBlock, &pHandle->sourceId, pPageIdList);
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
      if (code != 0) {
        return code;
      }
    }

    taosArrayClear(pHandle->pOrderedSource);
    taosArrayAddAll(pHandle->pOrderedSource, pResList);
    taosArrayDestroy(pResList);

    numOfSorted = taosArrayGetSize(pHandle->pOrderedSource);

    int64_t el = taosGetTimestampUs() - st;
    pHandle->totalElapsed += el;

    SDiskbasedBufStatis statis = getDBufStatis(pHandle->pBuf);
    qDebug("%s %d round mergesort, elapsed:%"PRId64" readDisk:%.2f Kb, flushDisk:%.2f Kb", pHandle->idStr, t + 1, el, statis.loadBytes/1024.0,
           statis.flushBytes/1024.0);

H
Haojun Liao 已提交
557 558
    if (pHandle->type == SORT_MULTISOURCE_MERGE) {
      pHandle->type = SORT_SINGLESOURCE_SORT;
559 560 561 562 563 564 565 566
      pHandle->comparFn = msortComparFn;
    }
  }

  pHandle->cmpParam.numOfSources = taosArrayGetSize(pHandle->pOrderedSource);
  return 0;
}

567
// TODO consider the page meta size
568 569 570 571 572 573 574 575 576 577 578 579 580
int32_t getProperSortPageSize(size_t rowSize) {
  uint32_t defaultPageSize = 4096;

  uint32_t pgSize = 0;
  if (rowSize * 4 > defaultPageSize) {
    pgSize = rowSize * 4;
  } else {
    pgSize = defaultPageSize;
  }

  return pgSize;
}

581
static int32_t createInitialSources(SSortHandle* pHandle) {
582
  size_t sortBufSize = pHandle->numOfPages * pHandle->pageSize;
H
Haojun Liao 已提交
583 584

  if (pHandle->type == SORT_SINGLESOURCE_SORT) {
wmmhello's avatar
wmmhello 已提交
585
    SSortSource* source = taosArrayGetP(pHandle->pOrderedSource, 0);
H
Haojun Liao 已提交
586
    taosArrayClear(pHandle->pOrderedSource);
587

588
    while (1) {
589
      SSDataBlock* pBlock = pHandle->fetchfp(source->param);
590 591 592 593
      if (pBlock == NULL) {
        break;
      }

594
      if (pHandle->pDataBlock == NULL) {
595 596 597
        pHandle->pageSize = getProperSortPageSize(blockDataGetRowSize(pBlock));

        // todo, number of pages are set according to the total available sort buffer
598 599
        pHandle->numOfPages = 1024;
        sortBufSize = pHandle->numOfPages * pHandle->pageSize;
600
        pHandle->pDataBlock = createOneDataBlock(pBlock, false);
601 602
      }

603 604 605
      if (pHandle->beforeFp != NULL) {
        pHandle->beforeFp(pBlock, pHandle->param);
      }
606

607 608 609 610
      int32_t code = blockDataMerge(pHandle->pDataBlock, pBlock);
      if (code != 0) {
        return code;
      }
611

612 613 614 615
      size_t size = blockDataGetSize(pHandle->pDataBlock);
      if (size > sortBufSize) {
        // Perform the in-memory sort and then flush data in the buffer into disk.
        int64_t p = taosGetTimestampUs();
wmmhello's avatar
wmmhello 已提交
616 617 618 619
        code = blockDataSort(pHandle->pDataBlock, pHandle->pSortInfo);
        if (code != 0) {
          return code;
        }
620

621 622
        int64_t el = taosGetTimestampUs() - p;
        pHandle->sortElapsed += el;
623

624
        doAddToBuf(pHandle->pDataBlock, pHandle);
625 626 627
      }
    }

628
    if (pHandle->pDataBlock != NULL && pHandle->pDataBlock->info.rows > 0) {
629 630 631
      size_t size = blockDataGetSize(pHandle->pDataBlock);

      // Perform the in-memory sort and then flush data in the buffer into disk.
632 633
      int64_t p = taosGetTimestampUs();

wmmhello's avatar
wmmhello 已提交
634 635 636 637
      int32_t code = blockDataSort(pHandle->pDataBlock, pHandle->pSortInfo);
      if (code != 0) {
        return code;
      }
638

639 640 641
      int64_t el = taosGetTimestampUs() - p;
      pHandle->sortElapsed += el;

642
      // All sorted data can fit in memory, external memory sort is not needed. Return to directly
643
      if (size <= sortBufSize && pHandle->pBuf == NULL) {
644 645 646
        pHandle->cmpParam.numOfSources = 1;
        pHandle->inMemSort = true;

647
        pHandle->loops = 1;
648 649 650 651 652 653 654
        pHandle->tupleHandle.rowIndex  = -1;
        pHandle->tupleHandle.pBlock = pHandle->pDataBlock;
        return 0;
      } else {
        doAddToBuf(pHandle->pDataBlock, pHandle);
      }
    }
H
Haojun Liao 已提交
655 656 657 658 659
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
660
int32_t tsortOpen(SSortHandle* pHandle) {
H
Haojun Liao 已提交
661 662 663 664 665 666 667 668 669 670
  if (pHandle->opened) {
    return 0;
  }

  if (pHandle->fetchfp == NULL || pHandle->comparFn == NULL) {
    return -1;
  }

  pHandle->opened = true;

671
  int32_t code = createInitialSources(pHandle);
H
Haojun Liao 已提交
672 673
  if (code != TSDB_CODE_SUCCESS) {
    return code;
674 675 676
  }

  // do internal sort
H
Haojun Liao 已提交
677
  code = doInternalMergeSort(pHandle);
678 679 680 681 682
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  int32_t numOfSources = taosArrayGetSize(pHandle->pOrderedSource);
H
Haojun Liao 已提交
683 684 685 686
  if (pHandle->pBuf != NULL) {
    ASSERT(numOfSources <= getNumOfInMemBufPages(pHandle->pBuf));
  }

H
Haojun Liao 已提交
687 688 689 690
  if (numOfSources == 0) {
    return 0;
  }

691 692 693 694 695
  code = sortComparInit(&pHandle->cmpParam, pHandle->pOrderedSource, 0, numOfSources - 1, pHandle);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

696
  return tMergeTreeCreate(&pHandle->pMergeTree, pHandle->cmpParam.numOfSources, &pHandle->cmpParam, pHandle->comparFn);
697 698
}

H
Haojun Liao 已提交
699
int32_t tsortClose(SSortHandle* pHandle) {
700
  // do nothing
701
  return TSDB_CODE_SUCCESS;
702 703
}

704 705 706 707
int32_t tsortSetFetchRawDataFp(SSortHandle* pHandle, _sort_fetch_block_fn_t fetchFp, void (*fp)(SSDataBlock*, void*), void* param) {
  pHandle->fetchfp = fetchFp;
  pHandle->beforeFp = fp;
  pHandle->param = param;
708
  return TSDB_CODE_SUCCESS;
709 710
}

H
Haojun Liao 已提交
711
int32_t tsortSetComparFp(SSortHandle* pHandle, _sort_merge_compar_fn_t fp) {
712
  pHandle->comparFn = fp;
713
  return TSDB_CODE_SUCCESS;
714 715
}

716 717 718 719 720
int32_t tsortSetCompareGroupId(SSortHandle* pHandle, bool compareGroupId) {
  pHandle->cmpParam.cmpGroupId = compareGroupId;
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
721
STupleHandle* tsortNextTuple(SSortHandle* pHandle) {
722 723 724 725
  if (pHandle->cmpParam.numOfSources == pHandle->numOfCompletedSources) {
    return NULL;
  }

726
  // All the data are hold in the buffer, no external sort is invoked.
727 728 729 730 731 732 733 734 735 736 737
  if (pHandle->inMemSort) {
    pHandle->tupleHandle.rowIndex += 1;
    if (pHandle->tupleHandle.rowIndex == pHandle->pDataBlock->info.rows) {
      pHandle->numOfCompletedSources = 1;
      return NULL;
    }

    return &pHandle->tupleHandle;
  }

  int32_t index = tMergeTreeGetChosenIndex(pHandle->pMergeTree);
wmmhello's avatar
wmmhello 已提交
738
  SSortSource *pSource = pHandle->cmpParam.pSources[index];
739 740 741 742 743 744 745 746 747 748 749 750 751

  if (pHandle->needAdjust) {
    int32_t code = adjustMergeTreeForNextTuple(pSource, pHandle->pMergeTree, pHandle, &pHandle->numOfCompletedSources);
    if (code != TSDB_CODE_SUCCESS) {
      terrno = code;
      return NULL;
    }
  }

  if (pHandle->cmpParam.numOfSources == pHandle->numOfCompletedSources) {
    return NULL;
  }

752
  // Get the adjusted value after the loser tree is updated.
753 754 755 756 757 758 759 760 761 762 763 764 765 766
  index = tMergeTreeGetChosenIndex(pHandle->pMergeTree);
  pSource = pHandle->cmpParam.pSources[index];

  assert(pSource->src.pBlock != NULL);

  pHandle->tupleHandle.rowIndex = pSource->src.rowIndex;
  pHandle->tupleHandle.pBlock = pSource->src.pBlock;

  pHandle->needAdjust = true;
  pSource->src.rowIndex += 1;

  return &pHandle->tupleHandle;
}

H
Haojun Liao 已提交
767
bool tsortIsNullVal(STupleHandle* pVHandle, int32_t colIndex) {
768
  SColumnInfoData* pColInfoSrc = taosArrayGet(pVHandle->pBlock->pDataBlock, colIndex);
769
  return colDataIsNull_s(pColInfoSrc, pVHandle->rowIndex);
770 771
}

H
Haojun Liao 已提交
772
void* tsortGetValue(STupleHandle* pVHandle, int32_t colIndex) {
773
  SColumnInfoData* pColInfo = TARRAY_GET_ELEM(pVHandle->pBlock->pDataBlock, colIndex);
774 775 776 777 778
  if (pColInfo->pData == NULL) {
    return NULL;
  } else {
    return colDataGetData(pColInfo, pVHandle->rowIndex);
  }
779
}
780

S
slzhou 已提交
781 782 783 784
uint64_t tsortGetGroupId(STupleHandle* pVHandle) {
  return pVHandle->pBlock->info.groupId;
}

785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
SSortExecInfo tsortGetSortExecInfo(SSortHandle* pHandle) {
  SSortExecInfo info = {0};

  info.sortBuffer = pHandle->pageSize * pHandle->numOfPages;
  info.sortMethod = pHandle->inMemSort? SORT_QSORT_T:SORT_SPILLED_MERGE_SORT_T;
  info.loops  = pHandle->loops;

  if (pHandle->pBuf != NULL) {
    SDiskbasedBufStatis st = getDBufStatis(pHandle->pBuf);
    info.writeBytes = st.flushBytes;
    info.readBytes = st.loadBytes;
  }

  return info;
}