joinoperator.c 25.7 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/>.
 */

16
#include "executorInt.h"
17
#include "filter.h"
18
#include "function.h"
19
#include "operator.h"
20 21
#include "os.h"
#include "querynodes.h"
22
#include "querytask.h"
23
#include "tcompare.h"
24
#include "tdatablock.h"
25
#include "thash.h"
26
#include "tmsg.h"
27 28
#include "ttypes.h"

29 30 31 32 33 34 35 36
typedef struct SJoinRowCtx {
  bool    rowRemains;
  int64_t ts;
  SArray* leftRowLocations;
  SArray* leftCreatedBlocks;
  SArray* rightCreatedBlocks;
  int32_t leftRowIdx;
  int32_t rightRowIdx;
37

38
  bool    rightUseBuildTable;
39
  SArray* rightRowLocations;
40 41
} SJoinRowCtx;

H
Haojun Liao 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54
typedef struct SJoinOperatorInfo {
  SSDataBlock* pRes;
  int32_t      joinType;
  int32_t      inputOrder;

  SSDataBlock* pLeft;
  int32_t      leftPos;
  SColumnInfo  leftCol;

  SSDataBlock* pRight;
  int32_t      rightPos;
  SColumnInfo  rightCol;
  SNode*       pCondAfterMerge;
S
shenglian zhou 已提交
55 56 57 58 59 60 61 62 63
  SNode*       pTagEqualConditions;

  SArray*      leftTagCols;
  char*        leftTagKeyBuf;
  int32_t      leftTagKeyLen;

  SArray*      rightTagCols;
  char*        rightTagKeyBuf;
  int32_t      rightTagKeyLen;
64

65
  SSHashObj*   rightBuildTable;
66
  SJoinRowCtx  rowCtx;
H
Haojun Liao 已提交
67 68
} SJoinOperatorInfo;

69
static void         setJoinColumnInfo(SColumnInfo* pColumn, const SColumnNode* pColumnNode);
70
static SSDataBlock* doMergeJoin(struct SOperatorInfo* pOperator);
71
static void         destroyMergeJoinOperator(void* param);
H
Haojun Liao 已提交
72 73
static void         extractTimeCondition(SJoinOperatorInfo* pInfo, SOperatorInfo** pDownstream, int32_t num,
                                         SSortMergeJoinPhysiNode* pJoinNode, const char* idStr);
74

H
Haojun Liao 已提交
75 76
static void extractTimeCondition(SJoinOperatorInfo* pInfo, SOperatorInfo** pDownstream,  int32_t num,
                                 SSortMergeJoinPhysiNode* pJoinNode, const char* idStr) {
77
  SNode* pMergeCondition = pJoinNode->pMergeCondition;
H
Haojun Liao 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
  if (nodeType(pMergeCondition) != QUERY_NODE_OPERATOR) {
    qError("not support this in join operator, %s", idStr);
    return;  // do not handle this
  }

  SOperatorNode* pNode = (SOperatorNode*)pMergeCondition;
  SColumnNode*   col1 = (SColumnNode*)pNode->pLeft;
  SColumnNode*   col2 = (SColumnNode*)pNode->pRight;
  SColumnNode*   leftTsCol = NULL;
  SColumnNode*   rightTsCol = NULL;
  if (col1->dataBlockId == col2->dataBlockId) {
    leftTsCol = col1;
    rightTsCol = col2;
  } else {
    if (col1->dataBlockId == pDownstream[0]->resultDataBlockId) {
      ASSERT(col2->dataBlockId == pDownstream[1]->resultDataBlockId);
94 95 96
      leftTsCol = col1;
      rightTsCol = col2;
    } else {
H
Haojun Liao 已提交
97 98 99 100
      ASSERT(col1->dataBlockId == pDownstream[1]->resultDataBlockId);
      ASSERT(col2->dataBlockId == pDownstream[0]->resultDataBlockId);
      leftTsCol = col2;
      rightTsCol = col1;
101
    }
H
Haojun Liao 已提交
102 103 104 105
  }
  setJoinColumnInfo(&pInfo->leftCol, leftTsCol);
  setJoinColumnInfo(&pInfo->rightCol, rightTsCol);
}
106

S
shenglian zhou 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
static void extractTagEqualColsFromOper(SJoinOperatorInfo* pInfo, SOperatorInfo** pDownstreams, SOperatorNode* pOperNode,
                                       SColumn* pLeft, SColumn* pRight) {
  SColumnNode* pLeftNode = (SColumnNode*)pOperNode->pLeft;
  SColumnNode* pRightNode = (SColumnNode*)pOperNode->pRight;
  if (pLeftNode->dataBlockId == pRightNode->dataBlockId || pLeftNode->dataBlockId == pDownstreams[0]->resultDataBlockId) {
    *pLeft = extractColumnFromColumnNode((SColumnNode*)pOperNode->pLeft);
    *pRight = extractColumnFromColumnNode((SColumnNode*)pOperNode->pRight);
  } else {
    *pLeft = extractColumnFromColumnNode((SColumnNode*)pOperNode->pRight);
    *pRight = extractColumnFromColumnNode((SColumnNode*)pOperNode->pLeft);
  }
}

