tscSubquery.c 72.0 KB
Newer Older
H
hjxilinx 已提交
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 "tscSubquery.h"
17 18
#include <tcompare.h>
#include <tschemautil.h>
H
hjxilinx 已提交
19 20
#include "os.h"
#include "qtsbuf.h"
S
slguan 已提交
21
#include "tscLog.h"
22
#include "tsclient.h"
H
hjxilinx 已提交
23 24 25 26 27 28

typedef struct SInsertSupporter {
  SSubqueryState* pState;
  SSqlObj*  pSql;
} SInsertSupporter;

H
hjxilinx 已提交
29 30
static void freeJoinSubqueryObj(SSqlObj* pSql);
static bool tscHashRemainDataInSubqueryResultSet(SSqlObj *pSql);
H
hjxilinx 已提交
31

32
static bool tsCompare(int32_t order, int64_t left, int64_t right) {
33
  if (order == TSDB_ORDER_ASC) {
H
hjxilinx 已提交
34 35 36 37 38 39
    return left < right;
  } else {
    return left > right;
  }
}

40 41
static int64_t doTSBlockIntersect(SSqlObj* pSql, SJoinSupporter* pSupporter1,
                                  SJoinSupporter* pSupporter2, TSKEY* st, TSKEY* et) {
H
hjxilinx 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
  STSBuf* output1 = tsBufCreate(true);
  STSBuf* output2 = tsBufCreate(true);

  *st = INT64_MAX;
  *et = INT64_MIN;

  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, pSql->cmd.clauseIndex);
  
  SLimitVal* pLimit = &pQueryInfo->limit;
  int32_t    order = pQueryInfo->order.order;
  
  SQueryInfo* pSubQueryInfo1 = tscGetQueryInfoDetail(&pSql->pSubs[0]->cmd, 0);
  SQueryInfo* pSubQueryInfo2 = tscGetQueryInfoDetail(&pSql->pSubs[1]->cmd, 0);
  
  pSubQueryInfo1->tsBuf = output1;
  pSubQueryInfo2->tsBuf = output2;

  tsBufResetPos(pSupporter1->pTSBuf);
  tsBufResetPos(pSupporter2->pTSBuf);

  // TODO add more details information
  if (!tsBufNextPos(pSupporter1->pTSBuf)) {
    tsBufFlush(output1);
    tsBufFlush(output2);

    tscTrace("%p input1 is empty, 0 for secondary query after ts blocks intersecting", pSql);
    return 0;
  }

  if (!tsBufNextPos(pSupporter2->pTSBuf)) {
    tsBufFlush(output1);
    tsBufFlush(output2);

    tscTrace("%p input2 is empty, 0 for secondary query after ts blocks intersecting", pSql);
    return 0;
  }

  int64_t numOfInput1 = 1;
  int64_t numOfInput2 = 1;

  while (1) {
    STSElem elem1 = tsBufGetElem(pSupporter1->pTSBuf);
    STSElem elem2 = tsBufGetElem(pSupporter2->pTSBuf);

#ifdef _DEBUG_VIEW
    tscPrint("%" PRId64 ", tags:%d \t %" PRId64 ", tags:%d", elem1.ts, elem1.tag, elem2.ts, elem2.tag);
#endif

90
    if (elem1.tag < elem2.tag || (elem1.tag == elem2.tag && tsCompare(order, elem1.ts, elem2.ts))) {
H
hjxilinx 已提交
91 92 93 94 95
      if (!tsBufNextPos(pSupporter1->pTSBuf)) {
        break;
      }

      numOfInput1++;
96
    } else if (elem1.tag > elem2.tag || (elem1.tag == elem2.tag && tsCompare(order, elem2.ts, elem1.ts))) {
H
hjxilinx 已提交
97 98 99 100 101 102 103 104 105 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
      if (!tsBufNextPos(pSupporter2->pTSBuf)) {
        break;
      }

      numOfInput2++;
    } else {
      /*
       * in case of stable query, limit/offset is not applied here. the limit/offset is applied to the
       * final results which is acquired after the secondry merge of in the client.
       */
      if (pLimit->offset == 0 || pQueryInfo->intervalTime > 0 || QUERY_IS_STABLE_QUERY(pQueryInfo->type)) {
        if (*st > elem1.ts) {
          *st = elem1.ts;
        }
  
        if (*et < elem1.ts) {
          *et = elem1.ts;
        }
        
        tsBufAppend(output1, elem1.vnode, elem1.tag, (const char*)&elem1.ts, sizeof(elem1.ts));
        tsBufAppend(output2, elem2.vnode, elem2.tag, (const char*)&elem2.ts, sizeof(elem2.ts));
      } else {
        pLimit->offset -= 1;
      }

      if (!tsBufNextPos(pSupporter1->pTSBuf)) {
        break;
      }

      numOfInput1++;

      if (!tsBufNextPos(pSupporter2->pTSBuf)) {
        break;
      }

      numOfInput2++;
    }
  }

  /*
   * failed to set the correct ts order yet in two cases:
   * 1. only one element
   * 2. only one element for each tag.
   */
  if (output1->tsOrder == -1) {
142 143
    output1->tsOrder = TSDB_ORDER_ASC;
    output2->tsOrder = TSDB_ORDER_ASC;
H
hjxilinx 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
  }

  tsBufFlush(output1);
  tsBufFlush(output2);

  tsBufDestory(pSupporter1->pTSBuf);
  tsBufDestory(pSupporter2->pTSBuf);

  tscTrace("%p input1:%" PRId64 ", input2:%" PRId64 ", final:%" PRId64 " for secondary query after ts blocks "
           "intersecting, skey:%" PRId64 ", ekey:%" PRId64, pSql,
           numOfInput1, numOfInput2, output1->numOfTotal, *st, *et);

  return output1->numOfTotal;
}

// todo handle failed to create sub query
160 161
SJoinSupporter* tscCreateJoinSupporter(SSqlObj* pSql, SSubqueryState* pState, int32_t index) {
  SJoinSupporter* pSupporter = calloc(1, sizeof(SJoinSupporter));
H
hjxilinx 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
  if (pSupporter == NULL) {
    return NULL;
  }

  pSupporter->pObj = pSql;
  pSupporter->pState = pState;

  pSupporter->subqueryIndex = index;
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, pSql->cmd.clauseIndex);
  
  pSupporter->interval = pQueryInfo->intervalTime;
  pSupporter->limit = pQueryInfo->limit;

  STableMetaInfo* pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, pSql->cmd.clauseIndex, index);
  pSupporter->uid = pTableMetaInfo->pTableMeta->uid;
  assert (pSupporter->uid != 0);

  getTmpfilePath("join-", pSupporter->path);
  pSupporter->f = fopen(pSupporter->path, "w");

  if (pSupporter->f == NULL) {
    tscError("%p failed to create tmp file:%s, reason:%s", pSql, pSupporter->path, strerror(errno));
  }

  return pSupporter;
}

189
void tscDestroyJoinSupporter(SJoinSupporter* pSupporter) {
H
hjxilinx 已提交
190 191 192 193
  if (pSupporter == NULL) {
    return;
  }

H
hjxilinx 已提交
194 195 196 197 198 199 200
  if (pSupporter->exprList != NULL) {
    tscSqlExprInfoDestroy(pSupporter->exprList);
  }
  
  if (pSupporter->colList != NULL) {
    tscColumnListDestroy(pSupporter->colList);
  }
H
hjxilinx 已提交
201

H
hjxilinx 已提交
202
  tscFieldInfoClear(&pSupporter->fieldsInfo);
H
hjxilinx 已提交
203 204 205 206

  if (pSupporter->f != NULL) {
    fclose(pSupporter->f);
    unlink(pSupporter->path);
H
hjxilinx 已提交
207
    pSupporter->f = NULL;
H
hjxilinx 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220
  }

  tscTagCondRelease(&pSupporter->tagCond);
  free(pSupporter);
}

/*
 * need the secondary query process
 * In case of count(ts)/count(*)/spread(ts) query, that are only applied to
 * primary timestamp column , the secondary query is not necessary
 *
 */
bool needSecondaryQuery(SQueryInfo* pQueryInfo) {
221 222 223
  size_t numOfCols = taosArrayGetSize(pQueryInfo->colList);
  
  for (int32_t i = 0; i < numOfCols; ++i) {
224 225
    SColumn* base = taosArrayGet(pQueryInfo->colList, i);
    if (base->colIndex.columnIndex != PRIMARYKEY_TIMESTAMP_COL_INDEX) {
H
hjxilinx 已提交
226 227 228 229 230 231 232 233 234 235 236
      return true;
    }
  }

  return false;
}

/*
 * launch secondary stage query to fetch the result that contains timestamp in set
 */
int32_t tscLaunchSecondPhaseSubqueries(SSqlObj* pSql) {
H
hjxilinx 已提交
237
  int32_t         numOfSub = 0;
238
  SJoinSupporter* pSupporter = NULL;
H
hjxilinx 已提交
239 240
  
  /*
H
hjxilinx 已提交
241 242
   * If the columns are not involved in the final select clause,
   * the corresponding query will not be issued.
H
hjxilinx 已提交
243 244 245
   */
  for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
    pSupporter = pSql->pSubs[i]->param;
H
hjxilinx 已提交
246
    if (taosArrayGetSize(pSupporter->exprList) > 0) {
H
hjxilinx 已提交
247 248 249 250 251 252 253 254 255 256
      ++numOfSub;
    }
  }
  
  assert(numOfSub > 0);
  
  // scan all subquery, if one sub query has only ts, ignore it
  tscTrace("%p start to launch secondary subqueries, total:%d, only:%d needs to query, others are not retrieve in "
      "select clause", pSql, pSql->numOfSubs, numOfSub);

H
hjxilinx 已提交
257
  //the subqueries that do not actually launch the secondary query to virtual node is set as completed.
258
  SSubqueryState* pState = pSupporter->pState;
H
hjxilinx 已提交
259 260 261 262 263 264 265 266 267 268 269
  pState->numOfTotal = pSql->numOfSubs;
  pState->numOfCompleted = (pSql->numOfSubs - numOfSub);
  
  bool success = true;
  
  for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
    SSqlObj *pPrevSub = pSql->pSubs[i];
    pSql->pSubs[i] = NULL;
    
    pSupporter = pPrevSub->param;
  
H
hjxilinx 已提交
270
    if (taosArrayGetSize(pSupporter->exprList) == 0) {
H
hjxilinx 已提交
271
      tscTrace("%p subIndex: %d, no need to launch query, ignore it", pSql, i);
H
hjxilinx 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284
    
      tscDestroyJoinSupporter(pSupporter);
      tscFreeSqlObj(pPrevSub);
    
      pSql->pSubs[i] = NULL;
      continue;
    }
  
    SQueryInfo *pSubQueryInfo = tscGetQueryInfoDetail(&pPrevSub->cmd, 0);
    STSBuf *pTSBuf = pSubQueryInfo->tsBuf;
    pSubQueryInfo->tsBuf = NULL;
  
    // free result for async object will also free sqlObj
H
hjxilinx 已提交
285
    assert(tscSqlExprNumOfExprs(pSubQueryInfo) == 1); // ts_comp query only requires one resutl columns
H
hjxilinx 已提交
286 287
    taos_free_result(pPrevSub);
  
288
    SSqlObj *pNew = createSubqueryObj(pSql, (int16_t) i, tscJoinQueryCallback, pSupporter, TSDB_SQL_SELECT, NULL);
H
hjxilinx 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301
    if (pNew == NULL) {
      tscDestroyJoinSupporter(pSupporter);
      success = false;
      break;
    }
  
    tscClearSubqueryInfo(&pNew->cmd);
    pSql->pSubs[i] = pNew;
  
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    pQueryInfo->tsBuf = pTSBuf;  // transfer the ownership of timestamp comp-z data to the new created object
  
    // set the second stage sub query for join process
H
hjxilinx 已提交
302
    TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_SEC_STAGE);
H
hjxilinx 已提交
303 304 305
  
    pQueryInfo->intervalTime = pSupporter->interval;
    pQueryInfo->groupbyExpr = pSupporter->groupbyExpr;
