tscSubquery.c 82.8 KB
Newer Older
H
hjxilinx 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
/*
 * 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/>.
 */
H
Hui Li 已提交
15 16
#define _GNU_SOURCE
 
H
Haojun Liao 已提交
17
#include "os.h"
H
hjxilinx 已提交
18

H
Haojun Liao 已提交
19 20
#include "qAst.h"
#include "qTsbuf.h"
H
Haojun Liao 已提交
21
#include "tcompare.h"
S
slguan 已提交
22
#include "tscLog.h"
H
Haojun Liao 已提交
23 24
#include "tscSubquery.h"
#include "tschemautil.h"
25
#include "tsclient.h"
H
hjxilinx 已提交
26 27 28

typedef struct SInsertSupporter {
  SSqlObj*  pSql;
29
  int32_t   index;
H
hjxilinx 已提交
30 31
} SInsertSupporter;

H
hjxilinx 已提交
32
static void freeJoinSubqueryObj(SSqlObj* pSql);
H
Haojun Liao 已提交
33
static bool tscHasRemainDataInSubqueryResultSet(SSqlObj *pSql);
H
hjxilinx 已提交
34

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

H
Haojun Liao 已提交
43 44
static int64_t doTSBlockIntersect(SSqlObj* pSql, SJoinSupporter* pSupporter1, SJoinSupporter* pSupporter2, STimeWindow * win) {
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, pSql->cmd.clauseIndex);
H
hjxilinx 已提交
45

H
Haojun Liao 已提交
46 47 48 49 50
  STSBuf* output1 = tsBufCreate(true, pQueryInfo->order.order);
  STSBuf* output2 = tsBufCreate(true, pQueryInfo->order.order);

  win->skey = INT64_MAX;
  win->ekey = INT64_MIN;
H
hjxilinx 已提交
51 52 53 54 55 56 57 58 59 60

  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;

H
Haojun Liao 已提交
61 62
  TSKEY st = taosGetTimestampUs();

63 64 65 66 67 68
  // no result generated, return directly
  if (pSupporter1->pTSBuf == NULL || pSupporter2->pTSBuf == NULL) {
    tscDebug("%p at least one ts-comp is empty, 0 for secondary query after ts blocks intersecting", pSql);
    return 0;
  }

H
hjxilinx 已提交
69 70 71 72 73 74 75
  tsBufResetPos(pSupporter1->pTSBuf);
  tsBufResetPos(pSupporter2->pTSBuf);

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

76
    tscDebug("%p input1 is empty, 0 for secondary query after ts blocks intersecting", pSql);
H
hjxilinx 已提交
77 78 79 80 81 82 83
    return 0;
  }

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

84
    tscDebug("%p input2 is empty, 0 for secondary query after ts blocks intersecting", pSql);
H
hjxilinx 已提交
85 86 87 88 89 90 91 92 93 94 95
    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
H
Haojun Liao 已提交
96
    tscInfo("%" PRId64 ", tags:%"PRId64" \t %" PRId64 ", tags:%"PRId64, elem1.ts, elem1.tag.i64Key, elem2.ts, elem2.tag.i64Key);
H
hjxilinx 已提交
97 98
#endif

H
Haojun Liao 已提交
99
    int32_t res = tVariantCompare(elem1.tag, elem2.tag);
100
    if (res == -1 || (res == 0 && tsCompare(order, elem1.ts, elem2.ts))) {
H
hjxilinx 已提交
101 102 103 104 105
      if (!tsBufNextPos(pSupporter1->pTSBuf)) {
        break;
      }

      numOfInput1++;
106
    } else if ((res > 0) || (res == 0 && tsCompare(order, elem2.ts, elem1.ts))) {
H
hjxilinx 已提交
107 108 109 110 111 112 113 114 115 116
      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.
       */
117
      if (pLimit->offset == 0 || pQueryInfo->interval.interval > 0 || QUERY_IS_STABLE_QUERY(pQueryInfo->type)) {
H
Haojun Liao 已提交
118 119
        if (win->skey > elem1.ts) {
          win->skey = elem1.ts;
H
hjxilinx 已提交
120 121
        }
  
H
Haojun Liao 已提交
122 123
        if (win->ekey < elem1.ts) {
          win->ekey = elem1.ts;
H
hjxilinx 已提交
124 125
        }
        
H
Haojun Liao 已提交
126 127
        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));
H
Haojun Liao 已提交
128

H
hjxilinx 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
      } 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) {
153 154
    output1->tsOrder = TSDB_ORDER_ASC;
    output2->tsOrder = TSDB_ORDER_ASC;
H
hjxilinx 已提交
155 156 157 158 159
  }

  tsBufFlush(output1);
  tsBufFlush(output2);

H
Haojun Liao 已提交
160 161
  tsBufDestroy(pSupporter1->pTSBuf);
  tsBufDestroy(pSupporter2->pTSBuf);
H
hjxilinx 已提交
162

H
Haojun Liao 已提交
163
  TSKEY et = taosGetTimestampUs();
H
Haojun Liao 已提交
164
  tscDebug("%p input1:%" PRId64 ", input2:%" PRId64 ", final:%" PRId64 " in %d vnodes for secondary query after ts blocks "
H
Haojun Liao 已提交
165 166
           "intersecting, skey:%" PRId64 ", ekey:%" PRId64 ", numOfVnode:%d, elasped time:%"PRId64" us", pSql, numOfInput1, numOfInput2, output1->numOfTotal,
           output1->numOfVnodes, win->skey, win->ekey, tsBufGetNumOfVnodes(output1), et - st);
H
hjxilinx 已提交
167 168 169 170 171

  return output1->numOfTotal;
}

// todo handle failed to create sub query
H
Haojun Liao 已提交
172
SJoinSupporter* tscCreateJoinSupporter(SSqlObj* pSql, int32_t index) {
173
  SJoinSupporter* pSupporter = calloc(1, sizeof(SJoinSupporter));
H
hjxilinx 已提交
174 175 176 177 178 179 180 181 182
  if (pSupporter == NULL) {
    return NULL;
  }

  pSupporter->pObj = pSql;

  pSupporter->subqueryIndex = index;
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, pSql->cmd.clauseIndex);
  
183
  memcpy(&pSupporter->interval, &pQueryInfo->interval, sizeof(pSupporter->interval));
H
hjxilinx 已提交
184 185 186
  pSupporter->limit = pQueryInfo->limit;

  STableMetaInfo* pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, pSql->cmd.clauseIndex, index);
187
  pSupporter->uid = pTableMetaInfo->pTableMeta->id.uid;
H
hjxilinx 已提交
188 189
  assert (pSupporter->uid != 0);

S
slguan 已提交
190
  taosGetTmpfilePath("join-", pSupporter->path);
H
hjxilinx 已提交
191 192
  pSupporter->f = fopen(pSupporter->path, "w");

H
Haojun Liao 已提交
193
  // todo handle error
H
hjxilinx 已提交
194 195 196 197 198 199 200
  if (pSupporter->f == NULL) {
    tscError("%p failed to create tmp file:%s, reason:%s", pSql, pSupporter->path, strerror(errno));
  }

  return pSupporter;
}

H
Haojun Liao 已提交
201
static void tscDestroyJoinSupporter(SJoinSupporter* pSupporter) {
H
hjxilinx 已提交
202 203 204 205
  if (pSupporter == NULL) {
    return;
  }

H
hjxilinx 已提交
206 207 208 209 210 211 212
  if (pSupporter->exprList != NULL) {
    tscSqlExprInfoDestroy(pSupporter->exprList);
  }
  
  if (pSupporter->colList != NULL) {
    tscColumnListDestroy(pSupporter->colList);
  }
H
hjxilinx 已提交
213

H
hjxilinx 已提交
214
  tscFieldInfoClear(&pSupporter->fieldsInfo);
H
hjxilinx 已提交
215 216 217 218

  if (pSupporter->f != NULL) {
    fclose(pSupporter->f);
    unlink(pSupporter->path);
H
hjxilinx 已提交
219
    pSupporter->f = NULL;
H
hjxilinx 已提交
220 221
  }

222 223 224 225 226
  if (pSupporter->pVgroupTables != NULL) {
    taosArrayDestroy(pSupporter->pVgroupTables);
    pSupporter->pVgroupTables = NULL;
  }

S
Shengliang Guan 已提交
227
  taosTFree(pSupporter->pIdTagList);
H
hjxilinx 已提交
228 229 230 231 232 233 234 235 236 237
  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
 *
 */
H
Haojun Liao 已提交
238
static UNUSED_FUNC bool needSecondaryQuery(SQueryInfo* pQueryInfo) {
239 240 241
  size_t numOfCols = taosArrayGetSize(pQueryInfo->colList);
  
  for (int32_t i = 0; i < numOfCols; ++i) {
242 243
    SColumn* base = taosArrayGet(pQueryInfo->colList, i);
    if (base->colIndex.columnIndex != PRIMARYKEY_TIMESTAMP_COL_INDEX) {
H
hjxilinx 已提交
244 245 246 247 248 249 250 251 252 253
      return true;
    }
  }

  return false;
}

/*
 * launch secondary stage query to fetch the result that contains timestamp in set
 */
H
Haojun Liao 已提交
254
static int32_t tscLaunchRealSubqueries(SSqlObj* pSql) {
H
hjxilinx 已提交
255
  int32_t         numOfSub = 0;
256
  SJoinSupporter* pSupporter = NULL;
H
hjxilinx 已提交
257
  
H
Haojun Liao 已提交
258
  //If the columns are not involved in the final select clause, the corresponding query will not be issued.
H
Haojun Liao 已提交
259
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
260
    pSupporter = pSql->pSubs[i]->param;
H
hjxilinx 已提交
261
    if (taosArrayGetSize(pSupporter->exprList) > 0) {
H
hjxilinx 已提交
262 263 264 265 266 267 268
      ++numOfSub;
    }
  }
  
  assert(numOfSub > 0);
  
  // scan all subquery, if one sub query has only ts, ignore it
H
Haojun Liao 已提交
269
  tscDebug("%p start to launch secondary subqueries, %d out of %d needs to query", pSql, numOfSub, pSql->subState.numOfSub);
H
hjxilinx 已提交
270

H
hjxilinx 已提交
271
  //the subqueries that do not actually launch the secondary query to virtual node is set as completed.
H
Haojun Liao 已提交
272
  SSubqueryState* pState = &pSql->subState;
H
Haojun Liao 已提交
273
  pState->numOfRemain = numOfSub;
H
Haojun Liao 已提交
274

H
hjxilinx 已提交
275 276
  bool success = true;
  
H
Haojun Liao 已提交
277
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
278 279 280 281 282
    SSqlObj *pPrevSub = pSql->pSubs[i];
    pSql->pSubs[i] = NULL;
    
    pSupporter = pPrevSub->param;
  
H
hjxilinx 已提交
283
    if (taosArrayGetSize(pSupporter->exprList) == 0) {
284
      tscDebug("%p subIndex: %d, no need to launch query, ignore it", pSql, i);
H
hjxilinx 已提交
285 286
    
      tscDestroyJoinSupporter(pSupporter);
287
      taos_free_result(pPrevSub);
H
hjxilinx 已提交
288 289 290 291 292 293 294 295 296 297
    
      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 已提交
298
    assert(tscSqlExprNumOfExprs(pSubQueryInfo) == 1); // ts_comp query only requires one resutl columns
H
hjxilinx 已提交
299 300
    taos_free_result(pPrevSub);
  
301
    SSqlObj *pNew = createSubqueryObj(pSql, (int16_t) i, tscJoinQueryCallback, pSupporter, TSDB_SQL_SELECT, NULL);
H
hjxilinx 已提交
302 303 304 305 306
    if (pNew == NULL) {
      tscDestroyJoinSupporter(pSupporter);
      success = false;
      break;
    }
B
Bomin Zhang 已提交
307

H
hjxilinx 已提交
308 309 310 311 312
    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
B
Bomin Zhang 已提交
313

H
hjxilinx 已提交
314
    // set the second stage sub query for join process
H
hjxilinx 已提交
315
    TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_SEC_STAGE);
316
    memcpy(&pQueryInfo->interval, &pSupporter->interval, sizeof(pQueryInfo->interval));
B
Bomin Zhang 已提交
317

H
hjxilinx 已提交
318
    tscTagCondCopy(&pQueryInfo->tagCond, &pSupporter->tagCond);
B
Bomin Zhang 已提交
319

H
hjxilinx 已提交
320 321 322
    pQueryInfo->colList = pSupporter->colList;
    pQueryInfo->exprList = pSupporter->exprList;
    pQueryInfo->fieldsInfo = pSupporter->fieldsInfo;
H
Haojun Liao 已提交
323

H
hjxilinx 已提交
324 325 326
    pSupporter->exprList = NULL;
    pSupporter->colList = NULL;
    memset(&pSupporter->fieldsInfo, 0, sizeof(SFieldInfo));
H
hjxilinx 已提交
327 328
  
    SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
H
Haojun Liao 已提交
329
    assert(pNew->subState.numOfSub == 0 && pNew->cmd.numOfClause == 1 && pNewQueryInfo->numOfTables == 1);
H
hjxilinx 已提交
330
  
H
hjxilinx 已提交
331
    tscFieldInfoUpdateOffset(pNewQueryInfo);
H
hjxilinx 已提交
332 333
  
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pNewQueryInfo, 0);
H
Haojun Liao 已提交
334
    pTableMetaInfo->pVgroupTables = pSupporter->pVgroupTables;
335
    pSupporter->pVgroupTables = NULL;
H
Haojun Liao 已提交
336

