joinoperator.c 25.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

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

S
shenglian zhou 已提交
38
  SSHashObj* buildTableTSRange;
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

  SJoinRowCtx  rowCtx;
H
Haojun Liao 已提交
66 67
} SJoinOperatorInfo;

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

H
Haojun Liao 已提交
74 75
static void extractTimeCondition(SJoinOperatorInfo* pInfo, SOperatorInfo** pDownstream,  int32_t num,
                                 SSortMergeJoinPhysiNode* pJoinNode, const char* idStr) {
76
  SNode* pMergeCondition = pJoinNode->pMergeCondition;
H
Haojun Liao 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
  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);
93 94 95
      leftTsCol = col1;
      rightTsCol = col2;
    } else {
H
Haojun Liao 已提交
96 97 98 99
      ASSERT(col1->dataBlockId == pDownstream[1]->resultDataBlockId);
      ASSERT(col2->dataBlockId == pDownstream[0]->resultDataBlockId);
      leftTsCol = col2;
      rightTsCol = col1;
100
    }
H
Haojun Liao 已提交
101 102 103 104
  }
  setJoinColumnInfo(&pInfo->leftCol, leftTsCol);
  setJoinColumnInfo(&pInfo->rightCol, rightTsCol);
}
105

S
shenglian zhou 已提交
106 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
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);
  }
}

142
static int32_t initTagColskeyBuf(int32_t* keyLen, char** keyBuf, const SArray* pGroupColList) {
S
shenglian zhou 已提交
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
  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;
}

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

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

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

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

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

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

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

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

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

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

238 239 240 241 242 243 244 245 246
    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;
247 248
  }

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

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

S
shenglian zhou 已提交
261
  pInfo->pTagEqualConditions = pJoinNode->pTagEqualCondtions;
262 263 264 265
  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);
266 267
    initTagColskeyBuf(&pInfo->leftTagKeyLen, &pInfo->leftTagKeyBuf, pInfo->leftTagCols);
    initTagColskeyBuf(&pInfo->rightTagKeyLen, &pInfo->rightTagKeyBuf, pInfo->rightTagCols);
268
  }
269
  pOperator->fpSet = createOperatorFpSet(optrDummyOpenFn, doMergeJoin, NULL, destroyMergeJoinOperator, optrDefaultBufFn, NULL);
H
Haojun Liao 已提交
270
  code = appendDownstream(pOperator, pDownstream, numOfDownstream);
271 272 273 274 275 276
  if (code != TSDB_CODE_SUCCESS) {
    goto _error;
  }

  return pOperator;

277
_error:
H
Haojun Liao 已提交
278 279 280 281
  if (pInfo != NULL) {
    destroyMergeJoinOperator(pInfo);
  }

282
  taosMemoryFree(pOperator);
H
Haojun Liao 已提交
283
  pTaskInfo->code = code;
284 285 286 287 288 289 290 291 292 293 294
  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;
}

295
void destroyMergeJoinOperator(void* param) {
296
  SJoinOperatorInfo* pJoinOperator = (SJoinOperatorInfo*)param;
297 298 299
  if (pJoinOperator->pTagEqualConditions != NULL) {
    taosMemoryFreeClear(pJoinOperator->rightTagKeyBuf);
    taosArrayDestroy(pJoinOperator->rightTagCols);
S
shenglian zhou 已提交
300

301 302 303
    taosMemoryFreeClear(pJoinOperator->leftTagKeyBuf);
    taosArrayDestroy(pJoinOperator->leftTagCols);
  }
304
  nodesDestroyNode(pJoinOperator->pCondAfterMerge);
305

S
shenglian zhou 已提交
306
  pJoinOperator->pRes = blockDataDestroy(pJoinOperator->pRes);
D
dapan1121 已提交
307
  taosMemoryFreeClear(param);
308
}
309 310

static void mergeJoinJoinLeftRight(struct SOperatorInfo* pOperator, SSDataBlock* pRes, int32_t currRow,
311 312
                                   SSDataBlock* pLeftBlock, int32_t leftPos, SSDataBlock* pRightBlock,
                                   int32_t rightPos) {
313 314 315 316 317 318 319 320 321 322 323 324
  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 已提交
325
    if (pLeftBlock->info.id.blockId == blockId) {
326 327
      pSrc = taosArrayGet(pLeftBlock->pDataBlock, slotId);
      rowIndex = leftPos;
328
    } else {
329 330
      pSrc = taosArrayGet(pRightBlock->pDataBlock, slotId);
      rowIndex = rightPos;
331
    }
332

333
    if (colDataIsNull_s(pSrc, rowIndex)) {
334
      colDataSetNULL(pDst, currRow);
335 336
    } else {
      char* p = colDataGetData(pSrc, rowIndex);
337
      colDataSetVal(pDst, currRow, p, false);
338 339 340
    }
  }
}
341
typedef struct SRowLocation {
342 343
  SSDataBlock* pDataBlock;
  int32_t      pos;
344 345
} SRowLocation;