static void extractTagEqualCondCols(SJoinOperatorInfo* pInfo, SOperatorInfo** pDownStream, SNode* pTagEqualNode,
                                    SArray* leftTagEqCols, SArray* rightTagEqCols) {
  SColumn left = {0};
  SColumn right = {0};
  if (nodeType(pTagEqualNode) == QUERY_NODE_LOGIC_CONDITION && ((SLogicConditionNode*)pTagEqualNode)->condType == LOGIC_COND_TYPE_AND) {
    SNode* pNode = NULL;
    FOREACH(pNode, ((SLogicConditionNode*)pTagEqualNode)->pParameterList) {
      SOperatorNode* pOperNode = (SOperatorNode*)pNode;
      extractTagEqualColsFromOper(pInfo, pDownStream, pOperNode, &left, &right);
      taosArrayPush(leftTagEqCols, &left);
      taosArrayPush(rightTagEqCols, &right);
    }
    return;
  }

  if (nodeType(pTagEqualNode) == QUERY_NODE_OPERATOR) {
    SOperatorNode* pOperNode = (SOperatorNode*)pTagEqualNode;
    extractTagEqualColsFromOper(pInfo, pDownStream, pOperNode, &left, &right);
    taosArrayPush(leftTagEqCols, &left);
    taosArrayPush(rightTagEqCols, &right);
  }
}

143
static int32_t initTagColskeyBuf(int32_t* keyLen, char** keyBuf, const SArray* pGroupColList) {
S
shenglian zhou 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
  int32_t numOfGroupCols = taosArrayGetSize(pGroupColList);
  for (int32_t i = 0; i < numOfGroupCols; ++i) {
    SColumn* pCol = (SColumn*)taosArrayGet(pGroupColList, i);
    (*keyLen) += pCol->bytes;  // actual data + null_flag
  }

  int32_t nullFlagSize = sizeof(int8_t) * numOfGroupCols;
  (*keyLen) += nullFlagSize;

  (*keyBuf) = taosMemoryCalloc(1, (*keyLen));
  if ((*keyBuf) == NULL) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  return TSDB_CODE_SUCCESS;
}

161
static int32_t fillKeyBufFromTagCols(SArray* pCols, SSDataBlock* pBlock, int32_t rowIndex, void* pKey) {
S
shenglian zhou 已提交
162 163
  SColumnDataAgg* pColAgg = NULL;
  size_t numOfGroupCols = taosArrayGetSize(pCols);
164 165
  char* isNull = (char*)pKey;
  char* pStart = (char*)pKey + sizeof(int8_t) * numOfGroupCols;
S
shenglian zhou 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180

  for (int32_t i = 0; i < numOfGroupCols; ++i) {
    SColumn*         pCol = (SColumn*) taosArrayGet(pCols, i);
    SColumnInfoData* pColInfoData = taosArrayGet(pBlock->pDataBlock, pCol->slotId);

    // valid range check. todo: return error code.
    if (pCol->slotId > taosArrayGetSize(pBlock->pDataBlock)) {
      continue;
    }

    if (pBlock->pBlockAgg != NULL) {
      pColAgg = pBlock->pBlockAgg[pCol->slotId];  // TODO is agg data matched?
    }

    if (colDataIsNull(pColInfoData, pBlock->info.rows, rowIndex, pColAgg)) {
181
      isNull[i] = 1;
S
shenglian zhou 已提交
182
    } else {
183
      isNull[i] = 0;
S
shenglian zhou 已提交
184
      char* val = colDataGetData(pColInfoData, rowIndex);
185
      if (pCol->type == TSDB_DATA_TYPE_JSON) {
S
shenglian zhou 已提交
186
        int32_t dataLen = getJsonValueLen(val);
187 188 189 190 191
        memcpy(pStart, val, dataLen);
        pStart += dataLen;
      } else if (IS_VAR_DATA_TYPE(pCol->type)) {
        varDataCopy(pStart, val);
        pStart += varDataTLen(val);
S
shenglian zhou 已提交
192
      } else {
193 194
        memcpy(pStart, val, pCol->bytes);
        pStart += pCol->bytes;
S
shenglian zhou 已提交
195 196 197 198 199 200
      }
    }
  }
  return (int32_t)(pStart - (char*)pKey);
}