H
hjxilinx 已提交
337 338 339 340 341 342
    /*
     * 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;
H
Haojun Liao 已提交
343 344 345 346 347

    SColumnIndex index = {.tableIndex = 0, .columnIndex = PRIMARYKEY_TIMESTAMP_COL_INDEX};
    SSchema* s = tscGetTableColumnSchema(pTableMetaInfo->pTableMeta, 0);

    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, 0);
H
Haojun Liao 已提交
348 349
    int16_t funcId = pExpr->functionId;

H
Haojun Liao 已提交
350
    if ((pExpr->colInfo.colId != PRIMARYKEY_TIMESTAMP_COL_INDEX) ||
H
Haojun Liao 已提交
351 352 353 354 355
        (funcId != TSDB_FUNC_TS && funcId != TSDB_FUNC_TS_DUMMY && funcId != TSDB_FUNC_PRJ)) {

      int16_t functionId = tscIsProjectionQuery(pQueryInfo)? TSDB_FUNC_PRJ : TSDB_FUNC_TS;

      tscAddSpecialColumnForSelect(pQueryInfo, 0, functionId, &index, s, TSDB_COL_NORMAL);
H
Haojun Liao 已提交
356 357
      tscPrintSelectClause(pNew, 0);
      tscFieldInfoUpdateOffset(pNewQueryInfo);
H
Haojun Liao 已提交
358 359 360 361

      pExpr = tscSqlExprGet(pQueryInfo, 0);
    }

362
    // set the join condition tag column info, todo extract method
H
Haojun Liao 已提交
363 364
    if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
      assert(pQueryInfo->tagCond.joinInfo.hasJoin);
365
      int16_t colId = tscGetJoinTagColIdByUid(&pQueryInfo->tagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
366

367
      // set the tag column id for executor to extract correct tag value
368
      pExpr->param[0] = (tVariant) {.i64Key = colId, .nType = TSDB_DATA_TYPE_BIGINT, .nLen = sizeof(int64_t)};
H
Haojun Liao 已提交
369
      pExpr->numOfParams = 1;
H
Haojun Liao 已提交
370 371
    }

H
Haojun Liao 已提交
372 373
    int32_t num = 0;
    int32_t *list = NULL;
H
Haojun Liao 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386
    tsBufGetVnodeIdList(pNewQueryInfo->tsBuf, &num, &list);

    if (pTableMetaInfo->pVgroupTables != NULL) {
      for(int32_t k = 0; k < taosArrayGetSize(pTableMetaInfo->pVgroupTables);) {
        SVgroupTableInfo* p = taosArrayGet(pTableMetaInfo->pVgroupTables, k);

        bool found = false;
        for(int32_t f = 0; f < num; ++f) {
          if (p->vgInfo.vgId == list[f]) {
            found = true;
            break;
          }
        }
H
Haojun Liao 已提交
387

H
Haojun Liao 已提交
388 389 390 391
        if (!found) {
          tscRemoveVgroupTableGroup(pTableMetaInfo->pVgroupTables, k);
        } else {
          k++;
H
Haojun Liao 已提交
392 393 394
        }
      }

H
Haojun Liao 已提交
395
      assert(taosArrayGetSize(pTableMetaInfo->pVgroupTables) > 0);
H
Haojun Liao 已提交
396
      TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_MULTITABLE_QUERY);
H
Haojun Liao 已提交
397 398 399 400
    }

    taosTFree(list);

401
    size_t numOfCols = taosArrayGetSize(pNewQueryInfo->colList);
S
TD-1057  
Shengliang Guan 已提交
402
    tscDebug("%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%d, exprInfo:%" PRIzu ", colList:%" PRIzu ", fieldsInfo:%d, name:%s",
H
Haojun Liao 已提交
403 404
             pSql, pNew, 0, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, taosArrayGetSize(pNewQueryInfo->exprList),
             numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, pTableMetaInfo->name);
H
hjxilinx 已提交
405 406 407 408
  }
  
  //prepare the subqueries object failed, abort
  if (!success) {
409
    pSql->res.code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
410
    tscError("%p failed to prepare subqueries objs for secondary phase query, numOfSub:%d, code:%d", pSql,
H
Haojun Liao 已提交
411
        pSql->subState.numOfSub, pSql->res.code);
H
hjxilinx 已提交
412
    freeJoinSubqueryObj(pSql);
H
hjxilinx 已提交
413 414 415 416
    
    return pSql->res.code;
  }
  
H
Haojun Liao 已提交
417
  for(int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
Haojun Liao 已提交
418
    if (pSql->pSubs[i] == NULL) {
H
hjxilinx 已提交
419 420
      continue;
    }
H
Haojun Liao 已提交
421

H
Haojun Liao 已提交
422
    tscDoQuery(pSql->pSubs[i]);
H
hjxilinx 已提交
423 424 425 426 427
  }

  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
428
void freeJoinSubqueryObj(SSqlObj* pSql) {
H
Haojun Liao 已提交
429
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
430 431 432 433 434
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
      continue;
    }
    
435
    SJoinSupporter* p = pSub->param;
H
hjxilinx 已提交
436
    tscDestroyJoinSupporter(p);
H
hjxilinx 已提交
437

H
hjxilinx 已提交
438 439
    if (pSub->res.code == TSDB_CODE_SUCCESS) {
      taos_free_result(pSub);
H
hjxilinx 已提交
440 441 442
    }
  }

H
Haojun Liao 已提交
443
  pSql->subState.numOfSub = 0;
H
hjxilinx 已提交
444 445
}

446
static void quitAllSubquery(SSqlObj* pSqlObj, SJoinSupporter* pSupporter) {
H
Haojun Liao 已提交
447
  assert(pSqlObj->subState.numOfRemain > 0);
H
Haojun Liao 已提交
448

H
Haojun Liao 已提交
449
  if (atomic_sub_fetch_32(&pSqlObj->subState.numOfRemain, 1) <= 0) {
H
hjxilinx 已提交
450
    tscError("%p all subquery return and query failed, global code:%d", pSqlObj, pSqlObj->res.code);
H
hjxilinx 已提交
451
    freeJoinSubqueryObj(pSqlObj);
H
hjxilinx 已提交
452 453 454 455
  }
}

// update the query time range according to the join results on timestamp
H
Haojun Liao 已提交
456 457 458
static void updateQueryTimeRange(SQueryInfo* pQueryInfo, STimeWindow* win) {
  assert(pQueryInfo->window.skey <= win->skey && pQueryInfo->window.ekey >= win->ekey);
  pQueryInfo->window = *win;
H
Haojun Liao 已提交
459 460


H
hjxilinx 已提交
461 462
}

weixin_48148422's avatar
weixin_48148422 已提交
463
int32_t tscCompareTidTags(const void* p1, const void* p2) {
H
Haojun Liao 已提交
464 465
  const STidTags* t1 = (const STidTags*) varDataVal(p1);
  const STidTags* t2 = (const STidTags*) varDataVal(p2);
466 467
  
  if (t1->vgId != t2->vgId) {
weixin_48148422's avatar
weixin_48148422 已提交
468 469
    return (t1->vgId > t2->vgId) ? 1 : -1;
  }
470

weixin_48148422's avatar
weixin_48148422 已提交
471 472
  if (t1->tid != t2->tid) {
    return (t1->tid > t2->tid) ? 1 : -1;
473
  }
weixin_48148422's avatar
weixin_48148422 已提交
474
  return 0;
475 476
}

H
Haojun Liao 已提交
477
void tscBuildVgroupTableInfo(SSqlObj* pSql, STableMetaInfo* pTableMetaInfo, SArray* tables) {
H
Haojun Liao 已提交
478 479
  SArray*   result = taosArrayInit(4, sizeof(SVgroupTableInfo));
  SArray*   vgTables = NULL;
weixin_48148422's avatar
weixin_48148422 已提交
480 481
  STidTags* prev = NULL;

H
Haojun Liao 已提交
482 483 484
  size_t numOfTables = taosArrayGetSize(tables);
  for (size_t i = 0; i < numOfTables; i++) {
    STidTags* tt = taosArrayGet(tables, i);
weixin_48148422's avatar
weixin_48148422 已提交
485

H
Haojun Liao 已提交
486
    if (prev == NULL || tt->vgId != prev->vgId) {
487
      SVgroupsInfo* pvg = pTableMetaInfo->vgroupList;
weixin_48148422's avatar
weixin_48148422 已提交
488

H
Haojun Liao 已提交
489 490 491
      SVgroupTableInfo info = {{0}};
      for (int32_t m = 0; m < pvg->numOfVgroups; ++m) {
        if (tt->vgId == pvg->vgroups[m].vgId) {
H
Haojun Liao 已提交
492
          tscSCMVgroupInfoCopy(&info.vgInfo, &pvg->vgroups[m]);
493 494 495
          break;
        }
      }
496
      assert(info.vgInfo.numOfEps != 0);
weixin_48148422's avatar
weixin_48148422 已提交
497

H
Haojun Liao 已提交
498
      vgTables = taosArrayInit(4, sizeof(STableIdInfo));
weixin_48148422's avatar
weixin_48148422 已提交
499
      info.itemList = vgTables;
H
Haojun Liao 已提交
500
      taosArrayPush(result, &info);
501
    }
weixin_48148422's avatar
weixin_48148422 已提交
502

503
    tscDebug("%p tid:%d, uid:%"PRIu64",vgId:%d added for vnode query", pSql, tt->tid, tt->uid, tt->vgId)
H
Haojun Liao 已提交
504 505
    STableIdInfo item = {.uid = tt->uid, .tid = tt->tid, .key = INT64_MIN};
    taosArrayPush(vgTables, &item);
weixin_48148422's avatar
weixin_48148422 已提交
506
    prev = tt;
507
  }
weixin_48148422's avatar
weixin_48148422 已提交
508 509

  pTableMetaInfo->pVgroupTables = result;
H
Haojun Liao 已提交
510
  pTableMetaInfo->vgroupIndex = 0;
511 512 513 514 515 516
}

static void issueTSCompQuery(SSqlObj* pSql, SJoinSupporter* pSupporter, SSqlObj* pParent) {
  SSqlCmd* pCmd = &pSql->cmd;
  tscClearSubqueryInfo(pCmd);
  tscFreeSqlResult(pSql);
H
Haojun Liao 已提交
517

518
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
Haojun Liao 已提交
519 520
  assert(pQueryInfo->numOfTables == 1);

521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
  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
H
Haojun Liao 已提交
536 537
  if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
    SSqlExpr *pExpr = tscSqlExprGet(pQueryInfo, 0);
538
    int16_t tagColId = tscGetJoinTagColIdByUid(&pSupporter->tagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
539 540 541 542
    pExpr->param->i64Key = tagColId;
    pExpr->numOfParams = 1;
  }

543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
  // 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);
  
559
  tscDebug(
H
Haojun Liao 已提交
560
      "%p subquery:%p tableIndex:%d, vgroupIndex:%d, numOfVgroups:%d, type:%d, ts_comp query to retrieve timestamps, "
S
TD-1057  
Shengliang Guan 已提交
561
      "numOfExpr:%" PRIzu ", colList:%" PRIzu ", numOfOutputFields:%d, name:%s",
H
Haojun Liao 已提交
562 563
      pParent, pSql, 0, pTableMetaInfo->vgroupIndex, pTableMetaInfo->vgroupList->numOfVgroups, pQueryInfo->type,
      tscSqlExprNumOfExprs(pQueryInfo), numOfCols, pQueryInfo->fieldsInfo.numOfOutput, pTableMetaInfo->name);
564 565 566 567
  
  tscProcessSql(pSql);
}

H
Haojun Liao 已提交
568
static bool checkForDuplicateTagVal(SSchema* pColSchema, SJoinSupporter* p1, SSqlObj* pPSqlObj) {
H
Haojun Liao 已提交
569 570 571
  for(int32_t i = 1; i < p1->num; ++i) {
    STidTags* prev = (STidTags*) varDataVal(p1->pIdTagList + (i - 1) * p1->tagSize);
    STidTags* p = (STidTags*) varDataVal(p1->pIdTagList + i * p1->tagSize);
572
    assert(prev->vgId >= 1 && p->vgId >= 1);
H
Haojun Liao 已提交
573 574

    if (doCompare(prev->tag, p->tag, pColSchema->type, pColSchema->bytes) == 0) {
H
Haojun Liao 已提交
575 576
      tscError("%p join tags have same value for different table, free all sub SqlObj and quit", pPSqlObj);
      pPSqlObj->res.code = TSDB_CODE_QRY_DUP_JOIN_KEY;
H
Haojun Liao 已提交
577 578 579 580 581 582 583
      return false;
    }
  }

  return true;
}

584
static int32_t getIntersectionOfTableTuple(SQueryInfo* pQueryInfo, SSqlObj* pParentSql, SArray** s1, SArray** s2) {
585
  tscDebug("%p all subqueries retrieve <tid, tags> complete, do tags match", pParentSql);
H
Haojun Liao 已提交
586 587 588 589 590 591 592 593

  SJoinSupporter* p1 = pParentSql->pSubs[0]->param;
  SJoinSupporter* p2 = pParentSql->pSubs[1]->param;

  qsort(p1->pIdTagList, p1->num, p1->tagSize, tscCompareTidTags);
  qsort(p2->pIdTagList, p2->num, p2->tagSize, tscCompareTidTags);

  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
594
  int16_t tagColId = tscGetJoinTagColIdByUid(&pQueryInfo->tagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
595 596 597

  SSchema* pColSchema = tscGetTableColumnSchemaById(pTableMetaInfo->pTableMeta, tagColId);

H
Haojun Liao 已提交
598 599 600
  // int16_t for padding
  *s1 = taosArrayInit(p1->num, p1->tagSize - sizeof(int16_t));
  *s2 = taosArrayInit(p2->num, p2->tagSize - sizeof(int16_t));
H
Haojun Liao 已提交
601

H
Haojun Liao 已提交
602
  if (!(checkForDuplicateTagVal(pColSchema, p1, pParentSql) && checkForDuplicateTagVal(pColSchema, p2, pParentSql))) {
603
    return TSDB_CODE_QRY_DUP_JOIN_KEY;
H
Haojun Liao 已提交
604 605 606 607 608 609
  }

  int32_t i = 0, j = 0;
  while(i < p1->num && j < p2->num) {
    STidTags* pp1 = (STidTags*) varDataVal(p1->pIdTagList + i * p1->tagSize);
    STidTags* pp2 = (STidTags*) varDataVal(p2->pIdTagList + j * p2->tagSize);
610
    assert(pp1->tid != 0 && pp2->tid != 0);
H
Haojun Liao 已提交
611 612 613

    int32_t ret = doCompare(pp1->tag, pp2->tag, pColSchema->type, pColSchema->bytes);
    if (ret == 0) {
614
      tscDebug("%p tag matched, vgId:%d, val:%d, tid:%d, uid:%"PRIu64", tid:%d, uid:%"PRIu64, pParentSql, pp1->vgId,
H
Haojun Liao 已提交
615 616 617 618 619 620 621 622 623 624 625 626
               *(int*) pp1->tag, pp1->tid, pp1->uid, pp2->tid, pp2->uid);

      taosArrayPush(*s1, pp1);
      taosArrayPush(*s2, pp2);
      j++;
      i++;
    } else if (ret > 0) {
      j++;
    } else {
      i++;
    }
  }
627 628

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
629 630
}

H
Haojun Liao 已提交
631
static void tidTagRetrieveCallback(void* param, TAOS_RES* tres, int32_t numOfRows) {
632
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
633

H
hjxilinx 已提交
634
  SSqlObj* pParentSql = pSupporter->pObj;
H
Haojun Liao 已提交
635

H
hjxilinx 已提交
636 637
  SSqlObj* pSql = (SSqlObj*)tres;
  SSqlCmd* pCmd = &pSql->cmd;
H
Haojun Liao 已提交
638 639 640
  SSqlRes* pRes = &pSql->res;

  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
Haojun Liao 已提交
641
  assert(TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_TAG_FILTER_QUERY));
H
Haojun Liao 已提交
642

H
Haojun Liao 已提交
643 644 645
  // check for the error code firstly
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    // todo retry if other subqueries are not failed
H
Haojun Liao 已提交
646

H
Haojun Liao 已提交
647 648
    assert(numOfRows < 0 && numOfRows == taos_errno(pSql));
    tscError("%p sub query failed, code:%s, index:%d", pSql, tstrerror(numOfRows), pSupporter->subqueryIndex);
H
Haojun Liao 已提交
649

H
Haojun Liao 已提交
650 651
    pParentSql->res.code = numOfRows;
    quitAllSubquery(pParentSql, pSupporter);
H
Haojun Liao 已提交
652

H
Haojun Liao 已提交
653 654 655
    tscQueueAsyncRes(pParentSql);
    return;
  }
H
Haojun Liao 已提交
656

H
Haojun Liao 已提交
657 658
  // keep the results in memory
  if (numOfRows > 0) {
659
    size_t validLen = (size_t)(pSupporter->tagSize * pRes->numOfRows);
H
Haojun Liao 已提交
660
    size_t length = pSupporter->totalLen + validLen;
H
Haojun Liao 已提交
661

H
Haojun Liao 已提交
662 663 664 665
    // todo handle memory error
    char* tmp = realloc(pSupporter->pIdTagList, length);
    if (tmp == NULL) {
      tscError("%p failed to malloc memory", pSql);
H
Haojun Liao 已提交
666

H
Haojun Liao 已提交
667 668
      pParentSql->res.code = TAOS_SYSTEM_ERROR(errno);
      quitAllSubquery(pParentSql, pSupporter);
H
Haojun Liao 已提交
669

H
Haojun Liao 已提交
670 671 672
      tscQueueAsyncRes(pParentSql);
      return;
    }
H
Haojun Liao 已提交
673

H
Haojun Liao 已提交
674
    pSupporter->pIdTagList = tmp;
H
Haojun Liao 已提交
675

H
Haojun Liao 已提交
676
    memcpy(pSupporter->pIdTagList + pSupporter->totalLen, pRes->data, validLen);
S
Shengliang Guan 已提交
677 678
    pSupporter->totalLen += (int32_t)validLen;
    pSupporter->num += (int32_t)pRes->numOfRows;
H
Haojun Liao 已提交
679

H
Haojun Liao 已提交
680 681 682 683 684 685
    // query not completed, continue to retrieve tid + tag tuples
    if (!pRes->completed) {
      taos_fetch_rows_a(tres, tidTagRetrieveCallback, param);
      return;
    }
  }
H
Haojun Liao 已提交
686

H
Haojun Liao 已提交
687 688 689 690
  // data in current vnode has all returned to client, try next vnode if exits
  // <tid + tag> tuples have been retrieved to client, try <tid + tag> tuples from the next vnode
  if (hasMoreVnodesToTry(pSql)) {
    STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
Haojun Liao 已提交
691

H
Haojun Liao 已提交
692 693 694
    int32_t totalVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
    pTableMetaInfo->vgroupIndex += 1;
    assert(pTableMetaInfo->vgroupIndex < totalVgroups);
H
Haojun Liao 已提交
695

696
    tscDebug("%p tid_tag from vgroup index:%d completed, try next vgroup:%d. total vgroups:%d. current numOfRes:%d",
H
Haojun Liao 已提交
697
             pSql, pTableMetaInfo->vgroupIndex - 1, pTableMetaInfo->vgroupIndex, totalVgroups, pSupporter->num);
H
Haojun Liao 已提交
698

H
Haojun Liao 已提交
699 700
    pCmd->command = TSDB_SQL_SELECT;
    tscResetForNextRetrieve(&pSql->res);
H
Haojun Liao 已提交
701

H
Haojun Liao 已提交
702 703 704 705 706
    // set the callback function
    pSql->fp = tscJoinQueryCallback;
    tscProcessSql(pSql);
    return;
  }
H
Haojun Liao 已提交
707

H
Haojun Liao 已提交
708 709
  // no data exists in next vnode, mark the <tid, tags> query completed
  // only when there is no subquery exits any more, proceeds to get the intersect of the <tid, tags> tuple sets.
H
Haojun Liao 已提交
710
  if (atomic_sub_fetch_32(&pParentSql->subState.numOfRemain, 1) > 0) {
H
Haojun Liao 已提交
711 712
    return;
  }
H
Haojun Liao 已提交
713

H
Haojun Liao 已提交
714
  SArray *s1 = NULL, *s2 = NULL;
715 716 717 718 719
  int32_t code = getIntersectionOfTableTuple(pQueryInfo, pParentSql, &s1, &s2);
  if (code != TSDB_CODE_SUCCESS) {
    freeJoinSubqueryObj(pParentSql);
    pParentSql->res.code = code;
    tscQueueAsyncRes(pParentSql);
720 721 722

    taosArrayDestroy(s1);
    taosArrayDestroy(s2);
723 724 725
    return;
  }

H
Haojun Liao 已提交
726
  if (taosArrayGetSize(s1) == 0 || taosArrayGetSize(s2) == 0) {  // no results,return.
727
    tscDebug("%p tag intersect does not generated qualified tables for join, free all sub SqlObj and quit", pParentSql);
H
Haojun Liao 已提交
728
    freeJoinSubqueryObj(pParentSql);
H
Haojun Liao 已提交
729

730 731
    // set no result command
    pParentSql->cmd.command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
H
Haojun Liao 已提交
732
    (*pParentSql->fp)(pParentSql->param, pParentSql, 0);
B
Bomin Zhang 已提交
733 734 735 736
  } else {
    // proceed to for ts_comp query
    SSqlCmd* pSubCmd1 = &pParentSql->pSubs[0]->cmd;
    SSqlCmd* pSubCmd2 = &pParentSql->pSubs[1]->cmd;
H
Haojun Liao 已提交
737

B
Bomin Zhang 已提交
738 739 740
    SQueryInfo*     pQueryInfo1 = tscGetQueryInfoDetail(pSubCmd1, 0);
    STableMetaInfo* pTableMetaInfo1 = tscGetMetaInfo(pQueryInfo1, 0);
    tscBuildVgroupTableInfo(pParentSql, pTableMetaInfo1, s1);
H
Haojun Liao 已提交
741

B
Bomin Zhang 已提交
742 743 744
    SQueryInfo*     pQueryInfo2 = tscGetQueryInfoDetail(pSubCmd2, 0);
    STableMetaInfo* pTableMetaInfo2 = tscGetMetaInfo(pQueryInfo2, 0);
    tscBuildVgroupTableInfo(pParentSql, pTableMetaInfo2, s2);
H
Haojun Liao 已提交
745

H
Haojun Liao 已提交
746 747 748 749 750 751
    SSqlObj* psub1 = pParentSql->pSubs[0];
    ((SJoinSupporter*)psub1->param)->pVgroupTables =  tscCloneVgroupTableInfo(pTableMetaInfo1->pVgroupTables);

    SSqlObj* psub2 = pParentSql->pSubs[1];
    ((SJoinSupporter*)psub2->param)->pVgroupTables =  tscCloneVgroupTableInfo(pTableMetaInfo2->pVgroupTables);

H
Haojun Liao 已提交
752 753
    pParentSql->subState.numOfSub = 2;
    pParentSql->subState.numOfRemain = pParentSql->subState.numOfSub;
H
Haojun Liao 已提交
754

H
Haojun Liao 已提交
755
    for (int32_t m = 0; m < pParentSql->subState.numOfSub; ++m) {
B
Bomin Zhang 已提交
756 757 758
      SSqlObj* sub = pParentSql->pSubs[m];
      issueTSCompQuery(sub, sub->param, pParentSql);
    }
H
Haojun Liao 已提交
759
  }
B
Bomin Zhang 已提交
760 761 762

  taosArrayDestroy(s1);
  taosArrayDestroy(s2);
H
Haojun Liao 已提交
763
}
H
Haojun Liao 已提交
764

H
Haojun Liao 已提交
765 766
static void tsCompRetrieveCallback(void* param, TAOS_RES* tres, int32_t numOfRows) {
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
767

H
Haojun Liao 已提交
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786
  SSqlObj* pParentSql = pSupporter->pObj;

  SSqlObj* pSql = (SSqlObj*)tres;
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;

  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  assert(!TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_SEC_STAGE));

  // check for the error code firstly
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    // todo retry if other subqueries are not failed yet 
    assert(numOfRows < 0 && numOfRows == taos_errno(pSql));
    tscError("%p sub query failed, code:%s, index:%d", pSql, tstrerror(numOfRows), pSupporter->subqueryIndex);

    pParentSql->res.code = numOfRows;
    quitAllSubquery(pParentSql, pSupporter);

    tscQueueAsyncRes(pParentSql);
787 788
    return;
  }
H
Haojun Liao 已提交
789

H
Haojun Liao 已提交
790
  if (numOfRows > 0) {  // write the compressed timestamp to disk file
791
    fwrite(pRes->data, (size_t)pRes->numOfRows, 1, pSupporter->f);
H
Haojun Liao 已提交
792 793 794 795 796 797 798 799 800 801
    fclose(pSupporter->f);
    pSupporter->f = NULL;

    STSBuf* pBuf = tsBufCreateFromFile(pSupporter->path, true);
    if (pBuf == NULL) {  // in error process, close the fd
      tscError("%p invalid ts comp file from vnode, abort subquery, file size:%d", pSql, numOfRows);

      pParentSql->res.code = TAOS_SYSTEM_ERROR(errno);
      tscQueueAsyncRes(pParentSql);

H
hjxilinx 已提交
802 803
      return;
    }
804

H
Haojun Liao 已提交
805
    if (pSupporter->pTSBuf == NULL) {
806
      tscDebug("%p create tmp file for ts block:%s, size:%d bytes", pSql, pBuf->path, numOfRows);
H
Haojun Liao 已提交
807 808 809
      pSupporter->pTSBuf = pBuf;
    } else {
      assert(pQueryInfo->numOfTables == 1);  // for subquery, only one
H
Haojun Liao 已提交
810
      tsBufMerge(pSupporter->pTSBuf, pBuf);
H
Haojun Liao 已提交
811
      tsBufDestroy(pBuf);
H
Haojun Liao 已提交
812
    }
H
hjxilinx 已提交
813

H
Haojun Liao 已提交
814 815
    // continue to retrieve ts-comp data from vnode
    if (!pRes->completed) {
S
slguan 已提交
816
      taosGetTmpfilePath("ts-join", pSupporter->path);
H
Haojun Liao 已提交
817
      pSupporter->f = fopen(pSupporter->path, "w");
S
Shengliang Guan 已提交
818
      pRes->row = (int32_t)pRes->numOfRows;
H
hjxilinx 已提交
819

H
Haojun Liao 已提交
820 821
      taos_fetch_rows_a(tres, tsCompRetrieveCallback, param);
      return;
H
hjxilinx 已提交
822
    }
H
Haojun Liao 已提交
823
  }
H
Haojun Liao 已提交
824

H
Haojun Liao 已提交
825 826
  if (hasMoreVnodesToTry(pSql)) {
    STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
Haojun Liao 已提交
827

H
Haojun Liao 已提交
828 829 830
    int32_t totalVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
    pTableMetaInfo->vgroupIndex += 1;
    assert(pTableMetaInfo->vgroupIndex < totalVgroups);
H
Haojun Liao 已提交
831

832
    tscDebug("%p results from vgroup index:%d completed, try next vgroup:%d. total vgroups:%d. current numOfRes:%" PRId64,
H
Haojun Liao 已提交
833 834
             pSql, pTableMetaInfo->vgroupIndex - 1, pTableMetaInfo->vgroupIndex, totalVgroups,
             pRes->numOfClauseTotal);
H
Haojun Liao 已提交
835

H
Haojun Liao 已提交
836 837
    pCmd->command = TSDB_SQL_SELECT;
    tscResetForNextRetrieve(&pSql->res);
H
Haojun Liao 已提交
838

H
Haojun Liao 已提交
839
    assert(pSupporter->f == NULL);
S
slguan 已提交
840
    taosGetTmpfilePath("ts-join", pSupporter->path);
H
Haojun Liao 已提交
841 842 843
    
    // TODO check for failure
    pSupporter->f = fopen(pSupporter->path, "w");
S
Shengliang Guan 已提交
844
    pRes->row = (int32_t)pRes->numOfRows;
H
Haojun Liao 已提交
845

H
Haojun Liao 已提交
846 847 848 849 850
    // set the callback function
    pSql->fp = tscJoinQueryCallback;
    tscProcessSql(pSql);
    return;
  }
H
Haojun Liao 已提交
851

H
Haojun Liao 已提交
852
  if (atomic_sub_fetch_32(&pParentSql->subState.numOfRemain, 1) > 0) {
H
Haojun Liao 已提交
853 854
    return;
  }
H
hjxilinx 已提交
855

856
  tscDebug("%p all subquery retrieve ts complete, do ts block intersect", pParentSql);
H
hjxilinx 已提交
857

H
Haojun Liao 已提交
858 859 860
  // proceeds to launched secondary query to retrieve final data
  SJoinSupporter* p1 = pParentSql->pSubs[0]->param;
  SJoinSupporter* p2 = pParentSql->pSubs[1]->param;
H
Haojun Liao 已提交
861

H
Haojun Liao 已提交
862 863 864
  STimeWindow win = TSWINDOW_INITIALIZER;
  int64_t num = doTSBlockIntersect(pParentSql, p1, p2, &win);
  if (num <= 0) {  // no result during ts intersect
865
    tscDebug("%p no results generated in ts intersection, free all sub SqlObj and quit", pParentSql);
H
Haojun Liao 已提交
866
    freeJoinSubqueryObj(pParentSql);
867 868 869

    // set no result command
    pParentSql->cmd.command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
H
Haojun Liao 已提交
870
    (*pParentSql->fp)(pParentSql->param, pParentSql, 0);
H
Haojun Liao 已提交
871 872 873 874 875 876
    return;
  }

  // launch the query the retrieve actual results from vnode along with the filtered timestamp
  SQueryInfo* pPQueryInfo = tscGetQueryInfoDetail(&pParentSql->cmd, pParentSql->cmd.clauseIndex);
  updateQueryTimeRange(pPQueryInfo, &win);
H
Haojun Liao 已提交
877 878

  //update the vgroup that involved in real data query
H
Haojun Liao 已提交
879
  tscLaunchRealSubqueries(pParentSql);
H
Haojun Liao 已提交
880
}
H
Haojun Liao 已提交
881

H
Haojun Liao 已提交
882 883
static void joinRetrieveFinalResCallback(void* param, TAOS_RES* tres, int numOfRows) {
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
884

H
Haojun Liao 已提交
885
  SSqlObj* pParentSql = pSupporter->pObj;
H
Haojun Liao 已提交
886

H
Haojun Liao 已提交
887 888 889
  SSqlObj* pSql = (SSqlObj*)tres;
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;
H
Haojun Liao 已提交
890

H
Haojun Liao 已提交
891 892 893
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(numOfRows == taos_errno(pSql));
H
hjxilinx 已提交
894

H
Haojun Liao 已提交
895 896
    pParentSql->res.code = numOfRows;
    tscError("%p retrieve failed, index:%d, code:%s", pSql, pSupporter->subqueryIndex, tstrerror(numOfRows));
H
Haojun Liao 已提交
897 898 899

    tscQueueAsyncRes(pParentSql);
    return;
H
Haojun Liao 已提交
900
  }
H
Haojun Liao 已提交
901

H
Haojun Liao 已提交
902 903 904
  if (numOfRows >= 0) {
    pRes->numOfTotal += pRes->numOfRows;
  }
H
Haojun Liao 已提交
905

H
Haojun Liao 已提交
906
  SSubqueryState* pState = &pParentSql->subState;
H
Haojun Liao 已提交
907 908 909
  if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) && numOfRows == 0) {
    STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
    assert(pQueryInfo->numOfTables == 1);
H
Haojun Liao 已提交
910

H
Haojun Liao 已提交
911
    // for projection query, need to try next vnode if current vnode is exhausted
H
Haojun Liao 已提交
912 913
    int32_t numOfVgroups = 0;  // TODO refactor
    if (pTableMetaInfo->pVgroupTables != NULL) {
S
Shengliang Guan 已提交
914
      numOfVgroups = (int32_t)taosArrayGetSize(pTableMetaInfo->pVgroupTables);
H
Haojun Liao 已提交
915 916 917 918 919
    } else {
      numOfVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
    }

    if ((++pTableMetaInfo->vgroupIndex) < numOfVgroups) {
H
Haojun Liao 已提交
920
      tscDebug("%p no result in current vnode anymore, try next vnode, vgIndex:%d", pSql, pTableMetaInfo->vgroupIndex);
H
Haojun Liao 已提交
921 922
      pSql->cmd.command = TSDB_SQL_SELECT;
      pSql->fp = tscJoinQueryCallback;
H
Haojun Liao 已提交
923

H
Haojun Liao 已提交
924 925
      tscProcessSql(pSql);
      return;
H
Haojun Liao 已提交
926 927
    } else {
      tscDebug("%p no result in current subquery anymore", pSql);
H
Haojun Liao 已提交
928 929 930
    }
  }

H
Haojun Liao 已提交
931 932
  if (atomic_sub_fetch_32(&pState->numOfRemain, 1) > 0) {
    tscDebug("%p sub:%p completed, remain:%d, total:%d", pParentSql, tres, pState->numOfRemain, pState->numOfSub);
H
Haojun Liao 已提交
933 934 935
    return;
  }

H
Haojun Liao 已提交
936
  tscDebug("%p all %d secondary subqueries retrieval completed, code:%d", tres, pState->numOfSub, pParentSql->res.code);
H
Haojun Liao 已提交
937 938 939 940 941 942 943

  if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
    freeJoinSubqueryObj(pParentSql);
    pParentSql->res.completed = true;
  }

  // update the records for each subquery in parent sql object.
H
Haojun Liao 已提交
944
  for (int32_t i = 0; i < pState->numOfSub; ++i) {
H
Haojun Liao 已提交
945
    if (pParentSql->pSubs[i] == NULL) {
H
Haojun Liao 已提交
946
      tscDebug("%p %p sub:%d not retrieve data", pParentSql, NULL, i);
H
Haojun Liao 已提交
947
      continue;
H
hjxilinx 已提交
948
    }
H
Haojun Liao 已提交
949 950

    SSqlRes* pRes1 = &pParentSql->pSubs[i]->res;
H
Haojun Liao 已提交
951 952 953 954 955 956 957 958 959 960

    if (pRes1->row > 0 && pRes1->numOfRows > 0) {
      tscDebug("%p sub:%p index:%d numOfRows:%"PRId64" total:%"PRId64 " (not retrieve)", pParentSql, pParentSql->pSubs[i], i,
               pRes1->numOfRows, pRes1->numOfTotal);
      assert(pRes1->row < pRes1->numOfRows);
    } else {
      pRes1->numOfClauseTotal += pRes1->numOfRows;
      tscDebug("%p sub:%p index:%d numOfRows:%"PRId64" total:%"PRId64, pParentSql, pParentSql->pSubs[i], i,
               pRes1->numOfRows, pRes1->numOfTotal);
    }
H
hjxilinx 已提交
961
  }
H
Haojun Liao 已提交
962 963 964

  // data has retrieved to client, build the join results
  tscBuildResFromSubqueries(pParentSql);
H
hjxilinx 已提交
965 966 967
}

void tscFetchDatablockFromSubquery(SSqlObj* pSql) {
H
Haojun Liao 已提交
968
  assert(pSql->subState.numOfSub >= 1);
H
hjxilinx 已提交
969
  
H
hjxilinx 已提交
970
  int32_t numOfFetch = 0;
H
Haojun Liao 已提交
971 972
  bool    hasData = true;
  bool    reachLimit = false;
H
Haojun Liao 已提交
973 974

  // if the subquery is NULL, it does not involved in the final result generation
H
Haojun Liao 已提交
975
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
976 977
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
H
hjxilinx 已提交
978 979
      continue;
    }
H
Haojun Liao 已提交
980

H
hjxilinx 已提交
981
    SSqlRes *pRes = &pSub->res;
H
Haojun Liao 已提交
982

H
hjxilinx 已提交
983 984
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSub->cmd, 0);

H
Haojun Liao 已提交
985 986
    if (!tscHasReachLimitation(pQueryInfo, pRes)) {
      if (pRes->row >= pRes->numOfRows) {
H
Haojun Liao 已提交
987
        // no data left in current result buffer
H
Haojun Liao 已提交
988 989
        hasData = false;

H
Haojun Liao 已提交
990 991
        // The current query is completed for the active vnode, try next vnode if exists
        // If it is completed, no need to fetch anymore.
H
Haojun Liao 已提交
992 993
        if (!pRes->completed) {
          numOfFetch++;
H
Haojun Liao 已提交
994
        }
H
hjxilinx 已提交
995
      }
H
Haojun Liao 已提交
996 997
    } else {  // has reach the limitation, no data anymore
      if (pRes->row >= pRes->numOfRows) {
H
Haojun Liao 已提交
998 999
        reachLimit = true;
        hasData    = false;
H
Haojun Liao 已提交
1000 1001
        break;
      }
H
hjxilinx 已提交
1002
    }
H
Haojun Liao 已提交
1003
  }
H
hjxilinx 已提交
1004

H
hjxilinx 已提交
1005 1006 1007 1008
  // has data remains in client side, and continue to return data to app
  if (hasData) {
    tscBuildResFromSubqueries(pSql);
    return;
H
Haojun Liao 已提交
1009
  }
H
Haojun Liao 已提交
1010

H
Haojun Liao 已提交
1011 1012
  // If at least one subquery is completed in current vnode, try the next vnode in case of multi-vnode
  // super table projection query.
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
  if (reachLimit) {
    pSql->res.completed = true;
    freeJoinSubqueryObj(pSql);

    if (pSql->res.code == TSDB_CODE_SUCCESS) {
      (*pSql->fp)(pSql->param, pSql, 0);
    } else {
      tscQueueAsyncRes(pSql);
    }

    return;
  }

  if (numOfFetch <= 0) {
H
Haojun Liao 已提交
1027 1028
    bool tryNextVnode = false;

1029
    SSqlObj*    pp = pSql->pSubs[0];
H
Haojun Liao 已提交
1030 1031
    SQueryInfo* pi = tscGetQueryInfoDetail(&pp->cmd, 0);

H
Haojun Liao 已提交
1032 1033
    // get the number of subquery that need to retrieve the next vnode.
    if (tscNonOrderedProjectionQueryOnSTable(pi, 0)) {
1034
      for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
Haojun Liao 已提交
1035 1036
        SSqlObj* pSub = pSql->pSubs[i];
        if (pSub != NULL && pSub->res.row >= pSub->res.numOfRows && pSub->res.completed) {
H
Haojun Liao 已提交
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
          pSql->subState.numOfRemain++;
        }
      }
    }

    for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
      SSqlObj* pSub = pSql->pSubs[i];
      if (pSub == NULL) {
        continue;
      }

      SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSub->cmd, 0);

1050 1051
      if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) && pSub->res.row >= pSub->res.numOfRows &&
          pSub->res.completed) {
H
Haojun Liao 已提交
1052 1053 1054 1055 1056 1057
        STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
        assert(pQueryInfo->numOfTables == 1);

        // for projection query, need to try next vnode if current vnode is exhausted
        int32_t numOfVgroups = 0;  // TODO refactor
        if (pTableMetaInfo->pVgroupTables != NULL) {
S
Shengliang Guan 已提交
1058
          numOfVgroups = (int32_t)taosArrayGetSize(pTableMetaInfo->pVgroupTables);
H
Haojun Liao 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
        } else {
          numOfVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
        }

        if ((++pTableMetaInfo->vgroupIndex) < numOfVgroups) {
          tscDebug("%p no result in current vnode anymore, try next vnode, vgIndex:%d", pSub,
                   pTableMetaInfo->vgroupIndex);
          pSub->cmd.command = TSDB_SQL_SELECT;
          pSub->fp = tscJoinQueryCallback;

          tscProcessSql(pSub);
          tryNextVnode = true;
        } else {
          tscDebug("%p no result in current subquery anymore", pSub);
        }
      }
    }

    if (tryNextVnode) {
      return;
    }
H
Haojun Liao 已提交
1080 1081 1082 1083

    pSql->res.completed = true;
    freeJoinSubqueryObj(pSql);

H
hjxilinx 已提交
1084 1085 1086 1087 1088
    if (pSql->res.code == TSDB_CODE_SUCCESS) {
      (*pSql->fp)(pSql->param, pSql, 0);
    } else {
      tscQueueAsyncRes(pSql);
    }
1089

H
hjxilinx 已提交
1090 1091 1092 1093
    return;
  }

  // TODO multi-vnode retrieve for projection query with limitation has bugs, since the global limiation is not handled
H
Haojun Liao 已提交
1094
  // retrieve data from current vnode.
1095
  tscDebug("%p retrieve data from %d subqueries", pSql, numOfFetch);
H
Haojun Liao 已提交
1096
  SJoinSupporter* pSupporter = NULL;
H
Haojun Liao 已提交
1097 1098
  pSql->subState.numOfRemain = numOfFetch;

H
Haojun Liao 已提交
1099
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
1100 1101 1102 1103
    SSqlObj* pSql1 = pSql->pSubs[i];
    if (pSql1 == NULL) {
      continue;
    }
H
Haojun Liao 已提交
1104

H
hjxilinx 已提交
1105 1106 1107
    SSqlRes* pRes1 = &pSql1->res;
    SSqlCmd* pCmd1 = &pSql1->cmd;

1108
    pSupporter = (SJoinSupporter*)pSql1->param;
H
hjxilinx 已提交
1109 1110 1111 1112 1113 1114 1115 1116

    // 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) {
1117
      tscDebug("%p subquery:%p retrieve data from vnode, subquery:%d, vgroupIndex:%d", pSql, pSql1,
H
hjxilinx 已提交
1118
               pSupporter->subqueryIndex, pTableMetaInfo->vgroupIndex);
H
hjxilinx 已提交
1119 1120

      tscResetForNextRetrieve(pRes1);
H
Haojun Liao 已提交
1121
      pSql1->fp = joinRetrieveFinalResCallback;
H
hjxilinx 已提交
1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136

      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;

H
Haojun Liao 已提交
1137
  tscDebug("%p all subquery response, retrieve data for subclause:%d", pSql, pCmd->clauseIndex);
H
hjxilinx 已提交
1138

H
Haojun Liao 已提交
1139
  // the column transfer support struct has been built
H
hjxilinx 已提交
1140
  if (pRes->pColumnIndex != NULL) {
H
Haojun Liao 已提交
1141
    return;
H
hjxilinx 已提交
1142 1143 1144 1145
  }

  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);

S
Shengliang Guan 已提交
1146
  int32_t numOfExprs = (int32_t)tscSqlExprNumOfExprs(pQueryInfo);
H
Haojun Liao 已提交
1147
  pRes->pColumnIndex = calloc(1, sizeof(SColumnIndex) * numOfExprs);
H
Haojun Liao 已提交
1148 1149 1150 1151
  if (pRes->pColumnIndex == NULL) {
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return;
  }
H
Haojun Liao 已提交
1152 1153

  for (int32_t i = 0; i < numOfExprs; ++i) {
H
hjxilinx 已提交
1154 1155 1156 1157 1158
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);

    int32_t tableIndexOfSub = -1;
    for (int32_t j = 0; j < pQueryInfo->numOfTables; ++j) {
      STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, j);
1159
      if (pTableMetaInfo->pTableMeta->id.uid == pExpr->uid) {
H
hjxilinx 已提交
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
        tableIndexOfSub = j;
        break;
      }
    }

    assert(tableIndexOfSub >= 0 && tableIndexOfSub < pQueryInfo->numOfTables);
    
    SSqlCmd* pSubCmd = &pSql->pSubs[tableIndexOfSub]->cmd;
    SQueryInfo* pSubQueryInfo = tscGetQueryInfoDetail(pSubCmd, 0);
    
H
Haojun Liao 已提交
1170 1171
    size_t numOfSubExpr = taosArrayGetSize(pSubQueryInfo->exprList);
    for (int32_t k = 0; k < numOfSubExpr; ++k) {
H
hjxilinx 已提交
1172 1173 1174 1175 1176 1177 1178
      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;
      }
    }
  }
H
Haojun Liao 已提交
1179 1180 1181 1182

  // restore the offset value for super table query in case of final result.
  tscRestoreSQLFuncForSTableQuery(pQueryInfo);
  tscFieldInfoUpdateOffset(pQueryInfo);
H
hjxilinx 已提交
1183 1184 1185 1186
}

void tscJoinQueryCallback(void* param, TAOS_RES* tres, int code) {
  SSqlObj* pSql = (SSqlObj*)tres;
H
Haojun Liao 已提交
1187

1188
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
1189 1190
  SSqlObj* pParentSql = pSupporter->pObj;

H
hjxilinx 已提交
1191
  // There is only one subquery and table for each subquery.
H
hjxilinx 已提交
1192
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
H
hjxilinx 已提交
1193
  assert(pQueryInfo->numOfTables == 1 && pSql->cmd.numOfClause == 1);
H
hjxilinx 已提交
1194

H
Haojun Liao 已提交
1195 1196 1197 1198 1199
  // retrieve actual query results from vnode during the second stage join subquery
  if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
    tscError("%p abort query due to other subquery failure. code:%d, global code:%d", pSql, code, pParentSql->res.code);
    quitAllSubquery(pParentSql, pSupporter);
    tscQueueAsyncRes(pParentSql);
H
hjxilinx 已提交
1200

H
Haojun Liao 已提交
1201 1202
    return;
  }
H
hjxilinx 已提交
1203

H
Haojun Liao 已提交
1204 1205 1206
  // TODO here retry is required, not directly returns to client
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(taos_errno(pSql) == code);
H
hjxilinx 已提交
1207

1208
    tscError("%p abort query, code:%s, global code:%s", pSql, tstrerror(code), tstrerror(pParentSql->res.code));
H
Haojun Liao 已提交
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
    pParentSql->res.code = code;

    quitAllSubquery(pParentSql, pSupporter);
    tscQueueAsyncRes(pParentSql);

    return;
  }

  // retrieve <tid, tag> tuples from vnode
  if (TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_TAG_FILTER_QUERY)) {
    pSql->fp = tidTagRetrieveCallback;
    pSql->cmd.command = TSDB_SQL_FETCH;
    tscProcessSql(pSql);
    return;
  }

  // retrieve ts_comp info from vnode
  if (!TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_SEC_STAGE)) {
    pSql->fp = tsCompRetrieveCallback;
    pSql->cmd.command = TSDB_SQL_FETCH;
    tscProcessSql(pSql);
    return;
  }

  // wait for the other subqueries response from vnode
H
Haojun Liao 已提交
1234
  if (atomic_sub_fetch_32(&pParentSql->subState.numOfRemain, 1) > 0) {
H
Haojun Liao 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245
    return;
  }

  tscSetupOutputColumnIndex(pParentSql);
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);

  /**
   * if the query is a continue query (vgroupIndex > 0 for projection query) for next vnode, do the retrieval of
   * data instead of returning to its invoker
   */
  if (pTableMetaInfo->vgroupIndex > 0 && tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0)) {
H
Haojun Liao 已提交
1246
//    pParentSql->subState.numOfRemain = pParentSql->subState.numOfSub;  // reset the record value
H
Haojun Liao 已提交
1247 1248 1249 1250 1251 1252 1253 1254

    pSql->fp = joinRetrieveFinalResCallback;  // continue retrieve data
    pSql->cmd.command = TSDB_SQL_FETCH;
    tscProcessSql(pSql);
  } else {  // first retrieve from vnode during the secondary stage sub-query
    // 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 已提交
1255
    } else {
H
Haojun Liao 已提交
1256
      tscQueueAsyncRes(pParentSql);
H
hjxilinx 已提交
1257 1258 1259 1260 1261 1262 1263
    }
  }
}

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