H
hjxilinx 已提交
306
    
H
hjxilinx 已提交
307 308
    tscTagCondCopy(&pQueryInfo->tagCond, &pSupporter->tagCond);
  
H
hjxilinx 已提交
309 310 311
    pQueryInfo->colList = pSupporter->colList;
    pQueryInfo->exprList = pSupporter->exprList;
    pQueryInfo->fieldsInfo = pSupporter->fieldsInfo;
H
hjxilinx 已提交
312
    
H
hjxilinx 已提交
313 314 315
    pSupporter->exprList = NULL;
    pSupporter->colList = NULL;
    memset(&pSupporter->fieldsInfo, 0, sizeof(SFieldInfo));
H
hjxilinx 已提交
316 317 318 319
  
    SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    assert(pNew->numOfSubs == 0 && pNew->cmd.numOfClause == 1 && pNewQueryInfo->numOfTables == 1);
  
H
hjxilinx 已提交
320
    tscFieldInfoUpdateOffset(pNewQueryInfo);
H
hjxilinx 已提交
321 322 323 324 325 326 327 328 329 330 331 332
  
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pNewQueryInfo, 0);
  
    /*
     * When handling the projection query, the offset value will be modified for table-table join, which is changed
     * during the timestamp intersection.
     */
    pSupporter->limit = pQueryInfo->limit;
    pNewQueryInfo->limit = pSupporter->limit;
  
    // fetch the join tag column
    if (UTIL_TABLE_IS_SUPERTABLE(pTableMetaInfo)) {
H
hjxilinx 已提交
333
      SSqlExpr* pExpr = tscSqlExprGet(pNewQueryInfo, 0);
H
hjxilinx 已提交
334 335 336 337 338 339 340
      assert(pQueryInfo->tagCond.joinInfo.hasJoin);
    
      int16_t tagColIndex = tscGetJoinTagColIndexByUid(&pQueryInfo->tagCond, pTableMetaInfo->pTableMeta->uid);
      pExpr->param[0].i64Key = tagColIndex;
      pExpr->numOfParams = 1;
    }
  
341
    size_t numOfCols = taosArrayGetSize(pNewQueryInfo->colList);
H
hjxilinx 已提交
342 343
    tscTrace("%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%d, exprInfo:%d, colList:%d, fieldsInfo:%d, name:%s",
             pSql, pNew, 0, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type,
H
hjxilinx 已提交
344
             taosArrayGetSize(pNewQueryInfo->exprList), numOfCols,
H
hjxilinx 已提交
345
             pNewQueryInfo->fieldsInfo.numOfOutput, pNewQueryInfo->pTableMetaInfo[0]->name);
H
hjxilinx 已提交
346 347 348 349 350 351 352
  }
  
  //prepare the subqueries object failed, abort
  if (!success) {
    pSql->res.code = TSDB_CODE_CLI_OUT_OF_MEMORY;
    tscError("%p failed to prepare subqueries objs for secondary phase query, numOfSub:%d, code:%d", pSql,
        pSql->numOfSubs, pSql->res.code);
H
hjxilinx 已提交
353
    freeJoinSubqueryObj(pSql);
H
hjxilinx 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
    
    return pSql->res.code;
  }
  
  for(int32_t i = 0; i < pSql->numOfSubs; ++i) {
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
      continue;
    }
    
    tscProcessSql(pSub);
  }

  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
370
void freeJoinSubqueryObj(SSqlObj* pSql) {
H
hjxilinx 已提交
371 372 373
  SSubqueryState* pState = NULL;

  for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
H
hjxilinx 已提交
374 375 376 377 378
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
      continue;
    }
    
379
    SJoinSupporter* p = pSub->param;
H
hjxilinx 已提交
380
    pState = p->pState;
H
hjxilinx 已提交
381

H
hjxilinx 已提交
382
    tscDestroyJoinSupporter(p);
H
hjxilinx 已提交
383

H
hjxilinx 已提交
384 385
    if (pSub->res.code == TSDB_CODE_SUCCESS) {
      taos_free_result(pSub);
H
hjxilinx 已提交
386 387 388 389 390 391 392
    }
  }

  tfree(pState);
  pSql->numOfSubs = 0;
}

393
static void quitAllSubquery(SSqlObj* pSqlObj, SJoinSupporter* pSupporter) {
H
hjxilinx 已提交
394 395 396
  int32_t numOfTotal = pSupporter->pState->numOfTotal;
  int32_t finished = atomic_add_fetch_32(&pSupporter->pState->numOfCompleted, 1);
  
397
  pSqlObj->res.code = pSupporter->pState->code;
H
hjxilinx 已提交
398 399
  if (finished >= numOfTotal) {
    tscError("%p all subquery return and query failed, global code:%d", pSqlObj, pSqlObj->res.code);
H
hjxilinx 已提交
400
    freeJoinSubqueryObj(pSqlObj);
H
hjxilinx 已提交
401 402 403 404 405
  }
}

// update the query time range according to the join results on timestamp
static void updateQueryTimeRange(SQueryInfo* pQueryInfo, int64_t st, int64_t et) {
H
hjxilinx 已提交
406
  assert(pQueryInfo->window.skey <= st && pQueryInfo->window.ekey >= et);
H
hjxilinx 已提交
407

H
hjxilinx 已提交
408 409
  pQueryInfo->window.skey = st;
  pQueryInfo->window.ekey = et;
H
hjxilinx 已提交
410 411
}

412
static void tSIntersectionAndLaunchSecQuery(SJoinSupporter* pSupporter, SSqlObj* pSql) {
H
hjxilinx 已提交
413
  SSqlObj* pParentSql = pSupporter->pObj;
414 415
//  SSqlCmd* pCmd = &pSql->cmd;
//  SSqlRes* pRes = &pSql->res;
H
hjxilinx 已提交
416
  
417
//  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
418 419
  SQueryInfo* pParentQueryInfo = tscGetQueryInfoDetail(&pParentSql->cmd, pParentSql->cmd.clauseIndex);
  
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
//  if (tscNonOrderedProjectionQueryOnSTable(pParentQueryInfo, 0)) {
//    STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
//    assert(pQueryInfo->numOfTables == 1);
//
//    // for projection query, need to try next vnode
////        int32_t totalVnode = pTableMetaInfo->pMetricMeta->numOfVnodes;
//    int32_t totalVnode = 0;
//    if ((++pTableMetaInfo->vgroupIndex) < totalVnode) {
//      tscTrace("%p current vnode:%d exhausted, try next:%d. total vnode:%d. current numOfRes:%d", pSql,
//               pTableMetaInfo->vgroupIndex - 1, pTableMetaInfo->vgroupIndex, totalVnode, pRes->numOfTotal);
//
//      pSql->cmd.command = TSDB_SQL_SELECT;
//      pSql->fp = tscJoinQueryCallback;
//      tscProcessSql(pSql);
//
//      return;
//    }
//  }
H
hjxilinx 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
  
  int32_t numOfTotal = pSupporter->pState->numOfTotal;
  int32_t finished = atomic_add_fetch_32(&pSupporter->pState->numOfCompleted, 1);
  
  if (finished >= numOfTotal) {
    assert(finished == numOfTotal);
    
    if (pSupporter->pState->code != TSDB_CODE_SUCCESS) {
      tscTrace("%p sub:%p, numOfSub:%d, quit from further procedure due to other queries failure", pParentSql, pSql,
               pSupporter->subqueryIndex);
      freeJoinSubqueryObj(pParentSql);
      return;
    }
    
    tscTrace("%p all subqueries retrieve ts complete, do ts block intersect", pParentSql);
    
454 455
    SJoinSupporter* p1 = pParentSql->pSubs[0]->param;
    SJoinSupporter* p2 = pParentSql->pSubs[1]->param;
H
hjxilinx 已提交
456 457 458 459 460 461 462 463 464 465 466 467 468
    
    TSKEY st, et;
    int64_t num = doTSBlockIntersect(pParentSql, p1, p2, &st, &et);
    if (num <= 0) {  // no result during ts intersect
      tscTrace("%p free all sub SqlObj and quit", pParentSql);
      freeJoinSubqueryObj(pParentSql);
    } else {
      updateQueryTimeRange(pParentQueryInfo, st, et);
      tscLaunchSecondPhaseSubqueries(pParentSql);
    }
  }
}

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 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
int32_t tagsOrderCompar(const void* p1, const void* p2) {
  STidTags* t1 = (STidTags*) p1;
  STidTags* t2 = (STidTags*) p2;
  
  if (t1->vgId != t2->vgId) {
    return (t1->vgId > t2->vgId)? 1:-1;
  } else {
    if (t1->tid != t2->tid) {
      return (t1->tid > t2->tid)? 1:-1;
    } else {
      return 0;
    }
  }
}

static void doBuildVgroupTableInfo(SArray* res, STableMetaInfo* pTableMetaInfo) {
  SArray* pGroup = taosArrayInit(4, sizeof(SVgroupTableInfo));
  
  SArray* vgTableIdItem = taosArrayInit(4, sizeof(STableIdInfo));
  int32_t size = taosArrayGetSize(res);
  
  STidTags* prev = taosArrayGet(res, 0);
  int32_t prevVgId = prev->vgId;
  
  STableIdInfo item = {.uid = prev->uid, .tid = prev->tid, .key = INT64_MIN};
  taosArrayPush(vgTableIdItem, &item);
  
  for(int32_t k = 1; k < size; ++k) {
    STidTags* t1 = taosArrayGet(res, k);
    if (prevVgId != t1->vgId) {
      
      SVgroupTableInfo info = {0};
      
      SVgroupsInfo* pvg = pTableMetaInfo->vgroupList;
      for(int32_t m = 0; m < pvg->numOfVgroups; ++m) {
        if (prevVgId == pvg->vgroups[m].vgId) {
          info.vgInfo = pvg->vgroups[m];
          break;
        }
      }
      
      assert(info.vgInfo.numOfIps != 0);
      info.itemList = vgTableIdItem;
      taosArrayPush(pGroup, &info);
      
      vgTableIdItem = taosArrayInit(4, sizeof(STableIdInfo));
      STableIdInfo item1 = {.uid = t1->uid, .tid = t1->tid, .key = INT64_MIN};
      taosArrayPush(vgTableIdItem, &item1);
      prevVgId = t1->vgId;
    } else {
      taosArrayPush(vgTableIdItem, &item);
    }
  }
  
  if (taosArrayGetSize(vgTableIdItem) > 0) {
    SVgroupTableInfo info = {0};
    SVgroupsInfo* pvg = pTableMetaInfo->vgroupList;
    
    for(int32_t m = 0; m < pvg->numOfVgroups; ++m) {
      if (prevVgId == pvg->vgroups[m].vgId) {
        info.vgInfo = pvg->vgroups[m];
        break;
      }
    }
    
    assert(info.vgInfo.numOfIps != 0);
    info.itemList = vgTableIdItem;
    taosArrayPush(pGroup, &info);
  }
  
  pTableMetaInfo->pVgroupTables = pGroup;
}

