tscSubquery.c 78.0 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
Haojun Liao 已提交
15
#include "os.h"
H
hjxilinx 已提交
16

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

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

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

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

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

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

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

  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;

60 61 62 63 64 65
  // 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 已提交
66 67 68 69 70 71 72
  tsBufResetPos(pSupporter1->pTSBuf);
  tsBufResetPos(pSupporter2->pTSBuf);

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

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

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

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

96
    if (elem1.tag < elem2.tag || (elem1.tag == elem2.tag && tsCompare(order, elem1.ts, elem2.ts))) {
H
hjxilinx 已提交
97 98 99 100 101
      if (!tsBufNextPos(pSupporter1->pTSBuf)) {
        break;
      }

      numOfInput1++;
102
    } else if (elem1.tag > elem2.tag || (elem1.tag == elem2.tag && tsCompare(order, elem2.ts, elem1.ts))) {
H
hjxilinx 已提交
103 104 105 106 107 108 109 110 111 112 113
      if (!tsBufNextPos(pSupporter2->pTSBuf)) {
        break;
      }

      numOfInput2++;
    } else {
      /*
       * in case of stable query, limit/offset is not applied here. the limit/offset is applied to the
       * final results which is acquired after the secondry merge of in the client.
       */
      if (pLimit->offset == 0 || pQueryInfo->intervalTime > 0 || QUERY_IS_STABLE_QUERY(pQueryInfo->type)) {
H
Haojun Liao 已提交
114 115
        if (win->skey > elem1.ts) {
          win->skey = elem1.ts;
H
hjxilinx 已提交
116 117
        }
  
H
Haojun Liao 已提交
118 119
        if (win->ekey < elem1.ts) {
          win->ekey = elem1.ts;
H
hjxilinx 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
        }
        
        tsBufAppend(output1, elem1.vnode, elem1.tag, (const char*)&elem1.ts, sizeof(elem1.ts));
        tsBufAppend(output2, elem2.vnode, elem2.tag, (const char*)&elem2.ts, sizeof(elem2.ts));
      } else {
        pLimit->offset -= 1;
      }

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

      numOfInput1++;

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

      numOfInput2++;
    }
  }

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

  tsBufFlush(output1);
  tsBufFlush(output2);

H
Haojun Liao 已提交
155 156
  tsBufDestroy(pSupporter1->pTSBuf);
  tsBufDestroy(pSupporter2->pTSBuf);
H
hjxilinx 已提交
157

158
  tscDebug("%p input1:%" PRId64 ", input2:%" PRId64 ", final:%" PRId64 " for secondary query after ts blocks "
H
Haojun Liao 已提交
159 160
           "intersecting, skey:%" PRId64 ", ekey:%" PRId64, pSql, numOfInput1, numOfInput2, output1->numOfTotal,
           win->skey, win->ekey);
H
hjxilinx 已提交
161 162 163 164 165

  return output1->numOfTotal;
}

// todo handle failed to create sub query
166 167
SJoinSupporter* tscCreateJoinSupporter(SSqlObj* pSql, SSubqueryState* pState, int32_t index) {
  SJoinSupporter* pSupporter = calloc(1, sizeof(SJoinSupporter));
H
hjxilinx 已提交
168 169 170 171 172 173 174 175 176 177
  if (pSupporter == NULL) {
    return NULL;
  }

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

  pSupporter->subqueryIndex = index;
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, pSql->cmd.clauseIndex);
  
H
Haojun Liao 已提交
178 179
  pSupporter->intervalTime = pQueryInfo->intervalTime;
  pSupporter->slidingTime = pQueryInfo->slidingTime;
H
hjxilinx 已提交
180 181 182
  pSupporter->limit = pQueryInfo->limit;

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

S
slguan 已提交
186
  taosGetTmpfilePath("join-", pSupporter->path);
H
hjxilinx 已提交
187 188
  pSupporter->f = fopen(pSupporter->path, "w");

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

  return pSupporter;
}

H
Haojun Liao 已提交
197
static void tscDestroyJoinSupporter(SJoinSupporter* pSupporter) {
H
hjxilinx 已提交
198 199 200 201
  if (pSupporter == NULL) {
    return;
  }

H
hjxilinx 已提交
202 203 204 205 206 207 208
  if (pSupporter->exprList != NULL) {
    tscSqlExprInfoDestroy(pSupporter->exprList);
  }
  
  if (pSupporter->colList != NULL) {
    tscColumnListDestroy(pSupporter->colList);
  }
H
hjxilinx 已提交
209

H
hjxilinx 已提交
210
  tscFieldInfoClear(&pSupporter->fieldsInfo);
H
hjxilinx 已提交
211 212 213 214

  if (pSupporter->f != NULL) {
    fclose(pSupporter->f);
    unlink(pSupporter->path);
H
hjxilinx 已提交
215
    pSupporter->f = NULL;
H
hjxilinx 已提交
216 217
  }

S
Shengliang Guan 已提交
218
  taosTFree(pSupporter->pIdTagList);
H
hjxilinx 已提交
219 220 221 222 223 224 225 226 227 228
  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 已提交
229
static UNUSED_FUNC bool needSecondaryQuery(SQueryInfo* pQueryInfo) {
230 231 232
  size_t numOfCols = taosArrayGetSize(pQueryInfo->colList);
  
  for (int32_t i = 0; i < numOfCols; ++i) {
233 234
    SColumn* base = taosArrayGet(pQueryInfo->colList, i);
    if (base->colIndex.columnIndex != PRIMARYKEY_TIMESTAMP_COL_INDEX) {
H
hjxilinx 已提交
235 236 237 238 239 240 241 242 243 244
      return true;
    }
  }

  return false;
}

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

H
hjxilinx 已提交
262
  //the subqueries that do not actually launch the secondary query to virtual node is set as completed.
263
  SSubqueryState* pState = pSupporter->pState;
H
hjxilinx 已提交
264
  pState->numOfTotal = pSql->numOfSubs;
H
Haojun Liao 已提交
265
  pState->numOfRemain = numOfSub;
H
hjxilinx 已提交
266 267 268 269 270 271 272 273 274
  
  bool success = true;
  
  for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
    SSqlObj *pPrevSub = pSql->pSubs[i];
    pSql->pSubs[i] = NULL;
    
    pSupporter = pPrevSub->param;
  
H
hjxilinx 已提交
275
    if (taosArrayGetSize(pSupporter->exprList) == 0) {
276
      tscDebug("%p subIndex: %d, no need to launch query, ignore it", pSql, i);
H
hjxilinx 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289
    
      tscDestroyJoinSupporter(pSupporter);
      tscFreeSqlObj(pPrevSub);
    
      pSql->pSubs[i] = NULL;
      continue;
    }
  
    SQueryInfo *pSubQueryInfo = tscGetQueryInfoDetail(&pPrevSub->cmd, 0);
    STSBuf *pTSBuf = pSubQueryInfo->tsBuf;
    pSubQueryInfo->tsBuf = NULL;
  
    // free result for async object will also free sqlObj
H
hjxilinx 已提交
290
    assert(tscSqlExprNumOfExprs(pSubQueryInfo) == 1); // ts_comp query only requires one resutl columns
H
hjxilinx 已提交
291 292
    taos_free_result(pPrevSub);
  
293
    SSqlObj *pNew = createSubqueryObj(pSql, (int16_t) i, tscJoinQueryCallback, pSupporter, TSDB_SQL_SELECT, NULL);
H
hjxilinx 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306
    if (pNew == NULL) {
      tscDestroyJoinSupporter(pSupporter);
      success = false;
      break;
    }
  
    tscClearSubqueryInfo(&pNew->cmd);
    pSql->pSubs[i] = pNew;
  
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    pQueryInfo->tsBuf = pTSBuf;  // transfer the ownership of timestamp comp-z data to the new created object
  
    // set the second stage sub query for join process
H
hjxilinx 已提交
307
    TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_SEC_STAGE);
H
Haojun Liao 已提交
308

H
Haojun Liao 已提交
309 310
    pQueryInfo->intervalTime = pSupporter->intervalTime;
    pQueryInfo->slidingTime = pSupporter->slidingTime;
H
hjxilinx 已提交
311
    pQueryInfo->groupbyExpr = pSupporter->groupbyExpr;
H
hjxilinx 已提交
312
    
H
hjxilinx 已提交
313 314
    tscTagCondCopy(&pQueryInfo->tagCond, &pSupporter->tagCond);
  
H
hjxilinx 已提交
315 316 317
    pQueryInfo->colList = pSupporter->colList;
    pQueryInfo->exprList = pSupporter->exprList;
    pQueryInfo->fieldsInfo = pSupporter->fieldsInfo;
H
hjxilinx 已提交
318
    
H
hjxilinx 已提交
319 320 321
    pSupporter->exprList = NULL;
    pSupporter->colList = NULL;
    memset(&pSupporter->fieldsInfo, 0, sizeof(SFieldInfo));
H
hjxilinx 已提交
322 323 324 325
  
    SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    assert(pNew->numOfSubs == 0 && pNew->cmd.numOfClause == 1 && pNewQueryInfo->numOfTables == 1);
  
H
hjxilinx 已提交
326
    tscFieldInfoUpdateOffset(pNewQueryInfo);
H
hjxilinx 已提交
327 328 329 330 331 332 333 334 335
  
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pNewQueryInfo, 0);
  
    /*
     * When handling the projection query, the offset value will be modified for table-table join, which is changed
     * during the timestamp intersection.
     */
    pSupporter->limit = pQueryInfo->limit;
    pNewQueryInfo->limit = pSupporter->limit;
H
Haojun Liao 已提交
336 337 338 339 340

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

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

H
Haojun Liao 已提交
343
    if ((pExpr->colInfo.colId != PRIMARYKEY_TIMESTAMP_COL_INDEX) ||
H
Haojun Liao 已提交
344 345 346 347 348
        (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 已提交
349 350
      tscPrintSelectClause(pNew, 0);
      tscFieldInfoUpdateOffset(pNewQueryInfo);
H
Haojun Liao 已提交
351 352 353 354 355 356 357

      pExpr = tscSqlExprGet(pQueryInfo, 0);
    }

    // set the join condition tag column info, to do extract method
    if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
      assert(pQueryInfo->tagCond.joinInfo.hasJoin);
358
      int16_t colId = tscGetJoinTagColIdByUid(&pQueryInfo->tagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
359 360 361

      pExpr->param[0].i64Key = colId;
      pExpr->numOfParams = 1;
H
Haojun Liao 已提交
362 363
    }

364
    size_t numOfCols = taosArrayGetSize(pNewQueryInfo->colList);
365
    tscDebug("%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%d, exprInfo:%zu, colList:%zu, fieldsInfo:%d, name:%s",
H
Haojun Liao 已提交
366 367
             pSql, pNew, 0, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, taosArrayGetSize(pNewQueryInfo->exprList),
             numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, pTableMetaInfo->name);
H
hjxilinx 已提交
368 369 370 371
  }
  
  //prepare the subqueries object failed, abort
  if (!success) {
372
    pSql->res.code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
373 374
    tscError("%p failed to prepare subqueries objs for secondary phase query, numOfSub:%d, code:%d", pSql,
        pSql->numOfSubs, pSql->res.code);
H
hjxilinx 已提交
375
    freeJoinSubqueryObj(pSql);
H
hjxilinx 已提交
376 377 378 379 380
    
    return pSql->res.code;
  }
  
  for(int32_t i = 0; i < pSql->numOfSubs; ++i) {
H
Haojun Liao 已提交
381
    if (pSql->pSubs[i] == NULL) {
H
hjxilinx 已提交
382 383
      continue;
    }
H
Haojun Liao 已提交
384

H
Haojun Liao 已提交
385
    tscDoQuery(pSql->pSubs[i]);
H
hjxilinx 已提交
386 387 388 389 390
  }

  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
391
void freeJoinSubqueryObj(SSqlObj* pSql) {
H
hjxilinx 已提交
392 393 394
  SSubqueryState* pState = NULL;

  for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
H
hjxilinx 已提交
395 396 397 398 399
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
      continue;
    }
    
400
    SJoinSupporter* p = pSub->param;
