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 186 187 188
  assert (pSupporter->uid != 0);

  getTmpfilePath("join-", pSupporter->path);
  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
  }

H
Haojun Liao 已提交
218
  tfree(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 410 411 412 413
    }
  }

  tfree(pState);
  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 644 645
    memcpy(pSupporter->pIdTagList + pSupporter->totalLen, pRes->data, validLen);
    pSupporter->totalLen += validLen;
    pSupporter->num += 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 776 777 778
    // continue to retrieve ts-comp data from vnode
    if (!pRes->completed) {
      getTmpfilePath("ts-join", pSupporter->path);
      pSupporter->f = fopen(pSupporter->path, "w");
      pRes->row = 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 800 801 802 803 804
    assert(pSupporter->f == NULL);
    getTmpfilePath("ts-join", pSupporter->path);
    
    // TODO check for failure
    pSupporter->f = fopen(pSupporter->path, "w");
    pRes->row = 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 1029
  }

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

H
Haojun Liao 已提交
1030 1031 1032 1033
  int32_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
  pRes->pColumnIndex = calloc(1, sizeof(SColumnIndex) * numOfExprs);

  for (int32_t i = 0; i < numOfExprs; ++i) {
H
hjxilinx 已提交
1034 1035 1036 1037 1038
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);

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

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

  // restore the offset value for super table query in case of final result.
  tscRestoreSQLFuncForSTableQuery(pQueryInfo);
  tscFieldInfoUpdateOffset(pQueryInfo);
H
hjxilinx 已提交
1063 1064 1065 1066
}

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

1068
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
1069 1070
  SSqlObj* pParentSql = pSupporter->pObj;

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

H
Haojun Liao 已提交
1075 1076 1077 1078 1079
  // 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 已提交
1080

H
Haojun Liao 已提交
1081 1082
    return;
  }
H
hjxilinx 已提交
1083

H
Haojun Liao 已提交
1084 1085 1086
  // TODO here retry is required, not directly returns to client
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(taos_errno(pSql) == code);
H
hjxilinx 已提交
1087

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

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

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

1146
int32_t tscLaunchJoinSubquery(SSqlObj *pSql, int16_t tableIndex, SJoinSupporter *pSupporter) {
H
hjxilinx 已提交
1147 1148 1149 1150
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  
  pSql->res.qhandle = 0x1;
H
Haojun Liao 已提交
1151 1152
  assert(pSql->res.numOfRows == 0);

H
hjxilinx 已提交
1153 1154 1155
  if (pSql->pSubs == NULL) {
    pSql->pSubs = calloc(pSupporter->pState->numOfTotal, POINTER_BYTES);
    if (pSql->pSubs == NULL) {
1156
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1157 1158 1159
    }
  }
  
1160
  SSqlObj *pNew = createSubqueryObj(pSql, tableIndex, tscJoinQueryCallback, pSupporter, TSDB_SQL_SELECT, NULL);
H
hjxilinx 已提交
1161
  if (pNew == NULL) {
1162
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
  }
  
  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);
    
1175 1176 1177 1178 1179 1180 1181
    // 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 已提交
1182 1183 1184 1185 1186 1187 1188
    pSupporter->colList = pNewQueryInfo->colList;
    pNewQueryInfo->colList = NULL;
    
    pSupporter->exprList = pNewQueryInfo->exprList;
    pNewQueryInfo->exprList = NULL;
    
    pSupporter->fieldsInfo = pNewQueryInfo->fieldsInfo;
H
hjxilinx 已提交
1189
  
H
hjxilinx 已提交
1190 1191
    // this data needs to be transfer to support struct
    memset(&pNewQueryInfo->fieldsInfo, 0, sizeof(SFieldInfo));
H
Haojun Liao 已提交
1192 1193
    tscTagCondCopy(&pSupporter->tagCond, &pNewQueryInfo->tagCond);//pNewQueryInfo->tagCond;

H
hjxilinx 已提交
1194 1195
    pNew->cmd.numOfCols = 0;
    pNewQueryInfo->intervalTime = 0;