201 202
SOperatorInfo* createMergeJoinOperatorInfo(SOperatorInfo** pDownstream, int32_t numOfDownstream,
                                           SSortMergeJoinPhysiNode* pJoinNode, SExecTaskInfo* pTaskInfo) {
203 204
  SJoinOperatorInfo* pInfo = taosMemoryCalloc(1, sizeof(SJoinOperatorInfo));
  SOperatorInfo*     pOperator = taosMemoryCalloc(1, sizeof(SOperatorInfo));
H
Haojun Liao 已提交
205 206

  int32_t code = TSDB_CODE_SUCCESS;
207
  if (pOperator == NULL || pInfo == NULL) {
H
Haojun Liao 已提交
208
    code = TSDB_CODE_OUT_OF_MEMORY;
209 210 211
    goto _error;
  }

H
Haojun Liao 已提交
212
  int32_t      numOfCols = 0;
H
Haojun Liao 已提交
213 214
  pInfo->pRes = createDataBlockFromDescNode(pJoinNode->node.pOutputDataBlockDesc);

H
Haojun Liao 已提交
215
  SExprInfo*   pExprInfo = createExprInfo(pJoinNode->pTargets, NULL, &numOfCols);
216
  initResultSizeInfo(&pOperator->resultInfo, 4096);
H
Haojun Liao 已提交
217
  blockDataEnsureCapacity(pInfo->pRes, pOperator->resultInfo.capacity);
H
Haojun Liao 已提交
218 219

  setOperatorInfo(pOperator, "MergeJoinOperator", QUERY_NODE_PHYSICAL_PLAN_MERGE_JOIN, false, OP_NOT_OPENED, pInfo, pTaskInfo);
220 221
  pOperator->exprSupp.pExprInfo = pExprInfo;
  pOperator->exprSupp.numOfExprs = numOfCols;
222

H
Haojun Liao 已提交
223
  extractTimeCondition(pInfo, pDownstream, numOfDownstream, pJoinNode, GET_TASKID(pTaskInfo));
224

225 226
  if (pJoinNode->pOnConditions != NULL && pJoinNode->node.pConditions != NULL) {
    pInfo->pCondAfterMerge = nodesMakeNode(QUERY_NODE_LOGIC_CONDITION);
H
Haojun Liao 已提交
227 228 229 230 231
    if (pInfo->pCondAfterMerge == NULL) {
      code = TSDB_CODE_OUT_OF_MEMORY;
      goto _error;
    }

232 233
    SLogicConditionNode* pLogicCond = (SLogicConditionNode*)(pInfo->pCondAfterMerge);
    pLogicCond->pParameterList = nodesMakeList();
H
Haojun Liao 已提交
234 235 236 237 238
    if (pLogicCond->pParameterList == NULL) {
      code = TSDB_CODE_OUT_OF_MEMORY;
      goto _error;
    }

239 240 241 242 243 244 245 246 247
    nodesListMakeAppend(&pLogicCond->pParameterList, nodesCloneNode(pJoinNode->pOnConditions));
    nodesListMakeAppend(&pLogicCond->pParameterList, nodesCloneNode(pJoinNode->node.pConditions));
    pLogicCond->condType = LOGIC_COND_TYPE_AND;
  } else if (pJoinNode->pOnConditions != NULL) {
    pInfo->pCondAfterMerge = nodesCloneNode(pJoinNode->pOnConditions);
  } else if (pJoinNode->node.pConditions != NULL) {
    pInfo->pCondAfterMerge = nodesCloneNode(pJoinNode->node.pConditions);
  } else {
    pInfo->pCondAfterMerge = NULL;
248 249
  }

H
Haojun Liao 已提交
250 251 252 253 254
  code = filterInitFromNode(pInfo->pCondAfterMerge, &pOperator->exprSupp.pFilterInfo, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

255
  pInfo->inputOrder = TSDB_ORDER_ASC;
256
  if (pJoinNode->inputTsOrder == ORDER_ASC) {
257
    pInfo->inputOrder = TSDB_ORDER_ASC;
258
  } else if (pJoinNode->inputTsOrder == ORDER_DESC) {
259
    pInfo->inputOrder = TSDB_ORDER_DESC;
260 261
  }

S
shenglian zhou 已提交
262
  pInfo->pTagEqualConditions = pJoinNode->pTagEqualCondtions;
263 264 265 266
  if (pInfo->pTagEqualConditions != NULL) {
    pInfo->leftTagCols = taosArrayInit(4, sizeof(SColumn));
    pInfo->rightTagCols = taosArrayInit(4, sizeof(SColumn));
    extractTagEqualCondCols(pInfo, pDownstream, pInfo->pTagEqualConditions, pInfo->leftTagCols, pInfo->rightTagCols);
267 268
    initTagColskeyBuf(&pInfo->leftTagKeyLen, &pInfo->leftTagKeyBuf, pInfo->leftTagCols);
    initTagColskeyBuf(&pInfo->rightTagKeyLen, &pInfo->rightTagKeyBuf, pInfo->rightTagCols);
269 270
    _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);
    pInfo->rightBuildTable = tSimpleHashInit(256,  hashFn);
271
  }
272
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, doMergeJoin, NULL, destroyMergeJoinOperator, optrDefaultBufFn, NULL);
H
Haojun Liao 已提交
273
  code = appendDownstream(pOperator, pDownstream, numOfDownstream);
