tsort.c 25.9 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 "query.h"
H
Hongze Cheng 已提交
17
#include "tcommon.h"
18

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

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

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

H
Hongze Cheng 已提交
38 39
  SArray* pSortInfo;
  SArray* pOrderedSource;
40

H
Hongze Cheng 已提交
41 42 43 44
  int32_t  loops;
  uint64_t sortElapsed;
  int64_t  startTs;
  uint64_t totalElapsed;
45 46

  int32_t           sourceId;
H
Hongze Cheng 已提交
47
  SSDataBlock*      pDataBlock;
48 49 50
  SMsortComparParam cmpParam;
  int32_t           numOfCompletedSources;
  bool              opened;
H
Hongze Cheng 已提交
51
  const char*       idStr;
52 53 54
  bool              inMemSort;
  bool              needAdjust;
  STupleHandle      tupleHandle;
H
Hongze Cheng 已提交
55
  void*             param;
56
  void (*beforeFp)(SSDataBlock* pBlock, void* param);
57 58 59

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

H
Hongze Cheng 已提交
63
static int32_t msortComparFn(const void* pLeft, const void* pRight, void* param);
64

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

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

H
Hongze Cheng 已提交
78 79
  pSortHandle->type = type;
  pSortHandle->pageSize = pageSize;
80
  pSortHandle->numOfPages = numOfPages;
H
Hongze Cheng 已提交
81 82
  pSortHandle->pSortInfo = pSortInfo;
  pSortHandle->loops = 0;
83 84 85 86

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

H
Hongze Cheng 已提交
88
  pSortHandle->pOrderedSource = taosArrayInit(4, POINTER_BYTES);
H
Haojun Liao 已提交
89
  pSortHandle->cmpParam.orderInfo = pSortInfo;
90
  pSortHandle->cmpParam.cmpGroupId = false;
91

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

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

  return pSortHandle;
}

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

  cmpParam->numOfSources = 0;
  return TSDB_CODE_SUCCESS;
}

113 114 115 116 117 118
void tsortClearOrderdSource(SArray *pOrderedSource) {
  for (size_t i = 0; i < taosArrayGetSize(pOrderedSource); i++) {
    SSortSource** pSource = taosArrayGet(pOrderedSource, i);
    if (NULL == *pSource) {
      continue;
    }
119 120 121 122
    // release pageIdList
    if ((*pSource)->pageIdList) {
      taosArrayDestroy((*pSource)->pageIdList);
    }
123
    if ((*pSource)->param && !(*pSource)->onlyRef) {
124
      taosMemoryFree((*pSource)->param);
125 126 127 128 129 130 131
    }
    taosMemoryFreeClear(*pSource);
  }

  taosArrayClear(pOrderedSource);
}

H
Haojun Liao 已提交
132
void tsortDestroySortHandle(SSortHandle* pSortHandle) {
133 134 135 136
  if (pSortHandle == NULL) {
    return;
  }

H
Haojun Liao 已提交
137
  tsortClose(pSortHandle);
138 139 140 141
  if (pSortHandle->pMergeTree != NULL) {
    tMergeTreeDestroy(pSortHandle->pMergeTree);
  }

H
Haojun Liao 已提交
142
  destroyDiskbasedBuf(pSortHandle->pBuf);
wafwerar's avatar
wafwerar 已提交
143
  taosMemoryFreeClear(pSortHandle->idStr);
wmmhello's avatar
wmmhello 已提交
144
  blockDataDestroy(pSortHandle->pDataBlock);
145 146

  tsortClearOrderdSource(pSortHandle->pOrderedSource);
wmmhello's avatar
wmmhello 已提交
147
  taosArrayDestroy(pSortHandle->pOrderedSource);
wafwerar's avatar
wafwerar 已提交
148
  taosMemoryFreeClear(pSortHandle);
149 150
}