H
Haojun Liao 已提交
1196 1197 1198 1199 1200
    pSupporter->limit = pNewQueryInfo->limit;

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

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

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

1214
      int32_t tagColId = tscGetJoinTagColIdByUid(pTagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
1215
      SSchema* s = tscGetTableColumnSchemaById(pTableMetaInfo->pTableMeta, tagColId);
H
Haojun Liao 已提交
1216 1217

      int16_t bytes = 0;
H
Haojun Liao 已提交
1218
      int16_t type  = 0;
H
Haojun Liao 已提交
1219 1220
      int32_t inter = 0;

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

H
Haojun Liao 已提交
1223 1224
      SSchema s1 = {.colId = s->colId, .type = type, .bytes = bytes};
      pSupporter->tagSize = s1.bytes;
1225
      assert(isValidDataType(s1.type) && s1.bytes > 0);
H
Haojun Liao 已提交
1226

1227 1228
      // set get tags query type
      TSDB_QUERY_SET_TYPE(pNewQueryInfo->type, TSDB_QUERY_TYPE_TAG_FILTER_QUERY);
H
Haojun Liao 已提交
1229
      tscAddSpecialColumnForSelect(pNewQueryInfo, 0, TSDB_FUNC_TID_TAG, &index, &s1, TSDB_COL_TAG);
1230
      size_t numOfCols = taosArrayGetSize(pNewQueryInfo->colList);
1231
  
1232
      tscDebug(
1233
          "%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%d, transfer to tid_tag query to retrieve (tableId, tags), "
B
Bomin Zhang 已提交
1234
          "exprInfo:%zu, colList:%zu, fieldsInfo:%d, tagIndex:%d, name:%s",
1235
          pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
H
Haojun Liao 已提交
1236
          numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, index.columnIndex, pNewQueryInfo->pTableMetaInfo[0]->name);
1237 1238 1239 1240 1241 1242 1243 1244
    } 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 已提交
1245
      if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
1246
        int16_t tagColId = tscGetJoinTagColIdByUid(&pSupporter->tagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
1247 1248 1249
        pExpr->param->i64Key = tagColId;
        pExpr->numOfParams = 1;
      }
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266

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

1267
      tscDebug(
B
Bomin Zhang 已提交
1268
          "%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%u, transfer to ts_comp query to retrieve timestamps, "
B
Bomin Zhang 已提交
1269
          "exprInfo:%zu, colList:%zu, fieldsInfo:%d, name:%s",
1270 1271 1272
          pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
          numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, pNewQueryInfo->pTableMetaInfo[0]->name);
    }
H
hjxilinx 已提交
1273
  } else {
H
hjxilinx 已提交
1274
    assert(0);
H
hjxilinx 已提交
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
    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 已提交
1289 1290
  pState->numOfRemain = pState->numOfTotal;

1291
  tscDebug("%p start subquery, total:%d", pSql, pQueryInfo->numOfTables);
H
hjxilinx 已提交
1292
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
1293
    SJoinSupporter *pSupporter = tscCreateJoinSupporter(pSql, pState, i);
H
hjxilinx 已提交
1294 1295 1296
    
    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 已提交
1297
      pState->numOfRemain = i;
1298
      pSql->res.code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1299 1300 1301 1302 1303 1304 1305
      
      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);
1306
      pSql->res.code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1307 1308 1309 1310
      
      break;
    }
  }
H
Haojun Liao 已提交
1311

1312
  pSql->cmd.command = (pSql->numOfSubs <= 0)? TSDB_SQL_RETRIEVE_EMPTY_RESULT:TSDB_SQL_TABLE_JOIN_RETRIEVE;
H
hjxilinx 已提交
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
  
  return TSDB_CODE_SUCCESS;
}

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

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

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

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

static void tscFreeSubSqlObj(SRetrieveSupport *trsupport, SSqlObj *pSql) {
1455
  tscDebug("%p start to free subquery result", pSql);
H
hjxilinx 已提交
1456
  
B
Bomin Zhang 已提交
1457
  taos_free_result(pSql);
H
hjxilinx 已提交
1458 1459 1460 1461 1462 1463 1464 1465 1466
  
  tfree(trsupport->localBuffer);
  
  pthread_mutex_unlock(&trsupport->queryMutex);
  pthread_mutex_destroy(&trsupport->queryMutex);
  
  tfree(trsupport);
}