274 275 276 277 278 279
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

  return pOperator;

280
_error:
H
Haojun Liao 已提交
281 282 283 284
  if (pInfo != NULL) {
    destroyMergeJoinOperator(pInfo);
  }

285
  taosMemoryFree(pOperator);
H
Haojun Liao 已提交
286
  pTaskInfo->code = code;
287 288 289 290 291 292 293 294 295 296 297
  return NULL;
}

void setJoinColumnInfo(SColumnInfo* pColumn, const SColumnNode* pColumnNode) {
  pColumn->slotId = pColumnNode->slotId;
  pColumn->type = pColumnNode->node.resType.type;
  pColumn->bytes = pColumnNode->node.resType.bytes;
  pColumn->precision = pColumnNode->node.resType.precision;
  pColumn->scale = pColumnNode->node.resType.scale;
}

298 299 300 301 302 303 304 305 306 307 308 309
static void mergeJoinDestoryBuildTable(SSHashObj* pBuildTable) {
  void* p = NULL;
  int32_t iter = 0;

  while ((p = tSimpleHashIterate(pBuildTable, p, &iter)) != NULL) {
    SArray* rows = (*(SArray**)p);
    taosArrayDestroy(rows);
  }

  tSimpleHashCleanup(pBuildTable);
}

310
void destroyMergeJoinOperator(void* param) {
311
  SJoinOperatorInfo* pJoinOperator = (SJoinOperatorInfo*)param;
312
  if (pJoinOperator->pTagEqualConditions != NULL) {
313
    mergeJoinDestoryBuildTable(pJoinOperator->rightBuildTable);
314 315
    taosMemoryFreeClear(pJoinOperator->rightTagKeyBuf);
    taosArrayDestroy(pJoinOperator->rightTagCols);
S
shenglian zhou 已提交
316

317 318 319
    taosMemoryFreeClear(pJoinOperator->leftTagKeyBuf);
    taosArrayDestroy(pJoinOperator->leftTagCols);
  }
320
  nodesDestroyNode(pJoinOperator->pCondAfterMerge);
321

S
shenglian zhou 已提交
322
  pJoinOperator->pRes = blockDataDestroy(pJoinOperator->pRes);
D
dapan1121 已提交
323
  taosMemoryFreeClear(param);
324
}
325 326

static void mergeJoinJoinLeftRight(struct SOperatorInfo* pOperator, SSDataBlock* pRes, int32_t currRow,
327 328
                                   SSDataBlock* pLeftBlock, int32_t leftPos, SSDataBlock* pRightBlock,
                                   int32_t rightPos) {
329 330 331 332 333 334 335 336 337 338 339 340
  SJoinOperatorInfo* pJoinInfo = pOperator->info;

  for (int32_t i = 0; i < pOperator->exprSupp.numOfExprs; ++i) {
    SColumnInfoData* pDst = taosArrayGet(pRes->pDataBlock, i);

    SExprInfo* pExprInfo = &pOperator->exprSupp.pExprInfo[i];

    int32_t blockId = pExprInfo->base.pParam[0].pCol->dataBlockId;
    int32_t slotId = pExprInfo->base.pParam[0].pCol->slotId;
    int32_t rowIndex = -1;

    SColumnInfoData* pSrc = NULL;
H
Haojun Liao 已提交
341
    if (pLeftBlock->info.id.blockId == blockId) {
342 343
      pSrc = taosArrayGet(pLeftBlock->pDataBlock, slotId);
      rowIndex = leftPos;
344
    } else {
345 346
      pSrc = taosArrayGet(pRightBlock->pDataBlock, slotId);
      rowIndex = rightPos;
347
    }
348

349
    if (colDataIsNull_s(pSrc, rowIndex)) {
350
      colDataSetNULL(pDst, currRow);
351 352
    } else {
      char* p = colDataGetData(pSrc, rowIndex);
353
      colDataSetVal(pDst, currRow, p, false);
354 355 356
    }
  }
}
357
typedef struct SRowLocation {
358 359
  SSDataBlock* pDataBlock;
  int32_t      pos;
360 361
} SRowLocation;