H
Haojun Liao 已提交
151
int32_t tsortAddSource(SSortHandle* pSortHandle, void* pSource) {
H
Haojun Liao 已提交
152
  taosArrayPush(pSortHandle->pOrderedSource, &pSource);
153
  return TSDB_CODE_SUCCESS;
154 155
}

H
Hongze Cheng 已提交
156 157
static int32_t doAddNewExternalMemSource(SDiskbasedBuf* pBuf, SArray* pAllSources, SSDataBlock* pBlock,
                                         int32_t* sourceId, SArray* pPageIdList) {
wmmhello's avatar
wmmhello 已提交
158
  SSortSource* pSource = taosMemoryCalloc(1, sizeof(SSortSource));
159
  if (pSource == NULL) {
H
Haojun Liao 已提交
160
    taosArrayDestroy(pPageIdList);
161 162 163 164
    return TSDB_CODE_QRY_OUT_OF_MEMORY;
  }

  pSource->src.pBlock = pBlock;
165
  pSource->pageIdList = pPageIdList;
166 167 168 169 170
  taosArrayPush(pAllSources, &pSource);

  (*sourceId) += 1;

  int32_t rowSize = blockDataGetSerialRowSize(pSource->src.pBlock);
171 172

  // The value of numOfRows must be greater than 0, which is guaranteed by the previous memory allocation
H
Hongze Cheng 已提交
173 174
  int32_t numOfRows =
      (getBufPageSize(pBuf) - blockDataGetSerialMetaSize(taosArrayGetSize(pBlock->pDataBlock))) / rowSize;
wmmhello's avatar
wmmhello 已提交
175
  ASSERT(numOfRows > 0);
H
Haojun Liao 已提交
176

177 178 179 180 181 182 183
  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 已提交
184 185 186 187 188
    if (!osTempSpaceAvailable()) {
      terrno = TSDB_CODE_NO_AVAIL_DISK;
      qError("Add to buf failed since %s", terrstr(terrno));
      return terrno;
    }
H
Hongze Cheng 已提交
189 190
    int32_t code = createDiskbasedBuf(&pHandle->pBuf, pHandle->pageSize, pHandle->numOfPages * pHandle->pageSize,
                                      "doAddToBuf", tsTempDir);
H
Haojun Liao 已提交
191
    dBufSetPrintInfo(pHandle->pBuf);
192 193 194 195 196
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

197
  SArray* pPageIdList = taosArrayInit(4, sizeof(int32_t));
H
Hongze Cheng 已提交
198
  while (start < pDataBlock->info.rows) {
199
    int32_t stop = 0;
200
    blockDataSplitRows(pDataBlock, pDataBlock->info.hasVarCol, start, &stop, pHandle->pageSize);
201 202
    SSDataBlock* p = blockDataExtractBlock(pDataBlock, start, stop - start + 1);
    if (p == NULL) {
H
Haojun Liao 已提交
203
      taosArrayDestroy(pPageIdList);
204 205 206 207
      return terrno;
    }

    int32_t pageId = -1;
H
Hongze Cheng 已提交
208
    void*   pPage = getNewBufPage(pHandle->pBuf, &pageId);
209
    if (pPage == NULL) {
wmmhello's avatar
wmmhello 已提交
210
      blockDataDestroy(p);
211 212 213
      return terrno;
    }

214 215
    taosArrayPush(pPageIdList, &pageId);

H
Hongze Cheng 已提交
216
    int32_t size = blockDataGetSize(p) + sizeof(int32_t) + taosArrayGetSize(p->pDataBlock) * sizeof(int32_t);
217 218
    assert(size <= getBufPageSize(pHandle->pBuf));

219
    blockDataToBuf(pPage, p);
220 221 222 223 224 225 226 227

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

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

228
  blockDataCleanup(pDataBlock);
229

230
  SSDataBlock* pBlock = createOneDataBlock(pDataBlock, false);
231
  return doAddNewExternalMemSource(pHandle->pBuf, pHandle->pOrderedSource, pBlock, &pHandle->sourceId, pPageIdList);
232 233
}

234 235 236 237 238
static void setCurrentSourceIsDone(SSortSource* pSource, SSortHandle* pHandle) {
  pSource->src.rowIndex = -1;
  ++pHandle->numOfCompletedSources;
}

H
Hongze Cheng 已提交
239 240 241
static int32_t sortComparInit(SMsortComparParam* cmpParam, SArray* pSources, int32_t startIndex, int32_t endIndex,
                              SSortHandle* pHandle) {
  cmpParam->pSources = taosArrayGet(pSources, startIndex);
242 243 244 245
  cmpParam->numOfSources = (endIndex - startIndex + 1);

  int32_t code = 0;

H
Haojun Liao 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  // multi-pass internal merge sort is required
  if (pHandle->pBuf == NULL) {
    if (!osTempSpaceAvailable()) {
      code = TSDB_CODE_NO_AVAIL_DISK;
      qError("Sort compare init failed since %s", terrstr(code));
      return code;
    }

    code = createDiskbasedBuf(&pHandle->pBuf, pHandle->pageSize, pHandle->numOfPages * pHandle->pageSize,
                              "sortComparInit", tsTempDir);
    dBufSetPrintInfo(pHandle->pBuf);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

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

266
      // set current source is done
267
      if (taosArrayGetSize(pSource->pageIdList) == 0) {
268 269
        setCurrentSourceIsDone(pSource, pHandle);
        continue;
270 271
      }

D
dapan1121 已提交
272
      int32_t* pPgId = taosArrayGet(pSource->pageIdList, pSource->pageIndex);
273

D
dapan1121 已提交
274
      void* pPage = getBufPage(pHandle->pBuf, *pPgId);
275
      code = blockDataFromBuf(pSource->src.pBlock, pPage);
276 277 278 279 280 281 282 283
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      releaseBufPage(pHandle->pBuf, pPage);
    }
  } else {
    for (int32_t i = 0; i < cmpParam->numOfSources; ++i) {
wmmhello's avatar
wmmhello 已提交
284
      SSortSource* pSource = cmpParam->pSources[i];
285
      pSource->src.pBlock = pHandle->fetchfp(pSource->param);
286

287
      // set current source is done
288
      if (pSource->src.pBlock == NULL) {
289
        setCurrentSourceIsDone(pSource, pHandle);
290
      }
291 292 293 294 295 296
    }
  }

  return code;
}