1467
static void tscRetrieveFromDnodeCallBack(void *param, TAOS_RES *tres, int numOfRows);
1468
static void tscHandleSubqueryError(SRetrieveSupport *trsupport, SSqlObj *pSql, int numOfRows);
H
hjxilinx 已提交
1469

H
Haojun Liao 已提交
1470
static void tscAbortFurtherRetryRetrieval(SRetrieveSupport *trsupport, TAOS_RES *tres, int32_t code) {
H
hjxilinx 已提交
1471 1472 1473 1474 1475 1476 1477 1478 1479
// 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
1480
  tscError("sub:%p failed to flush data to disk, reason:%s", tres, tstrerror(code));
H
hjxilinx 已提交
1481
#endif
H
Haojun Liao 已提交
1482

H
Haojun Liao 已提交
1483
  SSqlObj* pParentSql = trsupport->pParentSql;
H
Haojun Liao 已提交
1484 1485

  pParentSql->res.code = code;
H
hjxilinx 已提交
1486 1487 1488
  trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
  
  pthread_mutex_unlock(&trsupport->queryMutex);
H
Haojun Liao 已提交
1489
  tscHandleSubqueryError(trsupport, tres, pParentSql->res.code);
H
hjxilinx 已提交
1490 1491
}

H
Haojun Liao 已提交
1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
/*
 * 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) {
1515 1516
    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 已提交
1517

1518
    pParentSql->res.code = terrno;
H
Haojun Liao 已提交
1519 1520 1521 1522 1523 1524 1525 1526 1527
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;

    return pParentSql->res.code;
  }

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

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

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

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

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

H
hjxilinx 已提交
1570 1571 1572 1573
    return tscFreeSubSqlObj(trsupport, pSql);
  }
  
  // all subqueries are failed
H
Haojun Liao 已提交
1574 1575 1576
  tscError("%p retrieve from %d vnode(s) completed,code:%s.FAILED.", pParentSql, pState->numOfTotal,
      tstrerror(pParentSql->res.code));

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

1596 1597
static void tscAllDataRetrievedFromDnode(SRetrieveSupport *trsupport, SSqlObj* pSql) {
  int32_t           idx = trsupport->subqueryIndex;
H
Haojun Liao 已提交
1598
  SSqlObj *         pParentSql = trsupport->pParentSql;
1599 1600 1601 1602 1603
  tOrderDescriptor *pDesc = trsupport->pOrderDescriptor;
  
  SSubqueryState* pState = trsupport->pState;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
  
1604 1605
  STableMetaInfo* pTableMetaInfo = pQueryInfo->pTableMetaInfo[0];
  
1606
  // data in from current vnode is stored in cache and disk
1607
  uint32_t numOfRowsFromSubquery = trsupport->pExtMemBuffer[idx]->numOfTotalElems + trsupport->localBuffer->num;
1608 1609
    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,
1610
        numOfRowsFromSubquery, idx);
1611 1612 1613 1614
  
  tColModelCompact(pDesc->pColumnModel, trsupport->localBuffer, pDesc->pColumnModel->capacity);

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

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

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

H
hjxilinx 已提交
1678 1679
  SSqlObj *pSql = (SSqlObj *)tres;
  if (pSql == NULL) {  // sql object has been released in error process, return immediately
H
Haojun Liao 已提交
1680
    tscDebug("%p subquery has been released, idx:%d, abort", pParentSql, idx);
H
hjxilinx 已提交
1681 1682 1683 1684
    return;
  }
  
  SSubqueryState* pState = trsupport->pState;
H
Haojun Liao 已提交
1685
  assert(pState->numOfRemain <= pState->numOfTotal && pState->numOfRemain >= 0 && pParentSql->numOfSubs == pState->numOfTotal);
H
hjxilinx 已提交
1686 1687 1688
  
  // query process and cancel query process may execute at the same time
  pthread_mutex_lock(&trsupport->queryMutex);
H
Haojun Liao 已提交
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 1716 1717

  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 已提交
1718 1719 1720 1721 1722 1723 1724 1725 1726
  }
  
  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);
    
1727 1728
    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);
1729

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

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

    tscGetSrcColumnInfo(colInfo, pQueryInfo);
    tColModelDisplayEx(pDesc->pColumnModel, pRes->data, pRes->numOfRows, pRes->numOfRows, colInfo);
#endif
1743
    
H
Haojun Liao 已提交
1744 1745 1746 1747 1748
    // 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);
      return tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_NO_DISKSPACE);
H
hjxilinx 已提交
1749 1750 1751 1752
    }
    
    int32_t ret = saveToBuffer(trsupport->pExtMemBuffer[idx], pDesc, trsupport->localBuffer, pRes->data,
                               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);
dengyihao's avatar
dengyihao 已提交
1864
  tfree(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
H
Haojun Liao 已提交
1873
  tfree(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
1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
  int32_t v = (pParentObj->res.code != TSDB_CODE_SUCCESS)? pParentObj->res.code:pParentObj->res.numOfRows;
  (*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 1916 1917
  size_t size = taosArrayGetSize(pCmd->pDataBlocks);
  assert(size > 0);

  pSql->pSubs = calloc(size, POINTER_BYTES);
  pSql->numOfSubs = size;

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) {
H
Haojun Liao 已提交
1977 1978 1979 1980
    tfree(pSql->pSubs[j]->param);
    taos_free_result(pSql->pSubs[j]);
  }

H
Haojun Liao 已提交
1981
  tfree(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 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034
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;
    }

    numOfRes = MIN(numOfRes, pSql->pSubs[i]->res.numOfRows);
  }

  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
    pRes->tsrow  = calloc(numOfExprs, POINTER_BYTES);
    pRes->buffer = calloc(numOfExprs, POINTER_BYTES);
    pRes->length = calloc(numOfExprs, sizeof(int32_t));

    tscRestoreSQLFuncForSTableQuery(pQueryInfo);
  }

  while (1) {
H
Haojun Liao 已提交
2055
    assert (pRes->row >= pRes->numOfRows);
H
Haojun Liao 已提交
2056 2057 2058 2059 2060 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 2086 2087 2088 2089 2090

    doBuildResFromSubqueries(pSql);
    sem_post(&pSql->rspSem);

    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
//      sem_post(&pSql->rspSem);
//      return;
//    }

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

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

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

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

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

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

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

H
hjxilinx 已提交
2149 2150 2151 2152
  if (pRes->row >= pRes->numOfRows) {  // all the results has returned to invoker
    tfree(pRes->tsrow);
    return pRes->tsrow;
  }
H
Haojun Liao 已提交
2153

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

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

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

    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 已提交
2173 2174
    // calculate the result from several other columns
    if (pSup->pArithExprInfo != NULL) {
2175 2176 2177 2178 2179 2180 2181
      if (pRes->pArithSup == NULL) {
        SArithmeticSupport *sas = (SArithmeticSupport *) calloc(1, sizeof(SArithmeticSupport));
        sas->offset     = 0;
        sas->pArithExpr = pSup->pArithExprInfo;
        sas->numOfCols  = tscSqlExprNumOfExprs(pQueryInfo);
        sas->exprList   = pQueryInfo->exprList;
        sas->data       = calloc(sas->numOfCols, POINTER_BYTES);
H
Haojun Liao 已提交
2182

2183 2184
        pRes->pArithSup = sas;
      }
H
Haojun Liao 已提交
2185

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

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

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

H
Haojun Liao 已提交
2206
static UNUSED_FUNC bool tscHasRemainDataInSubqueryResultSet(SSqlObj *pSql) {
H
hjxilinx 已提交
2207 2208 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
  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 已提交
2249
          tscIsProjectionQuery(pQueryInfo1)) || (pRes1->numOfRows == 0)) {
H
hjxilinx 已提交
2250 2251 2252 2253 2254 2255 2256 2257
        hasData = false;
        break;
      }
    }
  }
  
  return hasData;
}