static void issueTSCompQuery(SSqlObj* pSql, SJoinSupporter* pSupporter, SSqlObj* pParent) {
  SSqlCmd* pCmd = &pSql->cmd;
  tscClearSubqueryInfo(pCmd);
  tscFreeSqlResult(pSql);
  
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
  
  tscInitQueryInfo(pQueryInfo);

  TSDB_QUERY_CLEAR_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_TAG_FILTER_QUERY);
  TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_MULTITABLE_QUERY);
  
  pCmd->command = TSDB_SQL_SELECT;
  pSql->fp = tscJoinQueryCallback;
  
  SSchema colSchema = {.type = TSDB_DATA_TYPE_BINARY, .bytes = 1};
  
  SColumnIndex index = {0, PRIMARYKEY_TIMESTAMP_COL_INDEX};
  tscAddSpecialColumnForSelect(pQueryInfo, 0, TSDB_FUNC_TS_COMP, &index, &colSchema, TSDB_COL_NORMAL);
  
  // set the tags value for ts_comp function
  SSqlExpr *pExpr = tscSqlExprGet(pQueryInfo, 0);
  int16_t tagColIndex = tscGetJoinTagColIndexByUid(&pSupporter->tagCond, pTableMetaInfo->pTableMeta->uid);
  
  pExpr->param->i64Key = tagColIndex;
  pExpr->numOfParams = 1;
  
  // add the filter tag column
  if (pSupporter->colList != NULL) {
    size_t s = taosArrayGetSize(pSupporter->colList);
    
    for (int32_t i = 0; i < s; ++i) {
      SColumn *pCol = taosArrayGetP(pSupporter->colList, i);
      
      if (pCol->numOfFilters > 0) {  // copy to the pNew->cmd.colList if it is filtered.
        SColumn *p = tscColumnClone(pCol);
        taosArrayPush(pQueryInfo->colList, &p);
      }
    }
  }
  
  size_t numOfCols = taosArrayGetSize(pQueryInfo->colList);
  
  tscTrace(
      "%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%d, transfer to ts_comp query to retrieve timestamps, "
      "exprInfo:%d, colList:%d, fieldsInfo:%d, name:%s",
      pParent, pSql, 0, pTableMetaInfo->vgroupIndex, pQueryInfo->type, tscSqlExprNumOfExprs(pQueryInfo),
      numOfCols, pQueryInfo->fieldsInfo.numOfOutput, pTableMetaInfo->name);
  
  tscProcessSql(pSql);
}

H
hjxilinx 已提交
595
static void joinRetrieveCallback(void* param, TAOS_RES* tres, int numOfRows) {
596
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
hjxilinx 已提交
597 598
  
  SSqlObj* pParentSql = pSupporter->pObj;
H
hjxilinx 已提交
599 600 601 602 603
  SSqlObj* pSql = (SSqlObj*)tres;
  SSqlCmd* pCmd = &pSql->cmd;
  
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
//  if (pSupporter->pState->code != TSDB_CODE_SUCCESS) {
//    tscError("%p abort query due to other subquery failure. code:%d, global code:%s", pSql, numOfRows,
//             tstrerror(pSupporter->pState->code));
//
//    quitAllSubquery(pParentSql, pSupporter);
//    return;
//  }
//
//  if (numOfRows < 0) {
//    tscError("%p sub query failed, code:%s, index:%d", pSql, tstrerror(numOfRows), pSupporter->subqueryIndex);
//    pSupporter->pState->code = numOfRows;
//    quitAllSubquery(pParentSql, pSupporter);
//    return;
//  }
  
  // response of tag retrieve
  if (TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_TAG_FILTER_QUERY)) {
    if (numOfRows == 0 || pSql->res.completed) {
      
      if (numOfRows > 0) {
        size_t length = pSupporter->totalLen + pSql->res.rspLen;
        char* tmp = realloc(pSupporter->pIdTagList, length);
        assert(tmp != NULL);
        pSupporter->pIdTagList = tmp;
        
        memcpy(pSupporter->pIdTagList, pSql->res.data, pSql->res.rspLen);
        pSupporter->totalLen += pSql->res.rspLen;
        pSupporter->num += pSql->res.numOfRows;
      }
      
      int32_t numOfTotal = pSupporter->pState->numOfTotal;
      int32_t finished = atomic_add_fetch_32(&pSupporter->pState->numOfCompleted, 1);
  
      if (finished < numOfTotal) {
        return;
      }
      
      // all subqueries are returned, start to compare the tags
      assert(finished == numOfTotal);
      tscTrace("%p all subqueries retrieve tags complete, do tags match", pParentSql);
  
      SJoinSupporter* p1 = pParentSql->pSubs[0]->param;
      SJoinSupporter* p2 = pParentSql->pSubs[1]->param;
  
      qsort(p1->pIdTagList, p1->num, p1->tagSize, tagsOrderCompar);
      qsort(p2->pIdTagList, p2->num, p2->tagSize, tagsOrderCompar);
      
      STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
  
      SSchema* pSchema = tscGetTableTagSchema(pTableMetaInfo->pTableMeta);// todo: tags mismatch, tags not completed
  
      SColumn *pCol = taosArrayGetP(pTableMetaInfo->tagColList, 0);
      SSchema *pColSchema = &pSchema[pCol->colIndex.columnIndex];
      
      SArray* s1 = taosArrayInit(p1->num, p1->tagSize);
      SArray* s2 = taosArrayInit(p2->num, p2->tagSize);
      
      int32_t i = 0, j = 0;
      while(i < p1->num && j < p2->num) {
        STidTags* pp1 = (STidTags*) p1->pIdTagList + i * p1->tagSize;
        STidTags* pp2 = (STidTags*) p2->pIdTagList + j * p2->tagSize;
       
        int32_t ret = doCompare(pp1->tag, pp2->tag, pColSchema->type, pColSchema->bytes);
        if (ret == 0) {
          taosArrayPush(s1, pp1);
          taosArrayPush(s2, pp2);
          j++;
          i++;
        } else if (ret > 0) {
          j++;
        } else {
          i++;
        }
      }
      
      if (taosArrayGetSize(s1) == 0 || taosArrayGetSize(s2) == 0) {// no results,return.
        tscTrace("%p free all sub SqlObj and quit", pParentSql);
        freeJoinSubqueryObj(pParentSql);
        return;
      } else {
        SSqlCmd* pSubCmd1 = &pParentSql->pSubs[0]->cmd;
        SSqlCmd* pSubCmd2 = &pParentSql->pSubs[1]->cmd;
        
        SQueryInfo* pQueryInfo1 = tscGetQueryInfoDetail(pSubCmd1, 0);
        STableMetaInfo* pTableMetaInfo1 = tscGetMetaInfo(pQueryInfo1, 0);
        doBuildVgroupTableInfo(s1, pTableMetaInfo1);
        
        SQueryInfo* pQueryInfo2 = tscGetQueryInfoDetail(pSubCmd2, 0);
        STableMetaInfo* pTableMetaInfo2 = tscGetMetaInfo(pQueryInfo2, 0);
        doBuildVgroupTableInfo(s2, pTableMetaInfo2);
  
        pSupporter->pState->numOfCompleted = 0;
        pSupporter->pState->code = 0;
        pSupporter->pState->numOfTotal = 2;
        
        for(int32_t m = 0; m < pParentSql->numOfSubs; ++m) {
          SSqlObj* psub = pParentSql->pSubs[m];
          issueTSCompQuery(psub, psub->param, pParentSql);
        }
      }
      
    } else {
      size_t length = pSupporter->totalLen + pSql->res.rspLen;
      char* tmp = realloc(pSupporter->pIdTagList, length);
      assert(tmp != NULL);
      
      pSupporter->pIdTagList = tmp;
      
      memcpy(pSupporter->pIdTagList, pSql->res.data, pSql->res.rspLen);
      pSupporter->totalLen += pSql->res.rspLen;
      pSupporter->num += pSql->res.numOfRows;
  
      // continue retrieve data from vnode
      taos_fetch_rows_a(tres, joinRetrieveCallback, param);
H
hjxilinx 已提交
718
    }
H
hjxilinx 已提交
719
    
720 721 722 723
    return;
  }
  
  if (!TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_SEC_STAGE)) {
H
hjxilinx 已提交
724 725 726 727 728 729
    if (numOfRows < 0) {
      tscError("%p sub query failed, code:%s, index:%d", pSql, tstrerror(numOfRows), pSupporter->subqueryIndex);
      pSupporter->pState->code = numOfRows;
      quitAllSubquery(pParentSql, pSupporter);
      return;
    }
730 731

    if (numOfRows == 0) {
H
hjxilinx 已提交
732 733 734
      tSIntersectionAndLaunchSecQuery(pSupporter, pSql);
      return;
    }
H
hjxilinx 已提交
735

H
hjxilinx 已提交
736 737 738 739 740 741 742 743
    // write the compressed timestamp to disk file
    fwrite(pSql->res.data, pSql->res.numOfRows, 1, pSupporter->f);
    fclose(pSupporter->f);
    pSupporter->f = NULL;
    
    STSBuf* pBuf = tsBufCreateFromFile(pSupporter->path, true);
    if (pBuf == NULL) {
      tscError("%p invalid ts comp file from vnode, abort subquery, file size:%d", pSql, numOfRows);
H
hjxilinx 已提交
744

H
hjxilinx 已提交
745 746 747 748
      pSupporter->pState->code = TSDB_CODE_APP_ERROR;  // todo set the informative code
      quitAllSubquery(pParentSql, pSupporter);
      return;
    }
H
hjxilinx 已提交
749

H
hjxilinx 已提交
750 751 752 753 754 755
    if (pSupporter->pTSBuf == NULL) {
      tscTrace("%p create tmp file for ts block:%s, size:%d bytes", pSql, pBuf->path, numOfRows);
      pSupporter->pTSBuf = pBuf;
    } else {
      assert(pQueryInfo->numOfTables == 1);  // for subquery, only one
      STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
756

H
hjxilinx 已提交
757 758 759 760 761 762 763
      tsBufMerge(pSupporter->pTSBuf, pBuf, pTableMetaInfo->vgroupIndex);
      tsBufDestory(pBuf);
    }
    
    if (pSql->res.completed) {
      tSIntersectionAndLaunchSecQuery(pSupporter, pSql);
    } else { // open a new file to save the incoming result
H
hjxilinx 已提交
764 765 766 767 768 769 770 771 772
      getTmpfilePath("ts-join", pSupporter->path);
      pSupporter->f = fopen(pSupporter->path, "w");
      pSql->res.row = pSql->res.numOfRows;

      taos_fetch_rows_a(tres, joinRetrieveCallback, param);
    }
  } else {  // secondary stage retrieve, driven by taos_fetch_row or other functions
    if (numOfRows < 0) {
      pSupporter->pState->code = numOfRows;
H
hjxilinx 已提交
773
      tscError("%p retrieve failed, code:%s, index:%d", pSql, tstrerror(numOfRows), pSupporter->subqueryIndex);
H
hjxilinx 已提交
774 775 776 777 778 779 780
    }

    if (numOfRows >= 0) {
      pSql->res.numOfTotal += pSql->res.numOfRows;
    }
  
    if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) && numOfRows == 0) {
H
hjxilinx 已提交
781
      STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
782
      assert(pQueryInfo->numOfTables == 1);
H
hjxilinx 已提交
783 784 785 786 787 788 789 790 791 792 793 794
  
        // for projection query, need to try next vnode if current vnode is exhausted
      if ((++pTableMetaInfo->vgroupIndex) < pTableMetaInfo->vgroupList->numOfVgroups) {
        pSupporter->pState->numOfCompleted = 0;
        pSupporter->pState->numOfTotal = 1;
  
        pSql->cmd.command = TSDB_SQL_SELECT;
        pSql->fp = tscJoinQueryCallback;
        tscProcessSql(pSql);
  
        return;
      }
H
hjxilinx 已提交
795 796 797 798 799 800 801 802 803 804 805
    }
  
    int32_t numOfTotal = pSupporter->pState->numOfTotal;
    int32_t finished = atomic_add_fetch_32(&pSupporter->pState->numOfCompleted, 1);
  
    if (finished >= numOfTotal) {
      assert(finished == numOfTotal);
      tscTrace("%p all %d secondary subquery retrieves completed, global code:%d", tres, numOfTotal,
               pParentSql->res.code);

      if (pSupporter->pState->code != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
806 807 808
        pParentSql->res.code = pSupporter->pState->code;
        freeJoinSubqueryObj(pParentSql);
        pParentSql->res.completed = true;
H
hjxilinx 已提交
809
      }
H
hjxilinx 已提交
810 811 812 813 814 815 816 817 818 819 820 821 822
  
      // update the records for each subquery in parent sql object.
      for(int32_t i = 0; i < pParentSql->numOfSubs; ++i) {
        if (pParentSql->pSubs[i] == NULL) {
          continue;
        }
    
        SSqlRes* pRes1 = &pParentSql->pSubs[i]->res;
        pRes1->numOfTotalInCurrentClause += pRes1->numOfRows;
      }
  
      // data has retrieved to client, build the join results
      tscBuildResFromSubqueries(pParentSql);
H
hjxilinx 已提交
823 824 825 826 827 828
    } else {
      tscTrace("%p sub:%p completed, completed:%d, total:%d", pParentSql, tres, finished, numOfTotal);
    }
  }
}