1264
static SSqlObj *tscCreateSTableSubquery(SSqlObj *pSql, SRetrieveSupport *trsupport, SSqlObj *prevSqlObj);
H
hjxilinx 已提交
1265

H
Haojun Liao 已提交
1266
int32_t tscCreateJoinSubquery(SSqlObj *pSql, int16_t tableIndex, SJoinSupporter *pSupporter) {
H
hjxilinx 已提交
1267 1268 1269 1270
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  
  pSql->res.qhandle = 0x1;
H
Haojun Liao 已提交
1271 1272
  assert(pSql->res.numOfRows == 0);

H
hjxilinx 已提交
1273
  if (pSql->pSubs == NULL) {
H
Haojun Liao 已提交
1274
    pSql->pSubs = calloc(pSql->subState.numOfSub, POINTER_BYTES);
H
hjxilinx 已提交
1275
    if (pSql->pSubs == NULL) {
1276
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1277 1278 1279
    }
  }
  
1280
  SSqlObj *pNew = createSubqueryObj(pSql, tableIndex, tscJoinQueryCallback, pSupporter, TSDB_SQL_SELECT, NULL);
H
hjxilinx 已提交
1281
  if (pNew == NULL) {
1282
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1283 1284
  }
  
H
Haojun Liao 已提交
1285 1286
  pSql->pSubs[pSql->subState.numOfRemain++] = pNew;
  assert(pSql->subState.numOfRemain <= pSql->subState.numOfSub);
H
hjxilinx 已提交
1287 1288 1289 1290 1291 1292 1293 1294
  
  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);
    