H
hjxilinx 已提交
401
    pState = p->pState;
H
hjxilinx 已提交
402

H
hjxilinx 已提交
403
    tscDestroyJoinSupporter(p);
H
hjxilinx 已提交
404

H
hjxilinx 已提交
405 406
    if (pSub->res.code == TSDB_CODE_SUCCESS) {
      taos_free_result(pSub);
H
hjxilinx 已提交
407 408 409
    }
  }

S
Shengliang Guan 已提交
410
  taosTFree(pState);
H
hjxilinx 已提交
411 412 413
  pSql->numOfSubs = 0;
}

414
static void quitAllSubquery(SSqlObj* pSqlObj, SJoinSupporter* pSupporter) {
H
Haojun Liao 已提交
415 416 417
  assert(pSupporter->pState->numOfRemain > 0);

  if (atomic_sub_fetch_32(&pSupporter->pState->numOfRemain, 1) <= 0) {
H
hjxilinx 已提交
418
    tscError("%p all subquery return and query failed, global code:%d", pSqlObj, pSqlObj->res.code);
H
hjxilinx 已提交
419
    freeJoinSubqueryObj(pSqlObj);
H
hjxilinx 已提交
420 421 422 423
  }
}

// update the query time range according to the join results on timestamp
H
Haojun Liao 已提交
424 425 426
static void updateQueryTimeRange(SQueryInfo* pQueryInfo, STimeWindow* win) {
  assert(pQueryInfo->window.skey <= win->skey && pQueryInfo->window.ekey >= win->ekey);
  pQueryInfo->window = *win;
H
hjxilinx 已提交
427 428
}

weixin_48148422's avatar
weixin_48148422 已提交
429
int32_t tscCompareTidTags(const void* p1, const void* p2) {
H
Haojun Liao 已提交
430 431
  const STidTags* t1 = (const STidTags*) varDataVal(p1);
  const STidTags* t2 = (const STidTags*) varDataVal(p2);
432 433
  
  if (t1->vgId != t2->vgId) {
weixin_48148422's avatar
weixin_48148422 已提交
434 435 436 437
    return (t1->vgId > t2->vgId) ? 1 : -1;
  }
  if (t1->tid != t2->tid) {
    return (t1->tid > t2->tid) ? 1 : -1;
438
  }
weixin_48148422's avatar
weixin_48148422 已提交
439
  return 0;
440 441
}

H
Haojun Liao 已提交
442
void tscBuildVgroupTableInfo(SSqlObj* pSql, STableMetaInfo* pTableMetaInfo, SArray* tables) {
H
Haojun Liao 已提交
443 444
  SArray*   result = taosArrayInit(4, sizeof(SVgroupTableInfo));
  SArray*   vgTables = NULL;
weixin_48148422's avatar
weixin_48148422 已提交
445 446
  STidTags* prev = NULL;

H
Haojun Liao 已提交
447 448 449
  size_t numOfTables = taosArrayGetSize(tables);
  for (size_t i = 0; i < numOfTables; i++) {
    STidTags* tt = taosArrayGet(tables, i);
weixin_48148422's avatar
weixin_48148422 已提交
450

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

H
Haojun Liao 已提交
454 455 456
      SVgroupTableInfo info = {{0}};
      for (int32_t m = 0; m < pvg->numOfVgroups; ++m) {
        if (tt->vgId == pvg->vgroups[m].vgId) {
457 458 459 460
          info.vgInfo = pvg->vgroups[m];
          break;
        }
      }
461
      assert(info.vgInfo.numOfEps != 0);
weixin_48148422's avatar
weixin_48148422 已提交
462

H
Haojun Liao 已提交
463
      vgTables = taosArrayInit(4, sizeof(STableIdInfo));
weixin_48148422's avatar
weixin_48148422 已提交
464
      info.itemList = vgTables;
H
Haojun Liao 已提交
465
      taosArrayPush(result, &info);
466
    }
weixin_48148422's avatar
weixin_48148422 已提交
467

468
    tscDebug("%p tid:%d, uid:%"PRIu64",vgId:%d added for vnode query", pSql, tt->tid, tt->uid, tt->vgId)
H
Haojun Liao 已提交
469 470
    STableIdInfo item = {.uid = tt->uid, .tid = tt->tid, .key = INT64_MIN};
    taosArrayPush(vgTables, &item);
weixin_48148422's avatar
weixin_48148422 已提交
471
    prev = tt;
472
  }
weixin_48148422's avatar
weixin_48148422 已提交
473 474

  pTableMetaInfo->pVgroupTables = result;
H
Haojun Liao 已提交
475
  pTableMetaInfo->vgroupIndex = 0;
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
}

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

  TSDB_QUERY_CLEAR_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_TAG_FILTER_QUERY);
  TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_MULTITABLE_QUERY);
  
  pCmd->command = TSDB_SQL_SELECT;
  pSql->fp = tscJoinQueryCallback;
  
  SSchema colSchema = {.type = TSDB_DATA_TYPE_BINARY, .bytes = 1};
  
  SColumnIndex index = {0, PRIMARYKEY_TIMESTAMP_COL_INDEX};
  tscAddSpecialColumnForSelect(pQueryInfo, 0, TSDB_FUNC_TS_COMP, &index, &colSchema, TSDB_COL_NORMAL);
  
  // set the tags value for ts_comp function
H
Haojun Liao 已提交
500 501
  if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
    SSqlExpr *pExpr = tscSqlExprGet(pQueryInfo, 0);
502
    int16_t tagColId = tscGetJoinTagColIdByUid(&pSupporter->tagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
503 504 505 506
    pExpr->param->i64Key = tagColId;
    pExpr->numOfParams = 1;
  }

507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
  // 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);
  
523
  tscDebug(
H
Haojun Liao 已提交
524
      "%p subquery:%p tableIndex:%d, vgroupIndex:%d, numOfVgroups:%d, type:%d, ts_comp query to retrieve timestamps, "
B
Bomin Zhang 已提交
525
      "numOfExpr:%zu, colList:%zu, numOfOutputFields:%d, name:%s",
H
Haojun Liao 已提交
526 527
      pParent, pSql, 0, pTableMetaInfo->vgroupIndex, pTableMetaInfo->vgroupList->numOfVgroups, pQueryInfo->type,
      tscSqlExprNumOfExprs(pQueryInfo), numOfCols, pQueryInfo->fieldsInfo.numOfOutput, pTableMetaInfo->name);
528 529 530 531
  
  tscProcessSql(pSql);
}

H
Haojun Liao 已提交
532
static bool checkForDuplicateTagVal(SQueryInfo* pQueryInfo, SJoinSupporter* p1, SSqlObj* pPSqlObj) {
H
Haojun Liao 已提交
533 534 535 536 537 538 539 540 541 542 543
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);

  SSchema* pSchema = tscGetTableTagSchema(pTableMetaInfo->pTableMeta);// todo: tags mismatch, tags not completed
  SColumn *pCol = taosArrayGetP(pTableMetaInfo->tagColList, 0);
  SSchema *pColSchema = &pSchema[pCol->colIndex.columnIndex];

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

    if (doCompare(prev->tag, p->tag, pColSchema->type, pColSchema->bytes) == 0) {
H
Haojun Liao 已提交
544 545
      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 已提交
546 547 548 549 550 551 552
      return false;
    }
  }

  return true;
}

553
static int32_t getIntersectionOfTableTuple(SQueryInfo* pQueryInfo, SSqlObj* pParentSql, SArray** s1, SArray** s2) {
554
  tscDebug("%p all subqueries retrieve <tid, tags> complete, do tags match", pParentSql);
H
Haojun Liao 已提交
555 556 557 558 559 560 561 562

  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);
563
  int16_t tagColId = tscGetJoinTagColIdByUid(&pQueryInfo->tagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
564 565 566 567 568 569

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

  *s1 = taosArrayInit(p1->num, p1->tagSize);
  *s2 = taosArrayInit(p2->num, p2->tagSize);

H
Haojun Liao 已提交
570
  if (!(checkForDuplicateTagVal(pQueryInfo, p1, pParentSql) && checkForDuplicateTagVal(pQueryInfo, p2, pParentSql))) {
571
    return TSDB_CODE_QRY_DUP_JOIN_KEY;
H
Haojun Liao 已提交
572 573 574 575 576 577 578 579 580
  }

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

    int32_t ret = doCompare(pp1->tag, pp2->tag, pColSchema->type, pColSchema->bytes);
    if (ret == 0) {
581
      tscDebug("%p tag matched, vgId:%d, val:%d, tid:%d, uid:%"PRIu64", tid:%d, uid:%"PRIu64, pParentSql, pp1->vgId,
H
Haojun Liao 已提交
582 583 584 585 586 587 588 589 590 591 592 593
               *(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++;
    }
  }
594 595

  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
596 597
}

H
Haojun Liao 已提交
598
static void tidTagRetrieveCallback(void* param, TAOS_RES* tres, int32_t numOfRows) {
599
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
600

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

H
hjxilinx 已提交
603 604
  SSqlObj* pSql = (SSqlObj*)tres;
  SSqlCmd* pCmd = &pSql->cmd;
H
Haojun Liao 已提交
605 606 607
  SSqlRes* pRes = &pSql->res;

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

H
Haojun Liao 已提交
610 611 612
  // check for the error code firstly
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    // todo retry if other subqueries are not failed
H
Haojun Liao 已提交
613

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

H
Haojun Liao 已提交
617 618
    pParentSql->res.code = numOfRows;
    quitAllSubquery(pParentSql, pSupporter);
H
Haojun Liao 已提交
619

H
Haojun Liao 已提交
620 621 622
    tscQueueAsyncRes(pParentSql);
    return;
  }
H
Haojun Liao 已提交
623

H
Haojun Liao 已提交
624 625 626 627
  // keep the results in memory
  if (numOfRows > 0) {
    size_t validLen = pSupporter->tagSize * pRes->numOfRows;
    size_t length = pSupporter->totalLen + validLen;
H
Haojun Liao 已提交
628

H
Haojun Liao 已提交
629 630 631 632
    // todo handle memory error
    char* tmp = realloc(pSupporter->pIdTagList, length);
    if (tmp == NULL) {
      tscError("%p failed to malloc memory", pSql);
H
Haojun Liao 已提交
633

H
Haojun Liao 已提交
634 635
      pParentSql->res.code = TAOS_SYSTEM_ERROR(errno);
      quitAllSubquery(pParentSql, pSupporter);
H
Haojun Liao 已提交
636

H
Haojun Liao 已提交
637 638 639
      tscQueueAsyncRes(pParentSql);
      return;
    }
H
Haojun Liao 已提交
640

H
Haojun Liao 已提交
641
    pSupporter->pIdTagList = tmp;
H
Haojun Liao 已提交
642

H
Haojun Liao 已提交
643
    memcpy(pSupporter->pIdTagList + pSupporter->totalLen, pRes->data, validLen);
S
Shengliang Guan 已提交
644 645
    pSupporter->totalLen += (int32_t)validLen;
    pSupporter->num += (int32_t)pRes->numOfRows;
H
Haojun Liao 已提交
646

H
Haojun Liao 已提交
647 648 649 650 651 652
    // query not completed, continue to retrieve tid + tag tuples
    if (!pRes->completed) {
      taos_fetch_rows_a(tres, tidTagRetrieveCallback, param);
      return;
    }
  }
H
Haojun Liao 已提交
653

H
Haojun Liao 已提交
654 655 656 657
  // 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 已提交
658

H
Haojun Liao 已提交
659 660 661
    int32_t totalVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
    pTableMetaInfo->vgroupIndex += 1;
    assert(pTableMetaInfo->vgroupIndex < totalVgroups);
H
Haojun Liao 已提交
662

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

H
Haojun Liao 已提交
666 667
    pCmd->command = TSDB_SQL_SELECT;
    tscResetForNextRetrieve(&pSql->res);
H
Haojun Liao 已提交
668

H
Haojun Liao 已提交
669 670 671 672 673
    // set the callback function
    pSql->fp = tscJoinQueryCallback;
    tscProcessSql(pSql);
    return;
  }
H
Haojun Liao 已提交
674