829
static SJoinSupporter* tscUpdateSubqueryStatus(SSqlObj* pSql, int32_t numOfFetch) {
H
hjxilinx 已提交
830
  int32_t notInvolved = 0;
831
  SJoinSupporter* pSupporter = NULL;
H
hjxilinx 已提交
832 833 834 835 836 837
  SSubqueryState* pState = NULL;
  
  for(int32_t i = 0; i < pSql->numOfSubs; ++i) {
    if (pSql->pSubs[i] == NULL) {
      notInvolved++;
    } else {
838
      pSupporter = (SJoinSupporter*)pSql->pSubs[i]->param;
H
hjxilinx 已提交
839 840 841 842 843 844 845 846 847 848 849 850 851
      pState = pSupporter->pState;
    }
  }
  
  pState->numOfTotal = pSql->numOfSubs;
  pState->numOfCompleted = pSql->numOfSubs - numOfFetch;
  
  return pSupporter;
}

void tscFetchDatablockFromSubquery(SSqlObj* pSql) {
  assert(pSql->numOfSubs >= 1);
  
H
hjxilinx 已提交
852 853
  int32_t numOfFetch = 0;
  bool hasData = true;
H
hjxilinx 已提交
854
  for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
H
hjxilinx 已提交
855 856 857
    // if the subquery is NULL, it does not involved in the final result generation
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
H
hjxilinx 已提交
858 859 860
      continue;
    }
    
H
hjxilinx 已提交
861 862
    SSqlRes *pRes = &pSub->res;
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSub->cmd, 0);
H
hjxilinx 已提交
863 864 865 866 867 868 869 870
//    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
  
//    if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0)) {
//      if (pRes->row >= pRes->numOfRows && pTableMetaInfo->vgroupIndex < pTableMetaInfo->vgroupList->numOfVgroups &&
//          (!tscHasReachLimitation(pQueryInfo, pRes)) && !pRes->completed) {
//        numOfFetch++;
//      }
//    } else {
H
hjxilinx 已提交
871 872 873 874 875 876 877 878 879 880 881 882
      if (!tscHasReachLimitation(pQueryInfo, pRes)) {
        if (pRes->row >= pRes->numOfRows) {
          hasData = false;

          if (!pRes->completed) {
            numOfFetch++;
          }
        }
      } else {  // has reach the limitation, no data anymore
        hasData = false;
      }
      
H
hjxilinx 已提交
883
    }
H
hjxilinx 已提交
884
//  }
H
hjxilinx 已提交
885

H
hjxilinx 已提交
886 887 888 889 890 891 892 893 894 895 896 897 898 899
  // has data remains in client side, and continue to return data to app
  if (hasData) {
    tscBuildResFromSubqueries(pSql);
    return;
  } else if (numOfFetch <= 0) {
    pSql->res.completed = true;
    freeJoinSubqueryObj(pSql);
    
    if (pSql->res.code == TSDB_CODE_SUCCESS) {
      (*pSql->fp)(pSql->param, pSql, 0);
    } else {
      tscQueueAsyncRes(pSql);
    }
    
H
hjxilinx 已提交
900 901 902 903 904
    return;
  }

  // TODO multi-vnode retrieve for projection query with limitation has bugs, since the global limiation is not handled
  tscTrace("%p retrieve data from %d subqueries", pSql, numOfFetch);
905
  SJoinSupporter* pSupporter = tscUpdateSubqueryStatus(pSql, numOfFetch);
H
hjxilinx 已提交
906 907 908 909 910 911 912 913 914 915
  
  for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
    SSqlObj* pSql1 = pSql->pSubs[i];
    if (pSql1 == NULL) {
      continue;
    }
    
    SSqlRes* pRes1 = &pSql1->res;
    SSqlCmd* pCmd1 = &pSql1->cmd;

916
    pSupporter = (SJoinSupporter*)pSql1->param;
H
hjxilinx 已提交
917 918 919 920 921 922 923 924

    // wait for all subqueries completed
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd1, 0);
    assert(pRes1->numOfRows >= 0 && pQueryInfo->numOfTables == 1);

    STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
    
    if (pRes1->row >= pRes1->numOfRows) {
H
hjxilinx 已提交
925 926
      tscTrace("%p subquery:%p retrieve data from vnode, subquery:%d, vgroupIndex:%d", pSql, pSql1,
               pSupporter->subqueryIndex, pTableMetaInfo->vgroupIndex);
H
hjxilinx 已提交
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951

      tscResetForNextRetrieve(pRes1);
      pSql1->fp = joinRetrieveCallback;

      if (pCmd1->command < TSDB_SQL_LOCAL) {
        pCmd1->command = (pCmd1->command > TSDB_SQL_MGMT) ? TSDB_SQL_RETRIEVE : TSDB_SQL_FETCH;
      }

      tscProcessSql(pSql1);
    }
  }
}

// all subqueries return, set the result output index
void tscSetupOutputColumnIndex(SSqlObj* pSql) {
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;

  tscTrace("%p all subquery response, retrieve data", pSql);

  if (pRes->pColumnIndex != NULL) {
    return;  // the column transfer support struct has been built
  }

  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
952
  pRes->pColumnIndex = calloc(1, sizeof(SColumnIndex) * pQueryInfo->fieldsInfo.numOfOutput);
H
hjxilinx 已提交
953

H
hjxilinx 已提交
954
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutput; ++i) {
H
hjxilinx 已提交
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);

    int32_t tableIndexOfSub = -1;
    for (int32_t j = 0; j < pQueryInfo->numOfTables; ++j) {
      STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, j);
      if (pTableMetaInfo->pTableMeta->uid == pExpr->uid) {
        tableIndexOfSub = j;
        break;
      }
    }

    assert(tableIndexOfSub >= 0 && tableIndexOfSub < pQueryInfo->numOfTables);
    
    SSqlCmd* pSubCmd = &pSql->pSubs[tableIndexOfSub]->cmd;
    SQueryInfo* pSubQueryInfo = tscGetQueryInfoDetail(pSubCmd, 0);
    
H
hjxilinx 已提交
971
    size_t numOfExprs = taosArrayGetSize(pSubQueryInfo->exprList);
H
hjxilinx 已提交
972
    for (int32_t k = 0; k < numOfExprs; ++k) {
H
hjxilinx 已提交
973 974 975 976 977 978 979 980 981 982 983
      SSqlExpr* pSubExpr = tscSqlExprGet(pSubQueryInfo, k);
      if (pExpr->functionId == pSubExpr->functionId && pExpr->colInfo.colId == pSubExpr->colInfo.colId) {
        pRes->pColumnIndex[i] = (SColumnIndex){.tableIndex = tableIndexOfSub, .columnIndex = k};
        break;
      }
    }
  }
}

void tscJoinQueryCallback(void* param, TAOS_RES* tres, int code) {
  SSqlObj* pSql = (SSqlObj*)tres;
H
hjxilinx 已提交
984
  
985
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
hjxilinx 已提交
986 987
  
  // There is only one subquery and table for each subquery.
H
hjxilinx 已提交
988
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
H
hjxilinx 已提交
989 990
  assert(pQueryInfo->numOfTables == 1 && pSql->cmd.numOfClause == 1);
  
991
  if (!TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_SEC_STAGE)) {
H
hjxilinx 已提交
992 993
    if (code != TSDB_CODE_SUCCESS) {  // direct call joinRetrieveCallback and set the error code
      joinRetrieveCallback(param, pSql, code);
H
hjxilinx 已提交
994
    } else {  // first stage query, continue to retrieve compressed time stamp data
H
hjxilinx 已提交
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
      pSql->fp = joinRetrieveCallback;
      pSql->cmd.command = TSDB_SQL_FETCH;
      tscProcessSql(pSql);
    }

  } else {  // second stage join subquery
    SSqlObj* pParentSql = pSupporter->pObj;

    if (pSupporter->pState->code != TSDB_CODE_SUCCESS) {
      tscError("%p abort query due to other subquery failure. code:%d, global code:%d", pSql, code,
               pSupporter->pState->code);
      quitAllSubquery(pParentSql, pSupporter);

      return;
    }

    if (code != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1012
      tscError("%p sub query failed, code:%s, set global code:%s, index:%d", pSql, tstrerror(code), tstrerror(code),
H
hjxilinx 已提交
1013
               pSupporter->subqueryIndex);
H
hjxilinx 已提交
1014 1015
      
      pSupporter->pState->code = code;
H
hjxilinx 已提交
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
      quitAllSubquery(pParentSql, pSupporter);
    } else {
      int32_t numOfTotal = pSupporter->pState->numOfTotal;
      int32_t finished = atomic_add_fetch_32(&pSupporter->pState->numOfCompleted, 1);
      
      if (finished >= numOfTotal) {
        assert(finished == numOfTotal);
        
        tscSetupOutputColumnIndex(pParentSql);
        STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);

        /**
H
hjxilinx 已提交
1028
         * if the query is a continue query (vgroupIndex > 0 for projection query) for next vnode, do the retrieval of
H
hjxilinx 已提交
1029 1030
         * data instead of returning to its invoker
         */
H
hjxilinx 已提交
1031
        if (pTableMetaInfo->vgroupIndex > 0 && tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0)) {
H
hjxilinx 已提交
1032 1033 1034 1035 1036 1037
          pSupporter->pState->numOfCompleted = 0;  // reset the record value

          pSql->fp = joinRetrieveCallback;  // continue retrieve data
          pSql->cmd.command = TSDB_SQL_FETCH;
          tscProcessSql(pSql);
        } else {  // first retrieve from vnode during the secondary stage sub-query
H
hjxilinx 已提交
1038 1039 1040
          // set the command flag must be after the semaphore been correctly set.
          if (pParentSql->res.code == TSDB_CODE_SUCCESS) {
            (*pParentSql->fp)(pParentSql->param, pParentSql, 0);
H
hjxilinx 已提交
1041
          } else {
H
hjxilinx 已提交
1042
            tscQueueAsyncRes(pParentSql);
H
hjxilinx 已提交
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
          }
        }
      }
    }
  }
}

/////////////////////////////////////////////////////////////////////////////////////////
static void tscRetrieveDataRes(void *param, TAOS_RES *tres, int code);

static SSqlObj *tscCreateSqlObjForSubquery(SSqlObj *pSql, SRetrieveSupport *trsupport, SSqlObj *prevSqlObj);