1295 1296 1297 1298 1299 1300 1301
    // 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 已提交
1302 1303 1304 1305 1306 1307 1308
    pSupporter->colList = pNewQueryInfo->colList;
    pNewQueryInfo->colList = NULL;
    
    pSupporter->exprList = pNewQueryInfo->exprList;
    pNewQueryInfo->exprList = NULL;
    
    pSupporter->fieldsInfo = pNewQueryInfo->fieldsInfo;
H
hjxilinx 已提交
1309
  
H
hjxilinx 已提交
1310 1311
    // this data needs to be transfer to support struct
    memset(&pNewQueryInfo->fieldsInfo, 0, sizeof(SFieldInfo));
H
Haojun Liao 已提交
1312 1313 1314
    if (tscTagCondCopy(&pSupporter->tagCond, &pNewQueryInfo->tagCond) != 0) {
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
    }
H
Haojun Liao 已提交
1315

H
hjxilinx 已提交
1316
    pNew->cmd.numOfCols = 0;
1317
    pNewQueryInfo->interval.interval = 0;
H
Haojun Liao 已提交
1318 1319 1320 1321 1322
    pSupporter->limit = pNewQueryInfo->limit;

    pNewQueryInfo->limit.limit = -1;
    pNewQueryInfo->limit.offset = 0;