H
Haojun Liao 已提交
675 676 677 678 679
  // 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.
  if (atomic_sub_fetch_32(&pSupporter->pState->numOfRemain, 1) > 0) {
    return;
  }
H
Haojun Liao 已提交
680

H
Haojun Liao 已提交
681
  SArray *s1 = NULL, *s2 = NULL;
682 683 684 685 686 687 688 689
  int32_t code = getIntersectionOfTableTuple(pQueryInfo, pParentSql, &s1, &s2);
  if (code != TSDB_CODE_SUCCESS) {
    freeJoinSubqueryObj(pParentSql);
    pParentSql->res.code = code;
    tscQueueAsyncRes(pParentSql);
    return;
  }

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

694 695
    // set no result command
    pParentSql->cmd.command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
H
Haojun Liao 已提交
696
    (*pParentSql->fp)(pParentSql->param, pParentSql, 0);
B
Bomin Zhang 已提交
697 698 699 700
  } else {
    // proceed to for ts_comp query
    SSqlCmd* pSubCmd1 = &pParentSql->pSubs[0]->cmd;
    SSqlCmd* pSubCmd2 = &pParentSql->pSubs[1]->cmd;
H
Haojun Liao 已提交
701

B
Bomin Zhang 已提交
702 703 704
    SQueryInfo*     pQueryInfo1 = tscGetQueryInfoDetail(pSubCmd1, 0);
    STableMetaInfo* pTableMetaInfo1 = tscGetMetaInfo(pQueryInfo1, 0);
    tscBuildVgroupTableInfo(pParentSql, pTableMetaInfo1, s1);
H
Haojun Liao 已提交
705

B
Bomin Zhang 已提交
706 707 708
    SQueryInfo*     pQueryInfo2 = tscGetQueryInfoDetail(pSubCmd2, 0);
    STableMetaInfo* pTableMetaInfo2 = tscGetMetaInfo(pQueryInfo2, 0);
    tscBuildVgroupTableInfo(pParentSql, pTableMetaInfo2, s2);
H
Haojun Liao 已提交
709

B
Bomin Zhang 已提交
710 711
    pSupporter->pState->numOfTotal = 2;
    pSupporter->pState->numOfRemain = pSupporter->pState->numOfTotal;
H
Haojun Liao 已提交
712

B
Bomin Zhang 已提交
713 714 715 716
    for (int32_t m = 0; m < pParentSql->numOfSubs; ++m) {
      SSqlObj* sub = pParentSql->pSubs[m];
      issueTSCompQuery(sub, sub->param, pParentSql);
    }
H
Haojun Liao 已提交
717
  }
B
Bomin Zhang 已提交
718 719 720

  taosArrayDestroy(s1);
  taosArrayDestroy(s2);
H
Haojun Liao 已提交
721
}
H
Haojun Liao 已提交
722

H
Haojun Liao 已提交
723 724
static void tsCompRetrieveCallback(void* param, TAOS_RES* tres, int32_t numOfRows) {
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
725

H
Haojun Liao 已提交
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
  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);
745 746
    return;
  }
H
Haojun Liao 已提交
747

H
Haojun Liao 已提交
748 749 750 751 752 753 754 755 756 757 758 759
  if (numOfRows > 0) {  // write the compressed timestamp to disk file
    fwrite(pRes->data, pRes->numOfRows, 1, pSupporter->f);
    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 已提交
760 761
      return;
    }
762

H
Haojun Liao 已提交
763
    if (pSupporter->pTSBuf == NULL) {
764
      tscDebug("%p create tmp file for ts block:%s, size:%d bytes", pSql, pBuf->path, numOfRows);
H
Haojun Liao 已提交
765 766 767 768
      pSupporter->pTSBuf = pBuf;
    } else {
      assert(pQueryInfo->numOfTables == 1);  // for subquery, only one
      STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
769

H
Haojun Liao 已提交
770
      tsBufMerge(pSupporter->pTSBuf, pBuf, pTableMetaInfo->vgroupIndex);
H
Haojun Liao 已提交
771
      tsBufDestroy(pBuf);
H
Haojun Liao 已提交
772
    }
H
hjxilinx 已提交
773

H
Haojun Liao 已提交
774 775
    // continue to retrieve ts-comp data from vnode
    if (!pRes->completed) {
S
slguan 已提交
776
      taosGetTmpfilePath("ts-join", pSupporter->path);
H
Haojun Liao 已提交
777
      pSupporter->f = fopen(pSupporter->path, "w");
S
Shengliang Guan 已提交
778
      pRes->row = (int32_t)pRes->numOfRows;
H
hjxilinx 已提交
779

H
Haojun Liao 已提交
780 781
      taos_fetch_rows_a(tres, tsCompRetrieveCallback, param);
      return;
H
hjxilinx 已提交
782
    }
H
Haojun Liao 已提交
783
  }
H
Haojun Liao 已提交
784

H
Haojun Liao 已提交
785 786
  if (hasMoreVnodesToTry(pSql)) {
    STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
Haojun Liao 已提交
787

H
Haojun Liao 已提交
788 789 790
    int32_t totalVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
    pTableMetaInfo->vgroupIndex += 1;
    assert(pTableMetaInfo->vgroupIndex < totalVgroups);
H
Haojun Liao 已提交
791

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

H
Haojun Liao 已提交
796 797
    pCmd->command = TSDB_SQL_SELECT;
    tscResetForNextRetrieve(&pSql->res);
H
Haojun Liao 已提交
798

H
Haojun Liao 已提交
799
    assert(pSupporter->f == NULL);
S
slguan 已提交
800
    taosGetTmpfilePath("ts-join", pSupporter->path);
H
Haojun Liao 已提交
801 802 803
    
    // TODO check for failure
    pSupporter->f = fopen(pSupporter->path, "w");
S
Shengliang Guan 已提交
804
    pRes->row = (int32_t)pRes->numOfRows;
H
Haojun Liao 已提交
805

H
Haojun Liao 已提交
806 807 808 809 810
    // set the callback function
    pSql->fp = tscJoinQueryCallback;
    tscProcessSql(pSql);
    return;
  }
H
Haojun Liao 已提交
811

H
Haojun Liao 已提交
812 813 814
  if (atomic_sub_fetch_32(&pSupporter->pState->numOfRemain, 1) > 0) {
    return;
  }
H
hjxilinx 已提交
815

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

H
Haojun Liao 已提交
818 819 820
  // proceeds to launched secondary query to retrieve final data
  SJoinSupporter* p1 = pParentSql->pSubs[0]->param;
  SJoinSupporter* p2 = pParentSql->pSubs[1]->param;
H
Haojun Liao 已提交
821

H
Haojun Liao 已提交
822 823 824
  STimeWindow win = TSWINDOW_INITIALIZER;
  int64_t num = doTSBlockIntersect(pParentSql, p1, p2, &win);
  if (num <= 0) {  // no result during ts intersect
825
    tscDebug("%p no results generated in ts intersection, free all sub SqlObj and quit", pParentSql);
H
Haojun Liao 已提交
826
    freeJoinSubqueryObj(pParentSql);
827 828 829

    // set no result command
    pParentSql->cmd.command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
H
Haojun Liao 已提交
830
    (*pParentSql->fp)(pParentSql->param, pParentSql, 0);
H
Haojun Liao 已提交
831 832 833 834 835 836
    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 已提交
837
  tscLaunchRealSubqueries(pParentSql);
H
Haojun Liao 已提交
838
}
H
Haojun Liao 已提交
839

H
Haojun Liao 已提交
840 841
static void joinRetrieveFinalResCallback(void* param, TAOS_RES* tres, int numOfRows) {
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
842

H
Haojun Liao 已提交
843 844
  SSqlObj* pParentSql = pSupporter->pObj;
  SSubqueryState* pState = pSupporter->pState;
H
Haojun Liao 已提交
845

H
Haojun Liao 已提交
846 847 848
  SSqlObj* pSql = (SSqlObj*)tres;
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;
H
Haojun Liao 已提交
849

H
Haojun Liao 已提交
850 851 852
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(numOfRows == taos_errno(pSql));
H
hjxilinx 已提交
853

H
Haojun Liao 已提交
854 855
    pParentSql->res.code = numOfRows;
    tscError("%p retrieve failed, index:%d, code:%s", pSql, pSupporter->subqueryIndex, tstrerror(numOfRows));
H
Haojun Liao 已提交
856 857 858

    tscQueueAsyncRes(pParentSql);
    return;
H
Haojun Liao 已提交
859
  }
H
Haojun Liao 已提交
860

H
Haojun Liao 已提交
861 862 863
  if (numOfRows >= 0) {
    pRes->numOfTotal += pRes->numOfRows;
  }
H
Haojun Liao 已提交
864

H
Haojun Liao 已提交
865 866 867
  if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) && numOfRows == 0) {
    STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
    assert(pQueryInfo->numOfTables == 1);
H
Haojun Liao 已提交
868

H
Haojun Liao 已提交
869 870 871 872 873 874 875 876 877 878 879 880 881 882
    // for projection query, need to try next vnode if current vnode is exhausted
    if ((++pTableMetaInfo->vgroupIndex) < pTableMetaInfo->vgroupList->numOfVgroups) {
      pState->numOfRemain = 1;
      pState->numOfTotal = 1;

      pSql->cmd.command = TSDB_SQL_SELECT;
      pSql->fp = tscJoinQueryCallback;
      tscProcessSql(pSql);

      return;
    }
  }

  if (atomic_sub_fetch_32(&pState->numOfRemain, 1) > 0) {
883
    tscDebug("%p sub:%p completed, remain:%d, total:%d", pParentSql, tres, pState->numOfRemain, pState->numOfTotal);
H
Haojun Liao 已提交
884 885 886
    return;
  }

887
  tscDebug("%p all %d secondary subqueries retrieval completed, code:%d", tres, pState->numOfTotal, pParentSql->res.code);
H
Haojun Liao 已提交
888 889 890 891 892 893 894 895 896 897

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

  // update the records for each subquery in parent sql object.
  for (int32_t i = 0; i < pParentSql->numOfSubs; ++i) {
    if (pParentSql->pSubs[i] == NULL) {
      continue;
H
hjxilinx 已提交
898
    }
H
Haojun Liao 已提交
899 900 901

    SSqlRes* pRes1 = &pParentSql->pSubs[i]->res;
    pRes1->numOfClauseTotal += pRes1->numOfRows;
H
hjxilinx 已提交
902
  }
H
Haojun Liao 已提交
903 904 905

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

908
static SJoinSupporter* tscUpdateSubqueryStatus(SSqlObj* pSql, int32_t numOfFetch) {
H
hjxilinx 已提交
909
  int32_t notInvolved = 0;
910
  SJoinSupporter* pSupporter = NULL;
H
hjxilinx 已提交
911 912 913 914 915 916
  SSubqueryState* pState = NULL;
  
  for(int32_t i = 0; i < pSql->numOfSubs; ++i) {
    if (pSql->pSubs[i] == NULL) {
      notInvolved++;
    } else {
917
      pSupporter = (SJoinSupporter*)pSql->pSubs[i]->param;
H
hjxilinx 已提交
918 919 920 921
      pState = pSupporter->pState;
    }
  }
  
922
  assert(pState != NULL);
B
Bomin Zhang 已提交
923 924 925 926
  if (pState != NULL) {
    pState->numOfTotal = pSql->numOfSubs;
    pState->numOfRemain = numOfFetch;
  }
H
hjxilinx 已提交
927 928 929 930 931 932 933
  
  return pSupporter;
}

void tscFetchDatablockFromSubquery(SSqlObj* pSql) {
  assert(pSql->numOfSubs >= 1);
  
H
hjxilinx 已提交
934 935
  int32_t numOfFetch = 0;
  bool hasData = true;
H
hjxilinx 已提交
936
  for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
H
hjxilinx 已提交
937 938 939
    // if the subquery is NULL, it does not involved in the final result generation
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
H
hjxilinx 已提交
940 941 942
      continue;
    }
    
H
hjxilinx 已提交
943 944 945
    SSqlRes *pRes = &pSub->res;
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSub->cmd, 0);