346
// pBlock[tsSlotId][startPos, endPos) == timestamp,
S
shenglian zhou 已提交
347
static int32_t mergeJoinGetBlockRowsEqualTs(SSDataBlock* pBlock, int16_t tsSlotId, int32_t startPos, int64_t timestamp,
348
                                            int32_t* pEndPos, SArray* rowLocations, SArray* createdBlocks) {
349 350
  int32_t numRows = pBlock->info.rows;
  ASSERT(startPos < numRows);
S
shenglian zhou 已提交
351
  SColumnInfoData* pCol = taosArrayGet(pBlock->pDataBlock, tsSlotId);
352 353

  int32_t i = startPos;
354
  for (; i < numRows; ++i) {
355
    char* pNextVal = colDataGetData(pCol, i);
356
    if (timestamp != *(int64_t*)pNextVal) {
357 358 359 360
      break;
    }
  }
  int32_t endPos = i;
S
shenglian zhou 已提交
361
  *pEndPos = endPos;
362

363 364 365 366
  if (endPos - startPos == 0) {
    return 0;
  }

367
  SSDataBlock* block = pBlock;
S
slzhou 已提交
368
  bool         createdNewBlock = false;
S
shenglian zhou 已提交
369
  if (endPos == numRows) {
S
slzhou 已提交
370
    block = blockDataExtractBlock(pBlock, startPos, endPos - startPos);
S
shenglian zhou 已提交
371
    taosArrayPush(createdBlocks, &block);
372
    createdNewBlock = true;
373
  }
374
  SRowLocation location = {0};
375 376
  for (int32_t j = startPos; j < endPos; ++j) {
    location.pDataBlock = block;
S
slzhou 已提交
377
    location.pos = (createdNewBlock ? j - startPos : j);
378
    taosArrayPush(rowLocations, &location);
379 380 381
  }
  return 0;
}
382

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
// 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;
    }
410

411 412 413 414 415 416 417 418 419
    mergeJoinGetBlockRowsEqualTs(dataBlock, tsSlotId, 0, timestamp, &endPos, rowLocations, createdBlocks);
  }
  if (endPos != -1) {
    if (whichChild == 0) {
      pJoinInfo->leftPos = endPos;
    } else if (whichChild == 1) {
      pJoinInfo->rightPos = endPos;
    }
  }
420 421 422
  return 0;
}

S
shenglian zhou 已提交
423
static int32_t mergeJoinCreateBuildTable(SJoinOperatorInfo* pInfo, SArray* rightRowLocations,SSHashObj** ppHashObj) {
424
  int32_t buildTableCap = TMIN(taosArrayGetSize(rightRowLocations), 256);
S
shenglian zhou 已提交
425 426 427 428
  _hash_fn_t hashFn = taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY);
  SSHashObj* buildTable = tSimpleHashInit(buildTableCap,  hashFn);
  for (int32_t i = 0; i < taosArrayGetSize(rightRowLocations); ++i) {
    SRowLocation* rightRow = taosArrayGet(rightRowLocations, i);
429
    int32_t keyLen = fillKeyBufFromTagCols(pInfo->rightTagCols, rightRow->pDataBlock, rightRow->pos, pInfo->rightTagKeyBuf);
S
shenglian zhou 已提交
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
    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);
    }
  }
  *ppHashObj = buildTable;
  return TSDB_CODE_SUCCESS;
}

static int32_t mergeJoinLeftRowsRightRows(SOperatorInfo* pOperator, SSDataBlock* pRes, int32_t* nRows,
                                         const SArray* leftRowLocations, int32_t leftRowIdx,
445
                                       int32_t rightRowIdx, SSHashObj* rightTableHash, SArray* rightRowLocations, bool* pReachThreshold) {
S
shenglian zhou 已提交
446 447 448 449 450 451 452 453 454
  *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);
455 456
    SArray* pRightRows = NULL;
    if (rightTableHash != NULL) {
457
      int32_t  keyLen = fillKeyBufFromTagCols(pJoinInfo->leftTagCols, leftRow->pDataBlock, leftRow->pos, pJoinInfo->leftTagKeyBuf);
458 459 460 461 462 463 464
      SArray** ppRightRows = tSimpleHashGet(rightTableHash, pJoinInfo->leftTagKeyBuf, keyLen);
      if (!ppRightRows) {
        continue;
      }
      pRightRows = *ppRightRows;
    } else {
      pRightRows = rightRowLocations;
S
shenglian zhou 已提交
465 466 467 468 469 470 471 472 473 474 475 476 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 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);
}