H
hjxilinx 已提交
1323 1324 1325
    // backup the data and clear it in the sqlcmd object
    memset(&pNewQueryInfo->groupbyExpr, 0, sizeof(SSqlGroupbyExpr));
    
H
hjxilinx 已提交
1326
    tscInitQueryInfo(pNewQueryInfo);
H
hjxilinx 已提交
1327 1328
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pNewQueryInfo, 0);
    
weixin_48148422's avatar
weixin_48148422 已提交
1329
    if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) { // return the tableId & tag
H
Haojun Liao 已提交
1330
      SColumnIndex colIndex = {0};
H
Haojun Liao 已提交
1331 1332 1333 1334

      STagCond* pTagCond = &pSupporter->tagCond;
      assert(pTagCond->joinInfo.hasJoin);

1335
      int32_t tagColId = tscGetJoinTagColIdByUid(pTagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
1336
      SSchema* s = tscGetTableColumnSchemaById(pTableMetaInfo->pTableMeta, tagColId);
H
Haojun Liao 已提交
1337

1338 1339 1340 1341 1342
      // get the tag colId column index
      int32_t numOfTags = tscGetNumOfTags(pTableMetaInfo->pTableMeta);
      SSchema* pSchema = tscGetTableTagSchema(pTableMetaInfo->pTableMeta);
      for(int32_t i = 0; i < numOfTags; ++i) {
        if (pSchema[i].colId == tagColId) {
H
Haojun Liao 已提交
1343
          colIndex.columnIndex = i;
1344 1345 1346 1347
          break;
        }
      }

H
Haojun Liao 已提交
1348
      int16_t bytes = 0;
H
Haojun Liao 已提交
1349
      int16_t type  = 0;
H
Haojun Liao 已提交
1350 1351
      int32_t inter = 0;

H
Haojun Liao 已提交
1352
      getResultDataInfo(s->type, s->bytes, TSDB_FUNC_TID_TAG, 0, &type, &bytes, &inter, 0, 0);
H
Haojun Liao 已提交
1353

S
Shengliang Guan 已提交
1354
      SSchema s1 = {.colId = s->colId, .type = (uint8_t)type, .bytes = bytes};
H
Haojun Liao 已提交
1355
      pSupporter->tagSize = s1.bytes;
1356
      assert(isValidDataType(s1.type) && s1.bytes > 0);
H
Haojun Liao 已提交
1357

1358 1359
      // set get tags query type
      TSDB_QUERY_SET_TYPE(pNewQueryInfo->type, TSDB_QUERY_TYPE_TAG_FILTER_QUERY);
H
Haojun Liao 已提交
1360
      tscAddSpecialColumnForSelect(pNewQueryInfo, 0, TSDB_FUNC_TID_TAG, &colIndex, &s1, TSDB_COL_TAG);
1361
      size_t numOfCols = taosArrayGetSize(pNewQueryInfo->colList);
1362
  
1363
      tscDebug(
1364
          "%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%d, transfer to tid_tag query to retrieve (tableId, tags), "
S
TD-1057  
Shengliang Guan 已提交
1365
          "exprInfo:%" PRIzu ", colList:%" PRIzu ", fieldsInfo:%d, tagIndex:%d, name:%s",
1366
          pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
H
Haojun Liao 已提交
1367
          numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, colIndex.columnIndex, pNewQueryInfo->pTableMetaInfo[0]->name);
1368 1369
    } else {
      SSchema      colSchema = {.type = TSDB_DATA_TYPE_BINARY, .bytes = 1};
H
Haojun Liao 已提交
1370 1371
      SColumnIndex colIndex = {0, PRIMARYKEY_TIMESTAMP_COL_INDEX};
      tscAddSpecialColumnForSelect(pNewQueryInfo, 0, TSDB_FUNC_TS_COMP, &colIndex, &colSchema, TSDB_COL_NORMAL);
1372 1373 1374 1375

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

H
Haojun Liao 已提交
1376
      if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
1377
        int16_t tagColId = tscGetJoinTagColIdByUid(&pSupporter->tagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
1378 1379 1380
        pExpr->param->i64Key = tagColId;
        pExpr->numOfParams = 1;
      }
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397

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

1398
      tscDebug(
B
Bomin Zhang 已提交
1399
          "%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%u, transfer to ts_comp query to retrieve timestamps, "
S
TD-1057  
Shengliang Guan 已提交
1400
          "exprInfo:%" PRIzu ", colList:%" PRIzu ", fieldsInfo:%d, name:%s",
1401 1402 1403
          pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
          numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, pNewQueryInfo->pTableMetaInfo[0]->name);
    }
H
hjxilinx 已提交
1404
  } else {
H
hjxilinx 已提交
1405
    assert(0);
H
hjxilinx 已提交
1406 1407 1408 1409
    SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    pNewQueryInfo->type |= TSDB_QUERY_TYPE_SUBQUERY;
  }

H
Haojun Liao 已提交
1410
  return TSDB_CODE_SUCCESS;
H
hjxilinx 已提交
1411 1412
}

H
Haojun Liao 已提交
1413
void tscHandleMasterJoinQuery(SSqlObj* pSql) {
H
hjxilinx 已提交
1414
  SSqlCmd* pCmd = &pSql->cmd;
H
Haojun Liao 已提交
1415 1416
  SSqlRes* pRes = &pSql->res;

H
hjxilinx 已提交
1417 1418
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  assert((pQueryInfo->type & TSDB_QUERY_TYPE_SUBQUERY) == 0);
1419

H
Haojun Liao 已提交
1420
  int32_t code = TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1421
  pSql->subState.numOfSub = pQueryInfo->numOfTables;
H
Haojun Liao 已提交
1422

H
Haojun Liao 已提交
1423 1424
  bool hasEmptySub = false;

1425
  tscDebug("%p start subquery, total:%d", pSql, pQueryInfo->numOfTables);
H
hjxilinx 已提交
1426
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
H
Haojun Liao 已提交
1427
    SJoinSupporter *pSupporter = tscCreateJoinSupporter(pSql, i);
H
hjxilinx 已提交
1428 1429 1430
    
    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);
H
Haojun Liao 已提交
1431 1432
      code = TSDB_CODE_TSC_OUT_OF_MEMORY;
      goto _error;
H
hjxilinx 已提交
1433 1434
    }
    
H
Haojun Liao 已提交
1435
    code = tscCreateJoinSubquery(pSql, i, pSupporter);
H
hjxilinx 已提交
1436 1437
    if (code != TSDB_CODE_SUCCESS) {  // failed to create subquery object, quit query
      tscDestroyJoinSupporter(pSupporter);
H
Haojun Liao 已提交
1438 1439 1440 1441 1442 1443 1444
      goto _error;
    }

    SSqlObj* pSub = pSql->pSubs[i];
    STableMetaInfo* pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSub->cmd, 0, 0);
    if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo) && (pTableMetaInfo->vgroupList->numOfVgroups == 0)) {
      hasEmptySub = true;
H
hjxilinx 已提交
1445 1446 1447
      break;
    }
  }
H
Haojun Liao 已提交
1448

H
Haojun Liao 已提交
1449 1450 1451 1452 1453
  if (hasEmptySub) {  // at least one subquery is empty, do nothing and return
    freeJoinSubqueryObj(pSql);
    pSql->cmd.command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
    (*pSql->fp)(pSql->param, pSql, 0);
  } else {
H
Haojun Liao 已提交
1454
    for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
Haojun Liao 已提交
1455 1456
      SSqlObj* pSub = pSql->pSubs[i];
      if ((code = tscProcessSql(pSub)) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1457
        pSql->subState.numOfRemain = i - 1;  // the already sent request will continue and do not go to the error process routine
H
Haojun Liao 已提交
1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
        break;
      }
    }

    pSql->cmd.command = TSDB_SQL_TABLE_JOIN_RETRIEVE;
  }

  return;

  _error:
  pRes->code = code;
  tscQueueAsyncRes(pSql);
H
hjxilinx 已提交
1470 1471
}

H
Haojun Liao 已提交
1472 1473
static void doCleanupSubqueries(SSqlObj *pSql, int32_t numOfSubs) {
  assert(numOfSubs <= pSql->subState.numOfSub && numOfSubs >= 0);
H
hjxilinx 已提交
1474 1475 1476 1477 1478 1479 1480
  
  for(int32_t i = 0; i < numOfSubs; ++i) {
    SSqlObj* pSub = pSql->pSubs[i];
    assert(pSub != NULL);
    
    SRetrieveSupport* pSupport = pSub->param;
    
S
Shengliang Guan 已提交
1481 1482
    taosTFree(pSupport->localBuffer);
    taosTFree(pSupport);
H
hjxilinx 已提交
1483
    
1484
    taos_free_result(pSub);
H
hjxilinx 已提交
1485 1486 1487 1488 1489 1490 1491 1492
  }
}

int32_t tscHandleMasterSTableQuery(SSqlObj *pSql) {
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;
  
  // pRes->code check only serves in launching metric sub-queries
1493
  if (pRes->code == TSDB_CODE_TSC_QUERY_CANCELLED) {
H
hjxilinx 已提交
1494
    pCmd->command = TSDB_SQL_RETRIEVE_LOCALMERGE;  // enable the abort of kill super table function.
H
hjxilinx 已提交
1495 1496 1497 1498 1499 1500 1501
    return pRes->code;
  }
  
  tExtMemBuffer **  pMemoryBuf = NULL;
  tOrderDescriptor *pDesc = NULL;
  SColumnModel *    pModel = NULL;
  
H
Haojun Liao 已提交
1502
  pRes->qhandle = 0x1;  // hack the qhandle check
H
hjxilinx 已提交
1503
  
1504
  const uint32_t nBufferSize = (1u << 16);  // 64KB
H
hjxilinx 已提交
1505
  
H
Haojun Liao 已提交
1506
  SQueryInfo     *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
1507
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
Haojun Liao 已提交
1508 1509
  SSubqueryState *pState = &pSql->subState;

H
Haojun Liao 已提交
1510 1511 1512 1513
  pState->numOfSub = 0;
  if (pTableMetaInfo->pVgroupTables == NULL) {
    pState->numOfSub = pTableMetaInfo->vgroupList->numOfVgroups;
  } else {
S
Shengliang Guan 已提交
1514
    pState->numOfSub = (int32_t)taosArrayGetSize(pTableMetaInfo->pVgroupTables);
H
Haojun Liao 已提交
1515 1516
  }

H
Haojun Liao 已提交
1517
  assert(pState->numOfSub > 0);
H
hjxilinx 已提交
1518 1519 1520
  
  int32_t ret = tscLocalReducerEnvCreate(pSql, &pMemoryBuf, &pDesc, &pModel, nBufferSize);
  if (ret != 0) {
1521
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1522
    tscQueueAsyncRes(pSql);
S
Shengliang Guan 已提交
1523
    taosTFree(pMemoryBuf);
H
hjxilinx 已提交
1524
    return ret;
H
hjxilinx 已提交
1525 1526
  }
  
H
Haojun Liao 已提交
1527
  pSql->pSubs = calloc(pState->numOfSub, POINTER_BYTES);
H
Haojun Liao 已提交
1528

H
Haojun Liao 已提交
1529
  tscDebug("%p retrieved query data from %d vnode(s)", pSql, pState->numOfSub);
H
Haojun Liao 已提交
1530

H
Haojun Liao 已提交
1531
  if (pSql->pSubs == NULL) {
H
Haojun Liao 已提交
1532 1533
    taosTFree(pSql->pSubs);
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
Haojun Liao 已提交
1534
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pState->numOfSub);
H
Haojun Liao 已提交
1535 1536 1537 1538 1539

    tscQueueAsyncRes(pSql);
    return ret;
  }

H
Haojun Liao 已提交
1540
  pState->numOfRemain = pState->numOfSub;
H
hjxilinx 已提交
1541 1542 1543
  pRes->code = TSDB_CODE_SUCCESS;
  
  int32_t i = 0;
H
Haojun Liao 已提交
1544
  for (; i < pState->numOfSub; ++i) {
H
hjxilinx 已提交
1545 1546 1547 1548 1549 1550 1551 1552
    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;
H
Haojun Liao 已提交
1553

H
hjxilinx 已提交
1554 1555 1556
    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));
S
Shengliang Guan 已提交
1557
      taosTFree(trs);
H
hjxilinx 已提交
1558 1559 1560
      break;
    }
    
H
Haojun Liao 已提交
1561 1562
    trs->subqueryIndex  = i;
    trs->pParentSql     = pSql;
H
hjxilinx 已提交
1563 1564
    trs->pFinalColModel = pModel;
    
1565
    SSqlObj *pNew = tscCreateSTableSubquery(pSql, trs, NULL);
H
hjxilinx 已提交
1566 1567
    if (pNew == NULL) {
      tscError("%p failed to malloc buffer for subObj, orderOfSub:%d, reason:%s", pSql, i, strerror(errno));
S
Shengliang Guan 已提交
1568 1569
      taosTFree(trs->localBuffer);
      taosTFree(trs);
H
hjxilinx 已提交
1570 1571 1572 1573 1574 1575 1576
      break;
    }
    
    // todo handle multi-vnode situation
    if (pQueryInfo->tsBuf) {
      SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
      pNewQueryInfo->tsBuf = tsBufClone(pQueryInfo->tsBuf);
H
Haojun Liao 已提交
1577
      assert(pNewQueryInfo->tsBuf != NULL);
H
hjxilinx 已提交
1578 1579
    }
    
1580
    tscDebug("%p sub:%p create subquery success. orderOfSub:%d", pSql, pNew, trs->subqueryIndex);
H
hjxilinx 已提交
1581 1582
  }
  