H
Haojun Liao 已提交
946 947 948 949 950 951
    if (!tscHasReachLimitation(pQueryInfo, pRes)) {
      if (pRes->row >= pRes->numOfRows) {
        hasData = false;

        if (!pRes->completed) {
          numOfFetch++;
H
Haojun Liao 已提交
952
        }
H
hjxilinx 已提交
953
      }
H
Haojun Liao 已提交
954 955 956 957 958
    } else {  // has reach the limitation, no data anymore
      if (pRes->row >= pRes->numOfRows) {
        hasData = false;
        break;
      }
H
hjxilinx 已提交
959
    }
H
Haojun Liao 已提交
960
  }
H
hjxilinx 已提交
961

H
hjxilinx 已提交
962 963 964 965 966 967 968 969 970 971 972 973 974 975
  // has data remains in client side, and continue to return data to app
  if (hasData) {
    tscBuildResFromSubqueries(pSql);
    return;
  } else if (numOfFetch <= 0) {
    pSql->res.completed = true;
    freeJoinSubqueryObj(pSql);
    
    if (pSql->res.code == TSDB_CODE_SUCCESS) {
      (*pSql->fp)(pSql->param, pSql, 0);
    } else {
      tscQueueAsyncRes(pSql);
    }
    
H
hjxilinx 已提交
976 977 978 979
    return;
  }

  // TODO multi-vnode retrieve for projection query with limitation has bugs, since the global limiation is not handled
980
  tscDebug("%p retrieve data from %d subqueries", pSql, numOfFetch);
981
  SJoinSupporter* pSupporter = tscUpdateSubqueryStatus(pSql, numOfFetch);
H
hjxilinx 已提交
982 983 984 985 986 987 988 989 990 991
  
  for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
    SSqlObj* pSql1 = pSql->pSubs[i];
    if (pSql1 == NULL) {
      continue;
    }
    
    SSqlRes* pRes1 = &pSql1->res;
    SSqlCmd* pCmd1 = &pSql1->cmd;

992
    pSupporter = (SJoinSupporter*)pSql1->param;
H
hjxilinx 已提交
993 994 995 996 997 998 999 1000

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

      tscResetForNextRetrieve(pRes1);
H
Haojun Liao 已提交
1005
      pSql1->fp = joinRetrieveFinalResCallback;
H
hjxilinx 已提交
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020

      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 已提交
1021
  tscDebug("%p all subquery response, retrieve data for subclause:%d", pSql, pCmd->clauseIndex);
H
hjxilinx 已提交
1022

H
Haojun Liao 已提交
1023
  // the column transfer support struct has been built
H
hjxilinx 已提交
1024
  if (pRes->pColumnIndex != NULL) {
H
Haojun Liao 已提交
1025
    return;
H
hjxilinx 已提交
1026 1027 1028
  }

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

H
hjxilinx 已提交
1031
  for (int32_t i = 0; i < pQueryInfo->fieldsInfo.numOfOutput; ++i) {
H
hjxilinx 已提交
1032 1033 1034 1035 1036
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);

    int32_t tableIndexOfSub = -1;
    for (int32_t j = 0; j < pQueryInfo->numOfTables; ++j) {
      STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, j);
1037
      if (pTableMetaInfo->pTableMeta->id.uid == pExpr->uid) {
H
hjxilinx 已提交
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
        tableIndexOfSub = j;
        break;
      }
    }

    assert(tableIndexOfSub >= 0 && tableIndexOfSub < pQueryInfo->numOfTables);
    
    SSqlCmd* pSubCmd = &pSql->pSubs[tableIndexOfSub]->cmd;
    SQueryInfo* pSubQueryInfo = tscGetQueryInfoDetail(pSubCmd, 0);
    
H
hjxilinx 已提交
1048
    size_t numOfExprs = taosArrayGetSize(pSubQueryInfo->exprList);
H
hjxilinx 已提交
1049
    for (int32_t k = 0; k < numOfExprs; ++k) {
H
hjxilinx 已提交
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
      SSqlExpr* pSubExpr = tscSqlExprGet(pSubQueryInfo, k);
      if (pExpr->functionId == pSubExpr->functionId && pExpr->colInfo.colId == pSubExpr->colInfo.colId) {
        pRes->pColumnIndex[i] = (SColumnIndex){.tableIndex = tableIndexOfSub, .columnIndex = k};
        break;
      }
    }
  }
}

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

1062
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
1063 1064
  SSqlObj* pParentSql = pSupporter->pObj;

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

H
Haojun Liao 已提交
1069 1070 1071 1072 1073
  // 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 已提交
1074

H
Haojun Liao 已提交
1075 1076
    return;
  }
H
hjxilinx 已提交
1077

H
Haojun Liao 已提交
1078 1079 1080
  // TODO here retry is required, not directly returns to client
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(taos_errno(pSql) == code);
H
hjxilinx 已提交
1081

H
Haojun Liao 已提交
1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
    tscError("%p abort query, code:%d, global code:%d", pSql, code, pParentSql->res.code);
    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
  if (atomic_sub_fetch_32(&pSupporter->pState->numOfRemain, 1) > 0) {
    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)) {
    pSupporter->pState->numOfRemain = pSupporter->pState->numOfTotal;  // reset the record value

    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 已提交
1129
    } else {
H
Haojun Liao 已提交
1130
      tscQueueAsyncRes(pParentSql);
H
hjxilinx 已提交
1131 1132 1133 1134 1135 1136 1137 1138 1139
    }
  }
}

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

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

1140
int32_t tscLaunchJoinSubquery(SSqlObj *pSql, int16_t tableIndex, SJoinSupporter *pSupporter) {
H
hjxilinx 已提交
1141 1142 1143 1144
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  
  pSql->res.qhandle = 0x1;
H
Haojun Liao 已提交
1145 1146
  assert(pSql->res.numOfRows == 0);

H
hjxilinx 已提交
1147 1148 1149
  if (pSql->pSubs == NULL) {
    pSql->pSubs = calloc(pSupporter->pState->numOfTotal, POINTER_BYTES);
    if (pSql->pSubs == NULL) {
1150
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1151 1152 1153
    }
  }
  
1154
  SSqlObj *pNew = createSubqueryObj(pSql, tableIndex, tscJoinQueryCallback, pSupporter, TSDB_SQL_SELECT, NULL);
H
hjxilinx 已提交
1155
  if (pNew == NULL) {
1156
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
  }
  
  pSql->pSubs[pSql->numOfSubs++] = pNew;
  assert(pSql->numOfSubs <= pSupporter->pState->numOfTotal);
  
  if (QUERY_IS_JOIN_QUERY(pQueryInfo->type)) {
    addGroupInfoForSubquery(pSql, pNew, 0, tableIndex);
    
    // refactor as one method
    SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    assert(pNewQueryInfo != NULL);
    
1169 1170 1171 1172 1173 1174 1175
    // 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 已提交
1176 1177 1178 1179 1180 1181 1182
    pSupporter->colList = pNewQueryInfo->colList;
    pNewQueryInfo->colList = NULL;
    
    pSupporter->exprList = pNewQueryInfo->exprList;
    pNewQueryInfo->exprList = NULL;
    
    pSupporter->fieldsInfo = pNewQueryInfo->fieldsInfo;
H
hjxilinx 已提交
1183
  
H
hjxilinx 已提交
1184 1185
    // this data needs to be transfer to support struct
    memset(&pNewQueryInfo->fieldsInfo, 0, sizeof(SFieldInfo));
H
Haojun Liao 已提交
1186 1187
    tscTagCondCopy(&pSupporter->tagCond, &pNewQueryInfo->tagCond);//pNewQueryInfo->tagCond;

H
hjxilinx 已提交
1188 1189
    pNew->cmd.numOfCols = 0;
    pNewQueryInfo->intervalTime = 0;
H
Haojun Liao 已提交
1190 1191 1192 1193 1194
    pSupporter->limit = pNewQueryInfo->limit;

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

H
hjxilinx 已提交
1195 1196 1197 1198
    // backup the data and clear it in the sqlcmd object
    pSupporter->groupbyExpr = pNewQueryInfo->groupbyExpr;
    memset(&pNewQueryInfo->groupbyExpr, 0, sizeof(SSqlGroupbyExpr));
    
H
hjxilinx 已提交
1199
    tscInitQueryInfo(pNewQueryInfo);
H
hjxilinx 已提交
1200 1201
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pNewQueryInfo, 0);
    
weixin_48148422's avatar
weixin_48148422 已提交
1202
    if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) { // return the tableId & tag
1203
      SColumnIndex index = {0};
H
Haojun Liao 已提交
1204 1205 1206 1207

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

1208
      int32_t tagColId = tscGetJoinTagColIdByUid(pTagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
1209
      SSchema* s = tscGetTableColumnSchemaById(pTableMetaInfo->pTableMeta, tagColId);
H
Haojun Liao 已提交
1210 1211

      int16_t bytes = 0;
H
Haojun Liao 已提交
1212
      int16_t type  = 0;
H
Haojun Liao 已提交
1213 1214
      int32_t inter = 0;

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

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

1221 1222
      // set get tags query type
      TSDB_QUERY_SET_TYPE(pNewQueryInfo->type, TSDB_QUERY_TYPE_TAG_FILTER_QUERY);
H
Haojun Liao 已提交
1223
      tscAddSpecialColumnForSelect(pNewQueryInfo, 0, TSDB_FUNC_TID_TAG, &index, &s1, TSDB_COL_TAG);
1224
      size_t numOfCols = taosArrayGetSize(pNewQueryInfo->colList);
1225
  
1226
      tscDebug(
1227
          "%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%d, transfer to tid_tag query to retrieve (tableId, tags), "
B
Bomin Zhang 已提交
1228
          "exprInfo:%zu, colList:%zu, fieldsInfo:%d, tagIndex:%d, name:%s",
1229
          pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
H
Haojun Liao 已提交
1230
          numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, index.columnIndex, pNewQueryInfo->pTableMetaInfo[0]->name);
1231 1232 1233 1234 1235 1236 1237 1238
    } else {
      SSchema      colSchema = {.type = TSDB_DATA_TYPE_BINARY, .bytes = 1};
      SColumnIndex index = {0, PRIMARYKEY_TIMESTAMP_COL_INDEX};
      tscAddSpecialColumnForSelect(pNewQueryInfo, 0, TSDB_FUNC_TS_COMP, &index, &colSchema, TSDB_COL_NORMAL);

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

H
Haojun Liao 已提交
1239
      if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
1240
        int16_t tagColId = tscGetJoinTagColIdByUid(&pSupporter->tagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
1241 1242 1243
        pExpr->param->i64Key = tagColId;
        pExpr->numOfParams = 1;
      }
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260

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

1261
      tscDebug(
B
Bomin Zhang 已提交
1262
          "%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%u, transfer to ts_comp query to retrieve timestamps, "
B
Bomin Zhang 已提交
1263
          "exprInfo:%zu, colList:%zu, fieldsInfo:%d, name:%s",
1264 1265 1266
          pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
          numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, pNewQueryInfo->pTableMetaInfo[0]->name);
    }
H
hjxilinx 已提交
1267
  } else {
H
hjxilinx 已提交
1268
    assert(0);
H
hjxilinx 已提交
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
    SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    pNewQueryInfo->type |= TSDB_QUERY_TYPE_SUBQUERY;
  }

  return tscProcessSql(pNew);
}

int32_t tscHandleMasterJoinQuery(SSqlObj* pSql) {
  SSqlCmd* pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  assert((pQueryInfo->type & TSDB_QUERY_TYPE_SUBQUERY) == 0);
  
  SSubqueryState *pState = calloc(1, sizeof(SSubqueryState));
  pState->numOfTotal = pQueryInfo->numOfTables;
H
Haojun Liao 已提交
1283 1284
  pState->numOfRemain = pState->numOfTotal;

1285
  tscDebug("%p start subquery, total:%d", pSql, pQueryInfo->numOfTables);
H
hjxilinx 已提交
1286
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
1287
    SJoinSupporter *pSupporter = tscCreateJoinSupporter(pSql, pState, i);
H
hjxilinx 已提交
1288 1289 1290
    
    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 已提交
1291
      pState->numOfRemain = i;
1292
      pSql->res.code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1293 1294 1295 1296 1297 1298 1299
      
      return pSql->res.code;
    }
    
    int32_t code = tscLaunchJoinSubquery(pSql, i, pSupporter);
    if (code != TSDB_CODE_SUCCESS) {  // failed to create subquery object, quit query
      tscDestroyJoinSupporter(pSupporter);
1300
      pSql->res.code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1301 1302 1303 1304
      
      break;
    }
  }