362
// pBlock[tsSlotId][startPos, endPos) == timestamp,
S
shenglian zhou 已提交
363
static int32_t mergeJoinGetBlockRowsEqualTs(SSDataBlock* pBlock, int16_t tsSlotId, int32_t startPos, int64_t timestamp,
364
                                            int32_t* pEndPos, SArray* rowLocations, SArray* createdBlocks) {
365 366
  int32_t numRows = pBlock->info.rows;
  ASSERT(startPos < numRows);
S
shenglian zhou 已提交
367
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, tsSlotId);
368 369

  int32_t i = startPos;
370
  for (; i < numRows; ++i) {
371
    char* pNextVal = colDataGetData(pCol, i);
372
    if (timestamp != *(int64_t*)pNextVal) {
373 374 375 376
      break;
    }
  }
  int32_t endPos = i;
S
shenglian zhou 已提交
377
  *pEndPos = endPos;
378

379 380 381 382
  if (endPos - startPos == 0) {
    return 0;
  }

383
  SSDataBlock* block = pBlock;
S
slzhou 已提交
384
  bool         createdNewBlock = false;
S
shenglian zhou 已提交
385
  if (endPos == numRows) {
S
slzhou 已提交
386
    block = blockDataExtractBlock(pBlock, startPos, endPos - startPos);
S
shenglian zhou 已提交
387
    taosArrayPush(createdBlocks, &block);
388
    createdNewBlock = true;
389
  }
390
  SRowLocation location = {0};
391 392
  for (int32_t j = startPos; j < endPos; ++j) {
    location.pDataBlock = block;
S
slzhou 已提交
393
    location.pos = (createdNewBlock ? j - startPos : j);
394
    taosArrayPush(rowLocations, &location);
395 396 397
  }
  return 0;
}
398

399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
// whichChild == 0, left child of join; whichChild ==1, right child of join
static int32_t mergeJoinGetDownStreamRowsEqualTimeStamp(SOperatorInfo* pOperator, int32_t whichChild, int16_t tsSlotId,
                                                        SSDataBlock* startDataBlock, int32_t startPos,
                                                        int64_t timestamp, SArray* rowLocations,
                                                        SArray* createdBlocks) {
  ASSERT(whichChild == 0 || whichChild == 1);

  SJoinOperatorInfo* pJoinInfo = pOperator->info;
  int32_t            endPos = -1;
  SSDataBlock*       dataBlock = startDataBlock;
  mergeJoinGetBlockRowsEqualTs(dataBlock, tsSlotId, startPos, timestamp, &endPos, rowLocations, createdBlocks);
  while (endPos == dataBlock->info.rows) {
    SOperatorInfo* ds = pOperator->pDownstream[whichChild];
    dataBlock = ds->fpSet.getNextFn(ds);
    if (whichChild == 0) {
      pJoinInfo->leftPos = 0;
      pJoinInfo->pLeft = dataBlock;
    } else if (whichChild == 1) {
      pJoinInfo->rightPos = 0;
      pJoinInfo->pRight = dataBlock;
    }

    if (dataBlock == NULL) {
      setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
      endPos = -1;
      break;
    }
426

427 428 429 430 431 432 433 434 435
    mergeJoinGetBlockRowsEqualTs(dataBlock, tsSlotId, 0, timestamp, &endPos, rowLocations, createdBlocks);
  }
  if (endPos != -1) {
    if (whichChild == 0) {
      pJoinInfo->leftPos = endPos;
    } else if (whichChild == 1) {
      pJoinInfo->rightPos = endPos;
    }
  }
436 437 438
  return 0;
}

439
static int32_t mergeJoinFillBuildTable(SJoinOperatorInfo* pInfo, SArray* rightRowLocations,SSHashObj* buildTable) {
S
shenglian zhou 已提交
440 441
  for (int32_t i = 0; i < taosArrayGetSize(rightRowLocations); ++i) {
    SRowLocation* rightRow = taosArrayGet(rightRowLocations, i);
442
    int32_t keyLen = fillKeyBufFromTagCols(pInfo->rightTagCols, rightRow->pDataBlock, rightRow->pos, pInfo->rightTagKeyBuf);
S
shenglian zhou 已提交
443 444 445 446 447 448 449 450 451 452 453 454 455 456
    SArray** ppRows = tSimpleHashGet(buildTable, pInfo->rightTagKeyBuf, keyLen);
    if (!ppRows) {
      SArray* rows = taosArrayInit(4, sizeof(SRowLocation));
      taosArrayPush(rows, rightRow);
      tSimpleHashPut(buildTable, pInfo->rightTagKeyBuf, keyLen, &rows, POINTER_BYTES);
    } else {
      taosArrayPush(*ppRows, rightRow);
    }
  }
  return TSDB_CODE_SUCCESS;
}