H
Hongze Cheng 已提交
297
static void appendOneRowToDataBlock(SSDataBlock* pBlock, const SSDataBlock* pSource, int32_t* rowIndex) {
298
  for (int32_t i = 0; i < taosArrayGetSize(pBlock->pDataBlock); ++i) {
299 300 301
    SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, i);

    SColumnInfoData* pSrcColInfo = taosArrayGet(pSource->pDataBlock, i);
H
Hongze Cheng 已提交
302
    bool             isNull = colDataIsNull(pSrcColInfo, pSource->info.rows, *rowIndex, NULL);
303 304 305 306

    if (isNull) {
      colDataAppend(pColInfo, pBlock->info.rows, NULL, true);
    } else {
307
      char* pData = colDataGetData(pSrcColInfo, *rowIndex);
308 309 310 311 312 313 314 315
      colDataAppend(pColInfo, pBlock->info.rows, pData, false);
    }
  }

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

H
Hongze Cheng 已提交
316 317
static int32_t adjustMergeTreeForNextTuple(SSortSource* pSource, SMultiwayMergeTreeInfo* pTree, SSortHandle* pHandle,
                                           int32_t* numOfCompleted) {
318 319 320 321 322 323 324
  /*
   * 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;

325
    if (pHandle->type == SORT_SINGLESOURCE_SORT) {
H
Hongze Cheng 已提交
326
      pSource->pageIndex++;
327 328 329 330 331 332
      if (pSource->pageIndex >= taosArrayGetSize(pSource->pageIdList)) {
        (*numOfCompleted) += 1;
        pSource->src.rowIndex = -1;
        pSource->pageIndex = -1;
        pSource->src.pBlock = blockDataDestroy(pSource->src.pBlock);
      } else {
D
dapan1121 已提交
333
        int32_t* pPgId = taosArrayGet(pSource->pageIdList, pSource->pageIndex);
334

H
Hongze Cheng 已提交
335 336
        void*   pPage = getBufPage(pHandle->pBuf, *pPgId);
        int32_t code = blockDataFromBuf(pSource->src.pBlock, pPage);
337 338 339 340 341
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }

        releaseBufPage(pHandle->pBuf, pPage);
342 343
      }
    } else {
wmmhello's avatar
wmmhello 已提交
344
      pSource->src.pBlock = pHandle->fetchfp(((SSortSource*)pSource)->param);
345 346 347
      if (pSource->src.pBlock == NULL) {
        (*numOfCompleted) += 1;
        pSource->src.rowIndex = -1;
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
      }
    }
  }

  /*
   * 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
369
  return TSDB_CODE_SUCCESS;
370 371
}

wmmhello's avatar
wmmhello 已提交
372
static SSDataBlock* getSortedBlockDataInner(SSortHandle* pHandle, SMsortComparParam* cmpParam, int32_t capacity) {
373
  blockDataCleanup(pHandle->pDataBlock);
374

H
Hongze Cheng 已提交
375
  while (1) {
376 377 378 379 380 381
    if (cmpParam->numOfSources == pHandle->numOfCompletedSources) {
      break;
    }

    int32_t index = tMergeTreeGetChosenIndex(pHandle->pMergeTree);

H
Hongze Cheng 已提交
382
    SSortSource* pSource = (*cmpParam).pSources[index];
383 384 385 386 387 388 389 390 391 392 393 394 395
    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;
    }
  }

H
Hongze Cheng 已提交
396
  return (pHandle->pDataBlock->info.rows > 0) ? pHandle->pDataBlock : NULL;
397 398
}

H
Hongze Cheng 已提交
399 400 401
int32_t msortComparFn(const void* pLeft, const void* pRight, void* param) {
  int32_t pLeftIdx = *(int32_t*)pLeft;
  int32_t pRightIdx = *(int32_t*)pRight;
402

H
Hongze Cheng 已提交
403
  SMsortComparParam* pParam = (SMsortComparParam*)param;
404

H
Hongze Cheng 已提交
405
  SArray* pInfo = pParam->orderInfo;
406

H
Hongze Cheng 已提交
407
  SSortSource* pLeftSource = pParam->pSources[pLeftIdx];
wmmhello's avatar
wmmhello 已提交
408
  SSortSource* pRightSource = pParam->pSources[pRightIdx];
409 410 411 412 413 414 415 416 417 418 419 420 421

  // 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;

422 423 424 425
  if (pParam->cmpGroupId) {
    if (pLeftBlock->info.groupId != pRightBlock->info.groupId) {
      return pLeftBlock->info.groupId < pRightBlock->info.groupId ? -1 : 1;
    }
426 427
  }

H
Hongze Cheng 已提交
428
  for (int32_t i = 0; i < pInfo->size; ++i) {
429
    SBlockOrderInfo* pOrder = TARRAY_GET_ELEM(pInfo, i);
H
Haojun Liao 已提交
430
    SColumnInfoData* pLeftColInfoData = TARRAY_GET_ELEM(pLeftBlock->pDataBlock, pOrder->slotId);
431

H
Hongze Cheng 已提交
432
    bool leftNull = false;
433
    if (pLeftColInfoData->hasNull) {
434 435 436
      if (pLeftBlock->pBlockAgg == NULL) {
        leftNull = colDataIsNull_s(pLeftColInfoData, pLeftSource->src.rowIndex);
      } else {
H
Hongze Cheng 已提交
437 438
        leftNull =
            colDataIsNull(pLeftColInfoData, pLeftBlock->info.rows, pLeftSource->src.rowIndex, pLeftBlock->pBlockAgg[i]);
439
      }
440 441
    }

H
Haojun Liao 已提交
442
    SColumnInfoData* pRightColInfoData = TARRAY_GET_ELEM(pRightBlock->pDataBlock, pOrder->slotId);
H
Hongze Cheng 已提交
443
    bool             rightNull = false;
444
    if (pRightColInfoData->hasNull) {
H
Haojun Liao 已提交
445
      if (pRightBlock->pBlockAgg == NULL) {
446 447
        rightNull = colDataIsNull_s(pRightColInfoData, pRightSource->src.rowIndex);
      } else {
H
Hongze Cheng 已提交
448 449
        rightNull = colDataIsNull(pRightColInfoData, pRightBlock->info.rows, pRightSource->src.rowIndex,
                                  pRightBlock->pBlockAgg[i]);
450
      }
451 452 453
    }

    if (leftNull && rightNull) {
H
Hongze Cheng 已提交
454
      continue;  // continue to next slot
455 456 457
    }

    if (rightNull) {
H
Hongze Cheng 已提交
458
      return pOrder->nullFirst ? 1 : -1;
459 460 461
    }

    if (leftNull) {
H
Hongze Cheng 已提交
462
      return pOrder->nullFirst ? -1 : 1;
463 464
    }

H
Hongze Cheng 已提交
465
    void* left1 = colDataGetData(pLeftColInfoData, pLeftSource->src.rowIndex);
466
    void* right1 = colDataGetData(pRightColInfoData, pRightSource->src.rowIndex);
467

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

470 471 472 473 474
    int ret = fn(left1, right1);
    if (ret == 0) {
      continue;
    } else {
      return ret;
475 476
    }
  }
477
  return 0;
478 479 480 481
}

static int32_t doInternalMergeSort(SSortHandle* pHandle) {
  size_t numOfSources = taosArrayGetSize(pHandle->pOrderedSource);
H
Haojun Liao 已提交
482 483 484
  if (numOfSources == 0) {
    return 0;
  }
485 486 487 488 489

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

  pHandle->totalElapsed = taosGetTimestampUs() - pHandle->startTs;
490 491 492 493 494 495 496

  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 {
H
Hongze Cheng 已提交
497 498
    qDebug("%s ordered source:%" PRIzu ", available buf:%d, no need internal sort", pHandle->idStr, numOfSources,
           pHandle->numOfPages);
499
  }
500

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

504 505 506
  // the initial pass + sortPass + final mergePass
  pHandle->loops = sortPass + 2;

507
  size_t numOfSorted = taosArrayGetSize(pHandle->pOrderedSource);
H
Hongze Cheng 已提交
508
  for (int32_t t = 0; t < sortPass; ++t) {
509 510 511 512 513 514 515 516
    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.
H
Hongze Cheng 已提交
517
    for (int32_t i = 0; i < sortGroup; ++i) {
518 519 520 521 522 523 524 525 526 527 528
      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) {
H
Haojun Liao 已提交
529
        taosArrayDestroy(pResList);
530 531 532
        return code;
      }

H
Hongze Cheng 已提交
533 534
      code =
          tMergeTreeCreate(&pHandle->pMergeTree, pHandle->cmpParam.numOfSources, &pHandle->cmpParam, pHandle->comparFn);
535
      if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
536
        taosArrayDestroy(pResList);
537 538 539
        return code;
      }

540
      SArray* pPageIdList = taosArrayInit(4, sizeof(int32_t));
541
      while (1) {
wmmhello's avatar
wmmhello 已提交
542
        SSDataBlock* pDataBlock = getSortedBlockDataInner(pHandle, &pHandle->cmpParam, numOfRows);
543 544 545 546 547
        if (pDataBlock == NULL) {
          break;
        }

        int32_t pageId = -1;
H
Hongze Cheng 已提交
548
        void*   pPage = getNewBufPage(pHandle->pBuf, &pageId);
549
        if (pPage == NULL) {
H
Haojun Liao 已提交
550 551
          taosArrayDestroy(pResList);
          taosArrayDestroy(pPageIdList);
552 553 554
          return terrno;
        }

555 556
        taosArrayPush(pPageIdList, &pageId);

H
Hongze Cheng 已提交
557 558
        int32_t size =
            blockDataGetSize(pDataBlock) + sizeof(int32_t) + taosArrayGetSize(pDataBlock->pDataBlock) * sizeof(int32_t);
559 560
        assert(size <= getBufPageSize(pHandle->pBuf));

561
        blockDataToBuf(pPage, pDataBlock);
562 563 564 565

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

566
        blockDataCleanup(pDataBlock);
567 568
      }

569
      sortComparCleanup(&pHandle->cmpParam);
570 571 572
      tMergeTreeDestroy(pHandle->pMergeTree);
      pHandle->numOfCompletedSources = 0;

573
      SSDataBlock* pBlock = createOneDataBlock(pHandle->pDataBlock, false);
574
      code = doAddNewExternalMemSource(pHandle->pBuf, pResList, pBlock, &pHandle->sourceId, pPageIdList);
H
Haojun Liao 已提交
575 576
      if (code != TSDB_CODE_SUCCESS) {
        taosArrayDestroy(pResList);
577 578 579 580
        return code;
      }
    }

581
    tsortClearOrderdSource(pHandle->pOrderedSource);
582 583 584 585 586 587 588 589 590
    taosArrayAddAll(pHandle->pOrderedSource, pResList);
    taosArrayDestroy(pResList);

    numOfSorted = taosArrayGetSize(pHandle->pOrderedSource);

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

    SDiskbasedBufStatis statis = getDBufStatis(pHandle->pBuf);
H
Hongze Cheng 已提交
591 592
    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);
593

H
Haojun Liao 已提交
594 595
    if (pHandle->type == SORT_MULTISOURCE_MERGE) {
      pHandle->type = SORT_SINGLESOURCE_SORT;
596 597 598 599 600 601 602 603
      pHandle->comparFn = msortComparFn;
    }
  }

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

604 605 606 607 608
// get sort page size
int32_t getProperSortPageSize(size_t rowSize, uint32_t numOfCols) {
  uint32_t pgSize = rowSize * 4 + blockDataGetSerialMetaSize(numOfCols);
  if (pgSize < DEFAULT_PAGESIZE) {
    return DEFAULT_PAGESIZE;
609 610 611 612 613
  }

  return pgSize;
}

614
static int32_t createInitialSources(SSortHandle* pHandle) {
615
  size_t sortBufSize = pHandle->numOfPages * pHandle->pageSize;
H
Haojun Liao 已提交
616 617

  if (pHandle->type == SORT_SINGLESOURCE_SORT) {
618 619 620 621 622
    SSortSource** pSource = taosArrayGet(pHandle->pOrderedSource, 0);
    SSortSource* source = *pSource;
    *pSource = NULL;
    
    tsortClearOrderdSource(pHandle->pOrderedSource);
623

624
    while (1) {
625
      SSDataBlock* pBlock = pHandle->fetchfp(source->param);
626 627 628 629
      if (pBlock == NULL) {
        break;
      }

630
      if (pHandle->pDataBlock == NULL) {
631 632
        uint32_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
        pHandle->pageSize = getProperSortPageSize(blockDataGetRowSize(pBlock), numOfCols);
633 634

        // todo, number of pages are set according to the total available sort buffer
635 636
        pHandle->numOfPages = 1024;
        sortBufSize = pHandle->numOfPages * pHandle->pageSize;
637
        pHandle->pDataBlock = createOneDataBlock(pBlock, false);
638 639
      }

640 641 642
      if (pHandle->beforeFp != NULL) {
        pHandle->beforeFp(pBlock, pHandle->param);
      }
643

644 645
      int32_t code = blockDataMerge(pHandle->pDataBlock, pBlock);
      if (code != 0) {
646 647 648 649
        if (source->param && !source->onlyRef) {
          taosMemoryFree(source->param);
        }
        taosMemoryFree(source);
650 651
        return code;
      }
652

653 654 655 656
      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 已提交
657 658
        code = blockDataSort(pHandle->pDataBlock, pHandle->pSortInfo);
        if (code != 0) {
659 660 661 662
          if (source->param && !source->onlyRef) {
            taosMemoryFree(source->param);
          }
          taosMemoryFree(source);
wmmhello's avatar
wmmhello 已提交
663 664
          return code;
        }
665

666 667
        int64_t el = taosGetTimestampUs() - p;
        pHandle->sortElapsed += el;
668

669
        doAddToBuf(pHandle->pDataBlock, pHandle);
670 671 672
      }
    }

673 674 675 676 677
    if (source->param && !source->onlyRef) {
      taosMemoryFree(source->param);
    }
    taosMemoryFree(source);

678
    if (pHandle->pDataBlock != NULL && pHandle->pDataBlock->info.rows > 0) {
679 680 681
      size_t size = blockDataGetSize(pHandle->pDataBlock);

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

wmmhello's avatar
wmmhello 已提交
684 685 686 687
      int32_t code = blockDataSort(pHandle->pDataBlock, pHandle->pSortInfo);
      if (code != 0) {
        return code;
      }
688

689 690 691
      int64_t el = taosGetTimestampUs() - p;
      pHandle->sortElapsed += el;

692
      // All sorted data can fit in memory, external memory sort is not needed. Return to directly
693
      if (size <= sortBufSize && pHandle->pBuf == NULL) {
694 695 696
        pHandle->cmpParam.numOfSources = 1;
        pHandle->inMemSort = true;

697
        pHandle->loops = 1;
H
Hongze Cheng 已提交
698
        pHandle->tupleHandle.rowIndex = -1;
699 700 701 702 703 704
        pHandle->tupleHandle.pBlock = pHandle->pDataBlock;
        return 0;
      } else {
        doAddToBuf(pHandle->pDataBlock, pHandle);
      }
    }
H
Haojun Liao 已提交
705 706 707 708 709
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
710
int32_t tsortOpen(SSortHandle* pHandle) {
H
Haojun Liao 已提交
711 712 713 714 715 716 717 718 719 720
  if (pHandle->opened) {
    return 0;
  }

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

  pHandle->opened = true;

721
  int32_t code = createInitialSources(pHandle);
H
Haojun Liao 已提交
722 723
  if (code != TSDB_CODE_SUCCESS) {
    return code;
724 725 726
  }

  // do internal sort
H
Haojun Liao 已提交
727
  code = doInternalMergeSort(pHandle);
728 729 730 731 732
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  int32_t numOfSources = taosArrayGetSize(pHandle->pOrderedSource);
H
Haojun Liao 已提交
733 734 735 736
  if (pHandle->pBuf != NULL) {
    ASSERT(numOfSources <= getNumOfInMemBufPages(pHandle->pBuf));
  }

H
Haojun Liao 已提交
737 738 739 740
  if (numOfSources == 0) {
    return 0;
  }

741 742 743 744 745
  code = sortComparInit(&pHandle->cmpParam, pHandle->pOrderedSource, 0, numOfSources - 1, pHandle);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

746
  return tMergeTreeCreate(&pHandle->pMergeTree, pHandle->cmpParam.numOfSources, &pHandle->cmpParam, pHandle->comparFn);
747 748
}

H
Haojun Liao 已提交
749
int32_t tsortClose(SSortHandle* pHandle) {
750
  // do nothing
751
  return TSDB_CODE_SUCCESS;
752 753
}

H
Hongze Cheng 已提交
754 755
int32_t tsortSetFetchRawDataFp(SSortHandle* pHandle, _sort_fetch_block_fn_t fetchFp, void (*fp)(SSDataBlock*, void*),
                               void* param) {
756 757 758
  pHandle->fetchfp = fetchFp;
  pHandle->beforeFp = fp;
  pHandle->param = param;
759
  return TSDB_CODE_SUCCESS;
760 761
}

H
Haojun Liao 已提交
762
int32_t tsortSetComparFp(SSortHandle* pHandle, _sort_merge_compar_fn_t fp) {
763
  pHandle->comparFn = fp;
764
  return TSDB_CODE_SUCCESS;
765 766
}

767 768 769 770 771
int32_t tsortSetCompareGroupId(SSortHandle* pHandle, bool compareGroupId) {
  pHandle->cmpParam.cmpGroupId = compareGroupId;
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
772
STupleHandle* tsortNextTuple(SSortHandle* pHandle) {
773 774 775 776
  if (pHandle->cmpParam.numOfSources == pHandle->numOfCompletedSources) {
    return NULL;
  }

777
  // All the data are hold in the buffer, no external sort is invoked.
778 779 780 781 782 783 784 785 786 787
  if (pHandle->inMemSort) {
    pHandle->tupleHandle.rowIndex += 1;
    if (pHandle->tupleHandle.rowIndex == pHandle->pDataBlock->info.rows) {
      pHandle->numOfCompletedSources = 1;
      return NULL;
    }

    return &pHandle->tupleHandle;
  }

H
Hongze Cheng 已提交
788 789
  int32_t      index = tMergeTreeGetChosenIndex(pHandle->pMergeTree);
  SSortSource* pSource = pHandle->cmpParam.pSources[index];
790 791 792 793 794 795 796 797 798 799 800 801 802

  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;
  }

803
  // Get the adjusted value after the loser tree is updated.
804 805 806
  index = tMergeTreeGetChosenIndex(pHandle->pMergeTree);
  pSource = pHandle->cmpParam.pSources[index];

807
  ASSERT(pSource->src.pBlock != NULL);
808 809 810 811 812 813 814 815 816 817

  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 已提交
818
bool tsortIsNullVal(STupleHandle* pVHandle, int32_t colIndex) {
819
  SColumnInfoData* pColInfoSrc = taosArrayGet(pVHandle->pBlock->pDataBlock, colIndex);
820
  return colDataIsNull_s(pColInfoSrc, pVHandle->rowIndex);
821 822
}

H
Haojun Liao 已提交
823
void* tsortGetValue(STupleHandle* pVHandle, int32_t colIndex) {
824
  SColumnInfoData* pColInfo = TARRAY_GET_ELEM(pVHandle->pBlock->pDataBlock, colIndex);
825 826 827 828 829
  if (pColInfo->pData == NULL) {
    return NULL;
  } else {
    return colDataGetData(pColInfo, pVHandle->rowIndex);
  }
830
}
831

H
Hongze Cheng 已提交
832
uint64_t tsortGetGroupId(STupleHandle* pVHandle) { return pVHandle->pBlock->info.groupId; }
S
slzhou 已提交
833

834 835 836
SSortExecInfo tsortGetSortExecInfo(SSortHandle* pHandle) {
  SSortExecInfo info = {0};

837 838 839 840 841 842 843 844 845 846 847 848 849
  if (pHandle == NULL) {
    info.sortMethod = SORT_QSORT_T; // by default
    info.sortBuffer = 2 * 1048576;  // 2mb by default
  } else {
    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;
    }
850 851 852 853
  }

  return info;
}