H
Haojun Liao 已提交
1305

1306
  pSql->cmd.command = (pSql->numOfSubs <= 0)? TSDB_SQL_RETRIEVE_EMPTY_RESULT:TSDB_SQL_TABLE_JOIN_RETRIEVE;
H
hjxilinx 已提交
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
  
  return TSDB_CODE_SUCCESS;
}

static void doCleanupSubqueries(SSqlObj *pSql, int32_t numOfSubs, SSubqueryState* pState) {
  assert(numOfSubs <= pSql->numOfSubs && numOfSubs >= 0 && pState != NULL);
  
  for(int32_t i = 0; i < numOfSubs; ++i) {
    SSqlObj* pSub = pSql->pSubs[i];
    assert(pSub != NULL);
    
    SRetrieveSupport* pSupport = pSub->param;
    
S
Shengliang Guan 已提交
1320
    taosTFree(pSupport->localBuffer);
H
hjxilinx 已提交
1321 1322 1323 1324
    
    pthread_mutex_unlock(&pSupport->queryMutex);
    pthread_mutex_destroy(&pSupport->queryMutex);
    
S
Shengliang Guan 已提交
1325
    taosTFree(pSupport);
H
hjxilinx 已提交
1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
    
    tscFreeSqlObj(pSub);
  }
  
  free(pState);
}

int32_t tscHandleMasterSTableQuery(SSqlObj *pSql) {
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;
  
  // pRes->code check only serves in launching metric sub-queries
1338
  if (pRes->code == TSDB_CODE_TSC_QUERY_CANCELLED) {
H
hjxilinx 已提交
1339
    pCmd->command = TSDB_SQL_RETRIEVE_LOCALMERGE;  // enable the abort of kill super table function.
H
hjxilinx 已提交
1340 1341 1342 1343 1344 1345 1346
    return pRes->code;
  }
  
  tExtMemBuffer **  pMemoryBuf = NULL;
  tOrderDescriptor *pDesc = NULL;
  SColumnModel *    pModel = NULL;
  
H
Haojun Liao 已提交
1347
  pRes->qhandle = 0x1;  // hack the qhandle check
H
hjxilinx 已提交
1348
  
1349
  const uint32_t nBufferSize = (1u << 16);  // 64KB
H
hjxilinx 已提交
1350 1351 1352
  
  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
hjxilinx 已提交
1353
  
H
hjxilinx 已提交
1354
  pSql->numOfSubs = pTableMetaInfo->vgroupList->numOfVgroups;
1355
  assert(pSql->numOfSubs > 0);
H
hjxilinx 已提交
1356 1357 1358
  
  int32_t ret = tscLocalReducerEnvCreate(pSql, &pMemoryBuf, &pDesc, &pModel, nBufferSize);
  if (ret != 0) {
1359
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1360
    tscQueueAsyncRes(pSql);
S
Shengliang Guan 已提交
1361
    taosTFree(pMemoryBuf);
H
hjxilinx 已提交
1362
    return ret;
H
hjxilinx 已提交
1363 1364
  }
  
1365
  pSql->pSubs = calloc(pSql->numOfSubs, POINTER_BYTES);
H
hjxilinx 已提交
1366
  
1367
  tscDebug("%p retrieved query data from %d vnode(s)", pSql, pSql->numOfSubs);
H
hjxilinx 已提交
1368
  SSubqueryState *pState = calloc(1, sizeof(SSubqueryState));
1369
  pState->numOfTotal = pSql->numOfSubs;
H
Haojun Liao 已提交
1370 1371
  pState->numOfRemain = pSql->numOfSubs;

H
hjxilinx 已提交
1372 1373 1374
  pRes->code = TSDB_CODE_SUCCESS;
  
  int32_t i = 0;
1375
  for (; i < pSql->numOfSubs; ++i) {
H
hjxilinx 已提交
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
    SRetrieveSupport *trs = (SRetrieveSupport *)calloc(1, sizeof(SRetrieveSupport));
    if (trs == NULL) {
      tscError("%p failed to malloc buffer for SRetrieveSupport, orderOfSub:%d, reason:%s", pSql, i, strerror(errno));
      break;
    }
    
    trs->pExtMemBuffer = pMemoryBuf;
    trs->pOrderDescriptor = pDesc;
    trs->pState = pState;
    
    trs->localBuffer = (tFilePage *)calloc(1, nBufferSize + sizeof(tFilePage));
    if (trs->localBuffer == NULL) {
      tscError("%p failed to malloc buffer for local buffer, orderOfSub:%d, reason:%s", pSql, i, strerror(errno));
S
Shengliang Guan 已提交
1389
      taosTFree(trs);
H
hjxilinx 已提交
1390 1391 1392 1393
      break;
    }
    
    trs->subqueryIndex = i;
H
Haojun Liao 已提交
1394
    trs->pParentSql = pSql;
H
hjxilinx 已提交
1395 1396
    trs->pFinalColModel = pModel;
    
H
Haojun Liao 已提交
1397 1398 1399
    pthread_mutexattr_t mutexattr;
    memset(&mutexattr, 0, sizeof(pthread_mutexattr_t));

H
hjxilinx 已提交
1400 1401 1402 1403 1404 1405 1406
    pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE_NP);
    pthread_mutex_init(&trs->queryMutex, &mutexattr);
    pthread_mutexattr_destroy(&mutexattr);
    
    SSqlObj *pNew = tscCreateSqlObjForSubquery(pSql, trs, NULL);
    if (pNew == NULL) {
      tscError("%p failed to malloc buffer for subObj, orderOfSub:%d, reason:%s", pSql, i, strerror(errno));
S
Shengliang Guan 已提交
1407 1408
      taosTFree(trs->localBuffer);
      taosTFree(trs);
H
hjxilinx 已提交
1409 1410 1411 1412 1413 1414 1415
      break;
    }
    
    // todo handle multi-vnode situation
    if (pQueryInfo->tsBuf) {
      SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
      pNewQueryInfo->tsBuf = tsBufClone(pQueryInfo->tsBuf);
H
Haojun Liao 已提交
1416
      assert(pNewQueryInfo->tsBuf != NULL);
H
hjxilinx 已提交
1417 1418
    }
    
1419
    tscDebug("%p sub:%p create subquery success. orderOfSub:%d", pSql, pNew, trs->subqueryIndex);
H
hjxilinx 已提交
1420 1421
  }
  
1422
  if (i < pSql->numOfSubs) {
H
hjxilinx 已提交
1423
    tscError("%p failed to prepare subquery structure and launch subqueries", pSql);
1424
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1425
    
1426
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pSql->numOfSubs);
H
hjxilinx 已提交
1427 1428 1429 1430
    doCleanupSubqueries(pSql, i, pState);
    return pRes->code;   // free all allocated resource
  }
  
1431
  if (pRes->code == TSDB_CODE_TSC_QUERY_CANCELLED) {
1432
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pSql->numOfSubs);
H
hjxilinx 已提交
1433 1434 1435 1436
    doCleanupSubqueries(pSql, i, pState);
    return pRes->code;
  }
  
1437
  for(int32_t j = 0; j < pSql->numOfSubs; ++j) {
H
hjxilinx 已提交
1438 1439 1440
    SSqlObj* pSub = pSql->pSubs[j];
    SRetrieveSupport* pSupport = pSub->param;
    
1441
    tscDebug("%p sub:%p launch subquery, orderOfSub:%d.", pSql, pSub, pSupport->subqueryIndex);
H
hjxilinx 已提交
1442 1443 1444 1445 1446 1447 1448
    tscProcessSql(pSub);
  }
  
  return TSDB_CODE_SUCCESS;
}

static void tscFreeSubSqlObj(SRetrieveSupport *trsupport, SSqlObj *pSql) {
1449
  tscDebug("%p start to free subquery result", pSql);
H
hjxilinx 已提交
1450
  
B
Bomin Zhang 已提交
1451
  taos_free_result(pSql);
H
hjxilinx 已提交
1452
  
S
Shengliang Guan 已提交
1453
  taosTFree(trsupport->localBuffer);
H
hjxilinx 已提交
1454 1455 1456 1457
  
  pthread_mutex_unlock(&trsupport->queryMutex);
  pthread_mutex_destroy(&trsupport->queryMutex);
  
S
Shengliang Guan 已提交
1458
  taosTFree(trsupport);
H
hjxilinx 已提交
1459 1460
}

1461
static void tscRetrieveFromDnodeCallBack(void *param, TAOS_RES *tres, int numOfRows);
1462
static void tscHandleSubqueryError(SRetrieveSupport *trsupport, SSqlObj *pSql, int numOfRows);
H
hjxilinx 已提交
1463

H
Haojun Liao 已提交
1464
static void tscAbortFurtherRetryRetrieval(SRetrieveSupport *trsupport, TAOS_RES *tres, int32_t code) {
H
hjxilinx 已提交
1465 1466 1467 1468 1469 1470 1471 1472 1473
// set no disk space error info
#ifdef WINDOWS
  LPVOID lpMsgBuf;
  FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL,
                GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),  // Default language
                (LPTSTR)&lpMsgBuf, 0, NULL);
  tscError("sub:%p failed to flush data to disk:reason:%s", tres, lpMsgBuf);
  LocalFree(lpMsgBuf);
#else
1474
  tscError("sub:%p failed to flush data to disk, reason:%s", tres, tstrerror(code));
H
hjxilinx 已提交
1475
#endif
H
Haojun Liao 已提交
1476

H
Haojun Liao 已提交
1477
  SSqlObj* pParentSql = trsupport->pParentSql;
H
Haojun Liao 已提交
1478 1479

  pParentSql->res.code = code;
H
hjxilinx 已提交
1480 1481 1482
  trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
  
  pthread_mutex_unlock(&trsupport->queryMutex);
H
Haojun Liao 已提交
1483
  tscHandleSubqueryError(trsupport, tres, pParentSql->res.code);
H
hjxilinx 已提交
1484 1485
}

H
Haojun Liao 已提交
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
/*
 * 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;
  pthread_mutex_unlock(&trsupport->queryMutex);

  tscTrace("%p sub:%p retrieve failed, code:%s, orderOfSub:%d, retry:%d", trsupport->pParentSql, pSql,
           tstrerror(code), subqueryIndex, trsupport->numOfRetry);

  SSqlObj *pNew = tscCreateSqlObjForSubquery(trsupport->pParentSql, trsupport, pSql);

  if (pNew == NULL) {
1509 1510
    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 已提交
1511

1512
    pParentSql->res.code = terrno;
H
Haojun Liao 已提交
1513 1514 1515 1516 1517 1518 1519 1520 1521
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;

    return pParentSql->res.code;
  }

  taos_free_result(pSql);
  return tscProcessSql(pNew);
}

1522
void tscHandleSubqueryError(SRetrieveSupport *trsupport, SSqlObj *pSql, int numOfRows) {
H
Haojun Liao 已提交
1523
  SSqlObj *pParentSql = trsupport->pParentSql;
H
hjxilinx 已提交
1524 1525 1526 1527
  int32_t  subqueryIndex = trsupport->subqueryIndex;
  
  assert(pSql != NULL);
  SSubqueryState* pState = trsupport->pState;
H
Haojun Liao 已提交
1528
  assert(pState->numOfRemain <= pState->numOfTotal && pState->numOfRemain >= 0 && pParentSql->numOfSubs == pState->numOfTotal);
H
hjxilinx 已提交
1529
  
1530
  // retrieved in subquery failed. OR query cancelled in retrieve phase.
H
Haojun Liao 已提交
1531 1532
  if (taos_errno(pSql) == TSDB_CODE_SUCCESS && pParentSql->res.code != TSDB_CODE_SUCCESS) {

H
hjxilinx 已提交
1533 1534
    /*
     * kill current sub-query connection, which may retrieve data from vnodes;
1535
     * Here we get: pPObj->res.code == TSDB_CODE_TSC_QUERY_CANCELLED
H
hjxilinx 已提交
1536 1537 1538
     */
    pSql->res.numOfRows = 0;
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;  // disable retry efforts
1539
    tscDebug("%p query is cancelled, sub:%p, orderOfSub:%d abort retrieve, code:%d", pParentSql, pSql,
H
Haojun Liao 已提交
1540
             subqueryIndex, pParentSql->res.code);