static void mergeJoinDestroyTSRangeCtx(SJoinOperatorInfo* pJoinInfo, SArray* leftRowLocations, SArray* leftCreatedBlocks,
504
                                       SArray* rightCreatedBlocks, SSHashObj* rightTableHash, 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 517 518 519
  if (rightRowLocations != NULL) {
    taosArrayDestroy(rightRowLocations);
  }
  if (rightTableHash != NULL) {
    mergeJoinDestoryBuildTable(rightTableHash);
  }
S
shenglian zhou 已提交
520 521 522 523 524 525 526 527 528

  taosArrayDestroy(leftCreatedBlocks);
  taosArrayDestroy(leftRowLocations);

  pJoinInfo->rowCtx.rowRemains = false;
  pJoinInfo->rowCtx.leftRowLocations = NULL;
  pJoinInfo->rowCtx.leftCreatedBlocks = NULL;
  pJoinInfo->rowCtx.rightCreatedBlocks = NULL;
  pJoinInfo->rowCtx.buildTableTSRange = NULL;
529
  pJoinInfo->rowCtx.rightRowLocations = NULL;
S
shenglian zhou 已提交
530 531
}

532 533
static int32_t mergeJoinJoinDownstreamTsRanges(SOperatorInfo* pOperator, int64_t timestamp, SSDataBlock* pRes,
                                               int32_t* nRows) {
534
  int32_t code = TSDB_CODE_SUCCESS;
535
  SJoinOperatorInfo* pJoinInfo = pOperator->info;
536
  SArray* leftRowLocations = NULL;
537
  SArray* rightRowLocations = NULL;
538 539 540 541
  SArray* leftCreatedBlocks = NULL;
  SArray* rightCreatedBlocks = NULL;
  int32_t leftRowIdx = 0;
  int32_t rightRowIdx = 0;
S
shenglian zhou 已提交
542 543
  SSHashObj* rightTableHash = NULL;

544 545 546
  if (pJoinInfo->rowCtx.rowRemains) {
    leftRowLocations = pJoinInfo->rowCtx.leftRowLocations;
    leftCreatedBlocks = pJoinInfo->rowCtx.leftCreatedBlocks;
S
shenglian zhou 已提交
547
    rightTableHash = pJoinInfo->rowCtx.buildTableTSRange;
548
    rightRowLocations = pJoinInfo->rowCtx.rightRowLocations;
549 550 551 552 553 554
    rightCreatedBlocks = pJoinInfo->rowCtx.rightCreatedBlocks;
    leftRowIdx = pJoinInfo->rowCtx.leftRowIdx;
    rightRowIdx = pJoinInfo->rowCtx.rightRowIdx;
  } else {
    leftRowLocations = taosArrayInit(8, sizeof(SRowLocation));
    leftCreatedBlocks = taosArrayInit(8, POINTER_BYTES);
555

556
    rightRowLocations = taosArrayInit(8, sizeof(SRowLocation));
557
    rightCreatedBlocks = taosArrayInit(8, POINTER_BYTES);
558

559 560 561 562
    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);
563 564 565 566 567
    if (pJoinInfo->pTagEqualConditions != NULL && taosArrayGetSize(rightRowLocations) > 16) {
      mergeJoinCreateBuildTable(pJoinInfo, rightRowLocations, &rightTableHash);
      taosArrayDestroy(rightRowLocations);
      rightRowLocations = NULL;
    }
568 569
  }
  
570
  size_t leftNumJoin = taosArrayGetSize(leftRowLocations);
S
shenglian zhou 已提交
571
  code = blockDataEnsureCapacity(pRes, pOperator->resultInfo.threshold);
572
  if (code != TSDB_CODE_SUCCESS) {
S
shenglian zhou 已提交
573 574
    qError("%s can not ensure block capacity for join. left: %zu", GET_TASKID(pOperator->pTaskInfo),
           leftNumJoin);
575
  }
576

S
shenglian zhou 已提交
577
  bool reachThreshold = false;
578

S
shenglian zhou 已提交
579 580
  if (code == TSDB_CODE_SUCCESS) {
    mergeJoinLeftRowsRightRows(pOperator, pRes, nRows, leftRowLocations, leftRowIdx,
581
                                                rightRowIdx, rightTableHash, rightRowLocations, &reachThreshold);
582
  }
583

