tsort.c 27.5 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 38 39 40 41 42
  SArray*        pSortInfo;
  SArray*        pOrderedSource;
  int32_t        loops;
  uint64_t       sortElapsed;
  int64_t        startTs;
  uint64_t       totalElapsed;
43 44

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

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

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

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

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

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

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

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

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

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

  return pSortHandle;
}

99
static int32_t sortComparCleanup(SMsortComparParam* cmpParam) {
100
  // NOTICE: pSource may be, if it is SORT_MULTISOURCE_MERGE
H
Hongze Cheng 已提交
101
  for (int32_t i = 0; i < cmpParam->numOfSources; ++i) {
102
    SSortSource* pSource = cmpParam->pSources[i];
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;
}

111
void tsortClearOrderdSource(SArray* pOrderedSource, int64_t *fetchUs, int64_t *fetchNum) {
112 113 114 115 116
  for (size_t i = 0; i < taosArrayGetSize(pOrderedSource); i++) {
    SSortSource** pSource = taosArrayGet(pOrderedSource, i);
    if (NULL == *pSource) {
      continue;
    }
117 118 119 120 121 122

    if (fetchUs) {
      *fetchUs += (*pSource)->fetchUs;
      *fetchNum += (*pSource)->fetchNum;
    }
    
123 124 125 126
    // release pageIdList
    if ((*pSource)->pageIdList) {
      taosArrayDestroy((*pSource)->pageIdList);
    }
127
    if ((*pSource)->param && !(*pSource)->onlyRef) {
128
      taosMemoryFree((*pSource)->param);
129
    }
dengyihao's avatar
dengyihao 已提交
130 131

    if (!(*pSource)->onlyRef && (*pSource)->src.pBlock) {
dengyihao's avatar
dengyihao 已提交
132 133
      blockDataDestroy((*pSource)->src.pBlock);
      (*pSource)->src.pBlock = NULL;
dengyihao's avatar
dengyihao 已提交
134
    }
dengyihao's avatar
dengyihao 已提交
135

136 137 138 139 140 141
    taosMemoryFreeClear(*pSource);
  }

  taosArrayClear(pOrderedSource);
}

H
Haojun Liao 已提交
142
void tsortDestroySortHandle(SSortHandle* pSortHandle) {
143 144 145 146
  if (pSortHandle == NULL) {
    return;
  }

H
Haojun Liao 已提交
147
  tsortClose(pSortHandle);
148 149 150 151
  if (pSortHandle->pMergeTree != NULL) {
    tMergeTreeDestroy(pSortHandle->pMergeTree);
  }

H
Haojun Liao 已提交
152
  destroyDiskbasedBuf(pSortHandle->pBuf);
wafwerar's avatar
wafwerar 已提交
153
  taosMemoryFreeClear(pSortHandle->idStr);
wmmhello's avatar
wmmhello 已提交
154
  blockDataDestroy(pSortHandle->pDataBlock);
155

156 157 158 159
  int64_t fetchUs = 0, fetchNum = 0;
  tsortClearOrderdSource(pSortHandle->pOrderedSource, &fetchUs, &fetchNum);
  qError("all source fetch time: %" PRId64 "us num:%" PRId64 " %s", fetchUs, fetchNum, pSortHandle->idStr);
  
wmmhello's avatar
wmmhello 已提交
160
  taosArrayDestroy(pSortHandle->pOrderedSource);
wafwerar's avatar
wafwerar 已提交
161
  taosMemoryFreeClear(pSortHandle);
162 163
}

H
Haojun Liao 已提交
164
int32_t tsortAddSource(SSortHandle* pSortHandle, void* pSource) {
H
Haojun Liao 已提交
165
  taosArrayPush(pSortHandle->pOrderedSource, &pSource);
166
  return TSDB_CODE_SUCCESS;
167 168
}

H
Hongze Cheng 已提交
169 170
static int32_t doAddNewExternalMemSource(SDiskbasedBuf* pBuf, SArray* pAllSources, SSDataBlock* pBlock,
                                         int32_t* sourceId, SArray* pPageIdList) {
wmmhello's avatar
wmmhello 已提交
171
  SSortSource* pSource = taosMemoryCalloc(1, sizeof(SSortSource));
172
  if (pSource == NULL) {
H
Haojun Liao 已提交
173
    taosArrayDestroy(pPageIdList);
S
Shengliang Guan 已提交
174
    return TSDB_CODE_OUT_OF_MEMORY;
175 176 177
  }

  pSource->src.pBlock = pBlock;
178
  pSource->pageIdList = pPageIdList;
179 180 181 182 183
  taosArrayPush(pAllSources, &pSource);

  (*sourceId) += 1;

  int32_t rowSize = blockDataGetSerialRowSize(pSource->src.pBlock);
184 185

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

190 191 192 193 194 195 196
  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 已提交
197 198 199 200 201
    if (!osTempSpaceAvailable()) {
      terrno = TSDB_CODE_NO_AVAIL_DISK;
      qError("Add to buf failed since %s", terrstr(terrno));
      return terrno;
    }
202

H
Hongze Cheng 已提交
203
    int32_t code = createDiskbasedBuf(&pHandle->pBuf, pHandle->pageSize, pHandle->numOfPages * pHandle->pageSize,
204
                                      "sortExternalBuf", tsTempDir);
H
Haojun Liao 已提交
205
    dBufSetPrintInfo(pHandle->pBuf);
206 207 208 209 210
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

211
  SArray* pPageIdList = taosArrayInit(4, sizeof(int32_t));
H
Hongze Cheng 已提交
212
  while (start < pDataBlock->info.rows) {
213
    int32_t stop = 0;
214
    blockDataSplitRows(pDataBlock, pDataBlock->info.hasVarCol, start, &stop, pHandle->pageSize);
215 216
    SSDataBlock* p = blockDataExtractBlock(pDataBlock, start, stop - start + 1);
    if (p == NULL) {
H
Haojun Liao 已提交
217
      taosArrayDestroy(pPageIdList);
218 219 220 221
      return terrno;
    }

    int32_t pageId = -1;
H
Hongze Cheng 已提交
222
    void*   pPage = getNewBufPage(pHandle->pBuf, &pageId);
223
    if (pPage == NULL) {
H
Haojun Liao 已提交
224
      taosArrayDestroy(pPageIdList);
wmmhello's avatar
wmmhello 已提交
225
      blockDataDestroy(p);
226 227 228
      return terrno;
    }

229 230
    taosArrayPush(pPageIdList, &pageId);

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

234
    blockDataToBuf(pPage, p);
235 236 237 238 239 240 241 242

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

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

243
  blockDataCleanup(pDataBlock);
244

245
  SSDataBlock* pBlock = createOneDataBlock(pDataBlock, false);
246
  return doAddNewExternalMemSource(pHandle->pBuf, pHandle->pOrderedSource, pBlock, &pHandle->sourceId, pPageIdList);
247 248
}

249
static void setCurrentSourceDone(SSortSource* pSource, SSortHandle* pHandle) {
250 251 252 253
  pSource->src.rowIndex = -1;
  ++pHandle->numOfCompletedSources;
}

254
static int32_t sortComparInit(SMsortComparParam* pParam, SArray* pSources, int32_t startIndex, int32_t endIndex,
H
Hongze Cheng 已提交
255
                              SSortHandle* pHandle) {
256 257
  pParam->pSources = taosArrayGet(pSources, startIndex);
  pParam->numOfSources = (endIndex - startIndex + 1);
258 259 260

  int32_t code = 0;

H
Haojun Liao 已提交
261 262 263 264
  // multi-pass internal merge sort is required
  if (pHandle->pBuf == NULL) {
    if (!osTempSpaceAvailable()) {
      code = TSDB_CODE_NO_AVAIL_DISK;
D
dapan1121 已提交
265 266
      terrno = code;
      qError("Sort compare init failed since %s, %s", tstrerror(code), pHandle->idStr);
H
Haojun Liao 已提交
267 268 269 270 271 272 273
      return code;
    }

    code = createDiskbasedBuf(&pHandle->pBuf, pHandle->pageSize, pHandle->numOfPages * pHandle->pageSize,
                              "sortComparInit", tsTempDir);
    dBufSetPrintInfo(pHandle->pBuf);
    if (code != TSDB_CODE_SUCCESS) {
D
dapan1121 已提交
274
      terrno = code;
H
Haojun Liao 已提交
275 276 277 278
      return code;
    }
  }

H
Haojun Liao 已提交
279
  if (pHandle->type == SORT_SINGLESOURCE_SORT) {
280 281
    for (int32_t i = 0; i < pParam->numOfSources; ++i) {
      SSortSource* pSource = pParam->pSources[i];
282

283
      // set current source is done
284
      if (taosArrayGetSize(pSource->pageIdList) == 0) {
285
        setCurrentSourceDone(pSource, pHandle);
286
        continue;
287 288
      }

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

D
dapan1121 已提交
291
      void* pPage = getBufPage(pHandle->pBuf, *pPgId);
292 293 294 295
      if (NULL == pPage) {
        return terrno;
      }
      
296
      code = blockDataFromBuf(pSource->src.pBlock, pPage);
297
      if (code != TSDB_CODE_SUCCESS) {
D
dapan1121 已提交
298
        terrno = code;
299 300 301 302 303 304
        return code;
      }

      releaseBufPage(pHandle->pBuf, pPage);
    }
  } else {
305 306 307 308 309
    qDebug("start init for the multiway merge sort, %s", pHandle->idStr);
    int64_t st = taosGetTimestampUs();

    for (int32_t i = 0; i < pParam->numOfSources; ++i) {
      SSortSource* pSource = pParam->pSources[i];
310
      pSource->src.pBlock = pHandle->fetchfp(pSource->param);
311

312
      // set current source is done
313
      if (pSource->src.pBlock == NULL) {
314
        setCurrentSourceDone(pSource, pHandle);
315
      }
316
    }
317 318

    int64_t et = taosGetTimestampUs();
319
    qError("init for merge sort completed, elapsed time:%.2f ms, %s", (et - st) / 1000.0, pHandle->idStr);
320 321 322 323 324
  }

  return code;
}

H
Hongze Cheng 已提交
325
static void appendOneRowToDataBlock(SSDataBlock* pBlock, const SSDataBlock* pSource, int32_t* rowIndex) {
326
  for (int32_t i = 0; i < taosArrayGetSize(pBlock->pDataBlock); ++i) {
327 328 329
    SColumnInfoData* pColInfo = taosArrayGet(pBlock->pDataBlock, i);

    SColumnInfoData* pSrcColInfo = taosArrayGet(pSource->pDataBlock, i);
H
Hongze Cheng 已提交
330
    bool             isNull = colDataIsNull(pSrcColInfo, pSource->info.rows, *rowIndex, NULL);
331 332

    if (isNull) {
333
      colDataSetVal(pColInfo, pBlock->info.rows, NULL, true);
334
    } else {
335
      char* pData = colDataGetData(pSrcColInfo, *rowIndex);
336
      colDataSetVal(pColInfo, pBlock->info.rows, pData, false);
337 338 339 340 341 342 343
    }
  }

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

H
Hongze Cheng 已提交
344 345
static int32_t adjustMergeTreeForNextTuple(SSortSource* pSource, SMultiwayMergeTreeInfo* pTree, SSortHandle* pHandle,
                                           int32_t* numOfCompleted) {
346 347 348 349 350 351 352
  /*
   * 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;

353
    if (pHandle->type == SORT_SINGLESOURCE_SORT) {
H
Hongze Cheng 已提交
354
      pSource->pageIndex++;
355 356 357 358 359 360
      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 已提交
361
        int32_t* pPgId = taosArrayGet(pSource->pageIdList, pSource->pageIndex);
362

H
Hongze Cheng 已提交
363
        void*   pPage = getBufPage(pHandle->pBuf, *pPgId);
364 365 366 367 368
        if (pPage == NULL) {
          qError("failed to get buffer, code:%s", tstrerror(terrno));
          return terrno;
        }

H
Hongze Cheng 已提交
369
        int32_t code = blockDataFromBuf(pSource->src.pBlock, pPage);
370 371 372 373 374
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }

        releaseBufPage(pHandle->pBuf, pPage);
375 376
      }
    } else {
377
      int64_t st = taosGetTimestampUs();      
wmmhello's avatar
wmmhello 已提交
378
      pSource->src.pBlock = pHandle->fetchfp(((SSortSource*)pSource)->param);
379 380
      pSource->fetchUs += taosGetTimestampUs() - st;
      pSource->fetchNum++;
381 382 383
      if (pSource->src.pBlock == NULL) {
        (*numOfCompleted) += 1;
        pSource->src.rowIndex = -1;
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
      }
    }
  }

  /*
   * 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
405
  return TSDB_CODE_SUCCESS;
406 407
}

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

H
Hongze Cheng 已提交
411
  while (1) {
412 413 414 415 416 417
    if (cmpParam->numOfSources == pHandle->numOfCompletedSources) {
      break;
    }

    int32_t index = tMergeTreeGetChosenIndex(pHandle->pMergeTree);

H
Hongze Cheng 已提交
418
    SSortSource* pSource = (*cmpParam).pSources[index];
419 420 421 422 423 424 425 426 427 428 429 430 431
    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 已提交
432
  return (pHandle->pDataBlock->info.rows > 0) ? pHandle->pDataBlock : NULL;
433 434
}

H
Hongze Cheng 已提交
435 436 437
int32_t msortComparFn(const void* pLeft, const void* pRight, void* param) {
  int32_t pLeftIdx = *(int32_t*)pLeft;
  int32_t pRightIdx = *(int32_t*)pRight;
438

H
Hongze Cheng 已提交
439
  SMsortComparParam* pParam = (SMsortComparParam*)param;
440

H
Hongze Cheng 已提交
441
  SArray* pInfo = pParam->orderInfo;
442

H
Hongze Cheng 已提交
443
  SSortSource* pLeftSource = pParam->pSources[pLeftIdx];
wmmhello's avatar
wmmhello 已提交
444
  SSortSource* pRightSource = pParam->pSources[pRightIdx];
445 446 447 448 449 450 451 452 453 454 455 456 457

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

458
  if (pParam->cmpGroupId) {
H
Haojun Liao 已提交
459 460
    if (pLeftBlock->info.id.groupId != pRightBlock->info.id.groupId) {
      return pLeftBlock->info.id.groupId < pRightBlock->info.id.groupId ? -1 : 1;
461
    }
462 463
  }

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

H
Hongze Cheng 已提交
468
    bool leftNull = false;
469
    if (pLeftColInfoData->hasNull) {
470 471 472
      if (pLeftBlock->pBlockAgg == NULL) {
        leftNull = colDataIsNull_s(pLeftColInfoData, pLeftSource->src.rowIndex);
      } else {
H
Hongze Cheng 已提交
473 474
        leftNull =
            colDataIsNull(pLeftColInfoData, pLeftBlock->info.rows, pLeftSource->src.rowIndex, pLeftBlock->pBlockAgg[i]);
475
      }
476 477
    }

H
Haojun Liao 已提交
478
    SColumnInfoData* pRightColInfoData = TARRAY_GET_ELEM(pRightBlock->pDataBlock, pOrder->slotId);
H
Hongze Cheng 已提交
479
    bool             rightNull = false;
480
    if (pRightColInfoData->hasNull) {
H
Haojun Liao 已提交
481
      if (pRightBlock->pBlockAgg == NULL) {
482 483
        rightNull = colDataIsNull_s(pRightColInfoData, pRightSource->src.rowIndex);
      } else {
H
Hongze Cheng 已提交
484 485
        rightNull = colDataIsNull(pRightColInfoData, pRightBlock->info.rows, pRightSource->src.rowIndex,
                                  pRightBlock->pBlockAgg[i]);
486
      }
487 488 489
    }

    if (leftNull && rightNull) {
H
Hongze Cheng 已提交
490
      continue;  // continue to next slot
491 492 493
    }

    if (rightNull) {
H
Hongze Cheng 已提交
494
      return pOrder->nullFirst ? 1 : -1;
495 496 497
    }

    if (leftNull) {
H
Hongze Cheng 已提交
498
      return pOrder->nullFirst ? -1 : 1;
499 500
    }

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

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

506 507 508 509 510
    int ret = fn(left1, right1);
    if (ret == 0) {
      continue;
    } else {
      return ret;
511 512
    }
  }
513
  return 0;
514 515 516 517
}

static int32_t doInternalMergeSort(SSortHandle* pHandle) {
  size_t numOfSources = taosArrayGetSize(pHandle->pOrderedSource);
H
Haojun Liao 已提交
518 519 520
  if (numOfSources == 0) {
    return 0;
  }
521 522 523 524 525

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

  pHandle->totalElapsed = taosGetTimestampUs() - pHandle->startTs;
526 527 528 529 530 531 532

  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 已提交
533 534
    qDebug("%s ordered source:%" PRIzu ", available buf:%d, no need internal sort", pHandle->idStr, numOfSources,
           pHandle->numOfPages);
535
  }
536

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

540 541 542
  // the initial pass + sortPass + final mergePass
  pHandle->loops = sortPass + 2;

543
  size_t numOfSorted = taosArrayGetSize(pHandle->pOrderedSource);
H
Hongze Cheng 已提交
544
  for (int32_t t = 0; t < sortPass; ++t) {
545 546 547 548 549 550 551 552
    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 已提交
553
    for (int32_t i = 0; i < sortGroup; ++i) {
554 555 556 557 558 559 560 561 562 563 564
      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 已提交
565
        taosArrayDestroy(pResList);
566 567 568
        return code;
      }

H
Hongze Cheng 已提交
569 570
      code =
          tMergeTreeCreate(&pHandle->pMergeTree, pHandle->cmpParam.numOfSources, &pHandle->cmpParam, pHandle->comparFn);
571
      if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
572
        taosArrayDestroy(pResList);
573 574 575
        return code;
      }

576
      SArray* pPageIdList = taosArrayInit(4, sizeof(int32_t));
577
      while (1) {
wmmhello's avatar
wmmhello 已提交
578
        SSDataBlock* pDataBlock = getSortedBlockDataInner(pHandle, &pHandle->cmpParam, numOfRows);
579 580 581 582 583
        if (pDataBlock == NULL) {
          break;
        }

        int32_t pageId = -1;
H
Hongze Cheng 已提交
584
        void*   pPage = getNewBufPage(pHandle->pBuf, &pageId);
585
        if (pPage == NULL) {
H
Haojun Liao 已提交
586 587
          taosArrayDestroy(pResList);
          taosArrayDestroy(pPageIdList);
588 589 590
          return terrno;
        }

591 592
        taosArrayPush(pPageIdList, &pageId);

H
Hongze Cheng 已提交
593 594
        int32_t size =
            blockDataGetSize(pDataBlock) + sizeof(int32_t) + taosArrayGetSize(pDataBlock->pDataBlock) * sizeof(int32_t);
595 596
        assert(size <= getBufPageSize(pHandle->pBuf));

597
        blockDataToBuf(pPage, pDataBlock);
598 599 600 601

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

602
        blockDataCleanup(pDataBlock);
603 604
      }

605
      sortComparCleanup(&pHandle->cmpParam);
606 607 608
      tMergeTreeDestroy(pHandle->pMergeTree);
      pHandle->numOfCompletedSources = 0;

609
      SSDataBlock* pBlock = createOneDataBlock(pHandle->pDataBlock, false);
610
      code = doAddNewExternalMemSource(pHandle->pBuf, pResList, pBlock, &pHandle->sourceId, pPageIdList);
H
Haojun Liao 已提交
611 612
      if (code != TSDB_CODE_SUCCESS) {
        taosArrayDestroy(pResList);
613 614 615 616
        return code;
      }
    }

617
    tsortClearOrderdSource(pHandle->pOrderedSource, NULL, NULL);
618 619 620 621 622 623 624 625 626
    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 已提交
627 628
    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);
629

H
Haojun Liao 已提交
630 631
    if (pHandle->type == SORT_MULTISOURCE_MERGE) {
      pHandle->type = SORT_SINGLESOURCE_SORT;
632 633 634 635 636 637 638 639
      pHandle->comparFn = msortComparFn;
    }
  }

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

640 641 642 643 644
// 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;
645 646 647 648 649
  }

  return pgSize;
}

650
static int32_t createInitialSources(SSortHandle* pHandle) {
651
  size_t sortBufSize = pHandle->numOfPages * pHandle->pageSize;
652
  int32_t code = 0;
H
Haojun Liao 已提交
653 654

  if (pHandle->type == SORT_SINGLESOURCE_SORT) {
655
    SSortSource** pSource = taosArrayGet(pHandle->pOrderedSource, 0);
dengyihao's avatar
dengyihao 已提交
656
    SSortSource*  source = *pSource;
657
    *pSource = NULL;
dengyihao's avatar
dengyihao 已提交
658

659
    tsortClearOrderdSource(pHandle->pOrderedSource, NULL, NULL);
660

661
    while (1) {
662
      SSDataBlock* pBlock = pHandle->fetchfp(source->param);
663 664 665 666
      if (pBlock == NULL) {
        break;
      }

667
      if (pHandle->pDataBlock == NULL) {
668 669
        uint32_t numOfCols = taosArrayGetSize(pBlock->pDataBlock);
        pHandle->pageSize = getProperSortPageSize(blockDataGetRowSize(pBlock), numOfCols);
670 671

        // todo, number of pages are set according to the total available sort buffer
672 673
        pHandle->numOfPages = 1024;
        sortBufSize = pHandle->numOfPages * pHandle->pageSize;
674
        pHandle->pDataBlock = createOneDataBlock(pBlock, false);
675 676
      }

677 678 679
      if (pHandle->beforeFp != NULL) {
        pHandle->beforeFp(pBlock, pHandle->param);
      }
680

681 682
      code = blockDataMerge(pHandle->pDataBlock, pBlock);
      if (code != TSDB_CODE_SUCCESS) {
683 684 685
        if (source->param && !source->onlyRef) {
          taosMemoryFree(source->param);
        }
dengyihao's avatar
dengyihao 已提交
686 687 688 689
        if (!source->onlyRef && source->src.pBlock) {
          blockDataDestroy(source->src.pBlock);
          source->src.pBlock = NULL;
        }
690
        taosMemoryFree(source);
691 692
        return code;
      }
693

694 695 696 697
      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 已提交
698 699
        code = blockDataSort(pHandle->pDataBlock, pHandle->pSortInfo);
        if (code != 0) {
700 701 702
          if (source->param && !source->onlyRef) {
            taosMemoryFree(source->param);
          }
dengyihao's avatar
dengyihao 已提交
703 704 705 706
          if (!source->onlyRef && source->src.pBlock) {
            blockDataDestroy(source->src.pBlock);
            source->src.pBlock = NULL;
          }
707

708
          taosMemoryFree(source);
wmmhello's avatar
wmmhello 已提交
709 710
          return code;
        }
711

712 713
        int64_t el = taosGetTimestampUs() - p;
        pHandle->sortElapsed += el;
714

715 716 717 718
        code = doAddToBuf(pHandle->pDataBlock, pHandle);
        if (code != TSDB_CODE_SUCCESS) {
          return code;
        }
719 720 721
      }
    }

722 723 724
    if (source->param && !source->onlyRef) {
      taosMemoryFree(source->param);
    }
725

726 727
    taosMemoryFree(source);

728
    if (pHandle->pDataBlock != NULL && pHandle->pDataBlock->info.rows > 0) {
729 730 731
      size_t size = blockDataGetSize(pHandle->pDataBlock);

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

734
      code = blockDataSort(pHandle->pDataBlock, pHandle->pSortInfo);
wmmhello's avatar
wmmhello 已提交
735 736 737
      if (code != 0) {
        return code;
      }
738

739 740 741
      int64_t el = taosGetTimestampUs() - p;
      pHandle->sortElapsed += el;

742
      // All sorted data can fit in memory, external memory sort is not needed. Return to directly
743
      if (size <= sortBufSize && pHandle->pBuf == NULL) {
744 745 746
        pHandle->cmpParam.numOfSources = 1;
        pHandle->inMemSort = true;

747
        pHandle->loops = 1;
H
Hongze Cheng 已提交
748
        pHandle->tupleHandle.rowIndex = -1;
749 750 751
        pHandle->tupleHandle.pBlock = pHandle->pDataBlock;
        return 0;
      } else {
752
        code = doAddToBuf(pHandle->pDataBlock, pHandle);
753 754
      }
    }
H
Haojun Liao 已提交
755 756
  }

757
  return code;
H
Haojun Liao 已提交
758 759
}

H
Haojun Liao 已提交
760
int32_t tsortOpen(SSortHandle* pHandle) {
H
Haojun Liao 已提交
761 762 763 764 765 766 767 768 769 770
  if (pHandle->opened) {
    return 0;
  }

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

  pHandle->opened = true;

771
  int32_t code = createInitialSources(pHandle);
H
Haojun Liao 已提交
772 773
  if (code != TSDB_CODE_SUCCESS) {
    return code;
774 775 776
  }

  // do internal sort
H
Haojun Liao 已提交
777
  code = doInternalMergeSort(pHandle);
778 779 780 781 782
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

  int32_t numOfSources = taosArrayGetSize(pHandle->pOrderedSource);
H
Haojun Liao 已提交
783 784 785 786
  if (pHandle->pBuf != NULL) {
    ASSERT(numOfSources <= getNumOfInMemBufPages(pHandle->pBuf));
  }

H
Haojun Liao 已提交
787 788 789 790
  if (numOfSources == 0) {
    return 0;
  }

791 792 793 794 795
  code = sortComparInit(&pHandle->cmpParam, pHandle->pOrderedSource, 0, numOfSources - 1, pHandle);
  if (code != TSDB_CODE_SUCCESS) {
    return code;
  }

796
  return tMergeTreeCreate(&pHandle->pMergeTree, pHandle->cmpParam.numOfSources, &pHandle->cmpParam, pHandle->comparFn);
797 798
}

H
Haojun Liao 已提交
799
int32_t tsortClose(SSortHandle* pHandle) {
800
  // do nothing
801
  return TSDB_CODE_SUCCESS;
802 803
}

H
Hongze Cheng 已提交
804 805
int32_t tsortSetFetchRawDataFp(SSortHandle* pHandle, _sort_fetch_block_fn_t fetchFp, void (*fp)(SSDataBlock*, void*),
                               void* param) {
806 807 808
  pHandle->fetchfp = fetchFp;
  pHandle->beforeFp = fp;
  pHandle->param = param;
809
  return TSDB_CODE_SUCCESS;
810 811
}

H
Haojun Liao 已提交
812
int32_t tsortSetComparFp(SSortHandle* pHandle, _sort_merge_compar_fn_t fp) {
813
  pHandle->comparFn = fp;
814
  return TSDB_CODE_SUCCESS;
815 816
}

817 818 819 820 821
int32_t tsortSetCompareGroupId(SSortHandle* pHandle, bool compareGroupId) {
  pHandle->cmpParam.cmpGroupId = compareGroupId;
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
822
STupleHandle* tsortNextTuple(SSortHandle* pHandle) {
823 824 825 826
  if (pHandle->cmpParam.numOfSources == pHandle->numOfCompletedSources) {
    return NULL;
  }

827
  // All the data are hold in the buffer, no external sort is invoked.
828 829 830 831 832 833 834 835 836 837
  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 已提交
838 839
  int32_t      index = tMergeTreeGetChosenIndex(pHandle->pMergeTree);
  SSortSource* pSource = pHandle->cmpParam.pSources[index];
840 841 842 843 844 845 846 847 848

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

H
Haojun Liao 已提交
849
  // all sources are completed.
850 851 852 853
  if (pHandle->cmpParam.numOfSources == pHandle->numOfCompletedSources) {
    return NULL;
  }

854
  // Get the adjusted value after the loser tree is updated.
855 856 857
  index = tMergeTreeGetChosenIndex(pHandle->pMergeTree);
  pSource = pHandle->cmpParam.pSources[index];

858
  ASSERT(pSource->src.pBlock != NULL);
859 860 861 862 863 864 865 866 867 868

  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 已提交
869
bool tsortIsNullVal(STupleHandle* pVHandle, int32_t colIndex) {
870
  SColumnInfoData* pColInfoSrc = taosArrayGet(pVHandle->pBlock->pDataBlock, colIndex);
871
  return colDataIsNull_s(pColInfoSrc, pVHandle->rowIndex);
872 873
}

H
Haojun Liao 已提交
874
void* tsortGetValue(STupleHandle* pVHandle, int32_t colIndex) {
875
  SColumnInfoData* pColInfo = TARRAY_GET_ELEM(pVHandle->pBlock->pDataBlock, colIndex);
876 877 878 879 880
  if (pColInfo->pData == NULL) {
    return NULL;
  } else {
    return colDataGetData(pColInfo, pVHandle->rowIndex);
  }
881
}
882

H
Haojun Liao 已提交
883
uint64_t tsortGetGroupId(STupleHandle* pVHandle) { return pVHandle->pBlock->info.id.groupId; }
S
slzhou 已提交
884

885 886 887
SSortExecInfo tsortGetSortExecInfo(SSortHandle* pHandle) {
  SSortExecInfo info = {0};

888
  if (pHandle == NULL) {
dengyihao's avatar
dengyihao 已提交
889 890
    info.sortMethod = SORT_QSORT_T;  // by default
    info.sortBuffer = 2 * 1048576;   // 2mb by default
891 892 893 894 895 896 897 898 899 900
  } 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;
    }
901 902 903 904
  }

  return info;
}