H
hjxilinx 已提交
1541
  }
H
Haojun Liao 已提交
1542

H
hjxilinx 已提交
1543
  if (numOfRows >= 0) {  // current query is successful, but other sub query failed, still abort current query.
1544
    tscDebug("%p sub:%p retrieve numOfRows:%d,orderOfSub:%d", pParentSql, pSql, numOfRows, subqueryIndex);
H
Haojun Liao 已提交
1545 1546
    tscError("%p sub:%p abort further retrieval due to other queries failure,orderOfSub:%d,code:%d", pParentSql, pSql,
             subqueryIndex, pParentSql->res.code);
H
hjxilinx 已提交
1547
  } else {
H
Haojun Liao 已提交
1548
    if (trsupport->numOfRetry++ < MAX_NUM_OF_SUBQUERY_RETRY && pParentSql->res.code == TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1549
      if (tscReissueSubquery(trsupport, pSql, numOfRows) == TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1550 1551 1552
        return;
      }
    } else {  // reach the maximum retry count, abort
H
Haojun Liao 已提交
1553 1554 1555
      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 已提交
1556 1557
    }
  }
H
Haojun Liao 已提交
1558 1559 1560

  int32_t remain = -1;
  if ((remain = atomic_sub_fetch_32(&pState->numOfRemain, 1)) > 0) {
1561
    tscDebug("%p sub:%p orderOfSub:%d freed, finished subqueries:%d", pParentSql, pSql, trsupport->subqueryIndex,
H
Haojun Liao 已提交
1562 1563
        pState->numOfTotal - remain);

S
Shengliang Guan 已提交
1564 1565
    tscFreeSubSqlObj(trsupport, pSql);
    return;
H
hjxilinx 已提交
1566 1567 1568
  }
  
  // all subqueries are failed
H
Haojun Liao 已提交
1569 1570 1571
  tscError("%p retrieve from %d vnode(s) completed,code:%s.FAILED.", pParentSql, pState->numOfTotal,
      tstrerror(pParentSql->res.code));

H
hjxilinx 已提交
1572 1573 1574 1575
  // release allocated resource
  tscLocalReducerEnvDestroy(trsupport->pExtMemBuffer, trsupport->pOrderDescriptor, trsupport->pFinalColModel,
                            pState->numOfTotal);
  
S
Shengliang Guan 已提交
1576
  taosTFree(trsupport->pState);
H
hjxilinx 已提交
1577 1578 1579
  tscFreeSubSqlObj(trsupport, pSql);
  
  // in case of second stage join subquery, invoke its callback function instead of regular QueueAsyncRes
H
Haojun Liao 已提交
1580
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pParentSql->cmd, 0);
H
hjxilinx 已提交
1581
  
H
Haojun Liao 已提交
1582
  if (!TSDB_QUERY_HAS_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_JOIN_SEC_STAGE)) {
H
Haojun Liao 已提交
1583
    (*pParentSql->fp)(pParentSql->param, pParentSql, pParentSql->res.code);
H
hjxilinx 已提交
1584
  } else {  // regular super table query
H
Haojun Liao 已提交
1585 1586
    if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
      tscQueueAsyncRes(pParentSql);
H
hjxilinx 已提交
1587 1588 1589 1590
    }
  }
}

1591 1592
static void tscAllDataRetrievedFromDnode(SRetrieveSupport *trsupport, SSqlObj* pSql) {
  int32_t           idx = trsupport->subqueryIndex;
H
Haojun Liao 已提交
1593
  SSqlObj *         pParentSql = trsupport->pParentSql;
1594 1595 1596 1597 1598
  tOrderDescriptor *pDesc = trsupport->pOrderDescriptor;
  
  SSubqueryState* pState = trsupport->pState;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
  
1599 1600
  STableMetaInfo* pTableMetaInfo = pQueryInfo->pTableMetaInfo[0];
  
1601
  // data in from current vnode is stored in cache and disk
S
Shengliang Guan 已提交
1602
  uint32_t numOfRowsFromSubquery = (uint32_t)(trsupport->pExtMemBuffer[idx]->numOfTotalElems + trsupport->localBuffer->num);
1603 1604
    tscDebug("%p sub:%p all data retrieved from ep:%s, vgId:%d, numOfRows:%d, orderOfSub:%d", pParentSql, pSql,
        pTableMetaInfo->vgroupList->vgroups[0].epAddr[0].fqdn, pTableMetaInfo->vgroupList->vgroups[0].vgId,
1605
        numOfRowsFromSubquery, idx);
1606 1607 1608 1609
  
  tColModelCompact(pDesc->pColumnModel, trsupport->localBuffer, pDesc->pColumnModel->capacity);

#ifdef _DEBUG_VIEW
1610
  printf("%" PRIu64 " rows data flushed to disk:\n", trsupport->localBuffer->num);
1611 1612
    SSrcColumnInfo colInfo[256] = {0};
    tscGetSrcColumnInfo(colInfo, pQueryInfo);
1613 1614
    tColModelDisplayEx(pDesc->pColumnModel, trsupport->localBuffer->data, trsupport->localBuffer->num,
                       trsupport->localBuffer->num, colInfo);
1615 1616
#endif
  
H
Haojun Liao 已提交
1617 1618 1619
  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 已提交
1620 1621
    tscAbortFurtherRetryRetrieval(trsupport, pSql, TSDB_CODE_TSC_NO_DISKSPACE);
    return;
1622 1623 1624
  }
  
  // each result for a vnode is ordered as an independant list,
H
Haojun Liao 已提交
1625
  // then used as an input of loser tree for disk-based merge
1626 1627
  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 已提交
1628 1629
    tscAbortFurtherRetryRetrieval(trsupport, pSql, code);
    return;
1630 1631
  }
  
H
Haojun Liao 已提交
1632 1633
  int32_t remain = -1;
  if ((remain = atomic_sub_fetch_32(&pState->numOfRemain, 1)) > 0) {
H
Haojun Liao 已提交
1634
    tscDebug("%p sub:%p orderOfSub:%d freed, finished subqueries:%d", pParentSql, pSql, trsupport->subqueryIndex,
H
Haojun Liao 已提交
1635 1636
        pState->numOfTotal - remain);

S
Shengliang Guan 已提交
1637 1638
    tscFreeSubSqlObj(trsupport, pSql);
    return;
1639 1640 1641 1642 1643
  }
  
  // all sub-queries are returned, start to local merge process
  pDesc->pColumnModel->capacity = trsupport->pExtMemBuffer[idx]->numOfElemsPerPage;
  
H
Haojun Liao 已提交
1644
  tscDebug("%p retrieve from %d vnodes completed.final NumOfRows:%" PRId64 ",start to build loser tree", pParentSql,
1645 1646
           pState->numOfTotal, pState->numOfRetrievedRows);
  
H
Haojun Liao 已提交
1647
  SQueryInfo *pPQueryInfo = tscGetQueryInfoDetail(&pParentSql->cmd, 0);
1648 1649
  tscClearInterpInfo(pPQueryInfo);
  
H
Haojun Liao 已提交
1650 1651
  tscCreateLocalReducer(trsupport->pExtMemBuffer, pState->numOfTotal, pDesc, trsupport->pFinalColModel, pParentSql);
  tscDebug("%p build loser tree completed", pParentSql);
1652
  
H
Haojun Liao 已提交
1653 1654 1655
  pParentSql->res.precision = pSql->res.precision;
  pParentSql->res.numOfRows = 0;
  pParentSql->res.row = 0;
1656 1657
  
  // only free once
S
Shengliang Guan 已提交
1658
  taosTFree(trsupport->pState);
1659 1660 1661
  tscFreeSubSqlObj(trsupport, pSql);
  
  // set the command flag must be after the semaphore been correctly set.
H
Haojun Liao 已提交
1662 1663 1664
  pParentSql->cmd.command = TSDB_SQL_RETRIEVE_LOCALMERGE;
  if (pParentSql->res.code == TSDB_CODE_SUCCESS) {
    (*pParentSql->fp)(pParentSql->param, pParentSql, 0);
1665
  } else {
H
Haojun Liao 已提交
1666
    tscQueueAsyncRes(pParentSql);
1667 1668 1669 1670
  }
}

static void tscRetrieveFromDnodeCallBack(void *param, TAOS_RES *tres, int numOfRows) {
H
hjxilinx 已提交
1671 1672
  SRetrieveSupport *trsupport = (SRetrieveSupport *)param;
  tOrderDescriptor *pDesc = trsupport->pOrderDescriptor;
H
Haojun Liao 已提交
1673
  int32_t           idx   = trsupport->subqueryIndex;
H
Haojun Liao 已提交
1674
  SSqlObj *         pParentSql = trsupport->pParentSql;
H
Haojun Liao 已提交
1675

H
hjxilinx 已提交
1676 1677
  SSqlObj *pSql = (SSqlObj *)tres;
  if (pSql == NULL) {  // sql object has been released in error process, return immediately
H
Haojun Liao 已提交
1678
    tscDebug("%p subquery has been released, idx:%d, abort", pParentSql, idx);
H
hjxilinx 已提交
1679 1680 1681 1682
    return;
  }
  
  SSubqueryState* pState = trsupport->pState;
H
Haojun Liao 已提交
1683
  assert(pState->numOfRemain <= pState->numOfTotal && pState->numOfRemain >= 0 && pParentSql->numOfSubs == pState->numOfTotal);
H
hjxilinx 已提交
1684 1685 1686
  
  // query process and cancel query process may execute at the same time
  pthread_mutex_lock(&trsupport->queryMutex);
H
Haojun Liao 已提交
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715

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

  if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
    tscTrace("%p query cancelled or failed, sub:%p, vgId:%d, orderOfSub:%d, code:%s, global code:%s",
             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));

    if (trsupport->numOfRetry++ < MAX_NUM_OF_SUBQUERY_RETRY) {
      tscTrace("%p sub:%p failed code:%s, retry:%d", pParentSql, pSql, tstrerror(numOfRows), trsupport->numOfRetry);

      if (tscReissueSubquery(trsupport, pSql, numOfRows) == TSDB_CODE_SUCCESS) {
        return;
      }
    } else {
      tscTrace("%p sub:%p reach the max retry times, set global code:%s", pParentSql, pSql, tstrerror(numOfRows));
      atomic_val_compare_exchange_32(&pParentSql->res.code, TSDB_CODE_SUCCESS, numOfRows);  // set global code and abort
    }

    tscHandleSubqueryError(param, tres, numOfRows);
    return;
H
hjxilinx 已提交
1716 1717 1718 1719 1720 1721 1722 1723 1724
  }
  
  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);
    
1725 1726
    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);
1727

H
hjxilinx 已提交
1728
    if (num > tsMaxNumOfOrderedResults && tscIsProjectionQueryOnSTable(pQueryInfo, 0)) {
B
Bomin Zhang 已提交
1729
      tscError("%p sub:%p num of OrderedRes is too many, max allowed:%" PRId32 " , current:%" PRId64,
H
Haojun Liao 已提交
1730
               pParentSql, pSql, tsMaxNumOfOrderedResults, num);
S
Shengliang Guan 已提交
1731 1732
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_SORTED_RES_TOO_MANY);
      return;
H
hjxilinx 已提交
1733 1734 1735
    }

#ifdef _DEBUG_VIEW
1736
    printf("received data from vnode: %"PRIu64" rows\n", pRes->numOfRows);
H
hjxilinx 已提交
1737 1738 1739 1740 1741
    SSrcColumnInfo colInfo[256] = {0};

    tscGetSrcColumnInfo(colInfo, pQueryInfo);
    tColModelDisplayEx(pDesc->pColumnModel, pRes->data, pRes->numOfRows, pRes->numOfRows, colInfo);