H
Haojun Liao 已提交
1583
  if (i < pState->numOfSub) {
H
hjxilinx 已提交
1584
    tscError("%p failed to prepare subquery structure and launch subqueries", pSql);
1585
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1586
    
H
Haojun Liao 已提交
1587
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pState->numOfSub);
H
Haojun Liao 已提交
1588
    doCleanupSubqueries(pSql, i);
H
hjxilinx 已提交
1589 1590 1591
    return pRes->code;   // free all allocated resource
  }
  
1592
  if (pRes->code == TSDB_CODE_TSC_QUERY_CANCELLED) {
H
Haojun Liao 已提交
1593
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pState->numOfSub);
H
Haojun Liao 已提交
1594
    doCleanupSubqueries(pSql, i);
H
hjxilinx 已提交
1595 1596 1597
    return pRes->code;
  }
  
H
Haojun Liao 已提交
1598
  for(int32_t j = 0; j < pState->numOfSub; ++j) {
H
hjxilinx 已提交
1599 1600 1601
    SSqlObj* pSub = pSql->pSubs[j];
    SRetrieveSupport* pSupport = pSub->param;
    
1602
    tscDebug("%p sub:%p launch subquery, orderOfSub:%d.", pSql, pSub, pSupport->subqueryIndex);
H
hjxilinx 已提交
1603 1604
    tscProcessSql(pSub);
  }
H
Haojun Liao 已提交
1605

H
hjxilinx 已提交
1606 1607 1608
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1609 1610
static void tscFreeRetrieveSup(SSqlObj *pSql) {
  SRetrieveSupport *trsupport = pSql->param;
1611

H
Haojun Liao 已提交
1612 1613 1614 1615 1616 1617 1618
  void* p = atomic_val_compare_exchange_ptr(&pSql->param, trsupport, 0);
  if (p == NULL) {
    tscDebug("%p retrieve supp already released", pSql);
    return;
  }

  tscDebug("%p start to free subquery supp obj:%p", pSql, trsupport);
H
Haojun Liao 已提交
1619 1620
//  int32_t  index = trsupport->subqueryIndex;
//  SSqlObj *pParentSql = trsupport->pParentSql;
1621

H
Haojun Liao 已提交
1622
//  assert(pSql == pParentSql->pSubs[index]);
S
Shengliang Guan 已提交
1623 1624
  taosTFree(trsupport->localBuffer);
  taosTFree(trsupport);
H
hjxilinx 已提交
1625 1626
}

1627
static void tscRetrieveFromDnodeCallBack(void *param, TAOS_RES *tres, int numOfRows);
1628
static void tscHandleSubqueryError(SRetrieveSupport *trsupport, SSqlObj *pSql, int numOfRows);
H
hjxilinx 已提交
1629

H
Haojun Liao 已提交
1630
static void tscAbortFurtherRetryRetrieval(SRetrieveSupport *trsupport, TAOS_RES *tres, int32_t code) {
H
hjxilinx 已提交
1631
// set no disk space error info
1632
  tscError("sub:%p failed to flush data to disk, reason:%s", tres, tstrerror(code));
H
Haojun Liao 已提交
1633
  SSqlObj* pParentSql = trsupport->pParentSql;
H
Haojun Liao 已提交
1634 1635

  pParentSql->res.code = code;
H
hjxilinx 已提交
1636
  trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
H
Haojun Liao 已提交
1637
  tscHandleSubqueryError(trsupport, tres, pParentSql->res.code);
H
hjxilinx 已提交
1638 1639
}

H
Haojun Liao 已提交
1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
/*
 * 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
 */
static int32_t tscReissueSubquery(SRetrieveSupport *trsupport, SSqlObj *pSql, int32_t code) {
  SSqlObj *pParentSql = trsupport->pParentSql;
  int32_t  subqueryIndex = trsupport->subqueryIndex;

  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
  SCMVgroupInfo* pVgroup = &pTableMetaInfo->vgroupList->vgroups[0];

  tExtMemBufferClear(trsupport->pExtMemBuffer[subqueryIndex]);

  // clear local saved number of results
  trsupport->localBuffer->num = 0;
1655
  tscError("%p sub:%p retrieve/query failed, code:%s, orderOfSub:%d, retry:%d", trsupport->pParentSql, pSql,
H
Haojun Liao 已提交
1656 1657
           tstrerror(code), subqueryIndex, trsupport->numOfRetry);

1658
  SSqlObj *pNew = tscCreateSTableSubquery(trsupport->pParentSql, trsupport, pSql);
H
Haojun Liao 已提交
1659
  if (pNew == NULL) {
1660 1661
    tscError("%p sub:%p failed to create new subquery due to error:%s, abort retry, vgId:%d, orderOfSub:%d",
             trsupport->pParentSql, pSql, tstrerror(terrno), pVgroup->vgId, trsupport->subqueryIndex);
H
Haojun Liao 已提交
1662

1663
    pParentSql->res.code = terrno;
H
Haojun Liao 已提交
1664 1665 1666 1667 1668
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;

    return pParentSql->res.code;
  }

1669 1670 1671 1672 1673
  int32_t ret = tscProcessSql(pNew);

  // if failed to process sql, let following code handle the pSql
  if (ret == TSDB_CODE_SUCCESS) {
    taos_free_result(pSql);
H
Haojun Liao 已提交
1674 1675 1676
    return ret;
  } else {
    return ret;
1677
  }
H
Haojun Liao 已提交
1678 1679
}

1680
void tscHandleSubqueryError(SRetrieveSupport *trsupport, SSqlObj *pSql, int numOfRows) {
H
Haojun Liao 已提交
1681 1682 1683 1684 1685
  // it has been freed already
  if (pSql->param != trsupport || pSql->param == NULL) {
    return;
  }

H
Haojun Liao 已提交
1686
  SSqlObj *pParentSql = trsupport->pParentSql;
H
hjxilinx 已提交
1687 1688 1689
  int32_t  subqueryIndex = trsupport->subqueryIndex;
  
  assert(pSql != NULL);
H
Haojun Liao 已提交
1690

H
Haojun Liao 已提交
1691 1692
  SSubqueryState* pState = &pParentSql->subState;
  assert(pState->numOfRemain <= pState->numOfSub && pState->numOfRemain >= 0);
H
Haojun Liao 已提交
1693

1694
  // retrieved in subquery failed. OR query cancelled in retrieve phase.
H
Haojun Liao 已提交
1695 1696
  if (taos_errno(pSql) == TSDB_CODE_SUCCESS && pParentSql->res.code != TSDB_CODE_SUCCESS) {

H
hjxilinx 已提交
1697 1698
    /*
     * kill current sub-query connection, which may retrieve data from vnodes;
1699
     * Here we get: pPObj->res.code == TSDB_CODE_TSC_QUERY_CANCELLED
H
hjxilinx 已提交
1700 1701 1702
     */
    pSql->res.numOfRows = 0;
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;  // disable retry efforts
1703 1704
    tscDebug("%p query is cancelled, sub:%p, orderOfSub:%d abort retrieve, code:%s", pParentSql, pSql,
             subqueryIndex, tstrerror(pParentSql->res.code));
H
hjxilinx 已提交
1705
  }
H
Haojun Liao 已提交
1706

H
hjxilinx 已提交
1707
  if (numOfRows >= 0) {  // current query is successful, but other sub query failed, still abort current query.
1708
    tscDebug("%p sub:%p retrieve numOfRows:%d,orderOfSub:%d", pParentSql, pSql, numOfRows, subqueryIndex);
1709 1710
    tscError("%p sub:%p abort further retrieval due to other queries failure,orderOfSub:%d,code:%s", pParentSql, pSql,
             subqueryIndex, tstrerror(pParentSql->res.code));
H
hjxilinx 已提交
1711
  } else {
H
Haojun Liao 已提交
1712
    if (trsupport->numOfRetry++ < MAX_NUM_OF_SUBQUERY_RETRY && pParentSql->res.code == TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1713
      if (tscReissueSubquery(trsupport, pSql, numOfRows) == TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1714 1715 1716
        return;
      }
    } else {  // reach the maximum retry count, abort
H
Haojun Liao 已提交
1717 1718 1719
      atomic_val_compare_exchange_32(&pParentSql->res.code, TSDB_CODE_SUCCESS, numOfRows);
      tscError("%p sub:%p retrieve failed,code:%s,orderOfSub:%d failed.no more retry,set global code:%s", pParentSql, pSql,
               tstrerror(numOfRows), subqueryIndex, tstrerror(pParentSql->res.code));
H
hjxilinx 已提交
1720 1721
    }
  }
H
Haojun Liao 已提交
1722

H
Haojun Liao 已提交
1723 1724
  int32_t remain = -1;
  if ((remain = atomic_sub_fetch_32(&pState->numOfRemain, 1)) > 0) {
1725
    tscDebug("%p sub:%p orderOfSub:%d freed, finished subqueries:%d", pParentSql, pSql, trsupport->subqueryIndex,
H
Haojun Liao 已提交
1726
        pState->numOfSub - remain);
H
Haojun Liao 已提交
1727

H
Haojun Liao 已提交
1728
    tscFreeRetrieveSup(pSql);
S
Shengliang Guan 已提交
1729
    return;
H
hjxilinx 已提交
1730 1731 1732
  }
  
  // all subqueries are failed
H
Haojun Liao 已提交
1733
  tscError("%p retrieve from %d vnode(s) completed,code:%s.FAILED.", pParentSql, pState->numOfSub,
H
Haojun Liao 已提交
1734 1735
      tstrerror(pParentSql->res.code));

H
hjxilinx 已提交
1736 1737
  // release allocated resource
  tscLocalReducerEnvDestroy(trsupport->pExtMemBuffer, trsupport->pOrderDescriptor, trsupport->pFinalColModel,
H
Haojun Liao 已提交
1738
                            pState->numOfSub);
H
hjxilinx 已提交
1739
  
H
Haojun Liao 已提交
1740
  tscFreeRetrieveSup(pSql);
1741

H
hjxilinx 已提交
1742
  // in case of second stage join subquery, invoke its callback function instead of regular QueueAsyncRes
1743 1744 1745 1746 1747 1748 1749 1750 1751
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pParentSql->cmd, 0);

  if (!TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_SEC_STAGE)) {
    (*pParentSql->fp)(pParentSql->param, pParentSql, pParentSql->res.code);
  } else {  // regular super table query
    if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
      tscQueueAsyncRes(pParentSql);
    }
  }
H
hjxilinx 已提交
1752 1753
}

1754 1755
static void tscAllDataRetrievedFromDnode(SRetrieveSupport *trsupport, SSqlObj* pSql) {
  int32_t           idx = trsupport->subqueryIndex;
H
Haojun Liao 已提交
1756
  SSqlObj *         pParentSql = trsupport->pParentSql;
1757 1758
  tOrderDescriptor *pDesc = trsupport->pOrderDescriptor;
  
H
Haojun Liao 已提交
1759
  SSubqueryState* pState = &pParentSql->subState;
1760 1761
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
  
1762 1763
  STableMetaInfo* pTableMetaInfo = pQueryInfo->pTableMetaInfo[0];
  
1764
  // data in from current vnode is stored in cache and disk
S
Shengliang Guan 已提交
1765
  uint32_t numOfRowsFromSubquery = (uint32_t)(trsupport->pExtMemBuffer[idx]->numOfTotalElems + trsupport->localBuffer->num);
H
Haojun Liao 已提交
1766 1767 1768
  SVgroupsInfo* vgroupsInfo = pTableMetaInfo->vgroupList;
  tscDebug("%p sub:%p all data retrieved from ep:%s, vgId:%d, numOfRows:%d, orderOfSub:%d", pParentSql, pSql,
           vgroupsInfo->vgroups[0].epAddr[0].fqdn, vgroupsInfo->vgroups[0].vgId, numOfRowsFromSubquery, idx);
1769 1770 1771 1772
  
  tColModelCompact(pDesc->pColumnModel, trsupport->localBuffer, pDesc->pColumnModel->capacity);

#ifdef _DEBUG_VIEW
1773
  printf("%" PRIu64 " rows data flushed to disk:\n", trsupport->localBuffer->num);
1774 1775
    SSrcColumnInfo colInfo[256] = {0};
    tscGetSrcColumnInfo(colInfo, pQueryInfo);
1776 1777
    tColModelDisplayEx(pDesc->pColumnModel, trsupport->localBuffer->data, trsupport->localBuffer->num,
                       trsupport->localBuffer->num, colInfo);
1778 1779
#endif
  
H
Haojun Liao 已提交
1780 1781 1782
  if (tsTotalTmpDirGB != 0 && tsAvailTmpDirectorySpace < tsReservedTmpDirectorySpace) {
    tscError("%p sub:%p client disk space remain %.3f GB, need at least %.3f GB, stop query", pParentSql, pSql,
             tsAvailTmpDirectorySpace, tsReservedTmpDirectorySpace);
S
Shengliang Guan 已提交
1783 1784
    tscAbortFurtherRetryRetrieval(trsupport, pSql, TSDB_CODE_TSC_NO_DISKSPACE);
    return;
1785 1786 1787
  }
  
  // each result for a vnode is ordered as an independant list,
H
Haojun Liao 已提交
1788
  // then used as an input of loser tree for disk-based merge
1789 1790
  int32_t code = tscFlushTmpBuffer(trsupport->pExtMemBuffer[idx], pDesc, trsupport->localBuffer, pQueryInfo->groupbyExpr.orderType);
  if (code != 0) { // set no disk space error info, and abort retry
S
Shengliang Guan 已提交
1791 1792
    tscAbortFurtherRetryRetrieval(trsupport, pSql, code);
    return;
1793 1794
  }
  
H
Haojun Liao 已提交
1795
  int32_t remain = -1;
H
Haojun Liao 已提交
1796
  if ((remain = atomic_sub_fetch_32(&pParentSql->subState.numOfRemain, 1)) > 0) {
H
Haojun Liao 已提交
1797
    tscDebug("%p sub:%p orderOfSub:%d freed, finished subqueries:%d", pParentSql, pSql, trsupport->subqueryIndex,
H
Haojun Liao 已提交
1798
        pState->numOfSub - remain);
H
Haojun Liao 已提交
1799

H
Haojun Liao 已提交
1800
    tscFreeRetrieveSup(pSql);
S
Shengliang Guan 已提交
1801
    return;
1802 1803 1804 1805 1806
  }
  
  // all sub-queries are returned, start to local merge process
  pDesc->pColumnModel->capacity = trsupport->pExtMemBuffer[idx]->numOfElemsPerPage;
  
H
Haojun Liao 已提交
1807
  tscDebug("%p retrieve from %d vnodes completed.final NumOfRows:%" PRId64 ",start to build loser tree", pParentSql,
H
Haojun Liao 已提交
1808
           pState->numOfSub, pState->numOfRetrievedRows);
1809
  
H
Haojun Liao 已提交
1810
  SQueryInfo *pPQueryInfo = tscGetQueryInfoDetail(&pParentSql->cmd, 0);
1811 1812
  tscClearInterpInfo(pPQueryInfo);
  
H
Haojun Liao 已提交
1813
  tscCreateLocalReducer(trsupport->pExtMemBuffer, pState->numOfSub, pDesc, trsupport->pFinalColModel, pParentSql);
H
Haojun Liao 已提交
1814
  tscDebug("%p build loser tree completed", pParentSql);
1815
  
H
Haojun Liao 已提交
1816 1817 1818
  pParentSql->res.precision = pSql->res.precision;
  pParentSql->res.numOfRows = 0;
  pParentSql->res.row = 0;
1819
  
H
Haojun Liao 已提交
1820
  tscFreeRetrieveSup(pSql);
H
Haojun Liao 已提交
1821

1822 1823 1824 1825 1826 1827 1828
  // set the command flag must be after the semaphore been correctly set.
  pParentSql->cmd.command = TSDB_SQL_RETRIEVE_LOCALMERGE;
  if (pParentSql->res.code == TSDB_CODE_SUCCESS) {
    (*pParentSql->fp)(pParentSql->param, pParentSql, 0);
  } else {
    tscQueueAsyncRes(pParentSql);
  }
1829 1830 1831
}