// todo merge with callback
1056
int32_t tscLaunchJoinSubquery(SSqlObj *pSql, int16_t tableIndex, SJoinSupporter *pSupporter) {
H
hjxilinx 已提交
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  
  pSql->res.qhandle = 0x1;
  pSql->res.numOfRows = 0;
  
  if (pSql->pSubs == NULL) {
    pSql->pSubs = calloc(pSupporter->pState->numOfTotal, POINTER_BYTES);
    if (pSql->pSubs == NULL) {
      return TSDB_CODE_CLI_OUT_OF_MEMORY;
    }
  }
  
1070
  SSqlObj *pNew = createSubqueryObj(pSql, tableIndex, tscJoinQueryCallback, pSupporter, TSDB_SQL_SELECT, NULL);
H
hjxilinx 已提交
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
  if (pNew == NULL) {
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
  
  pSql->pSubs[pSql->numOfSubs++] = pNew;
  assert(pSql->numOfSubs <= pSupporter->pState->numOfTotal);
  
  if (QUERY_IS_JOIN_QUERY(pQueryInfo->type)) {
    addGroupInfoForSubquery(pSql, pNew, 0, tableIndex);
    
    // refactor as one method
    SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    assert(pNewQueryInfo != NULL);
    
1085 1086 1087 1088 1089 1090 1091
    // update the table index
    size_t num = taosArrayGetSize(pNewQueryInfo->colList);
    for (int32_t i = 0; i < num; ++i) {
      SColumn* pCol = taosArrayGetP(pNewQueryInfo->colList, i);
      pCol->colIndex.tableIndex = 0;
    }
    
H
hjxilinx 已提交
1092 1093 1094 1095 1096 1097 1098
    pSupporter->colList = pNewQueryInfo->colList;
    pNewQueryInfo->colList = NULL;
    
    pSupporter->exprList = pNewQueryInfo->exprList;
    pNewQueryInfo->exprList = NULL;
    
    pSupporter->fieldsInfo = pNewQueryInfo->fieldsInfo;
H
hjxilinx 已提交
1099
  
H
hjxilinx 已提交
1100 1101
    // this data needs to be transfer to support struct
    memset(&pNewQueryInfo->fieldsInfo, 0, sizeof(SFieldInfo));
H
hjxilinx 已提交
1102
    
H
hjxilinx 已提交
1103 1104
    pSupporter->tagCond = pNewQueryInfo->tagCond;
    memset(&pNewQueryInfo->tagCond, 0, sizeof(STagCond));
H
hjxilinx 已提交
1105 1106 1107 1108 1109 1110 1111 1112 1113
    
    pNew->cmd.numOfCols = 0;
    pNewQueryInfo->intervalTime = 0;
    memset(&pNewQueryInfo->limit, 0, sizeof(SLimitVal));
    
    // backup the data and clear it in the sqlcmd object
    pSupporter->groupbyExpr = pNewQueryInfo->groupbyExpr;
    memset(&pNewQueryInfo->groupbyExpr, 0, sizeof(SSqlGroupbyExpr));
    
H
hjxilinx 已提交
1114
    tscInitQueryInfo(pNewQueryInfo);
H
hjxilinx 已提交
1115 1116
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pNewQueryInfo, 0);
    
1117 1118 1119
    if (UTIL_TABLE_IS_SUPERTABLE(pTableMetaInfo)) { // return the tableId & tag
      SSchema s = {0};
      SColumnIndex index = {0};
H
hjxilinx 已提交
1120
  
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
      size_t numOfTags = taosArrayGetSize(pTableMetaInfo->tagColList);
      for(int32_t i = 0; i < numOfTags; ++i) {
        SColumn* c = taosArrayGetP(pTableMetaInfo->tagColList, i);
        index = (SColumnIndex) {.tableIndex = 0, .columnIndex = c->colIndex.columnIndex};
        
        SSchema* pTagSchema = tscGetTableTagSchema(pTableMetaInfo->pTableMeta);
        s = pTagSchema[c->colIndex.columnIndex];
        
        int16_t bytes = 0;
        int16_t type = 0;
        int16_t inter = 0;
        
        getResultDataInfo(s.type, s.bytes, TSDB_FUNC_TID_TAG, 0, &type, &bytes, &inter, 0, 0);
        
        s.type = type;
        s.bytes = bytes;
        pSupporter->tagSize = s.bytes;
H
hjxilinx 已提交
1138
      }
1139
  
1140 1141 1142 1143
      // set get tags query type
      TSDB_QUERY_SET_TYPE(pNewQueryInfo->type, TSDB_QUERY_TYPE_TAG_FILTER_QUERY);
      tscAddSpecialColumnForSelect(pNewQueryInfo, 0, TSDB_FUNC_TID_TAG, &index, &s, TSDB_COL_TAG);
      size_t numOfCols = taosArrayGetSize(pNewQueryInfo->colList);
1144
  
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
      tscTrace(
          "%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%d, transfer to tid_tag query to retrieve (tableId, tags), "
          "exprInfo:%d, colList:%d, fieldsInfo:%d, name:%s",
          pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
          numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, pNewQueryInfo->pTableMetaInfo[0]->name);
      
    } else {
      SSchema      colSchema = {.type = TSDB_DATA_TYPE_BINARY, .bytes = 1};
      SColumnIndex index = {0, PRIMARYKEY_TIMESTAMP_COL_INDEX};
      tscAddSpecialColumnForSelect(pNewQueryInfo, 0, TSDB_FUNC_TS_COMP, &index, &colSchema, TSDB_COL_NORMAL);

      // set the tags value for ts_comp function
      SSqlExpr *pExpr = tscSqlExprGet(pNewQueryInfo, 0);

      int16_t tagColIndex = tscGetJoinTagColIndexByUid(&pSupporter->tagCond, pTableMetaInfo->pTableMeta->uid);

      pExpr->param->i64Key = tagColIndex;
      pExpr->numOfParams = 1;

      // add the filter tag column
      if (pSupporter->colList != NULL) {
        size_t s = taosArrayGetSize(pSupporter->colList);

        for (int32_t i = 0; i < s; ++i) {
          SColumn *pCol = taosArrayGetP(pSupporter->colList, i);

          if (pCol->numOfFilters > 0) {  // copy to the pNew->cmd.colList if it is filtered.
            SColumn *p = tscColumnClone(pCol);
            taosArrayPush(pNewQueryInfo->colList, &p);
          }
        }
      }

      size_t numOfCols = taosArrayGetSize(pNewQueryInfo->colList);

      tscTrace(
          "%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%d, transfer to ts_comp query to retrieve timestamps, "
          "exprInfo:%d, colList:%d, fieldsInfo:%d, name:%s",
          pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
          numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, pNewQueryInfo->pTableMetaInfo[0]->name);
    }
H
hjxilinx 已提交
1186
  } else {
H
hjxilinx 已提交
1187
    assert(0);
H
hjxilinx 已提交
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202
    SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    pNewQueryInfo->type |= TSDB_QUERY_TYPE_SUBQUERY;
  }

  return tscProcessSql(pNew);
}

int32_t tscHandleMasterJoinQuery(SSqlObj* pSql) {
  SSqlCmd* pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  assert((pQueryInfo->type & TSDB_QUERY_TYPE_SUBQUERY) == 0);
  
  SSubqueryState *pState = calloc(1, sizeof(SSubqueryState));
  pState->numOfTotal = pQueryInfo->numOfTables;
  
H
hjxilinx 已提交
1203
  tscTrace("%p start launch subquery, total:%d", pSql, pQueryInfo->numOfTables);
H
hjxilinx 已提交
1204
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
1205
    SJoinSupporter *pSupporter = tscCreateJoinSupporter(pSql, pState, i);
H
hjxilinx 已提交
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
    
    if (pSupporter == NULL) {  // failed to create support struct, abort current query
      tscError("%p tableIndex:%d, failed to allocate join support object, abort further query", pSql, i);
      pState->numOfCompleted = pQueryInfo->numOfTables - i - 1;
      pSql->res.code = TSDB_CODE_CLI_OUT_OF_MEMORY;
      
      return pSql->res.code;
    }
    
    int32_t code = tscLaunchJoinSubquery(pSql, i, pSupporter);
    if (code != TSDB_CODE_SUCCESS) {  // failed to create subquery object, quit query
      tscDestroyJoinSupporter(pSupporter);
      pSql->res.code = TSDB_CODE_CLI_OUT_OF_MEMORY;
      
      break;
    }
  }
  
H
hjxilinx 已提交
1224
  pSql->cmd.command = (pSql->numOfSubs <= 0)? TSDB_SQL_RETRIEVE_EMPTY_RESULT:TSDB_SQL_METRIC_JOIN_RETRIEVE;
H
hjxilinx 已提交
1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
  
  return TSDB_CODE_SUCCESS;
}

static void doCleanupSubqueries(SSqlObj *pSql, int32_t numOfSubs, SSubqueryState* pState) {
  assert(numOfSubs <= pSql->numOfSubs && numOfSubs >= 0 && pState != NULL);
  
  for(int32_t i = 0; i < numOfSubs; ++i) {
    SSqlObj* pSub = pSql->pSubs[i];
    assert(pSub != NULL);
    
    SRetrieveSupport* pSupport = pSub->param;
    
    tfree(pSupport->localBuffer);
    
    pthread_mutex_unlock(&pSupport->queryMutex);
    pthread_mutex_destroy(&pSupport->queryMutex);
    
    tfree(pSupport);
    
    tscFreeSqlObj(pSub);
  }
  
  free(pState);
}

int32_t tscHandleMasterSTableQuery(SSqlObj *pSql) {
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;
  
  // pRes->code check only serves in launching metric sub-queries
  if (pRes->code == TSDB_CODE_QUERY_CANCELLED) {
H
hjxilinx 已提交
1257
    pCmd->command = TSDB_SQL_RETRIEVE_LOCALMERGE;  // enable the abort of kill super table function.
H
hjxilinx 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266
    return pRes->code;
  }
  
  tExtMemBuffer **  pMemoryBuf = NULL;
  tOrderDescriptor *pDesc = NULL;
  SColumnModel *    pModel = NULL;
  
  pRes->qhandle = 1;  // hack the qhandle check
  
1267
  const uint32_t nBufferSize = (1u << 16);  // 64KB
H
hjxilinx 已提交
1268 1269 1270
  
  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
1271
  
H
hjxilinx 已提交
1272
  pSql->numOfSubs = pTableMetaInfo->vgroupList->numOfVgroups;
1273
  assert(pSql->numOfSubs > 0);
H
hjxilinx 已提交
1274 1275 1276 1277
  
  int32_t ret = tscLocalReducerEnvCreate(pSql, &pMemoryBuf, &pDesc, &pModel, nBufferSize);
  if (ret != 0) {
    pRes->code = TSDB_CODE_CLI_OUT_OF_MEMORY;
H
hjxilinx 已提交
1278 1279
    tscQueueAsyncRes(pSql);
    return ret;
H
hjxilinx 已提交
1280 1281
  }
  
1282
  pSql->pSubs = calloc(pSql->numOfSubs, POINTER_BYTES);
H
hjxilinx 已提交
1283
  
1284
  tscTrace("%p retrieved query data from %d vnode(s)", pSql, pSql->numOfSubs);
H
hjxilinx 已提交
1285
  SSubqueryState *pState = calloc(1, sizeof(SSubqueryState));
1286
  pState->numOfTotal = pSql->numOfSubs;
H
hjxilinx 已提交
1287 1288 1289
  pRes->code = TSDB_CODE_SUCCESS;
  
  int32_t i = 0;
1290
  for (; i < pSql->numOfSubs; ++i) {
H
hjxilinx 已提交
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    SRetrieveSupport *trs = (SRetrieveSupport *)calloc(1, sizeof(SRetrieveSupport));
    if (trs == NULL) {
      tscError("%p failed to malloc buffer for SRetrieveSupport, orderOfSub:%d, reason:%s", pSql, i, strerror(errno));
      break;
    }
    
    trs->pExtMemBuffer = pMemoryBuf;
    trs->pOrderDescriptor = pDesc;
    trs->pState = pState;
    
    trs->localBuffer = (tFilePage *)calloc(1, nBufferSize + sizeof(tFilePage));
    if (trs->localBuffer == NULL) {
      tscError("%p failed to malloc buffer for local buffer, orderOfSub:%d, reason:%s", pSql, i, strerror(errno));
      tfree(trs);
      break;
    }
    
    trs->subqueryIndex = i;
    trs->pParentSqlObj = pSql;
    trs->pFinalColModel = pModel;
    
H
hjxilinx 已提交
1312 1313 1314
    pthread_mutexattr_t mutexattr;
    memset(&mutexattr, 0, sizeof(pthread_mutexattr_t));
    
H
hjxilinx 已提交
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
    pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
    pthread_mutex_init(&trs->queryMutex, &mutexattr);
    pthread_mutexattr_destroy(&mutexattr);
    
    SSqlObj *pNew = tscCreateSqlObjForSubquery(pSql, trs, NULL);
    if (pNew == NULL) {
      tscError("%p failed to malloc buffer for subObj, orderOfSub:%d, reason:%s", pSql, i, strerror(errno));
      tfree(trs->localBuffer);
      tfree(trs);
      break;
    }
    
    // todo handle multi-vnode situation
    if (pQueryInfo->tsBuf) {
      SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
      pNewQueryInfo->tsBuf = tsBufClone(pQueryInfo->tsBuf);
    }
    
    tscTrace("%p sub:%p create subquery success. orderOfSub:%d", pSql, pNew, trs->subqueryIndex);
  }
  
1336
  if (i < pSql->numOfSubs) {
H
hjxilinx 已提交
1337 1338 1339
    tscError("%p failed to prepare subquery structure and launch subqueries", pSql);
    pRes->code = TSDB_CODE_CLI_OUT_OF_MEMORY;
    
1340
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pSql->numOfSubs);
H
hjxilinx 已提交
1341 1342 1343 1344 1345
    doCleanupSubqueries(pSql, i, pState);
    return pRes->code;   // free all allocated resource
  }
  
  if (pRes->code == TSDB_CODE_QUERY_CANCELLED) {
1346
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pSql->numOfSubs);
H
hjxilinx 已提交
1347 1348 1349 1350
    doCleanupSubqueries(pSql, i, pState);
    return pRes->code;
  }
  