#endif
1742
    
H
Haojun Liao 已提交
1743 1744 1745 1746
    // 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 已提交
1747 1748
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_NO_DISKSPACE);
      return;
H
hjxilinx 已提交
1749 1750 1751
    }
    
    int32_t ret = saveToBuffer(trsupport->pExtMemBuffer[idx], pDesc, trsupport->localBuffer, pRes->data,
S
Shengliang Guan 已提交
1752
                               (int32_t)pRes->numOfRows, pQueryInfo->groupbyExpr.orderType);
1753
    if (ret != 0) { // set no disk space error info, and abort retry
1754
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_NO_DISKSPACE);
1755
      
1756 1757
    } else if (pRes->completed) {
      tscAllDataRetrievedFromDnode(trsupport, pSql);
1758 1759
      return;
      
1760
    } else { // continue fetch data from dnode
H
hjxilinx 已提交
1761
      pthread_mutex_unlock(&trsupport->queryMutex);
1762
      taos_fetch_rows_a(tres, tscRetrieveFromDnodeCallBack, param);
H
hjxilinx 已提交
1763
    }
1764
    
1765 1766
  } else { // all data has been retrieved to client
    tscAllDataRetrievedFromDnode(trsupport, pSql);
H
hjxilinx 已提交
1767 1768 1769 1770 1771 1772
  }
}

static SSqlObj *tscCreateSqlObjForSubquery(SSqlObj *pSql, SRetrieveSupport *trsupport, SSqlObj *prevSqlObj) {
  const int32_t table_index = 0;
  
1773
  SSqlObj *pNew = createSubqueryObj(pSql, table_index, tscRetrieveDataRes, trsupport, TSDB_SQL_SELECT, prevSqlObj);
H
hjxilinx 已提交
1774 1775 1776 1777 1778 1779
  if (pNew != NULL) {  // the sub query of two-stage super table query
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    pQueryInfo->type |= TSDB_QUERY_TYPE_STABLE_SUBQUERY;
    
    assert(pQueryInfo->numOfTables == 1 && pNew->cmd.numOfClause == 1);
    
H
hjxilinx 已提交
1780
    // launch subquery for each vnode, so the subquery index equals to the vgroupIndex.
H
hjxilinx 已提交
1781
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, table_index);
H
hjxilinx 已提交
1782
    pTableMetaInfo->vgroupIndex = trsupport->subqueryIndex;
H
hjxilinx 已提交
1783 1784 1785 1786 1787 1788 1789 1790
    
    pSql->pSubs[trsupport->subqueryIndex] = pNew;
  }
  
  return pNew;
}

void tscRetrieveDataRes(void *param, TAOS_RES *tres, int code) {
1791
  SRetrieveSupport *trsupport = (SRetrieveSupport *) param;
H
hjxilinx 已提交
1792
  
H
Haojun Liao 已提交
1793
  SSqlObj*  pParentSql = trsupport->pParentSql;
1794
  SSqlObj*  pSql = (SSqlObj *) tres;
H
hjxilinx 已提交
1795
  
1796 1797
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
  assert(pSql->cmd.numOfClause == 1 && pQueryInfo->numOfTables == 1);
H
hjxilinx 已提交
1798
  
1799
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
H
Haojun Liao 已提交
1800
  SCMVgroupInfo* pVgroup = &pTableMetaInfo->vgroupList->vgroups[trsupport->subqueryIndex];
H
Haojun Liao 已提交
1801

H
Haojun Liao 已提交
1802
  // stable query killed or other subquery failed, all query stopped
H
Haojun Liao 已提交
1803
  if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1804
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
H
Haojun Liao 已提交
1805 1806 1807 1808 1809
    tscTrace("%p query cancelled or failed, sub:%p, vgId:%d, orderOfSub:%d, code:%s, global code:%s",
        pParentSql, pSql, pVgroup->vgId, trsupport->subqueryIndex, tstrerror(code), tstrerror(pParentSql->res.code));

    tscHandleSubqueryError(param, tres, code);
    return;
H
hjxilinx 已提交
1810 1811 1812
  }
  
  /*
H
Haojun Liao 已提交
1813
   * if a subquery on a vnode failed, all retrieve operations from vnode that occurs later
1814
   * than this one are actually not necessary, we simply call the tscRetrieveFromDnodeCallBack
H
hjxilinx 已提交
1815 1816
   * function to abort current and remain retrieve process.
   *
1817
   * NOTE: thread safe is required.
H
hjxilinx 已提交
1818
   */
H
Haojun Liao 已提交
1819 1820
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(code == taos_errno(pSql));
1821

H
Haojun Liao 已提交
1822 1823 1824
    if (trsupport->numOfRetry++ < MAX_NUM_OF_SUBQUERY_RETRY) {
      tscTrace("%p sub:%p failed code:%s, retry:%d", pParentSql, pSql, tstrerror(code), trsupport->numOfRetry);
      if (tscReissueSubquery(trsupport, pSql, code) == TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1825 1826
        return;
      }
1827
    } else {
H
Haojun Liao 已提交
1828 1829
      tscTrace("%p sub:%p reach the max retry times, set global code:%s", pParentSql, pSql, tstrerror(code));
      atomic_val_compare_exchange_32(&pParentSql->res.code, TSDB_CODE_SUCCESS, code);  // set global code and abort
1830
    }
H
Haojun Liao 已提交
1831 1832 1833 1834 1835

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

1836 1837
  tscTrace("%p sub:%p query complete, ep:%s, vgId:%d, orderOfSub:%d, retrieve data", trsupport->pParentSql, pSql,
             pVgroup->epAddr[0].fqdn, pVgroup->vgId, trsupport->subqueryIndex);
H
Haojun Liao 已提交
1838 1839 1840 1841 1842

  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 已提交
1843 1844 1845
  }
}

H
Haojun Liao 已提交
1846
static void multiVnodeInsertFinalize(void* param, TAOS_RES* tres, int numOfRows) {
H
hjxilinx 已提交
1847 1848 1849
  SInsertSupporter *pSupporter = (SInsertSupporter *)param;
  SSqlObj* pParentObj = pSupporter->pSql;
  SSubqueryState* pState = pSupporter->pState;
H
Haojun Liao 已提交
1850

H
Haojun Liao 已提交
1851
  // record the total inserted rows
H
Haojun Liao 已提交
1852 1853
  if (numOfRows > 0) {
    pParentObj->res.numOfRows += numOfRows;
H
Haojun Liao 已提交
1854 1855
  }

H
Haojun Liao 已提交
1856
  if (taos_errno(tres) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1857 1858 1859 1860
    SSqlObj* pSql = (SSqlObj*) tres;
    assert(pSql != NULL && pSql->res.code == numOfRows);
    
    pParentObj->res.code = pSql->res.code;
H
hjxilinx 已提交
1861
  }
H
Haojun Liao 已提交
1862

H
Haojun Liao 已提交
1863
  taos_free_result(tres);
S
Shengliang Guan 已提交
1864
  taosTFree(pSupporter);
H
Haojun Liao 已提交
1865

H
Haojun Liao 已提交
1866
  if (atomic_sub_fetch_32(&pState->numOfRemain, 1) > 0) {
H
hjxilinx 已提交
1867 1868 1869
    return;
  }
  
1870
  tscDebug("%p Async insertion completed, total inserted:%" PRId64, pParentObj, pParentObj->res.numOfRows);
H
Haojun Liao 已提交
1871

H
hjxilinx 已提交
1872
  // release data block data
S
Shengliang Guan 已提交
1873
  taosTFree(pState);
1874

H
hjxilinx 已提交
1875 1876
  // restore user defined fp
  pParentObj->fp = pParentObj->fetchFp;
1877 1878

  // todo remove this parameter in async callback function definition.
H
hjxilinx 已提交
1879
  // all data has been sent to vnode, call user function
S
Shengliang Guan 已提交
1880
  int32_t v = (pParentObj->res.code != TSDB_CODE_SUCCESS) ? pParentObj->res.code : (int32_t)pParentObj->res.numOfRows;
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
  (*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;
  assert(pSupporter->index < pSupporter->pState->numOfTotal);

  STableDataBlocks* pTableDataBlock = taosArrayGetP(pCmd->pDataBlocks, pSupporter->index);
H
Haojun Liao 已提交
1898 1899 1900 1901 1902
  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.
1903 1904 1905
  }

  return tscProcessSql(pSql);
H
hjxilinx 已提交
1906 1907 1908 1909 1910 1911
}

int32_t tscHandleMultivnodeInsert(SSqlObj *pSql) {
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;
  
1912 1913 1914 1915
  size_t size = taosArrayGetSize(pCmd->pDataBlocks);
  assert(size > 0);

  pSql->pSubs = calloc(size, POINTER_BYTES);
S
Shengliang Guan 已提交
1916
  pSql->numOfSubs = (uint16_t)size;
1917

1918
  tscDebug("%p submit data to %zu vnode(s)", pSql, size);
1919

H
hjxilinx 已提交
1920 1921
  SSubqueryState *pState = calloc(1, sizeof(SSubqueryState));
  pState->numOfTotal = pSql->numOfSubs;
dengyihao's avatar
dengyihao 已提交
1922
  pState->numOfRemain = pSql->numOfSubs;
1923
 
H
hjxilinx 已提交
1924
  pRes->code = TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1925
  int32_t numOfSub = 0;
H
Haojun Liao 已提交
1926

H
Haojun Liao 已提交
1927 1928
  while(numOfSub < pSql->numOfSubs) {
    SInsertSupporter* pSupporter = calloc(1, sizeof(SInsertSupporter));
1929
    pSupporter->pSql   = pSql;
H
Haojun Liao 已提交
1930
    pSupporter->pState = pState;
1931 1932 1933
    pSupporter->index  = numOfSub;

    SSqlObj *pNew = createSimpleSubObj(pSql, multiVnodeInsertFinalize, pSupporter, TSDB_SQL_INSERT);
H
hjxilinx 已提交
1934
    if (pNew == NULL) {
H
Haojun Liao 已提交
1935
      tscError("%p failed to malloc buffer for subObj, orderOfSub:%d, reason:%s", pSql, numOfSub, strerror(errno));
H
Haojun Liao 已提交
1936
      goto _error;
H
hjxilinx 已提交
1937
    }
1938 1939 1940
  
    /*
     * assign the callback function to fetchFp to make sure that the error process function can restore
H
Haojun Liao 已提交
1941
     * the callback function (multiVnodeInsertFinalize) correctly.
1942 1943
     */
    pNew->fetchFp = pNew->fp;
H
Haojun Liao 已提交
1944
    pSql->pSubs[numOfSub] = pNew;
H
Haojun Liao 已提交
1945

1946 1947
    STableDataBlocks* pTableDataBlock = taosArrayGetP(pCmd->pDataBlocks, numOfSub);
    pRes->code = tscCopyDataBlockToPayload(pNew, pTableDataBlock);
H
Haojun Liao 已提交
1948
    if (pRes->code == TSDB_CODE_SUCCESS) {
1949
      tscDebug("%p sub:%p create subObj success. orderOfSub:%d", pSql, pNew, numOfSub);
1950
      numOfSub++;
H
Haojun Liao 已提交
1951
    } else {
1952
      tscDebug("%p prepare submit data block failed in async insertion, vnodeIdx:%d, total:%zu, code:%s", pSql, numOfSub,
1953
               size, tstrerror(pRes->code));
H
Haojun Liao 已提交
1954
      goto _error;
H
Haojun Liao 已提交
1955
    }
H
hjxilinx 已提交
1956 1957
  }
  
H
Haojun Liao 已提交
1958
  if (numOfSub < pSql->numOfSubs) {
H
hjxilinx 已提交
1959
    tscError("%p failed to prepare subObj structure and launch sub-insertion", pSql);
1960
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1961 1962
    return pRes->code;  // free all allocated resource
  }
H
Haojun Liao 已提交
1963

1964 1965
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);

H
Haojun Liao 已提交
1966 1967
  // use the local variable
  for (int32_t j = 0; j < numOfSub; ++j) {
H
hjxilinx 已提交
1968
    SSqlObj *pSub = pSql->pSubs[j];
1969
    tscDebug("%p sub:%p launch sub insert, orderOfSub:%d", pSql, pSub, j);
H
hjxilinx 已提交
1970 1971
    tscProcessSql(pSub);
  }