static void tscRetrieveFromDnodeCallBack(void *param, TAOS_RES *tres, int numOfRows) {
H
Haojun Liao 已提交
1832 1833 1834 1835
  SSqlObj *pSql = (SSqlObj *)tres;
  assert(pSql != NULL);

  // this query has been freed already
H
hjxilinx 已提交
1836
  SRetrieveSupport *trsupport = (SRetrieveSupport *)param;
H
Haojun Liao 已提交
1837 1838 1839 1840 1841 1842
  if (pSql->param == NULL || param == NULL) {
    tscDebug("%p already freed in dnodecallback", pSql);
    assert(pSql->res.code == TSDB_CODE_TSC_QUERY_CANCELLED);
    return;
  }

H
hjxilinx 已提交
1843
  tOrderDescriptor *pDesc = trsupport->pOrderDescriptor;
H
Haojun Liao 已提交
1844
  int32_t           idx   = trsupport->subqueryIndex;
H
Haojun Liao 已提交
1845
  SSqlObj *         pParentSql = trsupport->pParentSql;
H
Haojun Liao 已提交
1846

H
Haojun Liao 已提交
1847 1848
  SSubqueryState* pState = &pParentSql->subState;
  assert(pState->numOfRemain <= pState->numOfSub && pState->numOfRemain >= 0);
H
hjxilinx 已提交
1849
  
H
Haojun Liao 已提交
1850
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
1851
  SCMVgroupInfo  *pVgroup = &pTableMetaInfo->vgroupList->vgroups[0];
H
Haojun Liao 已提交
1852 1853 1854

  if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
1855
    tscDebug("%p query cancelled/failed, sub:%p, vgId:%d, orderOfSub:%d, code:%s, global code:%s",
H
Haojun Liao 已提交
1856 1857 1858 1859 1860 1861 1862 1863 1864
             pParentSql, pSql, pVgroup->vgId, trsupport->subqueryIndex, tstrerror(numOfRows), tstrerror(pParentSql->res.code));

    tscHandleSubqueryError(param, tres, numOfRows);
    return;
  }

  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(numOfRows == taos_errno(pSql));

H
Haojun Liao 已提交
1865 1866 1867 1868
    if (numOfRows == TSDB_CODE_TSC_QUERY_CANCELLED) {
      trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
    }

H
Haojun Liao 已提交
1869
    if (trsupport->numOfRetry++ < MAX_NUM_OF_SUBQUERY_RETRY) {
1870
      tscError("%p sub:%p failed code:%s, retry:%d", pParentSql, pSql, tstrerror(numOfRows), trsupport->numOfRetry);
H
Haojun Liao 已提交
1871 1872 1873 1874 1875

      if (tscReissueSubquery(trsupport, pSql, numOfRows) == TSDB_CODE_SUCCESS) {
        return;
      }
    } else {
H
Haojun Liao 已提交
1876
      tscDebug("%p sub:%p reach the max retry times, set global code:%s", pParentSql, pSql, tstrerror(numOfRows));
H
Haojun Liao 已提交
1877 1878 1879 1880 1881
      atomic_val_compare_exchange_32(&pParentSql->res.code, TSDB_CODE_SUCCESS, numOfRows);  // set global code and abort
    }

    tscHandleSubqueryError(param, tres, numOfRows);
    return;
H
hjxilinx 已提交
1882 1883 1884 1885 1886 1887 1888 1889 1890
  }
  
  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);
    
1891 1892
    tscDebug("%p sub:%p retrieve numOfRows:%" PRId64 " totalNumOfRows:%" PRIu64 " from ep:%s, orderOfSub:%d", pParentSql, pSql,
             pRes->numOfRows, pState->numOfRetrievedRows, pSql->epSet.fqdn[pSql->epSet.inUse], idx);
1893

H
hjxilinx 已提交
1894
    if (num > tsMaxNumOfOrderedResults && tscIsProjectionQueryOnSTable(pQueryInfo, 0)) {
B
Bomin Zhang 已提交
1895
      tscError("%p sub:%p num of OrderedRes is too many, max allowed:%" PRId32 " , current:%" PRId64,
H
Haojun Liao 已提交
1896
               pParentSql, pSql, tsMaxNumOfOrderedResults, num);
S
Shengliang Guan 已提交
1897 1898
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_SORTED_RES_TOO_MANY);
      return;
H
hjxilinx 已提交
1899 1900 1901
    }

#ifdef _DEBUG_VIEW
1902
    printf("received data from vnode: %"PRIu64" rows\n", pRes->numOfRows);
H
hjxilinx 已提交
1903 1904 1905 1906 1907
    SSrcColumnInfo colInfo[256] = {0};

    tscGetSrcColumnInfo(colInfo, pQueryInfo);
    tColModelDisplayEx(pDesc->pColumnModel, pRes->data, pRes->numOfRows, pRes->numOfRows, colInfo);
#endif
1908
    
H
Haojun Liao 已提交
1909 1910 1911 1912
    // no disk space for tmp directory
    if (tsTotalTmpDirGB != 0 && tsAvailTmpDirectorySpace < tsReservedTmpDirectorySpace) {
      tscError("%p sub:%p client disk space remain %.3f GB, need at least %.3f GB, stop query", pParentSql, pSql,
               tsAvailTmpDirectorySpace, tsReservedTmpDirectorySpace);
S
Shengliang Guan 已提交
1913 1914
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_NO_DISKSPACE);
      return;
H
hjxilinx 已提交
1915 1916 1917
    }
    
    int32_t ret = saveToBuffer(trsupport->pExtMemBuffer[idx], pDesc, trsupport->localBuffer, pRes->data,
S
Shengliang Guan 已提交
1918
                               (int32_t)pRes->numOfRows, pQueryInfo->groupbyExpr.orderType);
1919
    if (ret != 0) { // set no disk space error info, and abort retry
1920
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_NO_DISKSPACE);
1921 1922 1923 1924
    } else if (pRes->completed) {
      tscAllDataRetrievedFromDnode(trsupport, pSql);
    } else { // continue fetch data from dnode
      taos_fetch_rows_a(tres, tscRetrieveFromDnodeCallBack, param);
H
hjxilinx 已提交
1925
    }
1926
    
1927 1928
  } else { // all data has been retrieved to client
    tscAllDataRetrievedFromDnode(trsupport, pSql);
H
hjxilinx 已提交
1929 1930 1931
  }
}

1932
static SSqlObj *tscCreateSTableSubquery(SSqlObj *pSql, SRetrieveSupport *trsupport, SSqlObj *prevSqlObj) {
H
hjxilinx 已提交
1933 1934
  const int32_t table_index = 0;
  
1935
  SSqlObj *pNew = createSubqueryObj(pSql, table_index, tscRetrieveDataRes, trsupport, TSDB_SQL_SELECT, prevSqlObj);
H
hjxilinx 已提交
1936 1937
  if (pNew != NULL) {  // the sub query of two-stage super table query
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
1938

H
hjxilinx 已提交
1939
    pQueryInfo->type |= TSDB_QUERY_TYPE_STABLE_SUBQUERY;
H
Haojun Liao 已提交
1940
    assert(pQueryInfo->numOfTables == 1 && pNew->cmd.numOfClause == 1 && trsupport->subqueryIndex < pSql->subState.numOfSub);
H
hjxilinx 已提交
1941
    
H
hjxilinx 已提交
1942
    // launch subquery for each vnode, so the subquery index equals to the vgroupIndex.
H
hjxilinx 已提交
1943
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, table_index);
H
hjxilinx 已提交
1944
    pTableMetaInfo->vgroupIndex = trsupport->subqueryIndex;
H
hjxilinx 已提交
1945 1946 1947 1948 1949 1950 1951 1952
    
    pSql->pSubs[trsupport->subqueryIndex] = pNew;
  }
  
  return pNew;
}

void tscRetrieveDataRes(void *param, TAOS_RES *tres, int code) {
1953
  SRetrieveSupport *trsupport = (SRetrieveSupport *) param;
H
hjxilinx 已提交
1954
  
H
Haojun Liao 已提交
1955
  SSqlObj*  pParentSql = trsupport->pParentSql;
1956
  SSqlObj*  pSql = (SSqlObj *) tres;
1957

1958 1959
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
  assert(pSql->cmd.numOfClause == 1 && pQueryInfo->numOfTables == 1);
H
hjxilinx 已提交
1960
  
1961
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
H
Haojun Liao 已提交
1962
  SCMVgroupInfo* pVgroup = &pTableMetaInfo->vgroupList->vgroups[trsupport->subqueryIndex];
H
Haojun Liao 已提交
1963

H
Haojun Liao 已提交
1964
  // stable query killed or other subquery failed, all query stopped
H
Haojun Liao 已提交
1965
  if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1966
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
H
Haojun Liao 已提交
1967
    tscError("%p query cancelled or failed, sub:%p, vgId:%d, orderOfSub:%d, code:%s, global code:%s",
H
Haojun Liao 已提交
1968 1969 1970 1971
        pParentSql, pSql, pVgroup->vgId, trsupport->subqueryIndex, tstrerror(code), tstrerror(pParentSql->res.code));

    tscHandleSubqueryError(param, tres, code);
    return;
H
hjxilinx 已提交
1972 1973 1974
  }
  
  /*
H
Haojun Liao 已提交
1975
   * if a subquery on a vnode failed, all retrieve operations from vnode that occurs later
1976
   * than this one are actually not necessary, we simply call the tscRetrieveFromDnodeCallBack
H
hjxilinx 已提交
1977 1978
   * function to abort current and remain retrieve process.
   *
1979
   * NOTE: thread safe is required.
H
hjxilinx 已提交
1980
   */
H
Haojun Liao 已提交
1981 1982
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(code == taos_errno(pSql));
1983

H
Haojun Liao 已提交
1984
    if (trsupport->numOfRetry++ < MAX_NUM_OF_SUBQUERY_RETRY) {
1985
      tscError("%p sub:%p failed code:%s, retry:%d", pParentSql, pSql, tstrerror(code), trsupport->numOfRetry);
H
Haojun Liao 已提交
1986
      if (tscReissueSubquery(trsupport, pSql, code) == TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1987 1988
        return;
      }
1989
    } else {
H
Haojun Liao 已提交
1990
      tscError("%p sub:%p reach the max retry times, set global code:%s", pParentSql, pSql, tstrerror(code));
H
Haojun Liao 已提交
1991
      atomic_val_compare_exchange_32(&pParentSql->res.code, TSDB_CODE_SUCCESS, code);  // set global code and abort
1992
    }
H
Haojun Liao 已提交
1993 1994 1995 1996 1997

    tscHandleSubqueryError(param, tres, pParentSql->res.code);
    return;
  }

H
Haojun Liao 已提交
1998
  tscDebug("%p sub:%p query complete, ep:%s, vgId:%d, orderOfSub:%d, retrieve data", trsupport->pParentSql, pSql,
1999
             pVgroup->epAddr[0].fqdn, pVgroup->vgId, trsupport->subqueryIndex);
H
Haojun Liao 已提交
2000 2001 2002 2003 2004

  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 已提交
2005 2006 2007
  }
}

H
Haojun Liao 已提交
2008
static void multiVnodeInsertFinalize(void* param, TAOS_RES* tres, int numOfRows) {
H
hjxilinx 已提交
2009 2010
  SInsertSupporter *pSupporter = (SInsertSupporter *)param;
  SSqlObj* pParentObj = pSupporter->pSql;
H
Haojun Liao 已提交
2011

H
Haojun Liao 已提交
2012
  // record the total inserted rows
H
Haojun Liao 已提交
2013 2014
  if (numOfRows > 0) {
    pParentObj->res.numOfRows += numOfRows;
H
Haojun Liao 已提交
2015 2016
  }

H
Haojun Liao 已提交
2017
  if (taos_errno(tres) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2018 2019 2020 2021
    SSqlObj* pSql = (SSqlObj*) tres;
    assert(pSql != NULL && pSql->res.code == numOfRows);
    
    pParentObj->res.code = pSql->res.code;
H
hjxilinx 已提交
2022
  }
H
Haojun Liao 已提交
2023

S
Shengliang Guan 已提交
2024
  taosTFree(pSupporter);
H
Haojun Liao 已提交
2025

H
Haojun Liao 已提交
2026
  if (atomic_sub_fetch_32(&pParentObj->subState.numOfRemain, 1) > 0) {
H
hjxilinx 已提交
2027 2028 2029
    return;
  }
  
2030
  tscDebug("%p Async insertion completed, total inserted:%" PRId64, pParentObj, pParentObj->res.numOfRows);
H
Haojun Liao 已提交
2031

H
hjxilinx 已提交
2032 2033
  // restore user defined fp
  pParentObj->fp = pParentObj->fetchFp;
2034 2035

  // todo remove this parameter in async callback function definition.
H
hjxilinx 已提交
2036
  // all data has been sent to vnode, call user function
S
Shengliang Guan 已提交
2037
  int32_t v = (pParentObj->res.code != TSDB_CODE_SUCCESS) ? pParentObj->res.code : (int32_t)pParentObj->res.numOfRows;
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051
  (*pParentObj->fp)(pParentObj->param, pParentObj, v);
}

/**
 * it is a subquery, so after parse the sql string, copy the submit block to payload of itself
 * @param pSql
 * @return
 */
int32_t tscHandleInsertRetry(SSqlObj* pSql) {
  assert(pSql != NULL && pSql->param != NULL);
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;

  SInsertSupporter* pSupporter = (SInsertSupporter*) pSql->param;
H
Haojun Liao 已提交
2052
  assert(pSupporter->index < pSupporter->pSql->subState.numOfSub);
2053 2054

  STableDataBlocks* pTableDataBlock = taosArrayGetP(pCmd->pDataBlocks, pSupporter->index);
H
Haojun Liao 已提交
2055 2056 2057 2058 2059
  int32_t code = tscCopyDataBlockToPayload(pSql, pTableDataBlock);

  if ((pRes->code = code)!= TSDB_CODE_SUCCESS) {
    tscQueueAsyncRes(pSql);
    return code;  // here the pSql may have been released already.
2060 2061 2062
  }

  return tscProcessSql(pSql);
H
hjxilinx 已提交
2063 2064 2065 2066
}