1351
  for(int32_t j = 0; j < pSql->numOfSubs; ++j) {
H
hjxilinx 已提交
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376
    SSqlObj* pSub = pSql->pSubs[j];
    SRetrieveSupport* pSupport = pSub->param;
    
    tscTrace("%p sub:%p launch subquery, orderOfSub:%d.", pSql, pSub, pSupport->subqueryIndex);
    tscProcessSql(pSub);
  }
  
  return TSDB_CODE_SUCCESS;
}

static void tscFreeSubSqlObj(SRetrieveSupport *trsupport, SSqlObj *pSql) {
  tscTrace("%p start to free subquery result", pSql);
  
  if (pSql->res.code == TSDB_CODE_SUCCESS) {
    taos_free_result(pSql);
  }
  
  tfree(trsupport->localBuffer);
  
  pthread_mutex_unlock(&trsupport->queryMutex);
  pthread_mutex_destroy(&trsupport->queryMutex);
  
  tfree(trsupport);
}

1377
static void tscRetrieveFromDnodeCallBack(void *param, TAOS_RES *tres, int numOfRows);
1378
static void tscHandleSubqueryError(SRetrieveSupport *trsupport, SSqlObj *pSql, int numOfRows);
H
hjxilinx 已提交
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389

static void tscAbortFurtherRetryRetrieval(SRetrieveSupport *trsupport, TAOS_RES *tres, int32_t errCode) {
// set no disk space error info
#ifdef WINDOWS
  LPVOID lpMsgBuf;
  FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
                GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),  // Default language
                (LPTSTR)&lpMsgBuf, 0, NULL);
  tscError("sub:%p failed to flush data to disk:reason:%s", tres, lpMsgBuf);
  LocalFree(lpMsgBuf);
#else
H
hjxilinx 已提交
1390
  tscError("sub:%p failed to flush data to disk:reason:%s", tres, strerror(errno));
H
hjxilinx 已提交
1391 1392 1393 1394 1395 1396 1397
#endif
  
  trsupport->pState->code = -errCode;
  trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
  
  pthread_mutex_unlock(&trsupport->queryMutex);
  
1398
  tscHandleSubqueryError(trsupport, tres, trsupport->pState->code);
H
hjxilinx 已提交
1399 1400
}

1401
void tscHandleSubqueryError(SRetrieveSupport *trsupport, SSqlObj *pSql, int numOfRows) {
H
hjxilinx 已提交
1402 1403 1404 1405 1406 1407 1408 1409
  SSqlObj *pPObj = trsupport->pParentSqlObj;
  int32_t  subqueryIndex = trsupport->subqueryIndex;
  
  assert(pSql != NULL);
  SSubqueryState* pState = trsupport->pState;
  assert(pState->numOfCompleted < pState->numOfTotal && pState->numOfCompleted >= 0 &&
      pPObj->numOfSubs == pState->numOfTotal);
  
1410
  // retrieved in subquery failed. OR query cancelled in retrieve phase.
H
hjxilinx 已提交
1411
  if (pState->code == TSDB_CODE_SUCCESS && pPObj->res.code != TSDB_CODE_SUCCESS) {
1412
    pState->code = pPObj->res.code;
H
hjxilinx 已提交
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439
    
    /*
     * kill current sub-query connection, which may retrieve data from vnodes;
     * Here we get: pPObj->res.code == TSDB_CODE_QUERY_CANCELLED
     */
    pSql->res.numOfRows = 0;
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;  // disable retry efforts
    tscTrace("%p query is cancelled, sub:%p, orderOfSub:%d abort retrieve, code:%d", trsupport->pParentSqlObj, pSql,
             subqueryIndex, pState->code);
  }
  
  if (numOfRows >= 0) {  // current query is successful, but other sub query failed, still abort current query.
    tscTrace("%p sub:%p retrieve numOfRows:%d,orderOfSub:%d", pPObj, pSql, numOfRows, subqueryIndex);
    tscError("%p sub:%p abort further retrieval due to other queries failure,orderOfSub:%d,code:%d", pPObj, pSql,
             subqueryIndex, pState->code);
  } else {
    if (trsupport->numOfRetry++ < MAX_NUM_OF_SUBQUERY_RETRY && pState->code == TSDB_CODE_SUCCESS) {
      /*
       * current query failed, and the retry count is less than the available
       * count, retry query clear previous retrieved data, then launch a new sub query
       */
      tExtMemBufferClear(trsupport->pExtMemBuffer[subqueryIndex]);
      
      // clear local saved number of results
      trsupport->localBuffer->numOfElems = 0;
      pthread_mutex_unlock(&trsupport->queryMutex);
      
H
hjxilinx 已提交
1440 1441
      tscTrace("%p sub:%p retrieve failed, code:%s, orderOfSub:%d, retry:%d", trsupport->pParentSqlObj, pSql,
          tstrerror(numOfRows), subqueryIndex, trsupport->numOfRetry);
H
hjxilinx 已提交
1442 1443 1444
      
      SSqlObj *pNew = tscCreateSqlObjForSubquery(trsupport->pParentSqlObj, trsupport, pSql);
      if (pNew == NULL) {
1445
        tscError("%p sub:%p failed to create new subquery sqlObj due to out of memory, abort retry",
H
hjxilinx 已提交
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
                 trsupport->pParentSqlObj, pSql);
        
        pState->code = TSDB_CODE_CLI_OUT_OF_MEMORY;
        trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
        return;
      }
      
      tscProcessSql(pNew);
      return;
    } else {  // reach the maximum retry count, abort
      atomic_val_compare_exchange_32(&pState->code, TSDB_CODE_SUCCESS, numOfRows);
H
hjxilinx 已提交
1457 1458
      tscError("%p sub:%p retrieve failed,code:%s,orderOfSub:%d failed.no more retry,set global code:%d", pPObj, pSql,
               numOfRows, subqueryIndex, tstrerror(pState->code));
H
hjxilinx 已提交
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471
    }
  }
  
  int32_t numOfTotal = pState->numOfTotal;
  
  int32_t finished = atomic_add_fetch_32(&pState->numOfCompleted, 1);
  if (finished < numOfTotal) {
    tscTrace("%p sub:%p orderOfSub:%d freed, finished subqueries:%d", pPObj, pSql, trsupport->subqueryIndex, finished);
    return tscFreeSubSqlObj(trsupport, pSql);
  }
  
  // all subqueries are failed
  tscError("%p retrieve from %d vnode(s) completed,code:%d.FAILED.", pPObj, pState->numOfTotal, pState->code);
1472
  pPObj->res.code = pState->code;
H
hjxilinx 已提交
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
  
  // release allocated resource
  tscLocalReducerEnvDestroy(trsupport->pExtMemBuffer, trsupport->pOrderDescriptor, trsupport->pFinalColModel,
                            pState->numOfTotal);
  
  tfree(trsupport->pState);
  tscFreeSubSqlObj(trsupport, pSql);
  
  // in case of second stage join subquery, invoke its callback function instead of regular QueueAsyncRes
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pPObj->cmd, 0);
  
  if ((pQueryInfo->type & TSDB_QUERY_TYPE_JOIN_SEC_STAGE) == TSDB_QUERY_TYPE_JOIN_SEC_STAGE) {
    (*pPObj->fp)(pPObj->param, pPObj, pPObj->res.code);
  } else {  // regular super table query
    if (pPObj->res.code != TSDB_CODE_SUCCESS) {
      tscQueueAsyncRes(pPObj);
    }
  }
}

1493 1494 1495 1496 1497 1498 1499 1500
static void tscAllDataRetrievedFromDnode(SRetrieveSupport *trsupport, SSqlObj* pSql) {
  int32_t           idx = trsupport->subqueryIndex;
  SSqlObj *         pPObj = trsupport->pParentSqlObj;
  tOrderDescriptor *pDesc = trsupport->pOrderDescriptor;
  
  SSubqueryState* pState = trsupport->pState;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
  
1501 1502
  STableMetaInfo* pTableMetaInfo = pQueryInfo->pTableMetaInfo[0];
  
1503
  // data in from current vnode is stored in cache and disk
1504 1505
  uint32_t numOfRowsFromSubquery = trsupport->pExtMemBuffer[idx]->numOfTotalElems + trsupport->localBuffer->numOfElems;
    tscTrace("%p sub:%p all data retrieved from ip:%u,vgId:%d, numOfRows:%d, orderOfSub:%d", pPObj, pSql,
J
jtao1735 已提交
1506
        pTableMetaInfo->vgroupList->vgroups[0].ipAddr[0].fqdn, pTableMetaInfo->vgroupList->vgroups[0].vgId,
1507
        numOfRowsFromSubquery, idx);
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
  
  tColModelCompact(pDesc->pColumnModel, trsupport->localBuffer, pDesc->pColumnModel->capacity);

#ifdef _DEBUG_VIEW
  printf("%" PRIu64 " rows data flushed to disk:\n", trsupport->localBuffer->numOfElems);
    SSrcColumnInfo colInfo[256] = {0};
    tscGetSrcColumnInfo(colInfo, pQueryInfo);
    tColModelDisplayEx(pDesc->pColumnModel, trsupport->localBuffer->data, trsupport->localBuffer->numOfElems,
                       trsupport->localBuffer->numOfElems, colInfo);
#endif
  
  if (tsTotalTmpDirGB != 0 && tsAvailTmpDirGB < tsMinimalTmpDirGB) {
    tscError("%p sub:%p client disk space remain %.3f GB, need at least %.3f GB, stop query", pPObj, pSql,
             tsAvailTmpDirGB, tsMinimalTmpDirGB);
    tscAbortFurtherRetryRetrieval(trsupport, pSql, TSDB_CODE_CLI_NO_DISKSPACE);
    return;
  }
  
  // each result for a vnode is ordered as an independant list,
  // then used as an input of loser tree for disk-based merge routine
  int32_t ret = tscFlushTmpBuffer(trsupport->pExtMemBuffer[idx], pDesc, trsupport->localBuffer,
                                  pQueryInfo->groupbyExpr.orderType);
  if (ret != 0) { // set no disk space error info, and abort retry
    return tscAbortFurtherRetryRetrieval(trsupport, pSql, TSDB_CODE_CLI_NO_DISKSPACE);
  }
  
  // keep this value local variable, since the pState variable may be released by other threads, if atomic_add opertion
  // increases the finished value up to pState->numOfTotal value, which means all subqueries are completed.
  // In this case, the comparsion between finished value and released pState->numOfTotal is not safe.
  int32_t numOfTotal = pState->numOfTotal;
  
  int32_t finished = atomic_add_fetch_32(&pState->numOfCompleted, 1);
  if (finished < numOfTotal) {
    tscTrace("%p sub:%p orderOfSub:%d freed, finished subqueries:%d", pPObj, pSql, trsupport->subqueryIndex, finished);
    return tscFreeSubSqlObj(trsupport, pSql);
  }
  
  // all sub-queries are returned, start to local merge process
  pDesc->pColumnModel->capacity = trsupport->pExtMemBuffer[idx]->numOfElemsPerPage;
  
  tscTrace("%p retrieve from %d vnodes completed.final NumOfRows:%d,start to build loser tree", pPObj,
           pState->numOfTotal, pState->numOfRetrievedRows);
  
  SQueryInfo *pPQueryInfo = tscGetQueryInfoDetail(&pPObj->cmd, 0);
  tscClearInterpInfo(pPQueryInfo);
  
  tscCreateLocalReducer(trsupport->pExtMemBuffer, pState->numOfTotal, pDesc, trsupport->pFinalColModel,
                        &pPObj->cmd, &pPObj->res);
  tscTrace("%p build loser tree completed", pPObj);
  
  pPObj->res.precision = pSql->res.precision;
  pPObj->res.numOfRows = 0;
  pPObj->res.row = 0;
  
  // only free once
  tfree(trsupport->pState);
  tscFreeSubSqlObj(trsupport, pSql);
  
  // set the command flag must be after the semaphore been correctly set.
H
hjxilinx 已提交
1567
  pPObj->cmd.command = TSDB_SQL_RETRIEVE_LOCALMERGE;
1568 1569 1570 1571 1572 1573 1574 1575
  if (pPObj->res.code == TSDB_CODE_SUCCESS) {
    (*pPObj->fp)(pPObj->param, pPObj, 0);
  } else {
    tscQueueAsyncRes(pPObj);
  }
}