H
Haojun Liao 已提交
1972

H
hjxilinx 已提交
1973
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1974 1975

  _error:
H
Haojun Liao 已提交
1976
  for(int32_t j = 0; j < numOfSub; ++j) {
S
Shengliang Guan 已提交
1977
    taosTFree(pSql->pSubs[j]->param);
H
Haojun Liao 已提交
1978 1979 1980
    taos_free_result(pSql->pSubs[j]);
  }

S
Shengliang Guan 已提交
1981
  taosTFree(pState);
H
Haojun Liao 已提交
1982
  return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1983
}
H
hjxilinx 已提交
1984

H
Haojun Liao 已提交
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007
static char* getResultBlockPosition(SSqlCmd* pCmd, SSqlRes* pRes, int32_t columnIndex, int16_t* bytes) {
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);

  SFieldSupInfo* pInfo = (SFieldSupInfo*) TARRAY_GET_ELEM(pQueryInfo->fieldsInfo.pSupportInfo, columnIndex);
  assert(pInfo->pSqlExpr != NULL);

  *bytes = pInfo->pSqlExpr->resBytes;
  char* pData = pRes->data + pInfo->pSqlExpr->offset * pRes->numOfRows;

  return pData;
}

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

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

  int32_t numOfRes = INT32_MAX;
  for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
    if (pSql->pSubs[i] == NULL) {
      continue;
    }

S
Shengliang Guan 已提交
2008
    numOfRes = (int32_t)(MIN(numOfRes, pSql->pSubs[i]->res.numOfRows));
H
Haojun Liao 已提交
2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
  }

  int32_t totalSize = tscGetResRowLength(pQueryInfo->exprList);
  pRes->pRsp = realloc(pRes->pRsp, numOfRes * totalSize);
  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];
    SSqlRes *pRes1 = &pSql->pSubs[pIndex->tableIndex]->res;
    SSqlCmd *pCmd1 = &pSql->pSubs[pIndex->tableIndex]->cmd;

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

    data += bytes * numOfRes;
    pRes1->row = numOfRes;
  }

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

H
hjxilinx 已提交
2035
void tscBuildResFromSubqueries(SSqlObj *pSql) {
H
Haojun Liao 已提交
2036 2037
  SSqlRes* pRes = &pSql->res;

H
hjxilinx 已提交
2038 2039 2040 2041
  if (pRes->code != TSDB_CODE_SUCCESS) {
    tscQueueAsyncRes(pSql);
    return;
  }
H
Haojun Liao 已提交
2042 2043 2044 2045

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

H
hjxilinx 已提交
2046
    size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
H
Haojun Liao 已提交
2047 2048 2049 2050 2051 2052 2053 2054 2055 2056
    pRes->tsrow  = calloc(numOfExprs, POINTER_BYTES);
    pRes->buffer = calloc(numOfExprs, POINTER_BYTES);
    pRes->length = calloc(numOfExprs, sizeof(int32_t));

    tscRestoreSQLFuncForSTableQuery(pQueryInfo);
  }

  while (1) {
    if (pRes->row < pRes->numOfRows) {
      assert(0);
H
hjxilinx 已提交
2057
    }
H
Haojun Liao 已提交
2058 2059

    doBuildResFromSubqueries(pSql);
S
TD-1057  
Shengliang Guan 已提交
2060
    tsem_post(&pSql->rspSem);
H
Haojun Liao 已提交
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085

    return;

    // continue retrieve data from vnode
//    if (!tscHasRemainDataInSubqueryResultSet(pSql)) {
//      tscDebug("%p at least one subquery exhausted, free all other %d subqueries", pSql, pSql->numOfSubs - 1);
//      SSubqueryState* pState = NULL;
//
//      // free all sub sqlobj
//      for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
//        SSqlObj* pChildObj = pSql->pSubs[i];
//        if (pChildObj == NULL) {
//          continue;
//        }
//
//        SJoinSupporter* pSupporter = (SJoinSupporter*)pChildObj->param;
//        pState = pSupporter->pState;
//
//        tscDestroyJoinSupporter(pChildObj->param);
//        taos_free_result(pChildObj);
//      }
//
//      free(pState);
//
//      pRes->completed = true;  // set query completed
S
TD-1057  
Shengliang Guan 已提交
2086
//      tsem_post(&pSql->rspSem);
H
Haojun Liao 已提交
2087 2088 2089 2090 2091 2092
//      return;
//    }

    tscFetchDatablockFromSubquery(pSql);
    if (pRes->code != TSDB_CODE_SUCCESS) {
      return;
H
hjxilinx 已提交
2093 2094
    }
  }
H
Haojun Liao 已提交
2095

H
hjxilinx 已提交
2096
  if (pSql->res.code == TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2097
    (*pSql->fp)(pSql->param, pSql, pRes->numOfRows);
H
hjxilinx 已提交
2098 2099 2100 2101 2102 2103 2104 2105
  } else {
    tscQueueAsyncRes(pSql);
  }
}

static void transferNcharData(SSqlObj *pSql, int32_t columnIndex, TAOS_FIELD *pField) {
  SSqlRes *pRes = &pSql->res;
  
H
Haojun Liao 已提交
2106
  if (pRes->tsrow[columnIndex] != NULL && pField->type == TSDB_DATA_TYPE_NCHAR) {
H
hjxilinx 已提交
2107 2108 2109 2110 2111 2112 2113 2114
    // 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);
    
2115 2116
    int32_t length = taosUcs4ToMbs(pRes->tsrow[columnIndex], pRes->length[columnIndex], pRes->buffer[columnIndex]);
    if ( length >= 0 ) {
H
hjxilinx 已提交
2117
      pRes->tsrow[columnIndex] = pRes->buffer[columnIndex];
2118
      pRes->length[columnIndex] = length;
H
hjxilinx 已提交
2119
    } else {
B
Bomin Zhang 已提交
2120
      tscError("%p charset:%s to %s. val:%s convert failed.", pSql, DEFAULT_UNICODE_ENCODEC, tsCharset, (char*)pRes->tsrow[columnIndex]);
H
hjxilinx 已提交
2121
      pRes->tsrow[columnIndex] = NULL;
2122
      pRes->length[columnIndex] = 0;
H
hjxilinx 已提交
2123 2124 2125 2126
    }
  }
}

2127 2128 2129 2130 2131 2132 2133 2134
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 已提交
2135
    if (strncmp(name, pExpr->aliasName, sizeof(pExpr->aliasName) - 1) == 0) {
2136 2137 2138 2139 2140 2141 2142 2143 2144
      index = i;
      break;
    }
  }

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

H
hjxilinx 已提交
2145 2146 2147
void **doSetResultRowData(SSqlObj *pSql, bool finalResult) {
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
H
Haojun Liao 已提交
2148

H
hjxilinx 已提交
2149
  assert(pRes->row >= 0 && pRes->row <= pRes->numOfRows);
H
Haojun Liao 已提交
2150

H
hjxilinx 已提交
2151
  if (pRes->row >= pRes->numOfRows) {  // all the results has returned to invoker
S
Shengliang Guan 已提交
2152
    taosTFree(pRes->tsrow);
H
hjxilinx 已提交
2153 2154
    return pRes->tsrow;
  }
H
Haojun Liao 已提交
2155

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

H
Haojun Liao 已提交
2158 2159
  size_t size = tscNumOfFields(pQueryInfo);
  for (int i = 0; i < size; ++i) {
H
Haojun Liao 已提交
2160
    SFieldSupInfo* pSup = TARRAY_GET_ELEM(pQueryInfo->fieldsInfo.pSupportInfo, i);
H
hjxilinx 已提交
2161
    if (pSup->pSqlExpr != NULL) {
2162
      tscGetResultColumnChr(pRes, &pQueryInfo->fieldsInfo, i);
H
hjxilinx 已提交
2163
    }
H
Haojun Liao 已提交
2164

H
hjxilinx 已提交
2165 2166 2167 2168
    // primary key column cannot be null in interval query, no need to check
    if (i == 0 && pQueryInfo->intervalTime > 0) {
      continue;
    }
H
Haojun Liao 已提交
2169 2170 2171 2172 2173 2174

    TAOS_FIELD *pField = TARRAY_GET_ELEM(pQueryInfo->fieldsInfo.pFields, i);
    if (pRes->tsrow[i] != NULL && pField->type == TSDB_DATA_TYPE_NCHAR) {
      transferNcharData(pSql, i, pField);
    }

H
hjxilinx 已提交
2175 2176
    // calculate the result from several other columns
    if (pSup->pArithExprInfo != NULL) {
2177 2178 2179 2180
      if (pRes->pArithSup == NULL) {
        SArithmeticSupport *sas = (SArithmeticSupport *) calloc(1, sizeof(SArithmeticSupport));
        sas->offset     = 0;
        sas->pArithExpr = pSup->pArithExprInfo;
S
Shengliang Guan 已提交
2181
        sas->numOfCols  = (int32_t)tscSqlExprNumOfExprs(pQueryInfo);
2182 2183
        sas->exprList   = pQueryInfo->exprList;
        sas->data       = calloc(sas->numOfCols, POINTER_BYTES);
H
Haojun Liao 已提交
2184

2185 2186
        pRes->pArithSup = sas;
      }
H
Haojun Liao 已提交
2187

2188 2189 2190 2191 2192 2193 2194 2195 2196
      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 已提交
2197

2198 2199 2200
      tExprTreeCalcTraverse(pRes->pArithSup->pArithExpr->pExpr, 1, pRes->buffer[i], pRes->pArithSup,
          TSDB_ORDER_ASC, getArithemicInputSrc);
      pRes->tsrow[i] = pRes->buffer[i];
H
hjxilinx 已提交
2201 2202
    }
  }
H
Haojun Liao 已提交
2203

H
hjxilinx 已提交
2204 2205 2206 2207
  pRes->row++;  // index increase one-step
  return pRes->tsrow;
}

H
Haojun Liao 已提交
2208
static UNUSED_FUNC bool tscHasRemainDataInSubqueryResultSet(SSqlObj *pSql) {
H
hjxilinx 已提交
2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
  bool     hasData = true;
  SSqlCmd *pCmd = &pSql->cmd;
  
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0)) {
    bool allSubqueryExhausted = true;
    
    for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
      if (pSql->pSubs[i] == NULL) {
        continue;
      }
      
      SSqlRes *pRes1 = &pSql->pSubs[i]->res;
      SSqlCmd *pCmd1 = &pSql->pSubs[i]->cmd;
      
      SQueryInfo *pQueryInfo1 = tscGetQueryInfoDetail(pCmd1, pCmd1->clauseIndex);
      assert(pQueryInfo1->numOfTables == 1);
      
      STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo1, 0);
      
      /*
       * if the global limitation is not reached, and current result has not exhausted, or next more vnodes are
       * available, goes on
       */
      if (pTableMetaInfo->vgroupIndex < pTableMetaInfo->vgroupList->numOfVgroups && pRes1->row < pRes1->numOfRows &&
          (!tscHasReachLimitation(pQueryInfo1, pRes1))) {
        allSubqueryExhausted = false;
        break;
      }
    }
    
    hasData = !allSubqueryExhausted;
  } else {  // otherwise, in case inner join, if any subquery exhausted, query completed.
    for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
      if (pSql->pSubs[i] == 0) {
        continue;
      }
      
      SSqlRes *   pRes1 = &pSql->pSubs[i]->res;
      SQueryInfo *pQueryInfo1 = tscGetQueryInfoDetail(&pSql->pSubs[i]->cmd, 0);
      
      if ((pRes1->row >= pRes1->numOfRows && tscHasReachLimitation(pQueryInfo1, pRes1) &&
H
Haojun Liao 已提交
2251
          tscIsProjectionQuery(pQueryInfo1)) || (pRes1->numOfRows == 0)) {
H
hjxilinx 已提交
2252 2253 2254 2255 2256 2257 2258 2259
        hasData = false;
        break;
      }
    }
  }
  
  return hasData;
}