static int32_t mergeJoinLeftRowsRightRows(SOperatorInfo* pOperator, SSDataBlock* pRes, int32_t* nRows,
                                         const SArray* leftRowLocations, int32_t leftRowIdx,
457
                                       int32_t rightRowIdx, bool useBuildTableTSRange, SArray* rightRowLocations, bool* pReachThreshold) {
S
shenglian zhou 已提交
458 459 460 461 462 463 464 465 466
  *pReachThreshold = false;
  uint32_t limitRowNum = pOperator->resultInfo.threshold;
  SJoinOperatorInfo* pJoinInfo = pOperator->info;
  size_t leftNumJoin = taosArrayGetSize(leftRowLocations);

  int32_t i,j;

  for (i = leftRowIdx; i < leftNumJoin; ++i, rightRowIdx = 0) {
    SRowLocation* leftRow = taosArrayGet(leftRowLocations, i);
467
    SArray* pRightRows = NULL;
468
    if (useBuildTableTSRange) {
469
      int32_t  keyLen = fillKeyBufFromTagCols(pJoinInfo->leftTagCols, leftRow->pDataBlock, leftRow->pos, pJoinInfo->leftTagKeyBuf);
470
      SArray** ppRightRows = tSimpleHashGet(pJoinInfo->rightBuildTable, pJoinInfo->leftTagKeyBuf, keyLen);
471 472 473 474 475 476
      if (!ppRightRows) {
        continue;
      }
      pRightRows = *ppRightRows;
    } else {
      pRightRows = rightRowLocations;
S
shenglian zhou 已提交
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
    }
    size_t rightRowsSize = taosArrayGetSize(pRightRows);
    for (j = rightRowIdx; j < rightRowsSize; ++j) {
      if (*nRows >= limitRowNum) {
        *pReachThreshold = true;
        break;
      }

      SRowLocation* rightRow = taosArrayGet(pRightRows, j);
      mergeJoinJoinLeftRight(pOperator, pRes, *nRows, leftRow->pDataBlock, leftRow->pos, rightRow->pDataBlock,
                             rightRow->pos);
      ++*nRows;
    }
    if (*pReachThreshold) {
      break;
    }
  }

  if (*pReachThreshold) {
    pJoinInfo->rowCtx.rowRemains = true;
    pJoinInfo->rowCtx.leftRowIdx = i;
    pJoinInfo->rowCtx.rightRowIdx = j;
  }
  return TSDB_CODE_SUCCESS;
}

static void mergeJoinDestroyTSRangeCtx(SJoinOperatorInfo* pJoinInfo, SArray* leftRowLocations, SArray* leftCreatedBlocks,
504
                                       SArray* rightCreatedBlocks, bool rightUseBuildTable, SArray* rightRowLocations) {
S
shenglian zhou 已提交
505 506 507 508 509 510 511 512 513
  for (int i = 0; i < taosArrayGetSize(rightCreatedBlocks); ++i) {
    SSDataBlock* pBlock = taosArrayGetP(rightCreatedBlocks, i);
    blockDataDestroy(pBlock);
  }
  taosArrayDestroy(rightCreatedBlocks);
  for (int i = 0; i < taosArrayGetSize(leftCreatedBlocks); ++i) {
    SSDataBlock* pBlock = taosArrayGetP(leftCreatedBlocks, i);
    blockDataDestroy(pBlock);
  }
514 515 516
  if (rightRowLocations != NULL) {
    taosArrayDestroy(rightRowLocations);
  }
517
  if (rightUseBuildTable) {
S
shenglian zhou 已提交
518 519 520 521 522 523
    void* p = NULL;
    int32_t iter = 0;
    while ((p = tSimpleHashIterate(pJoinInfo->rightBuildTable, p, &iter)) != NULL) {
      SArray* rows = (*(SArray**)p);
      taosArrayDestroy(rows);
    }
524
    tSimpleHashClear(pJoinInfo->rightBuildTable);
525
  }
S
shenglian zhou 已提交
526 527 528 529 530 531 532 533

  taosArrayDestroy(leftCreatedBlocks);
  taosArrayDestroy(leftRowLocations);

  pJoinInfo->rowCtx.rowRemains = false;
  pJoinInfo->rowCtx.leftRowLocations = NULL;
  pJoinInfo->rowCtx.leftCreatedBlocks = NULL;
  pJoinInfo->rowCtx.rightCreatedBlocks = NULL;
534
  pJoinInfo->rowCtx.rightUseBuildTable = false;
535
  pJoinInfo->rowCtx.rightRowLocations = NULL;
S
shenglian zhou 已提交
536 537
}