static void tscRetrieveFromDnodeCallBack(void *param, TAOS_RES *tres, int numOfRows) {
H
hjxilinx 已提交
1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
  SRetrieveSupport *trsupport = (SRetrieveSupport *)param;
  int32_t           idx = trsupport->subqueryIndex;
  SSqlObj *         pPObj = trsupport->pParentSqlObj;
  tOrderDescriptor *pDesc = trsupport->pOrderDescriptor;
  
  SSqlObj *pSql = (SSqlObj *)tres;
  if (pSql == NULL) {  // sql object has been released in error process, return immediately
    tscTrace("%p subquery has been released, idx:%d, abort", pPObj, idx);
    return;
  }
  
  SSubqueryState* pState = trsupport->pState;
  assert(pState->numOfCompleted < pState->numOfTotal && pState->numOfCompleted >= 0 &&
      pPObj->numOfSubs == pState->numOfTotal);
  
  // query process and cancel query process may execute at the same time
  pthread_mutex_lock(&trsupport->queryMutex);
  
  if (numOfRows < 0 || pState->code < 0 || pPObj->res.code != TSDB_CODE_SUCCESS) {
1595
    return tscHandleSubqueryError(trsupport, pSql, numOfRows);
H
hjxilinx 已提交
1596 1597 1598 1599 1600 1601 1602 1603 1604
  }
  
  SSqlRes *   pRes = &pSql->res;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
  
  if (numOfRows > 0) {
    assert(pRes->numOfRows == numOfRows);
    int64_t num = atomic_add_fetch_64(&pState->numOfRetrievedRows, numOfRows);
    
1605 1606
//    tscTrace("%p sub:%p retrieve numOfRows:%d totalNumOfRows:%d from ip:%u,vid:%d,orderOfSub:%d", pPObj, pSql,
//             pRes->numOfRows, pState->numOfRetrievedRows, pSvd->ip, pSvd->vnode, idx);
H
hjxilinx 已提交
1607 1608 1609 1610 1611 1612 1613 1614 1615
    
    if (num > tsMaxNumOfOrderedResults && tscIsProjectionQueryOnSTable(pQueryInfo, 0)) {
      tscError("%p sub:%p num of OrderedRes is too many, max allowed:%" PRId64 " , current:%" PRId64,
               pPObj, pSql, tsMaxNumOfOrderedResults, num);
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_SORTED_RES_TOO_MANY);
      return;
    }

#ifdef _DEBUG_VIEW
1616
    printf("received data from vnode: %"PRIu64" rows\n", pRes->numOfRows);
H
hjxilinx 已提交
1617 1618 1619 1620 1621
    SSrcColumnInfo colInfo[256] = {0};

    tscGetSrcColumnInfo(colInfo, pQueryInfo);
    tColModelDisplayEx(pDesc->pColumnModel, pRes->data, pRes->numOfRows, pRes->numOfRows, colInfo);
#endif
1622
    
H
hjxilinx 已提交
1623 1624 1625 1626 1627 1628 1629 1630 1631
    if (tsTotalTmpDirGB != 0 && tsAvailTmpDirGB < tsMinimalTmpDirGB) {
      tscError("%p sub:%p client disk space remain %.3f GB, need at least %.3f GB, stop query", pPObj, pSql,
               tsAvailTmpDirGB, tsMinimalTmpDirGB);
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_CLI_NO_DISKSPACE);
      return;
    }
    
    int32_t ret = saveToBuffer(trsupport->pExtMemBuffer[idx], pDesc, trsupport->localBuffer, pRes->data,
                               pRes->numOfRows, pQueryInfo->groupbyExpr.orderType);
1632
    if (ret < 0) { // set no disk space error info, and abort retry
H
hjxilinx 已提交
1633
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_CLI_NO_DISKSPACE);
1634
      
1635 1636
    } else if (pRes->completed) {
      tscAllDataRetrievedFromDnode(trsupport, pSql);
1637 1638
      return;
      
1639
    } else { // continue fetch data from dnode
H
hjxilinx 已提交
1640
      pthread_mutex_unlock(&trsupport->queryMutex);
1641
      taos_fetch_rows_a(tres, tscRetrieveFromDnodeCallBack, param);
H
hjxilinx 已提交
1642
    }
1643 1644
    
    pthread_mutex_unlock(&trsupport->queryMutex);
1645 1646
  } else { // all data has been retrieved to client
    tscAllDataRetrievedFromDnode(trsupport, pSql);
H
hjxilinx 已提交
1647 1648 1649 1650 1651 1652
  }
}

static SSqlObj *tscCreateSqlObjForSubquery(SSqlObj *pSql, SRetrieveSupport *trsupport, SSqlObj *prevSqlObj) {
  const int32_t table_index = 0;
  
1653
  SSqlObj *pNew = createSubqueryObj(pSql, table_index, tscRetrieveDataRes, trsupport, TSDB_SQL_SELECT, prevSqlObj);
H
hjxilinx 已提交
1654 1655 1656 1657 1658 1659
  if (pNew != NULL) {  // the sub query of two-stage super table query
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    pQueryInfo->type |= TSDB_QUERY_TYPE_STABLE_SUBQUERY;
    
    assert(pQueryInfo->numOfTables == 1 && pNew->cmd.numOfClause == 1);
    
H
hjxilinx 已提交
1660
    // launch subquery for each vnode, so the subquery index equals to the vgroupIndex.
H
hjxilinx 已提交
1661
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, table_index);
H
hjxilinx 已提交
1662
    pTableMetaInfo->vgroupIndex = trsupport->subqueryIndex;
H
hjxilinx 已提交
1663 1664 1665 1666 1667 1668 1669 1670
    
    pSql->pSubs[trsupport->subqueryIndex] = pNew;
  }
  
  return pNew;
}

void tscRetrieveDataRes(void *param, TAOS_RES *tres, int code) {
1671
  SRetrieveSupport *trsupport = (SRetrieveSupport *) param;
H
hjxilinx 已提交
1672 1673
  
  SSqlObj*  pParentSql = trsupport->pParentSqlObj;
1674
  SSqlObj*  pSql = (SSqlObj *) tres;
H
hjxilinx 已提交
1675
  
1676 1677
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
  assert(pSql->cmd.numOfClause == 1 && pQueryInfo->numOfTables == 1);
H
hjxilinx 已提交
1678
  
1679
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
H
hjxilinx 已提交
1680
  SCMVgroupInfo* pVgroup = &pTableMetaInfo->vgroupList->vgroups[0];
H
hjxilinx 已提交
1681 1682 1683 1684 1685 1686
  
  SSubqueryState* pState = trsupport->pState;
  assert(pState->numOfCompleted < pState->numOfTotal && pState->numOfCompleted >= 0 &&
      pParentSql->numOfSubs == pState->numOfTotal);
  
  if (pParentSql->res.code != TSDB_CODE_SUCCESS || pState->code != TSDB_CODE_SUCCESS) {
1687 1688
    
    // stable query is killed, abort further retry
H
hjxilinx 已提交
1689
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
1690
    
H
hjxilinx 已提交
1691
    if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
1692
      code = pParentSql->res.code;
H
hjxilinx 已提交
1693 1694 1695
    } else {
      code = pState->code;
    }
1696 1697 1698
    
    tscTrace("%p query cancelled or failed, sub:%p, orderOfSub:%d abort, code:%s", pParentSql, pSql,
             trsupport->subqueryIndex, tstrerror(code));
H
hjxilinx 已提交
1699 1700 1701 1702
  }
  
  /*
   * if a query on a vnode is failed, all retrieve operations from vnode that occurs later
1703
   * than this one are actually not necessary, we simply call the tscRetrieveFromDnodeCallBack
H
hjxilinx 已提交
1704 1705
   * function to abort current and remain retrieve process.
   *
1706
   * NOTE: thread safe is required.
H
hjxilinx 已提交
1707 1708 1709
   */
  if (code != TSDB_CODE_SUCCESS) {
    if (trsupport->numOfRetry++ >= MAX_NUM_OF_SUBQUERY_RETRY) {
1710
      tscTrace("%p sub:%p reach the max retry times, set global code:%d", pParentSql, pSql, code);
H
hjxilinx 已提交
1711
      atomic_val_compare_exchange_32(&pState->code, 0, code);
1712
    } else {  // does not reach the maximum retry time, go on
1713
      tscTrace("%p sub:%p failed code:%s, retry:%d", pParentSql, pSql, tstrerror(code), trsupport->numOfRetry);
H
hjxilinx 已提交
1714 1715 1716
      
      SSqlObj *pNew = tscCreateSqlObjForSubquery(pParentSql, trsupport, pSql);
      if (pNew == NULL) {
1717
        tscError("%p sub:%p failed to create new subquery due to out of memory, abort retry, vgId:%d, orderOfSub:%d",
H
hjxilinx 已提交
1718
                 trsupport->pParentSqlObj, pSql, pVgroup->vgId, trsupport->subqueryIndex);
H
hjxilinx 已提交
1719
        
1720
        pState->code = TSDB_CODE_CLI_OUT_OF_MEMORY;
H
hjxilinx 已提交
1721 1722
        trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
      } else {
1723 1724 1725
        SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
        assert(pNewQueryInfo->pTableMetaInfo[0]->pTableMeta != NULL);
        
H
hjxilinx 已提交
1726 1727 1728 1729 1730 1731
        tscProcessSql(pNew);
        return;
      }
    }
  }
  
1732 1733
  if (pState->code != TSDB_CODE_SUCCESS) {  // at least one peer subquery failed, abort current query
    tscTrace("%p sub:%p query failed,ip:%u,vgId:%d,orderOfSub:%d,global code:%d", pParentSql, pSql,
J
jtao1735 已提交
1734
               pVgroup->ipAddr[0].fqdn, pVgroup->vgId, trsupport->subqueryIndex, pState->code);
1735 1736
  
    tscHandleSubqueryError(param, tres, pState->code);
H
hjxilinx 已提交
1737
  } else {  // success, proceed to retrieve data from dnode
1738
    tscTrace("%p sub:%p query complete, ip:%u, vgId:%d, orderOfSub:%d, retrieve data", trsupport->pParentSqlObj, pSql,
J
jtao1735 已提交
1739
               pVgroup->ipAddr[0].fqdn, pVgroup->vgId, trsupport->subqueryIndex);
H
hjxilinx 已提交
1740
    
1741 1742 1743 1744 1745 1746
    if (pSql->res.qhandle == 0) { // qhandle is NULL, code is TSDB_CODE_SUCCESS means no results generated from this vnode
      tscRetrieveFromDnodeCallBack(param, pSql, 0);
    } else {
      taos_fetch_rows_a(tres, tscRetrieveFromDnodeCallBack, param);
    }
    
H
hjxilinx 已提交
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
  }
}