int32_t tscHandleMultivnodeInsert(SSqlObj *pSql) {
  SSqlCmd *pCmd = &pSql->cmd;
H
Haojun Liao 已提交
2067 2068
  SSqlRes *pRes = &pSql->res;

H
Haojun Liao 已提交
2069 2070
  pSql->subState.numOfSub = (uint16_t)taosArrayGetSize(pCmd->pDataBlocks);
  assert(pSql->subState.numOfSub > 0);
H
Haojun Liao 已提交
2071 2072

  pRes->code = TSDB_CODE_SUCCESS;
2073

H
Haojun Liao 已提交
2074 2075 2076
  // the number of already initialized subqueries
  int32_t numOfSub = 0;

H
Haojun Liao 已提交
2077 2078
  pSql->subState.numOfRemain = pSql->subState.numOfSub;
  pSql->pSubs = calloc(pSql->subState.numOfSub, POINTER_BYTES);
H
Haojun Liao 已提交
2079 2080 2081 2082
  if (pSql->pSubs == NULL) {
    goto _error;
  }

H
Haojun Liao 已提交
2083
  tscDebug("%p submit data to %d vnode(s)", pSql, pSql->subState.numOfSub);
2084

H
Haojun Liao 已提交
2085
  while(numOfSub < pSql->subState.numOfSub) {
H
Haojun Liao 已提交
2086
    SInsertSupporter* pSupporter = calloc(1, sizeof(SInsertSupporter));
H
Haojun Liao 已提交
2087 2088 2089 2090
    if (pSupporter == NULL) {
      goto _error;
    }

2091 2092 2093 2094
    pSupporter->pSql   = pSql;
    pSupporter->index  = numOfSub;

    SSqlObj *pNew = createSimpleSubObj(pSql, multiVnodeInsertFinalize, pSupporter, TSDB_SQL_INSERT);
H
hjxilinx 已提交
2095
    if (pNew == NULL) {
H
Haojun Liao 已提交
2096
      tscError("%p failed to malloc buffer for subObj, orderOfSub:%d, reason:%s", pSql, numOfSub, strerror(errno));
H
Haojun Liao 已提交
2097
      goto _error;
H
hjxilinx 已提交
2098
    }
2099 2100 2101
  
    /*
     * assign the callback function to fetchFp to make sure that the error process function can restore
H
Haojun Liao 已提交
2102
     * the callback function (multiVnodeInsertFinalize) correctly.
2103 2104
     */
    pNew->fetchFp = pNew->fp;
H
Haojun Liao 已提交
2105
    pSql->pSubs[numOfSub] = pNew;
H
Haojun Liao 已提交
2106

2107 2108
    STableDataBlocks* pTableDataBlock = taosArrayGetP(pCmd->pDataBlocks, numOfSub);
    pRes->code = tscCopyDataBlockToPayload(pNew, pTableDataBlock);
H
Haojun Liao 已提交
2109
    if (pRes->code == TSDB_CODE_SUCCESS) {
2110
      tscDebug("%p sub:%p create subObj success. orderOfSub:%d", pSql, pNew, numOfSub);
2111
      numOfSub++;
H
Haojun Liao 已提交
2112
    } else {
H
Haojun Liao 已提交
2113
      tscDebug("%p prepare submit data block failed in async insertion, vnodeIdx:%d, total:%d, code:%s", pSql, numOfSub,
H
Haojun Liao 已提交
2114
               pSql->subState.numOfSub, tstrerror(pRes->code));
H
Haojun Liao 已提交
2115
      goto _error;
H
Haojun Liao 已提交
2116
    }
H
hjxilinx 已提交
2117 2118
  }
  
H
Haojun Liao 已提交
2119
  if (numOfSub < pSql->subState.numOfSub) {
H
hjxilinx 已提交
2120
    tscError("%p failed to prepare subObj structure and launch sub-insertion", pSql);
2121
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
Haojun Liao 已提交
2122
    goto _error;
H
hjxilinx 已提交
2123
  }
H
Haojun Liao 已提交
2124

2125 2126
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);

H
Haojun Liao 已提交
2127 2128
  // use the local variable
  for (int32_t j = 0; j < numOfSub; ++j) {
H
hjxilinx 已提交
2129
    SSqlObj *pSub = pSql->pSubs[j];
2130
    tscDebug("%p sub:%p launch sub insert, orderOfSub:%d", pSql, pSub, j);
H
hjxilinx 已提交
2131 2132
    tscProcessSql(pSub);
  }
H
Haojun Liao 已提交
2133

H
hjxilinx 已提交
2134
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2135 2136 2137

  _error:
  return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
2138
}
H
hjxilinx 已提交
2139

H
Haojun Liao 已提交
2140 2141 2142
static char* getResultBlockPosition(SSqlCmd* pCmd, SSqlRes* pRes, int32_t columnIndex, int16_t* bytes) {
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);

H
Haojun Liao 已提交
2143
  SInternalField* pInfo = (SInternalField*) TARRAY_GET_ELEM(pQueryInfo->fieldsInfo.internalField, columnIndex);
H
Haojun Liao 已提交
2144 2145 2146
  assert(pInfo->pSqlExpr != NULL);

  *bytes = pInfo->pSqlExpr->resBytes;
H
Haojun Liao 已提交
2147
  char* pData = pRes->data + pInfo->pSqlExpr->offset * pRes->numOfRows + pRes->row * (*bytes);
H
Haojun Liao 已提交
2148 2149 2150 2151 2152 2153 2154 2155 2156 2157

  return pData;
}

static void doBuildResFromSubqueries(SSqlObj* pSql) {
  SSqlRes* pRes = &pSql->res;

  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, pSql->cmd.clauseIndex);

  int32_t numOfRes = INT32_MAX;
H
Haojun Liao 已提交
2158
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
Haojun Liao 已提交
2159 2160
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
H
Haojun Liao 已提交
2161 2162 2163
      continue;
    }

S
Shengliang Guan 已提交
2164
    int32_t remain = (int32_t)(pSub->res.numOfRows - pSub->res.row);
H
Haojun Liao 已提交
2165
    numOfRes = (int32_t)(MIN(numOfRes, remain));
H
Haojun Liao 已提交
2166 2167
  }

H
Haojun Liao 已提交
2168 2169 2170 2171
  if (numOfRes == 0) {
    return;
  }

H
Haojun Liao 已提交
2172
  int32_t totalSize = tscGetResRowLength(pQueryInfo->exprList);
H
Haojun Liao 已提交
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182

  assert(numOfRes * totalSize > 0);
  char* tmp = realloc(pRes->pRsp, numOfRes * totalSize);
  if (tmp == NULL) {
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return;
  } else {
    pRes->pRsp = tmp;
  }

H
Haojun Liao 已提交
2183 2184 2185 2186 2187 2188 2189 2190
  pRes->data = pRes->pRsp;

  char* data = pRes->data;
  int16_t bytes = 0;

  size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
  for(int32_t i = 0; i < numOfExprs; ++i) {
    SColumnIndex* pIndex = &pRes->pColumnIndex[i];
H
Haojun Liao 已提交
2191 2192
    SSqlRes*      pRes1 = &pSql->pSubs[pIndex->tableIndex]->res;
    SSqlCmd*      pCmd1 = &pSql->pSubs[pIndex->tableIndex]->cmd;
H
Haojun Liao 已提交
2193 2194 2195 2196 2197

    char* pData = getResultBlockPosition(pCmd1, pRes1, pIndex->columnIndex, &bytes);
    memcpy(data, pData, bytes * numOfRes);

    data += bytes * numOfRes;
H
Haojun Liao 已提交
2198 2199 2200 2201 2202 2203 2204 2205 2206 2207
  }

  for(int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
      continue;
    }

    pSub->res.row += numOfRes;
    assert(pSub->res.row <= pSub->res.numOfRows);
H
Haojun Liao 已提交
2208 2209 2210 2211 2212 2213
  }

  pRes->numOfRows = numOfRes;
  pRes->numOfClauseTotal += numOfRes;
}

H
hjxilinx 已提交
2214
void tscBuildResFromSubqueries(SSqlObj *pSql) {
H
Haojun Liao 已提交
2215 2216
  SSqlRes* pRes = &pSql->res;

H
hjxilinx 已提交
2217 2218 2219 2220
  if (pRes->code != TSDB_CODE_SUCCESS) {
    tscQueueAsyncRes(pSql);
    return;
  }
H
Haojun Liao 已提交
2221 2222 2223 2224

  if (pRes->tsrow == NULL) {
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, pSql->cmd.clauseIndex);

H
hjxilinx 已提交
2225
    size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
S
Shengliang Guan 已提交
2226
    pRes->numOfCols =  (int32_t)numOfExprs;
H
Haojun Liao 已提交
2227

H
Haojun Liao 已提交
2228 2229 2230 2231
    pRes->tsrow  = calloc(numOfExprs, POINTER_BYTES);
    pRes->buffer = calloc(numOfExprs, POINTER_BYTES);
    pRes->length = calloc(numOfExprs, sizeof(int32_t));

H
Haojun Liao 已提交
2232 2233 2234 2235 2236 2237
    if (pRes->tsrow == NULL || pRes->buffer == NULL || pRes->length == NULL) {
      pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
      tscQueueAsyncRes(pSql);
      return;
    }

H
Haojun Liao 已提交
2238 2239 2240 2241
    tscRestoreSQLFuncForSTableQuery(pQueryInfo);
  }

  while (1) {
H
Haojun Liao 已提交
2242
    assert (pRes->row >= pRes->numOfRows);
H
Haojun Liao 已提交
2243 2244

    doBuildResFromSubqueries(pSql);
S
TD-1057  
Shengliang Guan 已提交
2245
    tsem_post(&pSql->rspSem);
H
Haojun Liao 已提交
2246
    return;
H
hjxilinx 已提交
2247 2248 2249 2250 2251 2252
  }
}

static void transferNcharData(SSqlObj *pSql, int32_t columnIndex, TAOS_FIELD *pField) {
  SSqlRes *pRes = &pSql->res;
  
H
Haojun Liao 已提交
2253
  if (pRes->tsrow[columnIndex] != NULL && pField->type == TSDB_DATA_TYPE_NCHAR) {
H
hjxilinx 已提交
2254 2255 2256 2257 2258 2259 2260 2261
    // 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);
    
2262 2263
    int32_t length = taosUcs4ToMbs(pRes->tsrow[columnIndex], pRes->length[columnIndex], pRes->buffer[columnIndex]);
    if ( length >= 0 ) {
2264
      pRes->tsrow[columnIndex] = (unsigned char*)pRes->buffer[columnIndex];
2265
      pRes->length[columnIndex] = length;
H
hjxilinx 已提交
2266
    } else {
B
Bomin Zhang 已提交
2267
      tscError("%p charset:%s to %s. val:%s convert failed.", pSql, DEFAULT_UNICODE_ENCODEC, tsCharset, (char*)pRes->tsrow[columnIndex]);
H
hjxilinx 已提交
2268
      pRes->tsrow[columnIndex] = NULL;
2269
      pRes->length[columnIndex] = 0;
H
hjxilinx 已提交
2270 2271 2272 2273
    }
  }
}

2274 2275 2276 2277 2278 2279 2280 2281
static char *getArithemicInputSrc(void *param, const char *name, int32_t colId) {
  SArithmeticSupport *pSupport = (SArithmeticSupport *) param;

  int32_t index = -1;
  SSqlExpr* pExpr = NULL;
  
  for (int32_t i = 0; i < pSupport->numOfCols; ++i) {
    pExpr = taosArrayGetP(pSupport->exprList, i);
B
Bomin Zhang 已提交
2282
    if (strncmp(name, pExpr->aliasName, sizeof(pExpr->aliasName) - 1) == 0) {
2283 2284 2285 2286 2287 2288 2289 2290 2291
      index = i;
      break;
    }
  }

  assert(index >= 0 && index < pSupport->numOfCols);
  return pSupport->data[index] + pSupport->offset * pExpr->resBytes;
}

2292
TAOS_ROW doSetResultRowData(SSqlObj *pSql, bool finalResult) {
H
hjxilinx 已提交
2293 2294
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
H
Haojun Liao 已提交
2295

H
hjxilinx 已提交
2296 2297
  assert(pRes->row >= 0 && pRes->row <= pRes->numOfRows);
  if (pRes->row >= pRes->numOfRows) {  // all the results has returned to invoker
S
Shengliang Guan 已提交
2298
    taosTFree(pRes->tsrow);
H
hjxilinx 已提交
2299 2300
    return pRes->tsrow;
  }
H
Haojun Liao 已提交
2301

H
hjxilinx 已提交
2302
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
Haojun Liao 已提交
2303

H
Haojun Liao 已提交
2304 2305
  size_t size = tscNumOfFields(pQueryInfo);
  for (int i = 0; i < size; ++i) {
H
Haojun Liao 已提交
2306
    SInternalField* pSup = TARRAY_GET_ELEM(pQueryInfo->fieldsInfo.internalField, i);
H
hjxilinx 已提交
2307
    if (pSup->pSqlExpr != NULL) {
2308
      tscGetResultColumnChr(pRes, &pQueryInfo->fieldsInfo, i);
H
hjxilinx 已提交
2309
    }
H
Haojun Liao 已提交
2310

H
hjxilinx 已提交
2311
    // primary key column cannot be null in interval query, no need to check
2312
    if (i == 0 && pQueryInfo->interval.interval > 0) {
H
hjxilinx 已提交
2313 2314
      continue;
    }
H
Haojun Liao 已提交
2315

H
Haojun Liao 已提交
2316
    TAOS_FIELD *pField = TARRAY_GET_ELEM(pQueryInfo->fieldsInfo.internalField, i);
H
Haojun Liao 已提交
2317 2318 2319 2320
    if (pRes->tsrow[i] != NULL && pField->type == TSDB_DATA_TYPE_NCHAR) {
      transferNcharData(pSql, i, pField);
    }

H
hjxilinx 已提交
2321 2322
    // calculate the result from several other columns
    if (pSup->pArithExprInfo != NULL) {
2323
      if (pRes->pArithSup == NULL) {
H
Haojun Liao 已提交
2324
        pRes->pArithSup = (SArithmeticSupport*)calloc(1, sizeof(SArithmeticSupport));
2325
      }
H
Haojun Liao 已提交
2326

H
Haojun Liao 已提交
2327 2328 2329 2330 2331 2332
      pRes->pArithSup->offset     = 0;
      pRes->pArithSup->pArithExpr = pSup->pArithExprInfo;
      pRes->pArithSup->numOfCols  = (int32_t)tscSqlExprNumOfExprs(pQueryInfo);
      pRes->pArithSup->exprList   = pQueryInfo->exprList;
      pRes->pArithSup->data       = calloc(pRes->pArithSup->numOfCols, POINTER_BYTES);

2333 2334 2335 2336 2337 2338 2339 2340 2341
      if (pRes->buffer[i] == NULL) {
        TAOS_FIELD* field = tscFieldInfoGetField(&pQueryInfo->fieldsInfo, i);
        pRes->buffer[i] = malloc(field->bytes);
      }

      for(int32_t k = 0; k < pRes->pArithSup->numOfCols; ++k) {
        SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, k);
        pRes->pArithSup->data[k] = (pRes->data + pRes->numOfRows* pExpr->offset) + pRes->row*pExpr->resBytes;
      }
H
Haojun Liao 已提交
2342

2343 2344
      tExprTreeCalcTraverse(pRes->pArithSup->pArithExpr->pExpr, 1, pRes->buffer[i], pRes->pArithSup,
          TSDB_ORDER_ASC, getArithemicInputSrc);
2345
      pRes->tsrow[i] = (unsigned char*)pRes->buffer[i];
H
hjxilinx 已提交
2346 2347
    }
  }
H
Haojun Liao 已提交
2348

H
hjxilinx 已提交
2349 2350 2351 2352
  pRes->row++;  // index increase one-step
  return pRes->tsrow;
}

H
Haojun Liao 已提交
2353
static UNUSED_FUNC bool tscHasRemainDataInSubqueryResultSet(SSqlObj *pSql) {
H
hjxilinx 已提交
2354 2355 2356 2357 2358 2359 2360
  bool     hasData = true;
  SSqlCmd *pCmd = &pSql->cmd;
  
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0)) {
    bool allSubqueryExhausted = true;
    
H
Haojun Liao 已提交
2361
    for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
      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.
H
Haojun Liao 已提交
2387
    for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
2388 2389 2390 2391 2392 2393 2394 2395
      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) &&
H
Haojun Liao 已提交
2396
          tscIsProjectionQuery(pQueryInfo1)) || (pRes1->numOfRows == 0)) {
H
hjxilinx 已提交
2397 2398 2399 2400 2401 2402 2403 2404
        hasData = false;
        break;
      }
    }
  }
  
  return hasData;
}