538 539
static int32_t mergeJoinJoinDownstreamTsRanges(SOperatorInfo* pOperator, int64_t timestamp, SSDataBlock* pRes,
                                               int32_t* nRows) {
540
  int32_t code = TSDB_CODE_SUCCESS;
541
  SJoinOperatorInfo* pJoinInfo = pOperator->info;
542
  SArray* leftRowLocations = NULL;
543
  SArray* rightRowLocations = NULL;
544 545 546 547
  SArray* leftCreatedBlocks = NULL;
  SArray* rightCreatedBlocks = NULL;
  int32_t leftRowIdx = 0;
  int32_t rightRowIdx = 0;
S
shenglian zhou 已提交
548
  SSHashObj* rightTableHash = NULL;
549
  bool rightUseBuildTable = false;
S
shenglian zhou 已提交
550

551 552 553
  if (pJoinInfo->rowCtx.rowRemains) {
    leftRowLocations = pJoinInfo->rowCtx.leftRowLocations;
    leftCreatedBlocks = pJoinInfo->rowCtx.leftCreatedBlocks;
554
    rightUseBuildTable = pJoinInfo->rowCtx.rightUseBuildTable;
555
    rightRowLocations = pJoinInfo->rowCtx.rightRowLocations;
556 557 558 559 560 561
    rightCreatedBlocks = pJoinInfo->rowCtx.rightCreatedBlocks;
    leftRowIdx = pJoinInfo->rowCtx.leftRowIdx;
    rightRowIdx = pJoinInfo->rowCtx.rightRowIdx;
  } else {
    leftRowLocations = taosArrayInit(8, sizeof(SRowLocation));
    leftCreatedBlocks = taosArrayInit(8, POINTER_BYTES);
562

563
    rightRowLocations = taosArrayInit(8, sizeof(SRowLocation));
564
    rightCreatedBlocks = taosArrayInit(8, POINTER_BYTES);
565

566 567 568 569
    mergeJoinGetDownStreamRowsEqualTimeStamp(pOperator, 0, pJoinInfo->leftCol.slotId, pJoinInfo->pLeft,
                                             pJoinInfo->leftPos, timestamp, leftRowLocations, leftCreatedBlocks);
    mergeJoinGetDownStreamRowsEqualTimeStamp(pOperator, 1, pJoinInfo->rightCol.slotId, pJoinInfo->pRight,
                                             pJoinInfo->rightPos, timestamp, rightRowLocations, rightCreatedBlocks);
570
    if (pJoinInfo->pTagEqualConditions != NULL && taosArrayGetSize(rightRowLocations) > 16) {
571 572
      mergeJoinFillBuildTable(pJoinInfo, rightRowLocations, pJoinInfo->rightBuildTable);
      rightUseBuildTable = true;
573 574 575
      taosArrayDestroy(rightRowLocations);
      rightRowLocations = NULL;
    }
576 577
  }
  
578
  size_t leftNumJoin = taosArrayGetSize(leftRowLocations);
S
shenglian zhou 已提交
579
  code = blockDataEnsureCapacity(pRes, pOperator->resultInfo.threshold);
580
  if (code != TSDB_CODE_SUCCESS) {
S
shenglian zhou 已提交
581 582
    qError("%s can not ensure block capacity for join. left: %zu", GET_TASKID(pOperator->pTaskInfo),
           leftNumJoin);
583
  }
584

S
shenglian zhou 已提交
585
  bool reachThreshold = false;
586

S
shenglian zhou 已提交
587 588
  if (code == TSDB_CODE_SUCCESS) {
    mergeJoinLeftRowsRightRows(pOperator, pRes, nRows, leftRowLocations, leftRowIdx,
589
                                                rightRowIdx, rightUseBuildTable, rightRowLocations, &reachThreshold);
590
  }
591

S
shenglian zhou 已提交
592 593
  if (!reachThreshold) {
    mergeJoinDestroyTSRangeCtx(pJoinInfo, leftRowLocations, leftCreatedBlocks, rightCreatedBlocks,
594
                               rightUseBuildTable, rightRowLocations);
S
shenglian zhou 已提交
595 596 597 598 599 600 601

  } else {
      pJoinInfo->rowCtx.rowRemains = true;
      pJoinInfo->rowCtx.ts = timestamp;
      pJoinInfo->rowCtx.leftRowLocations = leftRowLocations;
      pJoinInfo->rowCtx.leftCreatedBlocks = leftCreatedBlocks;
      pJoinInfo->rowCtx.rightCreatedBlocks = rightCreatedBlocks;
602
      pJoinInfo->rowCtx.rightUseBuildTable = true;
603
      pJoinInfo->rowCtx.rightRowLocations = rightRowLocations;
604 605 606 607
  }
  return TSDB_CODE_SUCCESS;
}