static void multiVnodeInsertMerge(void* param, TAOS_RES* tres, int numOfRows) {
  SInsertSupporter *pSupporter = (SInsertSupporter *)param;
  SSqlObj* pParentObj = pSupporter->pSql;
  SSqlCmd* pParentCmd = &pParentObj->cmd;
  
  SSubqueryState* pState = pSupporter->pState;
  int32_t total = pState->numOfTotal;
  
  // increase the total inserted rows
  if (numOfRows > 0) {
    pParentObj->res.numOfRows += numOfRows;
  }
  
  int32_t completed = atomic_add_fetch_32(&pState->numOfCompleted, 1);
  if (completed < total) {
    return;
  }
  
  tscTrace("%p Async insertion completed, total inserted:%d", pParentObj, pParentObj->res.numOfRows);
  
1770 1771 1772
  tfree(pState);
  tfree(pSupporter);
  
H
hjxilinx 已提交
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
  // release data block data
  pParentCmd->pDataBlocks = tscDestroyBlockArrayList(pParentCmd->pDataBlocks);
  
  // restore user defined fp
  pParentObj->fp = pParentObj->fetchFp;
  
  // all data has been sent to vnode, call user function
  (*pParentObj->fp)(pParentObj->param, tres, numOfRows);
}

int32_t tscHandleMultivnodeInsert(SSqlObj *pSql) {
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;
  
  pRes->qhandle = 1;  // hack the qhandle check
  SDataBlockList *pDataBlocks = pCmd->pDataBlocks;
  
  pSql->pSubs = calloc(pDataBlocks->nSize, POINTER_BYTES);
  pSql->numOfSubs = pDataBlocks->nSize;
  assert(pDataBlocks->nSize > 0);
  
  tscTrace("%p submit data to %d vnode(s)", pSql, pDataBlocks->nSize);
  SSubqueryState *pState = calloc(1, sizeof(SSubqueryState));
  pState->numOfTotal = pSql->numOfSubs;
  
  pRes->code = TSDB_CODE_SUCCESS;
  
  int32_t i = 0;
  for (; i < pSql->numOfSubs; ++i) {
    SInsertSupporter* pSupporter = calloc(1, sizeof(SInsertSupporter));
    pSupporter->pSql = pSql;
    pSupporter->pState = pState;
    
1806
    SSqlObj *pNew = createSubqueryObj(pSql, 0, multiVnodeInsertMerge, pSupporter, TSDB_SQL_INSERT, NULL);
H
hjxilinx 已提交
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
    if (pNew == NULL) {
      tscError("%p failed to malloc buffer for subObj, orderOfSub:%d, reason:%s", pSql, i, strerror(errno));
      break;
    }
    
    pSql->pSubs[i] = pNew;
    tscTrace("%p sub:%p create subObj success. orderOfSub:%d", pSql, pNew, i);
  }
  
  if (i < pSql->numOfSubs) {
    tscError("%p failed to prepare subObj structure and launch sub-insertion", pSql);
    pRes->code = TSDB_CODE_CLI_OUT_OF_MEMORY;
    return pRes->code;  // free all allocated resource
  }
  
  for (int32_t j = 0; j < pSql->numOfSubs; ++j) {
    SSqlObj *pSub = pSql->pSubs[j];
    int32_t code = tscCopyDataBlockToPayload(pSub, pDataBlocks->pData[j]);
    
    if (code != TSDB_CODE_SUCCESS) {
      tscTrace("%p prepare submit data block failed in async insertion, vnodeIdx:%d, total:%d, code:%d", pSql, j,
               pDataBlocks->nSize, code);
    }
    
    tscTrace("%p sub:%p launch sub insert, orderOfSub:%d", pSql, pSub, j);
    tscProcessSql(pSub);
  }
  
  return TSDB_CODE_SUCCESS;
}
H
hjxilinx 已提交
1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857

void tscBuildResFromSubqueries(SSqlObj *pSql) {
  SSqlRes *pRes = &pSql->res;
  
  if (pRes->code != TSDB_CODE_SUCCESS) {
    tscQueueAsyncRes(pSql);
    return;
  }
  
  while (1) {
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, pSql->cmd.clauseIndex);
    size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
    
    if (pRes->tsrow == NULL) {
      pRes->tsrow = calloc(numOfExprs, POINTER_BYTES);
    }
    
    bool success = false;
    
    int32_t numOfTableHasRes = 0;
    for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
H
hjxilinx 已提交
1858
      if (pSql->pSubs[i] != NULL) {
H
hjxilinx 已提交
1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
        numOfTableHasRes++;
      }
    }
    
    if (numOfTableHasRes >= 2) {  // do merge result
      success = (doSetResultRowData(pSql->pSubs[0], false) != NULL) && (doSetResultRowData(pSql->pSubs[1], false) != NULL);
    } else {  // only one subquery
      SSqlObj *pSub = pSql->pSubs[0];
      if (pSub == NULL) {
        pSub = pSql->pSubs[1];
      }
      
      success = (doSetResultRowData(pSub, false) != NULL);
    }
    
    if (success) {  // current row of final output has been built, return to app
      for (int32_t i = 0; i < numOfExprs; ++i) {
        SColumnIndex* pIndex = &pRes->pColumnIndex[i];
        SSqlRes *pRes1 = &pSql->pSubs[pIndex->tableIndex]->res;
        pRes->tsrow[i] = pRes1->tsrow[pIndex->columnIndex];
      }
      
      pRes->numOfTotalInCurrentClause++;
      break;
    } else {  // continue retrieve data from vnode
      if (!tscHashRemainDataInSubqueryResultSet(pSql)) {
        tscTrace("%p at least one subquery exhausted, free all other %d subqueries", pSql, pSql->numOfSubs - 1);
        SSubqueryState *pState = NULL;
        
        // free all sub sqlobj
        for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
          SSqlObj *pChildObj = pSql->pSubs[i];
          if (pChildObj == NULL) {
            continue;
          }
          
1895
          SJoinSupporter *pSupporter = (SJoinSupporter *)pChildObj->param;
H
hjxilinx 已提交
1896 1897 1898 1899 1900 1901 1902
          pState = pSupporter->pState;
          
          tscDestroyJoinSupporter(pChildObj->param);
          taos_free_result(pChildObj);
        }
        
        free(pState);
H
hjxilinx 已提交
1903 1904 1905
        
        pRes->completed = true; // set query completed
        sem_post(&pSql->rspSem);
H
hjxilinx 已提交
1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
        return;
      }
      
      tscFetchDatablockFromSubquery(pSql);
      if (pRes->code != TSDB_CODE_SUCCESS) {
        return;
      }
    }
  }
  
  if (pSql->res.code == TSDB_CODE_SUCCESS) {
    (*pSql->fp)(pSql->param, pSql, 0);
  } else {
    tscQueueAsyncRes(pSql);
  }
}

static void transferNcharData(SSqlObj *pSql, int32_t columnIndex, TAOS_FIELD *pField) {
  SSqlRes *pRes = &pSql->res;
  
  if (isNull(pRes->tsrow[columnIndex], pField->type)) {
    pRes->tsrow[columnIndex] = NULL;
  } else if (pField->type == TSDB_DATA_TYPE_NCHAR) {
    // convert unicode to native code in a temporary buffer extra one byte for terminated symbol
    if (pRes->buffer[columnIndex] == NULL) {
      pRes->buffer[columnIndex] = malloc(pField->bytes + TSDB_NCHAR_SIZE);
    }
    
    /* string terminated char for binary data*/
    memset(pRes->buffer[columnIndex], 0, pField->bytes + TSDB_NCHAR_SIZE);
    
1937
    if (taosUcs4ToMbs(pRes->tsrow[columnIndex], pField->bytes - VARSTR_HEADER_SIZE, pRes->buffer[columnIndex])) {
H
hjxilinx 已提交
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969
      pRes->tsrow[columnIndex] = pRes->buffer[columnIndex];
    } else {
      tscError("%p charset:%s to %s. val:%ls convert failed.", pSql, DEFAULT_UNICODE_ENCODEC, tsCharset, pRes->tsrow);
      pRes->tsrow[columnIndex] = NULL;
    }
  }
}

void **doSetResultRowData(SSqlObj *pSql, bool finalResult) {
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
  
  assert(pRes->row >= 0 && pRes->row <= pRes->numOfRows);
  
  if(pCmd->command == TSDB_SQL_METRIC_JOIN_RETRIEVE) {
    if (pRes->completed) {
      tfree(pRes->tsrow);
    }

    return pRes->tsrow;
  }
  
  if (pRes->row >= pRes->numOfRows) {  // all the results has returned to invoker
    tfree(pRes->tsrow);
    return pRes->tsrow;
  }
  
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  
  for (int i = 0; i < tscNumOfFields(pQueryInfo); ++i) {
    SFieldSupInfo* pSup = tscFieldInfoGetSupp(&pQueryInfo->fieldsInfo, i);
    if (pSup->pSqlExpr != NULL) {
H
hjxilinx 已提交
1970
      pRes->tsrow[i] = tscGetResultColumnChr(pRes, pQueryInfo, i, pSup->pSqlExpr->resBytes);
H
hjxilinx 已提交
1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
    }
    
    // primary key column cannot be null in interval query, no need to check
    if (i == 0 && pQueryInfo->intervalTime > 0) {
      continue;
    }
    
    TAOS_FIELD *pField = tscFieldInfoGetField(&pQueryInfo->fieldsInfo, i);
    transferNcharData(pSql, i, pField);
    
    // calculate the result from several other columns
    if (pSup->pArithExprInfo != NULL) {
//      SArithmeticSupport *sas = (SArithmeticSupport *)calloc(1, sizeof(SArithmeticSupport));
//      sas->offset = 0;
//      sas-> = pQueryInfo->fieldsInfo.pExpr[i];
//
//      sas->numOfCols = sas->pExpr->binExprInfo.numOfCols;
//
//      if (pRes->buffer[i] == NULL) {
//        pRes->buffer[i] = malloc(tscFieldInfoGetField(pQueryInfo, i)->bytes);
//      }
//
//      for(int32_t k = 0; k < sas->numOfCols; ++k) {
//        int32_t columnIndex = sas->pExpr->binExprInfo.pReqColumns[k].colIdxInBuf;
//        SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, columnIndex);
//
//        sas->elemSize[k] = pExpr->resBytes;
//        sas->data[k] = (pRes->data + pRes->numOfRows* pExpr->offset) + pRes->row*pExpr->resBytes;
//      }
//
//      tSQLBinaryExprCalcTraverse(sas->pExpr->binExprInfo.pBinExpr, 1, pRes->buffer[i], sas, TSQL_SO_ASC, getArithemicInputSrc);
//      pRes->tsrow[i] = pRes->buffer[i];
//
//      free(sas); //todo optimization
    }
  }
  
  pRes->row++;  // index increase one-step
  return pRes->tsrow;
}

static bool tscHashRemainDataInSubqueryResultSet(SSqlObj *pSql) {
  bool     hasData = true;
  SSqlCmd *pCmd = &pSql->cmd;
  
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0)) {
    bool allSubqueryExhausted = true;
    
    for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
      if (pSql->pSubs[i] == NULL) {
        continue;
      }
      
      SSqlRes *pRes1 = &pSql->pSubs[i]->res;
      SSqlCmd *pCmd1 = &pSql->pSubs[i]->cmd;
      
      SQueryInfo *pQueryInfo1 = tscGetQueryInfoDetail(pCmd1, pCmd1->clauseIndex);
      assert(pQueryInfo1->numOfTables == 1);
      
      STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo1, 0);
      
      /*
       * if the global limitation is not reached, and current result has not exhausted, or next more vnodes are
       * available, goes on
       */
      if (pTableMetaInfo->vgroupIndex < pTableMetaInfo->vgroupList->numOfVgroups && pRes1->row < pRes1->numOfRows &&
          (!tscHasReachLimitation(pQueryInfo1, pRes1))) {
        allSubqueryExhausted = false;
        break;
      }
    }
    
    hasData = !allSubqueryExhausted;
  } else {  // otherwise, in case inner join, if any subquery exhausted, query completed.
    for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
      if (pSql->pSubs[i] == 0) {
        continue;
      }
      
      SSqlRes *   pRes1 = &pSql->pSubs[i]->res;
      SQueryInfo *pQueryInfo1 = tscGetQueryInfoDetail(&pSql->pSubs[i]->cmd, 0);
      
      if ((pRes1->row >= pRes1->numOfRows && tscHasReachLimitation(pQueryInfo1, pRes1) &&
          tscProjectionQueryOnTable(pQueryInfo1)) ||
          (pRes1->numOfRows == 0)) {
        hasData = false;
        break;
      }
    }
  }
  
  return hasData;
}