S
shenglian zhou 已提交
584 585
  if (!reachThreshold) {
    mergeJoinDestroyTSRangeCtx(pJoinInfo, leftRowLocations, leftCreatedBlocks, rightCreatedBlocks,
586
                               rightTableHash, rightRowLocations);
S
shenglian zhou 已提交
587 588 589 590 591 592 593 594

  } else {
      pJoinInfo->rowCtx.rowRemains = true;
      pJoinInfo->rowCtx.ts = timestamp;
      pJoinInfo->rowCtx.leftRowLocations = leftRowLocations;
      pJoinInfo->rowCtx.leftCreatedBlocks = leftCreatedBlocks;
      pJoinInfo->rowCtx.rightCreatedBlocks = rightCreatedBlocks;
      pJoinInfo->rowCtx.buildTableTSRange = rightTableHash;
595
      pJoinInfo->rowCtx.rightRowLocations = rightRowLocations;
596 597 598 599
  }
  return TSDB_CODE_SUCCESS;
}

600 601
static bool mergeJoinGetNextTimestamp(SOperatorInfo* pOperator, int64_t* pLeftTs, int64_t* pRightTs) {
  SJoinOperatorInfo* pJoinInfo = pOperator->info;
602

603 604 605
  if (pJoinInfo->pLeft == NULL || pJoinInfo->leftPos >= pJoinInfo->pLeft->info.rows) {
    SOperatorInfo* ds1 = pOperator->pDownstream[0];
    pJoinInfo->pLeft = ds1->fpSet.getNextFn(ds1);
606

607 608 609 610
    pJoinInfo->leftPos = 0;
    if (pJoinInfo->pLeft == NULL) {
      setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
      return false;
611
    }
612
  }
613

614 615 616
  if (pJoinInfo->pRight == NULL || pJoinInfo->rightPos >= pJoinInfo->pRight->info.rows) {
    SOperatorInfo* ds2 = pOperator->pDownstream[1];
    pJoinInfo->pRight = ds2->fpSet.getNextFn(ds2);
617

618 619 620 621
    pJoinInfo->rightPos = 0;
    if (pJoinInfo->pRight == NULL) {
      setTaskStatus(pOperator->pTaskInfo, TASK_COMPLETED);
      return false;
622
    }
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
  }
  // 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;
638

639
  int32_t nrows = pRes->info.rows;
640

641
  bool asc = (pJoinInfo->inputOrder == TSDB_ORDER_ASC) ? true : false;
642

643 644 645
  while (1) {
    int64_t leftTs = 0;
    int64_t rightTs = 0;
646 647 648 649 650 651 652 653
    if (pJoinInfo->rowCtx.rowRemains) {
      leftTs = pJoinInfo->rowCtx.ts;
      rightTs = pJoinInfo->rowCtx.ts;
    } else {
      bool    hasNextTs = mergeJoinGetNextTimestamp(pOperator, &leftTs, &rightTs);
      if (!hasNextTs) {
        break;
      }
654
    }
655

656
    if (leftTs == rightTs) {
657
      mergeJoinJoinDownstreamTsRanges(pOperator, leftTs, pRes, &nrows);
H
Haojun Liao 已提交
658
    } else if ((asc && leftTs < rightTs) || (!asc && leftTs > rightTs)) {
659 660
      pJoinInfo->leftPos += 1;

661
      if (pJoinInfo->leftPos >= pJoinInfo->pLeft->info.rows && pRes->info.rows < pOperator->resultInfo.threshold) {
662 663
        continue;
      }
H
Haojun Liao 已提交
664
    } else if ((asc && leftTs > rightTs) || (!asc && leftTs < rightTs)) {
665
      pJoinInfo->rightPos += 1;
666
      if (pJoinInfo->rightPos >= pJoinInfo->pRight->info.rows && pRes->info.rows < pOperator->resultInfo.threshold) {
667 668 669 670 671 672
        continue;
      }
    }

    // the pDataBlock are always the same one, no need to call this again
    pRes->info.rows = nrows;
H
Haojun Liao 已提交
673
    pRes->info.dataLoad = 1;
674 675 676 677
    if (pRes->info.rows >= pOperator->resultInfo.threshold) {
      break;
    }
  }
678 679 680 681
}

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

683 684
  SSDataBlock* pRes = pJoinInfo->pRes;
  blockDataCleanup(pRes);
H
Haojun Liao 已提交
685

686 687 688 689 690 691 692
  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 已提交
693 694
    if (pOperator->exprSupp.pFilterInfo != NULL) {
      doFilter(pRes, pOperator->exprSupp.pFilterInfo, NULL);
695
    }
696 697 698 699
    if (pRes->info.rows >= pOperator->resultInfo.threshold) {
      break;
    }
  }
700 701
  return (pRes->info.rows > 0) ? pRes : NULL;
}