608 609
static bool mergeJoinGetNextTimestamp(SOperatorInfo* pOperator, int64_t* pLeftTs, int64_t* pRightTs) {
  SJoinOperatorInfo* pJoinInfo = pOperator->info;
610

611 612 613
  if (pJoinInfo->pLeft == NULL || pJoinInfo->leftPos >= pJoinInfo->pLeft->info.rows) {
    SOperatorInfo* ds1 = pOperator->pDownstream[0];
    pJoinInfo->pLeft = ds1->fpSet.getNextFn(ds1);
614

615 616 617 618
    pJoinInfo->leftPos = 0;
    if (pJoinInfo->pLeft == NULL) {
      setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
      return false;
619
    }
620
  }
621

622 623 624
  if (pJoinInfo->pRight == NULL || pJoinInfo->rightPos >= pJoinInfo->pRight->info.rows) {
    SOperatorInfo* ds2 = pOperator->pDownstream[1];
    pJoinInfo->pRight = ds2->fpSet.getNextFn(ds2);
625

626 627 628 629
    pJoinInfo->rightPos = 0;
    if (pJoinInfo->pRight == NULL) {
      setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
      return false;
630
    }
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
  }
  // only the timestamp match support for ordinary table
  SColumnInfoData* pLeftCol = taosArrayGet(pJoinInfo->pLeft->pDataBlock, pJoinInfo->leftCol.slotId);
  char*            pLeftVal = colDataGetData(pLeftCol, pJoinInfo->leftPos);
  *pLeftTs = *(int64_t*)pLeftVal;

  SColumnInfoData* pRightCol = taosArrayGet(pJoinInfo->pRight->pDataBlock, pJoinInfo->rightCol.slotId);
  char*            pRightVal = colDataGetData(pRightCol, pJoinInfo->rightPos);
  *pRightTs = *(int64_t*)pRightVal;

  return true;
}

static void doMergeJoinImpl(struct SOperatorInfo* pOperator, SSDataBlock* pRes) {
  SJoinOperatorInfo* pJoinInfo = pOperator->info;
646

647
  int32_t nrows = pRes->info.rows;
648

649
  bool asc = (pJoinInfo->inputOrder == TSDB_ORDER_ASC) ? true : false;
650

651 652 653
  while (1) {
    int64_t leftTs = 0;
    int64_t rightTs = 0;
654 655 656 657 658 659 660 661
    if (pJoinInfo->rowCtx.rowRemains) {
      leftTs = pJoinInfo->rowCtx.ts;
      rightTs = pJoinInfo->rowCtx.ts;
    } else {
      bool    hasNextTs = mergeJoinGetNextTimestamp(pOperator, &leftTs, &rightTs);
      if (!hasNextTs) {
        break;
      }
662
    }
663

664
    if (leftTs == rightTs) {
665
      mergeJoinJoinDownstreamTsRanges(pOperator, leftTs, pRes, &nrows);
H
Haojun Liao 已提交
666
    } else if ((asc && leftTs < rightTs) || (!asc && leftTs > rightTs)) {
667 668
      pJoinInfo->leftPos += 1;

669
      if (pJoinInfo->leftPos >= pJoinInfo->pLeft->info.rows && pRes->info.rows < pOperator->resultInfo.threshold) {
670 671
        continue;
      }
H
Haojun Liao 已提交
672
    } else if ((asc && leftTs > rightTs) || (!asc && leftTs < rightTs)) {
673
      pJoinInfo->rightPos += 1;
674
      if (pJoinInfo->rightPos >= pJoinInfo->pRight->info.rows && pRes->info.rows < pOperator->resultInfo.threshold) {
675 676 677 678 679 680
        continue;
      }
    }

    // the pDataBlock are always the same one, no need to call this again
    pRes->info.rows = nrows;
H
Haojun Liao 已提交
681
    pRes->info.dataLoad = 1;
682 683 684 685
    if (pRes->info.rows >= pOperator->resultInfo.threshold) {
      break;
    }
  }
686 687 688 689
}

SSDataBlock* doMergeJoin(struct SOperatorInfo* pOperator) {
  SJoinOperatorInfo* pJoinInfo = pOperator->info;
690

691 692
  SSDataBlock* pRes = pJoinInfo->pRes;
  blockDataCleanup(pRes);
H
Haojun Liao 已提交
693

694 695 696 697 698 699 700
  while (true) {
    int32_t numOfRowsBefore = pRes->info.rows;
    doMergeJoinImpl(pOperator, pRes);
    int32_t numOfNewRows = pRes->info.rows - numOfRowsBefore;
    if (numOfNewRows == 0) {
      break;
    }
H
Haojun Liao 已提交
701 702
    if (pOperator->exprSupp.pFilterInfo != NULL) {
      doFilter(pRes, pOperator->exprSupp.pFilterInfo, NULL);
703
    }
704 705 706 707
    if (pRes->info.rows >= pOperator->resultInfo.threshold) {
      break;
    }
  }
708 709
  return (pRes->info.rows > 0) ? pRes : NULL;
}