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

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

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

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

H
Haojun Liao 已提交
35 36 37 38 39
static int32_t tsCompare(int32_t order, int64_t left, int64_t right) {
  if (left == right) {
    return 0;
  }

40
  if (order == TSDB_ORDER_ASC) {
H
Haojun Liao 已提交
41
    return left < right? -1:1;
H
hjxilinx 已提交
42
  } else {
H
Haojun Liao 已提交
43
    return left > right? -1:1;
H
hjxilinx 已提交
44 45 46
  }
}

47 48 49 50 51 52 53 54 55 56 57
static void skipRemainValue(STSBuf* pTSBuf, tVariant* tag1) {
  while (tsBufNextPos(pTSBuf)) {
    STSElem el1 = tsBufGetElem(pTSBuf);

    int32_t res = tVariantCompare(el1.tag, tag1);
    if (res != 0) { // it is a record with new tag
      return;
    }
  }
}

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

H
Haojun Liao 已提交
61 62 63 64 65
  STSBuf* output1 = tsBufCreate(true, pQueryInfo->order.order);
  STSBuf* output2 = tsBufCreate(true, pQueryInfo->order.order);

  win->skey = INT64_MAX;
  win->ekey = INT64_MIN;
H
hjxilinx 已提交
66 67 68

  SLimitVal* pLimit = &pQueryInfo->limit;
  int32_t    order = pQueryInfo->order.order;
H
Haojun Liao 已提交
69

H
hjxilinx 已提交
70 71
  SQueryInfo* pSubQueryInfo1 = tscGetQueryInfoDetail(&pSql->pSubs[0]->cmd, 0);
  SQueryInfo* pSubQueryInfo2 = tscGetQueryInfoDetail(&pSql->pSubs[1]->cmd, 0);
H
Haojun Liao 已提交
72

H
hjxilinx 已提交
73 74 75
  pSubQueryInfo1->tsBuf = output1;
  pSubQueryInfo2->tsBuf = output2;

H
Haojun Liao 已提交
76 77
  TSKEY st = taosGetTimestampUs();

78 79 80 81 82 83
  // 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 已提交
84 85 86 87 88 89 90
  tsBufResetPos(pSupporter1->pTSBuf);
  tsBufResetPos(pSupporter2->pTSBuf);

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

91
    tscDebug("%p input1 is empty, 0 for secondary query after ts blocks intersecting", pSql);
H
hjxilinx 已提交
92 93 94 95 96 97 98
    return 0;
  }

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

99
    tscDebug("%p input2 is empty, 0 for secondary query after ts blocks intersecting", pSql);
H
hjxilinx 已提交
100 101 102 103 104 105
    return 0;
  }

  int64_t numOfInput1 = 1;
  int64_t numOfInput2 = 1;

H
Haojun Liao 已提交
106 107
  while(1) {
    STSElem elem = tsBufGetElem(pSupporter1->pTSBuf);
H
hjxilinx 已提交
108

H
Haojun Liao 已提交
109
    // no data in pSupporter1 anymore, jump out of loop
110
    if (!tsBufIsValidElem(&elem)) {
H
Haojun Liao 已提交
111 112
      break;
    }
H
hjxilinx 已提交
113

114 115
    // find the data in supporter2 with the same tag value
    STSElem e2 = tsBufFindElemStartPosByTag(pSupporter2->pTSBuf, elem.tag);
H
hjxilinx 已提交
116

H
Haojun Liao 已提交
117 118 119
    /**
     * there are elements in pSupporter2 with the same tag, continue
     */
120 121 122 123
    tVariant tag1 = {0};
    tVariantAssign(&tag1, elem.tag);

    if (tsBufIsValidElem(&e2)) {
H
Haojun Liao 已提交
124 125 126 127
      while (1) {
        STSElem elem1 = tsBufGetElem(pSupporter1->pTSBuf);
        STSElem elem2 = tsBufGetElem(pSupporter2->pTSBuf);

128 129 130 131 132 133 134 135 136 137
        // data with current are exhausted
        if (!tsBufIsValidElem(&elem1) || tVariantCompare(elem1.tag, &tag1) != 0) {
          break;
        }

        if (!tsBufIsValidElem(&elem2) || tVariantCompare(elem2.tag, &tag1) != 0) { // ignore all records with the same tag
          skipRemainValue(pSupporter1->pTSBuf, &tag1);
          break;
        }

H
Haojun Liao 已提交
138 139
        /*
         * in case of stable query, limit/offset is not applied here. the limit/offset is applied to the
140
         * final results which is acquired after the secondary merge of in the client.
H
Haojun Liao 已提交
141 142 143
         */
        int32_t re = tsCompare(order, elem1.ts, elem2.ts);
        if (re < 0) {
144
          tsBufNextPos(pSupporter1->pTSBuf);
H
Haojun Liao 已提交
145 146
          numOfInput1++;
        } else if (re > 0) {
147
          tsBufNextPos(pSupporter2->pTSBuf);
H
Haojun Liao 已提交
148 149 150 151 152 153 154 155 156 157 158
          numOfInput2++;
        } else {
          if (pLimit->offset == 0 || pQueryInfo->interval.interval > 0 || QUERY_IS_STABLE_QUERY(pQueryInfo->type)) {
            if (win->skey > elem1.ts) {
              win->skey = elem1.ts;
            }

            if (win->ekey < elem1.ts) {
              win->ekey = elem1.ts;
            }

H
Haojun Liao 已提交
159 160
            tsBufAppend(output1, elem1.id, elem1.tag, (const char*)&elem1.ts, sizeof(elem1.ts));
            tsBufAppend(output2, elem2.id, elem2.tag, (const char*)&elem2.ts, sizeof(elem2.ts));
H
Haojun Liao 已提交
161
          } else {
162
            pLimit->offset -= 1;//offset apply to projection?
H
Haojun Liao 已提交
163 164
          }

165
          tsBufNextPos(pSupporter1->pTSBuf);
H
Haojun Liao 已提交
166 167
          numOfInput1++;

168
          tsBufNextPos(pSupporter2->pTSBuf);
H
Haojun Liao 已提交
169 170
          numOfInput2++;
        }
H
hjxilinx 已提交
171
      }
H
Haojun Liao 已提交
172
    } else {  // no data in pSupporter2, ignore current data in pSupporter2
173
      skipRemainValue(pSupporter1->pTSBuf, &tag1);
H
hjxilinx 已提交
174 175 176 177 178 179 180 181 182
    }
  }

  /*
   * 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) {
183 184
    output1->tsOrder = TSDB_ORDER_ASC;
    output2->tsOrder = TSDB_ORDER_ASC;
H
hjxilinx 已提交
185 186 187 188 189
  }

  tsBufFlush(output1);
  tsBufFlush(output2);

H
Haojun Liao 已提交
190 191
  tsBufDestroy(pSupporter1->pTSBuf);
  tsBufDestroy(pSupporter2->pTSBuf);
H
hjxilinx 已提交
192

H
Haojun Liao 已提交
193
  TSKEY et = taosGetTimestampUs();
H
Haojun Liao 已提交
194
  tscDebug("%p input1:%" PRId64 ", input2:%" PRId64 ", final:%" PRId64 " in %d vnodes for secondary query after ts blocks "
H
Haojun Liao 已提交
195
           "intersecting, skey:%" PRId64 ", ekey:%" PRId64 ", numOfVnode:%d, elapsed time:%" PRId64 " us",
H
Haojun Liao 已提交
196 197
           pSql, numOfInput1, numOfInput2, output1->numOfTotal, output1->numOfGroups, win->skey, win->ekey,
           tsBufGetNumOfGroup(output1), et - st);
H
hjxilinx 已提交
198 199 200 201 202

  return output1->numOfTotal;
}

// todo handle failed to create sub query
H
Haojun Liao 已提交
203
SJoinSupporter* tscCreateJoinSupporter(SSqlObj* pSql, int32_t index) {
204
  SJoinSupporter* pSupporter = calloc(1, sizeof(SJoinSupporter));
H
hjxilinx 已提交
205 206 207 208 209 210 211 212 213
  if (pSupporter == NULL) {
    return NULL;
  }

  pSupporter->pObj = pSql;

  pSupporter->subqueryIndex = index;
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, pSql->cmd.clauseIndex);
  
214
  memcpy(&pSupporter->interval, &pQueryInfo->interval, sizeof(pSupporter->interval));
H
hjxilinx 已提交
215 216 217
  pSupporter->limit = pQueryInfo->limit;

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

S
slguan 已提交
221
  taosGetTmpfilePath("join-", pSupporter->path);
H
hjxilinx 已提交
222 223
  pSupporter->f = fopen(pSupporter->path, "w");

H
Haojun Liao 已提交
224
  // todo handle error
H
hjxilinx 已提交
225 226 227 228 229 230 231
  if (pSupporter->f == NULL) {
    tscError("%p failed to create tmp file:%s, reason:%s", pSql, pSupporter->path, strerror(errno));
  }

  return pSupporter;
}

H
Haojun Liao 已提交
232
static void tscDestroyJoinSupporter(SJoinSupporter* pSupporter) {
H
hjxilinx 已提交
233 234 235 236
  if (pSupporter == NULL) {
    return;
  }

H
hjxilinx 已提交
237 238 239 240 241 242 243
  if (pSupporter->exprList != NULL) {
    tscSqlExprInfoDestroy(pSupporter->exprList);
  }
  
  if (pSupporter->colList != NULL) {
    tscColumnListDestroy(pSupporter->colList);
  }
H
hjxilinx 已提交
244

H
hjxilinx 已提交
245
  tscFieldInfoClear(&pSupporter->fieldsInfo);
H
hjxilinx 已提交
246 247 248 249

  if (pSupporter->f != NULL) {
    fclose(pSupporter->f);
    unlink(pSupporter->path);
H
hjxilinx 已提交
250
    pSupporter->f = NULL;
H
hjxilinx 已提交
251 252
  }

253 254 255 256 257
  if (pSupporter->pVgroupTables != NULL) {
    taosArrayDestroy(pSupporter->pVgroupTables);
    pSupporter->pVgroupTables = NULL;
  }

S
Shengliang Guan 已提交
258
  taosTFree(pSupporter->pIdTagList);
H
hjxilinx 已提交
259 260 261 262 263 264 265 266 267 268
  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 已提交
269
static UNUSED_FUNC bool needSecondaryQuery(SQueryInfo* pQueryInfo) {
270 271 272
  size_t numOfCols = taosArrayGetSize(pQueryInfo->colList);
  
  for (int32_t i = 0; i < numOfCols; ++i) {
273 274
    SColumn* base = taosArrayGet(pQueryInfo->colList, i);
    if (base->colIndex.columnIndex != PRIMARYKEY_TIMESTAMP_COL_INDEX) {
H
hjxilinx 已提交
275 276 277 278 279 280 281
      return true;
    }
  }

  return false;
}

282 283 284
static void filterVgroupTables(SQueryInfo* pQueryInfo, SArray* pVgroupTables) {
  int32_t  num = 0;
  int32_t* list = NULL;
H
Haojun Liao 已提交
285
  tsBufGetGroupIdList(pQueryInfo->tsBuf, &num, &list);
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316

  // The virtual node, of which all tables are disqualified after the timestamp intersection,
  // is removed to avoid next stage query.
  // TODO: If tables from some vnodes are not qualified for next stage query, discard them.
  for (int32_t k = 0; k < taosArrayGetSize(pVgroupTables);) {
    SVgroupTableInfo* p = taosArrayGet(pVgroupTables, k);

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

    if (!found) {
      tscRemoveVgroupTableGroup(pVgroupTables, k);
    } else {
      k++;
    }
  }

  assert(taosArrayGetSize(pVgroupTables) > 0);
  TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_MULTITABLE_QUERY);

  taosTFree(list);
}

static SArray* buildVgroupTableByResult(SQueryInfo* pQueryInfo, SArray* pVgroupTables) {
  int32_t  num = 0;
  int32_t* list = NULL;
H
Haojun Liao 已提交
317
  tsBufGetGroupIdList(pQueryInfo->tsBuf, &num, &list);
318

S
Shengliang Guan 已提交
319
  size_t numOfGroups = taosArrayGetSize(pVgroupTables);
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343

  SArray* pNew = taosArrayInit(num, sizeof(SVgroupTableInfo));

  SVgroupTableInfo info;
  for (int32_t i = 0; i < num; ++i) {
    int32_t vnodeId = list[i];

    for (int32_t j = 0; j < numOfGroups; ++j) {
      SVgroupTableInfo* p1 = taosArrayGet(pVgroupTables, j);
      if (p1->vgInfo.vgId == vnodeId) {
        tscVgroupTableCopy(&info, p1);
        break;
      }
    }

    taosArrayPush(pNew, &info);
  }

  taosTFree(list);
  TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_MULTITABLE_QUERY);

  return pNew;
}

H
hjxilinx 已提交
344 345 346
/*
 * launch secondary stage query to fetch the result that contains timestamp in set
 */
H
Haojun Liao 已提交
347
static int32_t tscLaunchRealSubqueries(SSqlObj* pSql) {
H
hjxilinx 已提交
348
  int32_t         numOfSub = 0;
349
  SJoinSupporter* pSupporter = NULL;
H
hjxilinx 已提交
350
  
H
Haojun Liao 已提交
351
  //If the columns are not involved in the final select clause, the corresponding query will not be issued.
H
Haojun Liao 已提交
352
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
353
    pSupporter = pSql->pSubs[i]->param;
H
hjxilinx 已提交
354
    if (taosArrayGetSize(pSupporter->exprList) > 0) {
H
hjxilinx 已提交
355 356 357 358 359 360 361
      ++numOfSub;
    }
  }
  
  assert(numOfSub > 0);
  
  // scan all subquery, if one sub query has only ts, ignore it
H
Haojun Liao 已提交
362
  tscDebug("%p start to launch secondary subqueries, %d out of %d needs to query", pSql, numOfSub, pSql->subState.numOfSub);
H
hjxilinx 已提交
363

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

H
hjxilinx 已提交
368 369
  bool success = true;
  
H
Haojun Liao 已提交
370
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
371 372 373 374 375
    SSqlObj *pPrevSub = pSql->pSubs[i];
    pSql->pSubs[i] = NULL;
    
    pSupporter = pPrevSub->param;
  
H
hjxilinx 已提交
376
    if (taosArrayGetSize(pSupporter->exprList) == 0) {
377
      tscDebug("%p subIndex: %d, no need to launch query, ignore it", pSql, i);
H
hjxilinx 已提交
378 379
    
      tscDestroyJoinSupporter(pSupporter);
380
      taos_free_result(pPrevSub);
H
hjxilinx 已提交
381 382 383 384 385 386 387 388 389 390
    
      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 已提交
391
    assert(tscSqlExprNumOfExprs(pSubQueryInfo) == 1); // ts_comp query only requires one resutl columns
H
hjxilinx 已提交
392 393
    taos_free_result(pPrevSub);
  
394
    SSqlObj *pNew = createSubqueryObj(pSql, (int16_t) i, tscJoinQueryCallback, pSupporter, TSDB_SQL_SELECT, NULL);
H
hjxilinx 已提交
395 396 397 398 399
    if (pNew == NULL) {
      tscDestroyJoinSupporter(pSupporter);
      success = false;
      break;
    }
B
Bomin Zhang 已提交
400

H
hjxilinx 已提交
401 402 403 404 405
    tscClearSubqueryInfo(&pNew->cmd);
    pSql->pSubs[i] = pNew;
  
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    pQueryInfo->tsBuf = pTSBuf;  // transfer the ownership of timestamp comp-z data to the new created object
B
Bomin Zhang 已提交
406

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

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

H
hjxilinx 已提交
413 414 415
    pQueryInfo->colList = pSupporter->colList;
    pQueryInfo->exprList = pSupporter->exprList;
    pQueryInfo->fieldsInfo = pSupporter->fieldsInfo;
H
Haojun Liao 已提交
416
    pQueryInfo->groupbyExpr = pSupporter->groupInfo;
H
Haojun Liao 已提交
417

418
    assert(pNew->subState.numOfSub == 0 && pNew->cmd.numOfClause == 1 && pQueryInfo->numOfTables == 1);
H
hjxilinx 已提交
419
  
420
    tscFieldInfoUpdateOffset(pQueryInfo);
H
hjxilinx 已提交
421
  
422
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
Haojun Liao 已提交
423
    pTableMetaInfo->pVgroupTables = pSupporter->pVgroupTables;
H
Haojun Liao 已提交
424 425 426

    pSupporter->exprList = NULL;
    pSupporter->colList = NULL;
427
    pSupporter->pVgroupTables = NULL;
H
Haojun Liao 已提交
428 429
    memset(&pSupporter->fieldsInfo, 0, sizeof(SFieldInfo));
    memset(&pSupporter->groupInfo, 0, sizeof(SSqlGroupbyExpr));
H
Haojun Liao 已提交
430

H
hjxilinx 已提交
431 432 433 434 435
    /*
     * 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;
436
    pQueryInfo->limit = pSupporter->limit;
H
Haojun Liao 已提交
437 438 439 440 441

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

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

H
Haojun Liao 已提交
444
    if ((pExpr->colInfo.colId != PRIMARYKEY_TIMESTAMP_COL_INDEX) ||
H
Haojun Liao 已提交
445 446 447 448 449
        (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 已提交
450
      tscPrintSelectClause(pNew, 0);
451
      tscFieldInfoUpdateOffset(pQueryInfo);
H
Haojun Liao 已提交
452 453 454 455

      pExpr = tscSqlExprGet(pQueryInfo, 0);
    }

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

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

466 467 468 469 470 471 472 473
    if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
      assert(pTableMetaInfo->pVgroupTables != NULL);
      if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0)) {
        SArray* p = buildVgroupTableByResult(pQueryInfo, pTableMetaInfo->pVgroupTables);
        tscFreeVgroupTableInfo(pTableMetaInfo->pVgroupTables);
        pTableMetaInfo->pVgroupTables = p;
      } else {
        filterVgroupTables(pQueryInfo, pTableMetaInfo->pVgroupTables);
H
Haojun Liao 已提交
474 475 476
      }
    }

477
    size_t numOfCols = taosArrayGetSize(pQueryInfo->colList);
S
TD-1057  
Shengliang Guan 已提交
478
    tscDebug("%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%d, exprInfo:%" PRIzu ", colList:%" PRIzu ", fieldsInfo:%d, name:%s",
479 480
             pSql, pNew, 0, pTableMetaInfo->vgroupIndex, pQueryInfo->type, taosArrayGetSize(pQueryInfo->exprList),
             numOfCols, pQueryInfo->fieldsInfo.numOfOutput, pTableMetaInfo->name);
H
hjxilinx 已提交
481 482 483 484
  }
  
  //prepare the subqueries object failed, abort
  if (!success) {
485
    pSql->res.code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
486
    tscError("%p failed to prepare subqueries objs for secondary phase query, numOfSub:%d, code:%d", pSql,
H
Haojun Liao 已提交
487
        pSql->subState.numOfSub, pSql->res.code);
H
hjxilinx 已提交
488
    freeJoinSubqueryObj(pSql);
H
hjxilinx 已提交
489 490 491 492
    
    return pSql->res.code;
  }
  
H
Haojun Liao 已提交
493
  for(int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
Haojun Liao 已提交
494
    if (pSql->pSubs[i] == NULL) {
H
hjxilinx 已提交
495 496
      continue;
    }
H
Haojun Liao 已提交
497

H
Haojun Liao 已提交
498
    tscDoQuery(pSql->pSubs[i]);
H
hjxilinx 已提交
499 500 501 502 503
  }

  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
504
void freeJoinSubqueryObj(SSqlObj* pSql) {
H
Haojun Liao 已提交
505
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
506 507 508 509 510
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
      continue;
    }
    
511
    SJoinSupporter* p = pSub->param;
H
hjxilinx 已提交
512
    tscDestroyJoinSupporter(p);
H
hjxilinx 已提交
513

H
hjxilinx 已提交
514 515
    if (pSub->res.code == TSDB_CODE_SUCCESS) {
      taos_free_result(pSub);
H
hjxilinx 已提交
516 517 518
    }
  }

H
Haojun Liao 已提交
519
  pSql->subState.numOfSub = 0;
H
hjxilinx 已提交
520 521
}

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

H
Haojun Liao 已提交
525
  if (atomic_sub_fetch_32(&pSqlObj->subState.numOfRemain, 1) <= 0) {
526
    tscError("%p all subquery return and query failed, global code:%s", pSqlObj, tstrerror(pSqlObj->res.code));
H
hjxilinx 已提交
527
    freeJoinSubqueryObj(pSqlObj);
H
hjxilinx 已提交
528 529 530 531
  }
}

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


H
hjxilinx 已提交
537 538
}

H
Haojun Liao 已提交
539 540 541
int32_t tidTagsCompar(const void* p1, const void* p2) {
  const STidTags* t1 = (const STidTags*) (p1);
  const STidTags* t2 = (const STidTags*) (p2);
542 543
  
  if (t1->vgId != t2->vgId) {
weixin_48148422's avatar
weixin_48148422 已提交
544 545
    return (t1->vgId > t2->vgId) ? 1 : -1;
  }
546

H
Haojun Liao 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
  tstr* tag1 = (tstr*) t1->tag;
  tstr* tag2 = (tstr*) t2->tag;

  if (tag1->len != tag2->len) {
    return (tag1->len > tag2->len)? 1: -1;
  }

  return strncmp(tag1->data, tag2->data, tag1->len);
}

int32_t tagValCompar(const void* p1, const void* p2) {
  const STidTags* t1 = (const STidTags*) varDataVal(p1);
  const STidTags* t2 = (const STidTags*) varDataVal(p2);

  tstr* tag1 = (tstr*) t1->tag;
  tstr* tag2 = (tstr*) t2->tag;

  if (tag1->len != tag2->len) {
    return (tag1->len > tag2->len)? 1: -1;
566
  }
H
Haojun Liao 已提交
567

H
Haojun Liao 已提交
568
  return memcmp(tag1->data, tag2->data, tag1->len);
569 570
}

H
Haojun Liao 已提交
571
void tscBuildVgroupTableInfo(SSqlObj* pSql, STableMetaInfo* pTableMetaInfo, SArray* tables) {
H
Haojun Liao 已提交
572 573
  SArray*   result = taosArrayInit(4, sizeof(SVgroupTableInfo));
  SArray*   vgTables = NULL;
weixin_48148422's avatar
weixin_48148422 已提交
574 575
  STidTags* prev = NULL;

H
Haojun Liao 已提交
576 577 578
  size_t numOfTables = taosArrayGetSize(tables);
  for (size_t i = 0; i < numOfTables; i++) {
    STidTags* tt = taosArrayGet(tables, i);
weixin_48148422's avatar
weixin_48148422 已提交
579

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

H
Haojun Liao 已提交
583 584 585
      SVgroupTableInfo info = {{0}};
      for (int32_t m = 0; m < pvg->numOfVgroups; ++m) {
        if (tt->vgId == pvg->vgroups[m].vgId) {
S
TD-1732  
Shengliang Guan 已提交
586
          tscSVgroupInfoCopy(&info.vgInfo, &pvg->vgroups[m]);
587 588 589
          break;
        }
      }
590
      assert(info.vgInfo.numOfEps != 0);
weixin_48148422's avatar
weixin_48148422 已提交
591

H
Haojun Liao 已提交
592
      vgTables = taosArrayInit(4, sizeof(STableIdInfo));
weixin_48148422's avatar
weixin_48148422 已提交
593
      info.itemList = vgTables;
H
Haojun Liao 已提交
594 595 596 597 598 599

      if (taosArrayGetSize(result) > 0) {
        SVgroupTableInfo* prevGroup = taosArrayGet(result, taosArrayGetSize(result) - 1);
        tscDebug("%p vgId:%d, tables:%"PRId64, pSql, prevGroup->vgInfo.vgId, taosArrayGetSize(prevGroup->itemList));
      }

H
Haojun Liao 已提交
600
      taosArrayPush(result, &info);
601
    }
weixin_48148422's avatar
weixin_48148422 已提交
602

H
Haojun Liao 已提交
603 604
    STableIdInfo item = {.uid = tt->uid, .tid = tt->tid, .key = INT64_MIN};
    taosArrayPush(vgTables, &item);
H
Haojun Liao 已提交
605

H
Haojun Liao 已提交
606
    tscTrace("%p tid:%d, uid:%"PRIu64",vgId:%d added", pSql, tt->tid, tt->uid, tt->vgId);
weixin_48148422's avatar
weixin_48148422 已提交
607
    prev = tt;
608
  }
weixin_48148422's avatar
weixin_48148422 已提交
609 610

  pTableMetaInfo->pVgroupTables = result;
H
Haojun Liao 已提交
611
  pTableMetaInfo->vgroupIndex = 0;
H
Haojun Liao 已提交
612 613 614 615 616

  if (taosArrayGetSize(result) > 0) {
    SVgroupTableInfo* g = taosArrayGet(result, taosArrayGetSize(result) - 1);
    tscDebug("%p vgId:%d, tables:%"PRId64, pSql, g->vgInfo.vgId, taosArrayGetSize(g->itemList));
  }
617 618 619 620 621 622
}

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

624
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
Haojun Liao 已提交
625 626
  assert(pQueryInfo->numOfTables == 1);

627 628 629 630 631 632 633 634 635 636 637 638 639 640 641
  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 已提交
642 643
  if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
    SSqlExpr *pExpr = tscSqlExprGet(pQueryInfo, 0);
644
    int16_t tagColId = tscGetJoinTagColIdByUid(&pSupporter->tagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
645 646 647 648
    pExpr->param->i64Key = tagColId;
    pExpr->numOfParams = 1;
  }

649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664
  // 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);
  
665
  tscDebug(
H
Haojun Liao 已提交
666
      "%p subquery:%p tableIndex:%d, vgroupIndex:%d, numOfVgroups:%d, type:%d, ts_comp query to retrieve timestamps, "
S
TD-1057  
Shengliang Guan 已提交
667
      "numOfExpr:%" PRIzu ", colList:%" PRIzu ", numOfOutputFields:%d, name:%s",
H
Haojun Liao 已提交
668 669
      pParent, pSql, 0, pTableMetaInfo->vgroupIndex, pTableMetaInfo->vgroupList->numOfVgroups, pQueryInfo->type,
      tscSqlExprNumOfExprs(pQueryInfo), numOfCols, pQueryInfo->fieldsInfo.numOfOutput, pTableMetaInfo->name);
670 671 672 673
  
  tscProcessSql(pSql);
}

H
Haojun Liao 已提交
674
static bool checkForDuplicateTagVal(SSchema* pColSchema, SJoinSupporter* p1, SSqlObj* pPSqlObj) {
H
Haojun Liao 已提交
675 676 677
  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);
678
    assert(prev->vgId >= 1 && p->vgId >= 1);
H
Haojun Liao 已提交
679 680

    if (doCompare(prev->tag, p->tag, pColSchema->type, pColSchema->bytes) == 0) {
H
Haojun Liao 已提交
681 682
      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 已提交
683 684 685 686 687 688 689
      return false;
    }
  }

  return true;
}

690
static int32_t getIntersectionOfTableTuple(SQueryInfo* pQueryInfo, SSqlObj* pParentSql, SArray** s1, SArray** s2) {
H
Haojun Liao 已提交
691 692 693
  SJoinSupporter* p1 = pParentSql->pSubs[0]->param;
  SJoinSupporter* p2 = pParentSql->pSubs[1]->param;

H
Haojun Liao 已提交
694 695
  tscDebug("%p all subquery retrieve <tid, tags> complete, do tags match, %d, %d", pParentSql, p1->num, p2->num);

H
Haojun Liao 已提交
696 697 698
  // sort according to the tag value
  qsort(p1->pIdTagList, p1->num, p1->tagSize, tagValCompar);
  qsort(p2->pIdTagList, p2->num, p2->tagSize, tagValCompar);
H
Haojun Liao 已提交
699 700

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

H
Haojun Liao 已提交
703
  SSchema* pColSchema = tscGetColumnSchemaById(pTableMetaInfo->pTableMeta, tagColId);
H
Haojun Liao 已提交
704

H
Haojun Liao 已提交
705
  // int16_t for padding
H
Haojun Liao 已提交
706 707 708
  int32_t size = p1->tagSize - sizeof(int16_t);
  *s1 = taosArrayInit(p1->num, size);
  *s2 = taosArrayInit(p2->num, size);
H
Haojun Liao 已提交
709

H
Haojun Liao 已提交
710
  if (!(checkForDuplicateTagVal(pColSchema, p1, pParentSql) && checkForDuplicateTagVal(pColSchema, p2, pParentSql))) {
711
    return TSDB_CODE_QRY_DUP_JOIN_KEY;
H
Haojun Liao 已提交
712 713 714 715 716 717
  }

  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);
718
    assert(pp1->tid != 0 && pp2->tid != 0);
H
Haojun Liao 已提交
719 720 721

    int32_t ret = doCompare(pp1->tag, pp2->tag, pColSchema->type, pColSchema->bytes);
    if (ret == 0) {
722
      tscDebug("%p tag matched, vgId:%d, val:%d, tid:%d, uid:%"PRIu64", tid:%d, uid:%"PRIu64, pParentSql, pp1->vgId,
H
Haojun Liao 已提交
723 724 725 726 727 728 729 730 731 732 733 734
               *(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++;
    }
  }
735

H
Haojun Liao 已提交
736 737 738 739 740 741 742 743
  // reorganize the tid-tag value according to both the vgroup id and tag values
  // sort according to the tag value
  size_t t1 = taosArrayGetSize(*s1);
  size_t t2 = taosArrayGetSize(*s2);

  qsort((*s1)->pData, t1, size, tidTagsCompar);
  qsort((*s2)->pData, t2, size, tidTagsCompar);

H
Haojun Liao 已提交
744 745 746 747 748 749 750 751 752 753 754 755
#if 0
  for(int32_t k = 0; k < t1; ++k) {
    STidTags* p =  (*s1)->pData + size * k;
    printf("%d, tag:%s\n", p->vgId, ((tstr*)(p->tag))->data);
  }

  for(int32_t k = 0; k < t1; ++k) {
    STidTags* p =  (*s2)->pData + size * k;
    printf("%d, tag:%s\n", p->vgId, ((tstr*)(p->tag))->data);
  }
#endif

H
Haojun Liao 已提交
756
  tscDebug("%p tags match complete, result: %"PRId64", %"PRId64, pParentSql, t1, t2);
757
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
758 759
}

H
Haojun Liao 已提交
760
static void tidTagRetrieveCallback(void* param, TAOS_RES* tres, int32_t numOfRows) {
761
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
762

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

H
hjxilinx 已提交
765 766
  SSqlObj* pSql = (SSqlObj*)tres;
  SSqlCmd* pCmd = &pSql->cmd;
H
Haojun Liao 已提交
767 768 769
  SSqlRes* pRes = &pSql->res;

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

H
Haojun Liao 已提交
772 773 774
  // check for the error code firstly
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    // todo retry if other subqueries are not failed
H
Haojun Liao 已提交
775

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

H
Haojun Liao 已提交
779 780
    pParentSql->res.code = numOfRows;
    quitAllSubquery(pParentSql, pSupporter);
H
Haojun Liao 已提交
781

H
Haojun Liao 已提交
782 783 784
    tscQueueAsyncRes(pParentSql);
    return;
  }
H
Haojun Liao 已提交
785

H
Haojun Liao 已提交
786 787
  // keep the results in memory
  if (numOfRows > 0) {
788
    size_t validLen = (size_t)(pSupporter->tagSize * pRes->numOfRows);
H
Haojun Liao 已提交
789
    size_t length = pSupporter->totalLen + validLen;
H
Haojun Liao 已提交
790

H
Haojun Liao 已提交
791 792 793 794
    // todo handle memory error
    char* tmp = realloc(pSupporter->pIdTagList, length);
    if (tmp == NULL) {
      tscError("%p failed to malloc memory", pSql);
H
Haojun Liao 已提交
795

H
Haojun Liao 已提交
796 797
      pParentSql->res.code = TAOS_SYSTEM_ERROR(errno);
      quitAllSubquery(pParentSql, pSupporter);
H
Haojun Liao 已提交
798

H
Haojun Liao 已提交
799 800 801
      tscQueueAsyncRes(pParentSql);
      return;
    }
H
Haojun Liao 已提交
802

H
Haojun Liao 已提交
803
    pSupporter->pIdTagList = tmp;
H
Haojun Liao 已提交
804

H
Haojun Liao 已提交
805
    memcpy(pSupporter->pIdTagList + pSupporter->totalLen, pRes->data, validLen);
S
Shengliang Guan 已提交
806 807
    pSupporter->totalLen += (int32_t)validLen;
    pSupporter->num += (int32_t)pRes->numOfRows;
H
Haojun Liao 已提交
808

H
Haojun Liao 已提交
809 810 811 812 813 814
    // query not completed, continue to retrieve tid + tag tuples
    if (!pRes->completed) {
      taos_fetch_rows_a(tres, tidTagRetrieveCallback, param);
      return;
    }
  }
H
Haojun Liao 已提交
815

H
Haojun Liao 已提交
816 817 818 819
  // 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 已提交
820

H
Haojun Liao 已提交
821 822 823
    int32_t totalVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
    pTableMetaInfo->vgroupIndex += 1;
    assert(pTableMetaInfo->vgroupIndex < totalVgroups);
H
Haojun Liao 已提交
824

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

H
Haojun Liao 已提交
828 829
    pCmd->command = TSDB_SQL_SELECT;
    tscResetForNextRetrieve(&pSql->res);
H
Haojun Liao 已提交
830

H
Haojun Liao 已提交
831 832 833 834 835
    // set the callback function
    pSql->fp = tscJoinQueryCallback;
    tscProcessSql(pSql);
    return;
  }
H
Haojun Liao 已提交
836

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

H
Haojun Liao 已提交
843
  SArray *s1 = NULL, *s2 = NULL;
844 845 846 847 848
  int32_t code = getIntersectionOfTableTuple(pQueryInfo, pParentSql, &s1, &s2);
  if (code != TSDB_CODE_SUCCESS) {
    freeJoinSubqueryObj(pParentSql);
    pParentSql->res.code = code;
    tscQueueAsyncRes(pParentSql);
849 850 851

    taosArrayDestroy(s1);
    taosArrayDestroy(s2);
852 853 854
    return;
  }

H
Haojun Liao 已提交
855
  if (taosArrayGetSize(s1) == 0 || taosArrayGetSize(s2) == 0) {  // no results,return.
H
Haojun Liao 已提交
856 857
    assert(pParentSql->fp != tscJoinQueryCallback);

858
    tscDebug("%p tag intersect does not generated qualified tables for join, free all sub SqlObj and quit", pParentSql);
H
Haojun Liao 已提交
859
    freeJoinSubqueryObj(pParentSql);
H
Haojun Liao 已提交
860

861 862
    // set no result command
    pParentSql->cmd.command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
H
Haojun Liao 已提交
863 864
    assert(pParentSql->fp != tscJoinQueryCallback);

H
Haojun Liao 已提交
865
    (*pParentSql->fp)(pParentSql->param, pParentSql, 0);
B
Bomin Zhang 已提交
866 867 868 869
  } else {
    // proceed to for ts_comp query
    SSqlCmd* pSubCmd1 = &pParentSql->pSubs[0]->cmd;
    SSqlCmd* pSubCmd2 = &pParentSql->pSubs[1]->cmd;
H
Haojun Liao 已提交
870

B
Bomin Zhang 已提交
871 872 873
    SQueryInfo*     pQueryInfo1 = tscGetQueryInfoDetail(pSubCmd1, 0);
    STableMetaInfo* pTableMetaInfo1 = tscGetMetaInfo(pQueryInfo1, 0);
    tscBuildVgroupTableInfo(pParentSql, pTableMetaInfo1, s1);
H
Haojun Liao 已提交
874

B
Bomin Zhang 已提交
875 876 877
    SQueryInfo*     pQueryInfo2 = tscGetQueryInfoDetail(pSubCmd2, 0);
    STableMetaInfo* pTableMetaInfo2 = tscGetMetaInfo(pQueryInfo2, 0);
    tscBuildVgroupTableInfo(pParentSql, pTableMetaInfo2, s2);
H
Haojun Liao 已提交
878

H
Haojun Liao 已提交
879
    SSqlObj* psub1 = pParentSql->pSubs[0];
H
Haojun Liao 已提交
880
    ((SJoinSupporter*)psub1->param)->pVgroupTables =  tscVgroupTableInfoClone(pTableMetaInfo1->pVgroupTables);
H
Haojun Liao 已提交
881 882

    SSqlObj* psub2 = pParentSql->pSubs[1];
H
Haojun Liao 已提交
883
    ((SJoinSupporter*)psub2->param)->pVgroupTables =  tscVgroupTableInfoClone(pTableMetaInfo2->pVgroupTables);
H
Haojun Liao 已提交
884

H
Haojun Liao 已提交
885 886
    pParentSql->subState.numOfSub = 2;
    pParentSql->subState.numOfRemain = pParentSql->subState.numOfSub;
H
Haojun Liao 已提交
887

H
Haojun Liao 已提交
888
    for (int32_t m = 0; m < pParentSql->subState.numOfSub; ++m) {
B
Bomin Zhang 已提交
889 890 891
      SSqlObj* sub = pParentSql->pSubs[m];
      issueTSCompQuery(sub, sub->param, pParentSql);
    }
H
Haojun Liao 已提交
892
  }
B
Bomin Zhang 已提交
893 894 895

  taosArrayDestroy(s1);
  taosArrayDestroy(s2);
H
Haojun Liao 已提交
896
}
H
Haojun Liao 已提交
897

H
Haojun Liao 已提交
898 899
static void tsCompRetrieveCallback(void* param, TAOS_RES* tres, int32_t numOfRows) {
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
900

H
Haojun Liao 已提交
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919
  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);
920 921
    return;
  }
H
Haojun Liao 已提交
922

H
Haojun Liao 已提交
923
  if (numOfRows > 0) {  // write the compressed timestamp to disk file
924
    fwrite(pRes->data, (size_t)pRes->numOfRows, 1, pSupporter->f);
H
Haojun Liao 已提交
925 926 927 928 929 930 931 932 933 934
    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 已提交
935 936
      return;
    }
937

H
Haojun Liao 已提交
938
    if (pSupporter->pTSBuf == NULL) {
939
      tscDebug("%p create tmp file for ts block:%s, size:%d bytes", pSql, pBuf->path, numOfRows);
H
Haojun Liao 已提交
940 941 942
      pSupporter->pTSBuf = pBuf;
    } else {
      assert(pQueryInfo->numOfTables == 1);  // for subquery, only one
H
Haojun Liao 已提交
943
      tsBufMerge(pSupporter->pTSBuf, pBuf);
H
Haojun Liao 已提交
944
      tsBufDestroy(pBuf);
H
Haojun Liao 已提交
945
    }
H
hjxilinx 已提交
946

H
Haojun Liao 已提交
947 948
    // continue to retrieve ts-comp data from vnode
    if (!pRes->completed) {
S
slguan 已提交
949
      taosGetTmpfilePath("ts-join", pSupporter->path);
H
Haojun Liao 已提交
950
      pSupporter->f = fopen(pSupporter->path, "w");
S
Shengliang Guan 已提交
951
      pRes->row = (int32_t)pRes->numOfRows;
H
hjxilinx 已提交
952

H
Haojun Liao 已提交
953 954
      taos_fetch_rows_a(tres, tsCompRetrieveCallback, param);
      return;
H
hjxilinx 已提交
955
    }
H
Haojun Liao 已提交
956
  }
H
Haojun Liao 已提交
957

H
Haojun Liao 已提交
958 959
  if (hasMoreVnodesToTry(pSql)) {
    STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
Haojun Liao 已提交
960

H
Haojun Liao 已提交
961 962 963
    int32_t totalVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
    pTableMetaInfo->vgroupIndex += 1;
    assert(pTableMetaInfo->vgroupIndex < totalVgroups);
H
Haojun Liao 已提交
964

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

H
Haojun Liao 已提交
969 970
    pCmd->command = TSDB_SQL_SELECT;
    tscResetForNextRetrieve(&pSql->res);
H
Haojun Liao 已提交
971

H
Haojun Liao 已提交
972
    assert(pSupporter->f == NULL);
S
slguan 已提交
973
    taosGetTmpfilePath("ts-join", pSupporter->path);
H
Haojun Liao 已提交
974 975 976
    
    // TODO check for failure
    pSupporter->f = fopen(pSupporter->path, "w");
S
Shengliang Guan 已提交
977
    pRes->row = (int32_t)pRes->numOfRows;
H
Haojun Liao 已提交
978

H
Haojun Liao 已提交
979 980 981 982 983
    // set the callback function
    pSql->fp = tscJoinQueryCallback;
    tscProcessSql(pSql);
    return;
  }
H
Haojun Liao 已提交
984

H
Haojun Liao 已提交
985
  if (atomic_sub_fetch_32(&pParentSql->subState.numOfRemain, 1) > 0) {
H
Haojun Liao 已提交
986 987
    return;
  }
H
hjxilinx 已提交
988

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

H
Haojun Liao 已提交
991 992 993
  // proceeds to launched secondary query to retrieve final data
  SJoinSupporter* p1 = pParentSql->pSubs[0]->param;
  SJoinSupporter* p2 = pParentSql->pSubs[1]->param;
H
Haojun Liao 已提交
994

H
Haojun Liao 已提交
995 996 997
  STimeWindow win = TSWINDOW_INITIALIZER;
  int64_t num = doTSBlockIntersect(pParentSql, p1, p2, &win);
  if (num <= 0) {  // no result during ts intersect
998
    tscDebug("%p no results generated in ts intersection, free all sub SqlObj and quit", pParentSql);
H
Haojun Liao 已提交
999
    freeJoinSubqueryObj(pParentSql);
1000 1001 1002

    // set no result command
    pParentSql->cmd.command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
H
Haojun Liao 已提交
1003
    (*pParentSql->fp)(pParentSql->param, pParentSql, 0);
H
Haojun Liao 已提交
1004 1005 1006 1007 1008 1009
    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 已提交
1010 1011

  //update the vgroup that involved in real data query
H
Haojun Liao 已提交
1012
  tscLaunchRealSubqueries(pParentSql);
H
Haojun Liao 已提交
1013
}
H
Haojun Liao 已提交
1014

H
Haojun Liao 已提交
1015 1016
static void joinRetrieveFinalResCallback(void* param, TAOS_RES* tres, int numOfRows) {
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
1017

H
Haojun Liao 已提交
1018
  SSqlObj* pParentSql = pSupporter->pObj;
H
Haojun Liao 已提交
1019

H
Haojun Liao 已提交
1020 1021 1022
  SSqlObj* pSql = (SSqlObj*)tres;
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;
H
Haojun Liao 已提交
1023

H
Haojun Liao 已提交
1024 1025 1026
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(numOfRows == taos_errno(pSql));
H
hjxilinx 已提交
1027

H
Haojun Liao 已提交
1028 1029
    pParentSql->res.code = numOfRows;
    tscError("%p retrieve failed, index:%d, code:%s", pSql, pSupporter->subqueryIndex, tstrerror(numOfRows));
H
Haojun Liao 已提交
1030 1031 1032

    tscQueueAsyncRes(pParentSql);
    return;
H
Haojun Liao 已提交
1033
  }
H
Haojun Liao 已提交
1034

H
Haojun Liao 已提交
1035 1036 1037
  if (numOfRows >= 0) {
    pRes->numOfTotal += pRes->numOfRows;
  }
H
Haojun Liao 已提交
1038

H
Haojun Liao 已提交
1039
  SSubqueryState* pState = &pParentSql->subState;
H
Haojun Liao 已提交
1040 1041 1042
  if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) && numOfRows == 0) {
    STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
    assert(pQueryInfo->numOfTables == 1);
H
Haojun Liao 已提交
1043

H
Haojun Liao 已提交
1044
    // for projection query, need to try next vnode if current vnode is exhausted
H
Haojun Liao 已提交
1045 1046
    int32_t numOfVgroups = 0;  // TODO refactor
    if (pTableMetaInfo->pVgroupTables != NULL) {
S
Shengliang Guan 已提交
1047
      numOfVgroups = (int32_t)taosArrayGetSize(pTableMetaInfo->pVgroupTables);
H
Haojun Liao 已提交
1048 1049 1050 1051 1052
    } else {
      numOfVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
    }

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

H
Haojun Liao 已提交
1057 1058
      tscProcessSql(pSql);
      return;
H
Haojun Liao 已提交
1059 1060
    } else {
      tscDebug("%p no result in current subquery anymore", pSql);
H
Haojun Liao 已提交
1061 1062 1063
    }
  }

1064
  assert(pState->numOfRemain > 0);
H
Haojun Liao 已提交
1065 1066
  if (atomic_sub_fetch_32(&pState->numOfRemain, 1) > 0) {
    tscDebug("%p sub:%p completed, remain:%d, total:%d", pParentSql, tres, pState->numOfRemain, pState->numOfSub);
H
Haojun Liao 已提交
1067 1068 1069
    return;
  }

H
Haojun Liao 已提交
1070
  tscDebug("%p all %d secondary subqueries retrieval completed, code:%d", tres, pState->numOfSub, pParentSql->res.code);
H
Haojun Liao 已提交
1071 1072 1073 1074 1075 1076 1077

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

  // update the records for each subquery in parent sql object.
1078
  bool stableQuery = tscIsTwoStageSTableQuery(pQueryInfo, 0);
H
Haojun Liao 已提交
1079
  for (int32_t i = 0; i < pState->numOfSub; ++i) {
H
Haojun Liao 已提交
1080
    if (pParentSql->pSubs[i] == NULL) {
H
Haojun Liao 已提交
1081
      tscDebug("%p %p sub:%d not retrieve data", pParentSql, NULL, i);
H
Haojun Liao 已提交
1082
      continue;
H
hjxilinx 已提交
1083
    }
H
Haojun Liao 已提交
1084 1085

    SSqlRes* pRes1 = &pParentSql->pSubs[i]->res;
H
Haojun Liao 已提交
1086 1087 1088 1089 1090 1091

    if (pRes1->row > 0 && pRes1->numOfRows > 0) {
      tscDebug("%p sub:%p index:%d numOfRows:%"PRId64" total:%"PRId64 " (not retrieve)", pParentSql, pParentSql->pSubs[i], i,
               pRes1->numOfRows, pRes1->numOfTotal);
      assert(pRes1->row < pRes1->numOfRows);
    } else {
1092
      if (!stableQuery) {
1093 1094 1095
        pRes1->numOfClauseTotal += pRes1->numOfRows;
      }

H
Haojun Liao 已提交
1096 1097 1098
      tscDebug("%p sub:%p index:%d numOfRows:%"PRId64" total:%"PRId64, pParentSql, pParentSql->pSubs[i], i,
               pRes1->numOfRows, pRes1->numOfTotal);
    }
H
hjxilinx 已提交
1099
  }
H
Haojun Liao 已提交
1100 1101 1102

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

1105
void tscFetchDatablockForSubquery(SSqlObj* pSql) {
H
Haojun Liao 已提交
1106
  assert(pSql->subState.numOfSub >= 1);
H
hjxilinx 已提交
1107
  
H
hjxilinx 已提交
1108
  int32_t numOfFetch = 0;
H
Haojun Liao 已提交
1109 1110
  bool    hasData = true;
  bool    reachLimit = false;
H
Haojun Liao 已提交
1111 1112

  // if the subquery is NULL, it does not involved in the final result generation
H
Haojun Liao 已提交
1113
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
1114 1115
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
H
hjxilinx 已提交
1116 1117
      continue;
    }
H
Haojun Liao 已提交
1118

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

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

H
Haojun Liao 已提交
1123 1124
    if (!tscHasReachLimitation(pQueryInfo, pRes)) {
      if (pRes->row >= pRes->numOfRows) {
H
Haojun Liao 已提交
1125
        // no data left in current result buffer
H
Haojun Liao 已提交
1126 1127
        hasData = false;

H
Haojun Liao 已提交
1128 1129
        // The current query is completed for the active vnode, try next vnode if exists
        // If it is completed, no need to fetch anymore.
H
Haojun Liao 已提交
1130 1131
        if (!pRes->completed) {
          numOfFetch++;
H
Haojun Liao 已提交
1132
        }
H
hjxilinx 已提交
1133
      }
H
Haojun Liao 已提交
1134 1135
    } else {  // has reach the limitation, no data anymore
      if (pRes->row >= pRes->numOfRows) {
H
Haojun Liao 已提交
1136 1137
        reachLimit = true;
        hasData    = false;
H
Haojun Liao 已提交
1138 1139
        break;
      }
H
hjxilinx 已提交
1140
    }
H
Haojun Liao 已提交
1141
  }
H
hjxilinx 已提交
1142

H
hjxilinx 已提交
1143 1144 1145 1146
  // has data remains in client side, and continue to return data to app
  if (hasData) {
    tscBuildResFromSubqueries(pSql);
    return;
H
Haojun Liao 已提交
1147
  }
H
Haojun Liao 已提交
1148

H
Haojun Liao 已提交
1149 1150
  // If at least one subquery is completed in current vnode, try the next vnode in case of multi-vnode
  // super table projection query.
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
  if (reachLimit) {
    pSql->res.completed = true;
    freeJoinSubqueryObj(pSql);

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

    return;
  }

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

1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    bool orderedPrjQuery = false;
    for(int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
      SSqlObj* pSub = pSql->pSubs[i];
      if (pSub == NULL) {
        continue;
      }

      SQueryInfo* p = tscGetQueryInfoDetail(&pSub->cmd, 0);
      orderedPrjQuery = tscNonOrderedProjectionQueryOnSTable(p, 0);
      if (orderedPrjQuery) {
        break;
      }
    }
H
Haojun Liao 已提交
1180

H
Haojun Liao 已提交
1181
    // get the number of subquery that need to retrieve the next vnode.
1182
    if (orderedPrjQuery) {
1183
      for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
Haojun Liao 已提交
1184 1185
        SSqlObj* pSub = pSql->pSubs[i];
        if (pSub != NULL && pSub->res.row >= pSub->res.numOfRows && pSub->res.completed) {
H
Haojun Liao 已提交
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
          pSql->subState.numOfRemain++;
        }
      }
    }

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

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

1199 1200
      if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) && pSub->res.row >= pSub->res.numOfRows &&
          pSub->res.completed) {
H
Haojun Liao 已提交
1201 1202 1203 1204 1205 1206
        STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
        assert(pQueryInfo->numOfTables == 1);

        // for projection query, need to try next vnode if current vnode is exhausted
        int32_t numOfVgroups = 0;  // TODO refactor
        if (pTableMetaInfo->pVgroupTables != NULL) {
S
Shengliang Guan 已提交
1207
          numOfVgroups = (int32_t)taosArrayGetSize(pTableMetaInfo->pVgroupTables);
H
Haojun Liao 已提交
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
        } else {
          numOfVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
        }

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

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

    if (tryNextVnode) {
      return;
    }
H
Haojun Liao 已提交
1229 1230 1231 1232

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

H
hjxilinx 已提交
1233 1234 1235 1236 1237
    if (pSql->res.code == TSDB_CODE_SUCCESS) {
      (*pSql->fp)(pSql->param, pSql, 0);
    } else {
      tscQueueAsyncRes(pSql);
    }
1238

H
hjxilinx 已提交
1239 1240 1241 1242
    return;
  }

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

H
Haojun Liao 已提交
1248
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
1249 1250 1251 1252
    SSqlObj* pSql1 = pSql->pSubs[i];
    if (pSql1 == NULL) {
      continue;
    }
H
Haojun Liao 已提交
1253

H
hjxilinx 已提交
1254 1255 1256
    SSqlRes* pRes1 = &pSql1->res;
    SSqlCmd* pCmd1 = &pSql1->cmd;

1257
    pSupporter = (SJoinSupporter*)pSql1->param;
H
hjxilinx 已提交
1258 1259 1260 1261 1262 1263 1264 1265

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

      tscResetForNextRetrieve(pRes1);
H
Haojun Liao 已提交
1270
      pSql1->fp = joinRetrieveFinalResCallback;
H
hjxilinx 已提交
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286

      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 已提交
1287
  // the column transfer support struct has been built
H
hjxilinx 已提交
1288
  if (pRes->pColumnIndex != NULL) {
H
Haojun Liao 已提交
1289
    return;
H
hjxilinx 已提交
1290 1291 1292 1293
  }

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

S
Shengliang Guan 已提交
1294
  int32_t numOfExprs = (int32_t)tscSqlExprNumOfExprs(pQueryInfo);
H
Haojun Liao 已提交
1295
  pRes->pColumnIndex = calloc(1, sizeof(SColumnIndex) * numOfExprs);
H
Haojun Liao 已提交
1296 1297 1298 1299
  if (pRes->pColumnIndex == NULL) {
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return;
  }
H
Haojun Liao 已提交
1300 1301

  for (int32_t i = 0; i < numOfExprs; ++i) {
H
hjxilinx 已提交
1302 1303 1304 1305 1306
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);

    int32_t tableIndexOfSub = -1;
    for (int32_t j = 0; j < pQueryInfo->numOfTables; ++j) {
      STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, j);
1307
      if (pTableMetaInfo->pTableMeta->id.uid == pExpr->uid) {
H
hjxilinx 已提交
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
        tableIndexOfSub = j;
        break;
      }
    }

    assert(tableIndexOfSub >= 0 && tableIndexOfSub < pQueryInfo->numOfTables);
    
    SSqlCmd* pSubCmd = &pSql->pSubs[tableIndexOfSub]->cmd;
    SQueryInfo* pSubQueryInfo = tscGetQueryInfoDetail(pSubCmd, 0);
    
H
Haojun Liao 已提交
1318 1319
    size_t numOfSubExpr = taosArrayGetSize(pSubQueryInfo->exprList);
    for (int32_t k = 0; k < numOfSubExpr; ++k) {
H
hjxilinx 已提交
1320 1321 1322 1323 1324 1325 1326
      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 已提交
1327 1328 1329 1330

  // restore the offset value for super table query in case of final result.
  tscRestoreSQLFuncForSTableQuery(pQueryInfo);
  tscFieldInfoUpdateOffset(pQueryInfo);
H
hjxilinx 已提交
1331 1332 1333 1334
}

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

1336
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
1337 1338
  SSqlObj* pParentSql = pSupporter->pObj;

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

H
Haojun Liao 已提交
1343 1344 1345 1346 1347
  // 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 已提交
1348

H
Haojun Liao 已提交
1349 1350
    return;
  }
H
hjxilinx 已提交
1351

H
Haojun Liao 已提交
1352 1353 1354
  // TODO here retry is required, not directly returns to client
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(taos_errno(pSql) == code);
H
hjxilinx 已提交
1355

1356
    tscError("%p abort query, code:%s, global code:%s", pSql, tstrerror(code), tstrerror(pParentSql->res.code));
H
Haojun Liao 已提交
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
    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;
  }

1381 1382 1383 1384 1385 1386 1387 1388

  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);

  // In case of consequence query from other vnode, do not wait for other query response here.
  if (!(pTableMetaInfo->vgroupIndex > 0 && tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0))) {
    if (atomic_sub_fetch_32(&pParentSql->subState.numOfRemain, 1) > 0) {
      return;
    }
H
Haojun Liao 已提交
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
  }

  tscSetupOutputColumnIndex(pParentSql);

  /**
   * 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)) {
    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 已提交
1405
    } else {
H
Haojun Liao 已提交
1406
      tscQueueAsyncRes(pParentSql);
H
hjxilinx 已提交
1407 1408 1409 1410 1411 1412 1413
    }
  }
}

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

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

H
Haojun Liao 已提交
1416
int32_t tscCreateJoinSubquery(SSqlObj *pSql, int16_t tableIndex, SJoinSupporter *pSupporter) {
H
hjxilinx 已提交
1417 1418 1419 1420
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  
  pSql->res.qhandle = 0x1;
H
Haojun Liao 已提交
1421 1422
  assert(pSql->res.numOfRows == 0);

H
hjxilinx 已提交
1423
  if (pSql->pSubs == NULL) {
H
Haojun Liao 已提交
1424
    pSql->pSubs = calloc(pSql->subState.numOfSub, POINTER_BYTES);
H
hjxilinx 已提交
1425
    if (pSql->pSubs == NULL) {
1426
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1427 1428 1429
    }
  }
  
1430
  SSqlObj *pNew = createSubqueryObj(pSql, tableIndex, tscJoinQueryCallback, pSupporter, TSDB_SQL_SELECT, NULL);
H
hjxilinx 已提交
1431
  if (pNew == NULL) {
1432
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1433 1434
  }
  
H
Haojun Liao 已提交
1435 1436
  pSql->pSubs[pSql->subState.numOfRemain++] = pNew;
  assert(pSql->subState.numOfRemain <= pSql->subState.numOfSub);
H
hjxilinx 已提交
1437 1438 1439 1440 1441 1442 1443 1444
  
  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);
    
1445 1446 1447 1448 1449 1450 1451
    // 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 已提交
1452 1453 1454 1455 1456 1457 1458
    pSupporter->colList = pNewQueryInfo->colList;
    pNewQueryInfo->colList = NULL;
    
    pSupporter->exprList = pNewQueryInfo->exprList;
    pNewQueryInfo->exprList = NULL;
    
    pSupporter->fieldsInfo = pNewQueryInfo->fieldsInfo;
H
hjxilinx 已提交
1459
  
H
hjxilinx 已提交
1460 1461
    // this data needs to be transfer to support struct
    memset(&pNewQueryInfo->fieldsInfo, 0, sizeof(SFieldInfo));
H
Haojun Liao 已提交
1462 1463 1464
    if (tscTagCondCopy(&pSupporter->tagCond, &pNewQueryInfo->tagCond) != 0) {
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
    }
H
Haojun Liao 已提交
1465

H
Haojun Liao 已提交
1466 1467 1468
    pSupporter->groupInfo = pNewQueryInfo->groupbyExpr;
    memset(&pNewQueryInfo->groupbyExpr, 0, sizeof(SSqlGroupbyExpr));

H
hjxilinx 已提交
1469
    pNew->cmd.numOfCols = 0;
1470
    pNewQueryInfo->interval.interval = 0;
H
Haojun Liao 已提交
1471 1472 1473 1474 1475
    pSupporter->limit = pNewQueryInfo->limit;

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

H
hjxilinx 已提交
1476 1477 1478
    // backup the data and clear it in the sqlcmd object
    memset(&pNewQueryInfo->groupbyExpr, 0, sizeof(SSqlGroupbyExpr));
    
H
hjxilinx 已提交
1479
    tscInitQueryInfo(pNewQueryInfo);
H
hjxilinx 已提交
1480 1481
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pNewQueryInfo, 0);
    
weixin_48148422's avatar
weixin_48148422 已提交
1482
    if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) { // return the tableId & tag
H
Haojun Liao 已提交
1483
      SColumnIndex colIndex = {0};
H
Haojun Liao 已提交
1484 1485 1486 1487

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

1488
      int32_t tagColId = tscGetJoinTagColIdByUid(pTagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
1489 1490 1491
      SSchema* s = tscGetColumnSchemaById(pTableMetaInfo->pTableMeta, tagColId);

      colIndex.columnIndex = tscGetTagColIndexById(pTableMetaInfo->pTableMeta, tagColId);
1492

H
Haojun Liao 已提交
1493
      int16_t bytes = 0;
H
Haojun Liao 已提交
1494
      int16_t type  = 0;
H
Haojun Liao 已提交
1495 1496
      int32_t inter = 0;

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

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

1503 1504
      // set get tags query type
      TSDB_QUERY_SET_TYPE(pNewQueryInfo->type, TSDB_QUERY_TYPE_TAG_FILTER_QUERY);
H
Haojun Liao 已提交
1505
      tscAddSpecialColumnForSelect(pNewQueryInfo, 0, TSDB_FUNC_TID_TAG, &colIndex, &s1, TSDB_COL_TAG);
1506
      size_t numOfCols = taosArrayGetSize(pNewQueryInfo->colList);
1507
  
1508
      tscDebug(
1509
          "%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%d, transfer to tid_tag query to retrieve (tableId, tags), "
S
TD-1057  
Shengliang Guan 已提交
1510
          "exprInfo:%" PRIzu ", colList:%" PRIzu ", fieldsInfo:%d, tagIndex:%d, name:%s",
1511
          pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
H
Haojun Liao 已提交
1512
          numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, colIndex.columnIndex, pNewQueryInfo->pTableMetaInfo[0]->name);
1513 1514
    } else {
      SSchema      colSchema = {.type = TSDB_DATA_TYPE_BINARY, .bytes = 1};
H
Haojun Liao 已提交
1515 1516
      SColumnIndex colIndex = {0, PRIMARYKEY_TIMESTAMP_COL_INDEX};
      tscAddSpecialColumnForSelect(pNewQueryInfo, 0, TSDB_FUNC_TS_COMP, &colIndex, &colSchema, TSDB_COL_NORMAL);
1517 1518 1519 1520

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

H
Haojun Liao 已提交
1521
      if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
1522
        int16_t tagColId = tscGetJoinTagColIdByUid(&pSupporter->tagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
1523 1524 1525
        pExpr->param->i64Key = tagColId;
        pExpr->numOfParams = 1;
      }
1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542

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

1543
      tscDebug(
B
Bomin Zhang 已提交
1544
          "%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%u, transfer to ts_comp query to retrieve timestamps, "
S
TD-1057  
Shengliang Guan 已提交
1545
          "exprInfo:%" PRIzu ", colList:%" PRIzu ", fieldsInfo:%d, name:%s",
1546 1547 1548
          pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
          numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, pNewQueryInfo->pTableMetaInfo[0]->name);
    }
H
hjxilinx 已提交
1549
  } else {
H
hjxilinx 已提交
1550
    assert(0);
H
hjxilinx 已提交
1551 1552 1553 1554
    SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    pNewQueryInfo->type |= TSDB_QUERY_TYPE_SUBQUERY;
  }

H
Haojun Liao 已提交
1555
  return TSDB_CODE_SUCCESS;
H
hjxilinx 已提交
1556 1557
}

H
Haojun Liao 已提交
1558
void tscHandleMasterJoinQuery(SSqlObj* pSql) {
H
hjxilinx 已提交
1559
  SSqlCmd* pCmd = &pSql->cmd;
H
Haojun Liao 已提交
1560 1561
  SSqlRes* pRes = &pSql->res;

H
hjxilinx 已提交
1562 1563
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  assert((pQueryInfo->type & TSDB_QUERY_TYPE_SUBQUERY) == 0);
1564

H
Haojun Liao 已提交
1565
  int32_t code = TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1566
  pSql->subState.numOfSub = pQueryInfo->numOfTables;
H
Haojun Liao 已提交
1567

H
Haojun Liao 已提交
1568 1569
  bool hasEmptySub = false;

1570
  tscDebug("%p start subquery, total:%d", pSql, pQueryInfo->numOfTables);
H
hjxilinx 已提交
1571
  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
H
Haojun Liao 已提交
1572

H
Haojun Liao 已提交
1573
    SJoinSupporter *pSupporter = tscCreateJoinSupporter(pSql, i);
H
hjxilinx 已提交
1574 1575 1576
    
    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 已提交
1577 1578
      code = TSDB_CODE_TSC_OUT_OF_MEMORY;
      goto _error;
H
hjxilinx 已提交
1579 1580
    }
    
H
Haojun Liao 已提交
1581
    code = tscCreateJoinSubquery(pSql, i, pSupporter);
H
hjxilinx 已提交
1582 1583
    if (code != TSDB_CODE_SUCCESS) {  // failed to create subquery object, quit query
      tscDestroyJoinSupporter(pSupporter);
H
Haojun Liao 已提交
1584 1585 1586 1587 1588 1589 1590
      goto _error;
    }

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

H
Haojun Liao 已提交
1595 1596 1597 1598 1599
  if (hasEmptySub) {  // at least one subquery is empty, do nothing and return
    freeJoinSubqueryObj(pSql);
    pSql->cmd.command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
    (*pSql->fp)(pSql->param, pSql, 0);
  } else {
H
Haojun Liao 已提交
1600
    for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
Haojun Liao 已提交
1601 1602
      SSqlObj* pSub = pSql->pSubs[i];
      if ((code = tscProcessSql(pSub)) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1603
        pSql->subState.numOfRemain = i - 1;  // the already sent request will continue and do not go to the error process routine
H
Haojun Liao 已提交
1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
        break;
      }
    }

    pSql->cmd.command = TSDB_SQL_TABLE_JOIN_RETRIEVE;
  }

  return;

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

H
Haojun Liao 已提交
1618 1619
static void doCleanupSubqueries(SSqlObj *pSql, int32_t numOfSubs) {
  assert(numOfSubs <= pSql->subState.numOfSub && numOfSubs >= 0);
H
hjxilinx 已提交
1620 1621 1622 1623 1624 1625 1626
  
  for(int32_t i = 0; i < numOfSubs; ++i) {
    SSqlObj* pSub = pSql->pSubs[i];
    assert(pSub != NULL);
    
    SRetrieveSupport* pSupport = pSub->param;
    
S
Shengliang Guan 已提交
1627 1628
    taosTFree(pSupport->localBuffer);
    taosTFree(pSupport);
H
hjxilinx 已提交
1629
    
1630
    taos_free_result(pSub);
H
hjxilinx 已提交
1631 1632 1633 1634 1635 1636 1637 1638
  }
}

int32_t tscHandleMasterSTableQuery(SSqlObj *pSql) {
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;
  
  // pRes->code check only serves in launching metric sub-queries
1639
  if (pRes->code == TSDB_CODE_TSC_QUERY_CANCELLED) {
H
hjxilinx 已提交
1640
    pCmd->command = TSDB_SQL_RETRIEVE_LOCALMERGE;  // enable the abort of kill super table function.
H
hjxilinx 已提交
1641 1642 1643 1644 1645 1646 1647
    return pRes->code;
  }
  
  tExtMemBuffer **  pMemoryBuf = NULL;
  tOrderDescriptor *pDesc = NULL;
  SColumnModel *    pModel = NULL;
  
H
Haojun Liao 已提交
1648
  pRes->qhandle = 0x1;  // hack the qhandle check
H
hjxilinx 已提交
1649
  
1650
  const uint32_t nBufferSize = (1u << 16);  // 64KB
H
hjxilinx 已提交
1651
  
H
Haojun Liao 已提交
1652
  SQueryInfo     *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
1653
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
Haojun Liao 已提交
1654 1655
  SSubqueryState *pState = &pSql->subState;

H
Haojun Liao 已提交
1656 1657 1658 1659
  pState->numOfSub = 0;
  if (pTableMetaInfo->pVgroupTables == NULL) {
    pState->numOfSub = pTableMetaInfo->vgroupList->numOfVgroups;
  } else {
S
Shengliang Guan 已提交
1660
    pState->numOfSub = (int32_t)taosArrayGetSize(pTableMetaInfo->pVgroupTables);
H
Haojun Liao 已提交
1661 1662
  }

H
Haojun Liao 已提交
1663
  assert(pState->numOfSub > 0);
H
hjxilinx 已提交
1664 1665 1666
  
  int32_t ret = tscLocalReducerEnvCreate(pSql, &pMemoryBuf, &pDesc, &pModel, nBufferSize);
  if (ret != 0) {
1667
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1668
    tscQueueAsyncRes(pSql);
S
Shengliang Guan 已提交
1669
    taosTFree(pMemoryBuf);
H
hjxilinx 已提交
1670
    return ret;
H
hjxilinx 已提交
1671 1672
  }
  
H
Haojun Liao 已提交
1673
  pSql->pSubs = calloc(pState->numOfSub, POINTER_BYTES);
H
Haojun Liao 已提交
1674

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

H
Haojun Liao 已提交
1677
  if (pSql->pSubs == NULL) {
H
Haojun Liao 已提交
1678 1679
    taosTFree(pSql->pSubs);
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
Haojun Liao 已提交
1680
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pState->numOfSub);
H
Haojun Liao 已提交
1681 1682 1683 1684 1685

    tscQueueAsyncRes(pSql);
    return ret;
  }

H
Haojun Liao 已提交
1686
  pState->numOfRemain = pState->numOfSub;
H
hjxilinx 已提交
1687 1688 1689
  pRes->code = TSDB_CODE_SUCCESS;
  
  int32_t i = 0;
H
Haojun Liao 已提交
1690
  for (; i < pState->numOfSub; ++i) {
H
hjxilinx 已提交
1691 1692 1693 1694 1695 1696 1697 1698
    SRetrieveSupport *trs = (SRetrieveSupport *)calloc(1, sizeof(SRetrieveSupport));
    if (trs == NULL) {
      tscError("%p failed to malloc buffer for SRetrieveSupport, orderOfSub:%d, reason:%s", pSql, i, strerror(errno));
      break;
    }
    
    trs->pExtMemBuffer = pMemoryBuf;
    trs->pOrderDescriptor = pDesc;
H
Haojun Liao 已提交
1699

H
hjxilinx 已提交
1700 1701 1702
    trs->localBuffer = (tFilePage *)calloc(1, nBufferSize + sizeof(tFilePage));
    if (trs->localBuffer == NULL) {
      tscError("%p failed to malloc buffer for local buffer, orderOfSub:%d, reason:%s", pSql, i, strerror(errno));
S
Shengliang Guan 已提交
1703
      taosTFree(trs);
H
hjxilinx 已提交
1704 1705 1706
      break;
    }
    
H
Haojun Liao 已提交
1707 1708
    trs->subqueryIndex  = i;
    trs->pParentSql     = pSql;
H
hjxilinx 已提交
1709 1710
    trs->pFinalColModel = pModel;
    
1711
    SSqlObj *pNew = tscCreateSTableSubquery(pSql, trs, NULL);
H
hjxilinx 已提交
1712 1713
    if (pNew == NULL) {
      tscError("%p failed to malloc buffer for subObj, orderOfSub:%d, reason:%s", pSql, i, strerror(errno));
S
Shengliang Guan 已提交
1714 1715
      taosTFree(trs->localBuffer);
      taosTFree(trs);
H
hjxilinx 已提交
1716 1717 1718 1719 1720 1721 1722
      break;
    }
    
    // todo handle multi-vnode situation
    if (pQueryInfo->tsBuf) {
      SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
      pNewQueryInfo->tsBuf = tsBufClone(pQueryInfo->tsBuf);
H
Haojun Liao 已提交
1723
      assert(pNewQueryInfo->tsBuf != NULL);
H
hjxilinx 已提交
1724 1725
    }
    
1726
    tscDebug("%p sub:%p create subquery success. orderOfSub:%d", pSql, pNew, trs->subqueryIndex);
H
hjxilinx 已提交
1727 1728
  }
  
H
Haojun Liao 已提交
1729
  if (i < pState->numOfSub) {
H
hjxilinx 已提交
1730
    tscError("%p failed to prepare subquery structure and launch subqueries", pSql);
1731
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1732
    
H
Haojun Liao 已提交
1733
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pState->numOfSub);
H
Haojun Liao 已提交
1734
    doCleanupSubqueries(pSql, i);
H
hjxilinx 已提交
1735 1736 1737
    return pRes->code;   // free all allocated resource
  }
  
1738
  if (pRes->code == TSDB_CODE_TSC_QUERY_CANCELLED) {
H
Haojun Liao 已提交
1739
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pState->numOfSub);
H
Haojun Liao 已提交
1740
    doCleanupSubqueries(pSql, i);
H
hjxilinx 已提交
1741 1742 1743
    return pRes->code;
  }
  
H
Haojun Liao 已提交
1744
  for(int32_t j = 0; j < pState->numOfSub; ++j) {
H
hjxilinx 已提交
1745 1746 1747
    SSqlObj* pSub = pSql->pSubs[j];
    SRetrieveSupport* pSupport = pSub->param;
    
1748
    tscDebug("%p sub:%p launch subquery, orderOfSub:%d.", pSql, pSub, pSupport->subqueryIndex);
H
hjxilinx 已提交
1749 1750
    tscProcessSql(pSub);
  }
H
Haojun Liao 已提交
1751

H
hjxilinx 已提交
1752 1753 1754
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1755 1756
static void tscFreeRetrieveSup(SSqlObj *pSql) {
  SRetrieveSupport *trsupport = pSql->param;
1757

H
Haojun Liao 已提交
1758 1759 1760 1761 1762 1763 1764
  void* p = atomic_val_compare_exchange_ptr(&pSql->param, trsupport, 0);
  if (p == NULL) {
    tscDebug("%p retrieve supp already released", pSql);
    return;
  }

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

H
Haojun Liao 已提交
1768
//  assert(pSql == pParentSql->pSubs[index]);
S
Shengliang Guan 已提交
1769 1770
  taosTFree(trsupport->localBuffer);
  taosTFree(trsupport);
H
hjxilinx 已提交
1771 1772
}

1773
static void tscRetrieveFromDnodeCallBack(void *param, TAOS_RES *tres, int numOfRows);
1774
static void tscHandleSubqueryError(SRetrieveSupport *trsupport, SSqlObj *pSql, int numOfRows);
H
hjxilinx 已提交
1775

H
Haojun Liao 已提交
1776
static void tscAbortFurtherRetryRetrieval(SRetrieveSupport *trsupport, TAOS_RES *tres, int32_t code) {
H
hjxilinx 已提交
1777
// set no disk space error info
1778
  tscError("sub:%p failed to flush data to disk, reason:%s", tres, tstrerror(code));
H
Haojun Liao 已提交
1779
  SSqlObj* pParentSql = trsupport->pParentSql;
H
Haojun Liao 已提交
1780 1781

  pParentSql->res.code = code;
H
hjxilinx 已提交
1782
  trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
H
Haojun Liao 已提交
1783
  tscHandleSubqueryError(trsupport, tres, pParentSql->res.code);
H
hjxilinx 已提交
1784 1785
}

H
Haojun Liao 已提交
1786 1787 1788 1789 1790 1791 1792 1793
/*
 * 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;

S
TD-1732  
Shengliang Guan 已提交
1794 1795
  STableMetaInfo* pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
  SVgroupInfo* pVgroup = &pTableMetaInfo->vgroupList->vgroups[0];
H
Haojun Liao 已提交
1796 1797 1798 1799 1800

  tExtMemBufferClear(trsupport->pExtMemBuffer[subqueryIndex]);

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

1804
  SSqlObj *pNew = tscCreateSTableSubquery(trsupport->pParentSql, trsupport, pSql);
H
Haojun Liao 已提交
1805
  if (pNew == NULL) {
1806 1807
    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 已提交
1808

1809
    pParentSql->res.code = terrno;
H
Haojun Liao 已提交
1810 1811 1812 1813 1814
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;

    return pParentSql->res.code;
  }

1815 1816 1817 1818 1819
  int32_t ret = tscProcessSql(pNew);

  // if failed to process sql, let following code handle the pSql
  if (ret == TSDB_CODE_SUCCESS) {
    taos_free_result(pSql);
H
Haojun Liao 已提交
1820 1821 1822
    return ret;
  } else {
    return ret;
1823
  }
H
Haojun Liao 已提交
1824 1825
}

1826
void tscHandleSubqueryError(SRetrieveSupport *trsupport, SSqlObj *pSql, int numOfRows) {
H
Haojun Liao 已提交
1827 1828 1829 1830 1831
  // it has been freed already
  if (pSql->param != trsupport || pSql->param == NULL) {
    return;
  }

H
Haojun Liao 已提交
1832
  SSqlObj *pParentSql = trsupport->pParentSql;
H
hjxilinx 已提交
1833 1834 1835
  int32_t  subqueryIndex = trsupport->subqueryIndex;
  
  assert(pSql != NULL);
H
Haojun Liao 已提交
1836

H
Haojun Liao 已提交
1837 1838
  SSubqueryState* pState = &pParentSql->subState;
  assert(pState->numOfRemain <= pState->numOfSub && pState->numOfRemain >= 0);
H
Haojun Liao 已提交
1839

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

H
hjxilinx 已提交
1843 1844
    /*
     * kill current sub-query connection, which may retrieve data from vnodes;
1845
     * Here we get: pPObj->res.code == TSDB_CODE_TSC_QUERY_CANCELLED
H
hjxilinx 已提交
1846 1847 1848
     */
    pSql->res.numOfRows = 0;
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;  // disable retry efforts
1849 1850
    tscDebug("%p query is cancelled, sub:%p, orderOfSub:%d abort retrieve, code:%s", pParentSql, pSql,
             subqueryIndex, tstrerror(pParentSql->res.code));
H
hjxilinx 已提交
1851
  }
H
Haojun Liao 已提交
1852

H
hjxilinx 已提交
1853
  if (numOfRows >= 0) {  // current query is successful, but other sub query failed, still abort current query.
1854
    tscDebug("%p sub:%p retrieve numOfRows:%d,orderOfSub:%d", pParentSql, pSql, numOfRows, subqueryIndex);
1855 1856
    tscError("%p sub:%p abort further retrieval due to other queries failure,orderOfSub:%d,code:%s", pParentSql, pSql,
             subqueryIndex, tstrerror(pParentSql->res.code));
H
hjxilinx 已提交
1857
  } else {
H
Haojun Liao 已提交
1858
    if (trsupport->numOfRetry++ < MAX_NUM_OF_SUBQUERY_RETRY && pParentSql->res.code == TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1859
      if (tscReissueSubquery(trsupport, pSql, numOfRows) == TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1860 1861 1862
        return;
      }
    } else {  // reach the maximum retry count, abort
H
Haojun Liao 已提交
1863 1864 1865
      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 已提交
1866 1867
    }
  }
H
Haojun Liao 已提交
1868

H
Haojun Liao 已提交
1869 1870
  int32_t remain = -1;
  if ((remain = atomic_sub_fetch_32(&pState->numOfRemain, 1)) > 0) {
1871
    tscDebug("%p sub:%p orderOfSub:%d freed, finished subqueries:%d", pParentSql, pSql, trsupport->subqueryIndex,
H
Haojun Liao 已提交
1872
        pState->numOfSub - remain);
H
Haojun Liao 已提交
1873

H
Haojun Liao 已提交
1874
    tscFreeRetrieveSup(pSql);
S
Shengliang Guan 已提交
1875
    return;
H
hjxilinx 已提交
1876 1877 1878
  }
  
  // all subqueries are failed
H
Haojun Liao 已提交
1879
  tscError("%p retrieve from %d vnode(s) completed,code:%s.FAILED.", pParentSql, pState->numOfSub,
H
Haojun Liao 已提交
1880 1881
      tstrerror(pParentSql->res.code));

H
hjxilinx 已提交
1882 1883
  // release allocated resource
  tscLocalReducerEnvDestroy(trsupport->pExtMemBuffer, trsupport->pOrderDescriptor, trsupport->pFinalColModel,
H
Haojun Liao 已提交
1884
                            pState->numOfSub);
H
hjxilinx 已提交
1885
  
H
Haojun Liao 已提交
1886
  tscFreeRetrieveSup(pSql);
1887

H
hjxilinx 已提交
1888
  // in case of second stage join subquery, invoke its callback function instead of regular QueueAsyncRes
1889 1890 1891 1892 1893 1894 1895 1896 1897
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pParentSql->cmd, 0);

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

1900 1901
static void tscAllDataRetrievedFromDnode(SRetrieveSupport *trsupport, SSqlObj* pSql) {
  int32_t           idx = trsupport->subqueryIndex;
H
Haojun Liao 已提交
1902
  SSqlObj *         pParentSql = trsupport->pParentSql;
1903 1904
  tOrderDescriptor *pDesc = trsupport->pOrderDescriptor;
  
H
Haojun Liao 已提交
1905
  SSubqueryState* pState = &pParentSql->subState;
1906 1907
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
  
1908 1909
  STableMetaInfo* pTableMetaInfo = pQueryInfo->pTableMetaInfo[0];
  
1910
  // data in from current vnode is stored in cache and disk
S
Shengliang Guan 已提交
1911
  uint32_t numOfRowsFromSubquery = (uint32_t)(trsupport->pExtMemBuffer[idx]->numOfTotalElems + trsupport->localBuffer->num);
H
Haojun Liao 已提交
1912 1913 1914
  SVgroupsInfo* vgroupsInfo = pTableMetaInfo->vgroupList;
  tscDebug("%p sub:%p all data retrieved from ep:%s, vgId:%d, numOfRows:%d, orderOfSub:%d", pParentSql, pSql,
           vgroupsInfo->vgroups[0].epAddr[0].fqdn, vgroupsInfo->vgroups[0].vgId, numOfRowsFromSubquery, idx);
1915 1916 1917 1918
  
  tColModelCompact(pDesc->pColumnModel, trsupport->localBuffer, pDesc->pColumnModel->capacity);

#ifdef _DEBUG_VIEW
1919
  printf("%" PRIu64 " rows data flushed to disk:\n", trsupport->localBuffer->num);
1920 1921
    SSrcColumnInfo colInfo[256] = {0};
    tscGetSrcColumnInfo(colInfo, pQueryInfo);
1922 1923
    tColModelDisplayEx(pDesc->pColumnModel, trsupport->localBuffer->data, trsupport->localBuffer->num,
                       trsupport->localBuffer->num, colInfo);
1924 1925
#endif
  
H
Haojun Liao 已提交
1926 1927 1928
  if (tsTotalTmpDirGB != 0 && tsAvailTmpDirectorySpace < tsReservedTmpDirectorySpace) {
    tscError("%p sub:%p client disk space remain %.3f GB, need at least %.3f GB, stop query", pParentSql, pSql,
             tsAvailTmpDirectorySpace, tsReservedTmpDirectorySpace);
S
Shengliang Guan 已提交
1929 1930
    tscAbortFurtherRetryRetrieval(trsupport, pSql, TSDB_CODE_TSC_NO_DISKSPACE);
    return;
1931 1932 1933
  }
  
  // each result for a vnode is ordered as an independant list,
H
Haojun Liao 已提交
1934
  // then used as an input of loser tree for disk-based merge
1935 1936
  int32_t code = tscFlushTmpBuffer(trsupport->pExtMemBuffer[idx], pDesc, trsupport->localBuffer, pQueryInfo->groupbyExpr.orderType);
  if (code != 0) { // set no disk space error info, and abort retry
S
Shengliang Guan 已提交
1937 1938
    tscAbortFurtherRetryRetrieval(trsupport, pSql, code);
    return;
1939 1940
  }
  
H
Haojun Liao 已提交
1941
  int32_t remain = -1;
H
Haojun Liao 已提交
1942
  if ((remain = atomic_sub_fetch_32(&pParentSql->subState.numOfRemain, 1)) > 0) {
H
Haojun Liao 已提交
1943
    tscDebug("%p sub:%p orderOfSub:%d freed, finished subqueries:%d", pParentSql, pSql, trsupport->subqueryIndex,
H
Haojun Liao 已提交
1944
        pState->numOfSub - remain);
H
Haojun Liao 已提交
1945

H
Haojun Liao 已提交
1946
    tscFreeRetrieveSup(pSql);
S
Shengliang Guan 已提交
1947
    return;
1948 1949 1950 1951 1952
  }
  
  // all sub-queries are returned, start to local merge process
  pDesc->pColumnModel->capacity = trsupport->pExtMemBuffer[idx]->numOfElemsPerPage;
  
H
Haojun Liao 已提交
1953
  tscDebug("%p retrieve from %d vnodes completed.final NumOfRows:%" PRId64 ",start to build loser tree", pParentSql,
H
Haojun Liao 已提交
1954
           pState->numOfSub, pState->numOfRetrievedRows);
1955
  
H
Haojun Liao 已提交
1956
  SQueryInfo *pPQueryInfo = tscGetQueryInfoDetail(&pParentSql->cmd, 0);
1957 1958
  tscClearInterpInfo(pPQueryInfo);
  
H
Haojun Liao 已提交
1959
  tscCreateLocalReducer(trsupport->pExtMemBuffer, pState->numOfSub, pDesc, trsupport->pFinalColModel, pParentSql);
H
Haojun Liao 已提交
1960
  tscDebug("%p build loser tree completed", pParentSql);
1961
  
H
Haojun Liao 已提交
1962 1963 1964
  pParentSql->res.precision = pSql->res.precision;
  pParentSql->res.numOfRows = 0;
  pParentSql->res.row = 0;
1965
  
H
Haojun Liao 已提交
1966
  tscFreeRetrieveSup(pSql);
H
Haojun Liao 已提交
1967

1968 1969 1970 1971 1972 1973 1974
  // set the command flag must be after the semaphore been correctly set.
  pParentSql->cmd.command = TSDB_SQL_RETRIEVE_LOCALMERGE;
  if (pParentSql->res.code == TSDB_CODE_SUCCESS) {
    (*pParentSql->fp)(pParentSql->param, pParentSql, 0);
  } else {
    tscQueueAsyncRes(pParentSql);
  }
1975 1976 1977
}

static void tscRetrieveFromDnodeCallBack(void *param, TAOS_RES *tres, int numOfRows) {
H
Haojun Liao 已提交
1978 1979 1980 1981
  SSqlObj *pSql = (SSqlObj *)tres;
  assert(pSql != NULL);

  // this query has been freed already
H
hjxilinx 已提交
1982
  SRetrieveSupport *trsupport = (SRetrieveSupport *)param;
H
Haojun Liao 已提交
1983 1984 1985 1986 1987 1988
  if (pSql->param == NULL || param == NULL) {
    tscDebug("%p already freed in dnodecallback", pSql);
    assert(pSql->res.code == TSDB_CODE_TSC_QUERY_CANCELLED);
    return;
  }

H
hjxilinx 已提交
1989
  tOrderDescriptor *pDesc = trsupport->pOrderDescriptor;
H
Haojun Liao 已提交
1990
  int32_t           idx   = trsupport->subqueryIndex;
H
Haojun Liao 已提交
1991
  SSqlObj *         pParentSql = trsupport->pParentSql;
H
Haojun Liao 已提交
1992

H
Haojun Liao 已提交
1993 1994
  SSubqueryState* pState = &pParentSql->subState;
  assert(pState->numOfRemain <= pState->numOfSub && pState->numOfRemain >= 0);
H
hjxilinx 已提交
1995
  
H
Haojun Liao 已提交
1996
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
S
TD-1732  
Shengliang Guan 已提交
1997
  SVgroupInfo  *pVgroup = &pTableMetaInfo->vgroupList->vgroups[0];
H
Haojun Liao 已提交
1998 1999 2000

  if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
2001
    tscDebug("%p query cancelled/failed, sub:%p, vgId:%d, orderOfSub:%d, code:%s, global code:%s",
H
Haojun Liao 已提交
2002 2003 2004 2005 2006 2007 2008 2009 2010
             pParentSql, pSql, pVgroup->vgId, trsupport->subqueryIndex, tstrerror(numOfRows), tstrerror(pParentSql->res.code));

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

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

H
Haojun Liao 已提交
2011 2012 2013 2014
    if (numOfRows == TSDB_CODE_TSC_QUERY_CANCELLED) {
      trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
    }

H
Haojun Liao 已提交
2015
    if (trsupport->numOfRetry++ < MAX_NUM_OF_SUBQUERY_RETRY) {
2016
      tscError("%p sub:%p failed code:%s, retry:%d", pParentSql, pSql, tstrerror(numOfRows), trsupport->numOfRetry);
H
Haojun Liao 已提交
2017 2018 2019 2020 2021

      if (tscReissueSubquery(trsupport, pSql, numOfRows) == TSDB_CODE_SUCCESS) {
        return;
      }
    } else {
H
Haojun Liao 已提交
2022
      tscDebug("%p sub:%p reach the max retry times, set global code:%s", pParentSql, pSql, tstrerror(numOfRows));
H
Haojun Liao 已提交
2023 2024 2025 2026 2027
      atomic_val_compare_exchange_32(&pParentSql->res.code, TSDB_CODE_SUCCESS, numOfRows);  // set global code and abort
    }

    tscHandleSubqueryError(param, tres, numOfRows);
    return;
H
hjxilinx 已提交
2028 2029 2030 2031 2032 2033 2034 2035 2036
  }
  
  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);
    
2037 2038
    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);
2039

H
hjxilinx 已提交
2040
    if (num > tsMaxNumOfOrderedResults && tscIsProjectionQueryOnSTable(pQueryInfo, 0)) {
B
Bomin Zhang 已提交
2041
      tscError("%p sub:%p num of OrderedRes is too many, max allowed:%" PRId32 " , current:%" PRId64,
H
Haojun Liao 已提交
2042
               pParentSql, pSql, tsMaxNumOfOrderedResults, num);
S
Shengliang Guan 已提交
2043 2044
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_SORTED_RES_TOO_MANY);
      return;
H
hjxilinx 已提交
2045 2046 2047
    }

#ifdef _DEBUG_VIEW
2048
    printf("received data from vnode: %"PRIu64" rows\n", pRes->numOfRows);
H
hjxilinx 已提交
2049 2050 2051 2052 2053
    SSrcColumnInfo colInfo[256] = {0};

    tscGetSrcColumnInfo(colInfo, pQueryInfo);
    tColModelDisplayEx(pDesc->pColumnModel, pRes->data, pRes->numOfRows, pRes->numOfRows, colInfo);
#endif
2054
    
H
Haojun Liao 已提交
2055 2056 2057 2058
    // no disk space for tmp directory
    if (tsTotalTmpDirGB != 0 && tsAvailTmpDirectorySpace < tsReservedTmpDirectorySpace) {
      tscError("%p sub:%p client disk space remain %.3f GB, need at least %.3f GB, stop query", pParentSql, pSql,
               tsAvailTmpDirectorySpace, tsReservedTmpDirectorySpace);
S
Shengliang Guan 已提交
2059 2060
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_NO_DISKSPACE);
      return;
H
hjxilinx 已提交
2061 2062 2063
    }
    
    int32_t ret = saveToBuffer(trsupport->pExtMemBuffer[idx], pDesc, trsupport->localBuffer, pRes->data,
S
Shengliang Guan 已提交
2064
                               (int32_t)pRes->numOfRows, pQueryInfo->groupbyExpr.orderType);
2065
    if (ret != 0) { // set no disk space error info, and abort retry
2066
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_NO_DISKSPACE);
2067 2068 2069 2070
    } else if (pRes->completed) {
      tscAllDataRetrievedFromDnode(trsupport, pSql);
    } else { // continue fetch data from dnode
      taos_fetch_rows_a(tres, tscRetrieveFromDnodeCallBack, param);
H
hjxilinx 已提交
2071
    }
2072
    
2073 2074
  } else { // all data has been retrieved to client
    tscAllDataRetrievedFromDnode(trsupport, pSql);
H
hjxilinx 已提交
2075 2076 2077
  }
}

2078
static SSqlObj *tscCreateSTableSubquery(SSqlObj *pSql, SRetrieveSupport *trsupport, SSqlObj *prevSqlObj) {
H
hjxilinx 已提交
2079 2080
  const int32_t table_index = 0;
  
2081
  SSqlObj *pNew = createSubqueryObj(pSql, table_index, tscRetrieveDataRes, trsupport, TSDB_SQL_SELECT, prevSqlObj);
H
hjxilinx 已提交
2082 2083
  if (pNew != NULL) {  // the sub query of two-stage super table query
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
2084

H
hjxilinx 已提交
2085
    pQueryInfo->type |= TSDB_QUERY_TYPE_STABLE_SUBQUERY;
H
Haojun Liao 已提交
2086
    assert(pQueryInfo->numOfTables == 1 && pNew->cmd.numOfClause == 1 && trsupport->subqueryIndex < pSql->subState.numOfSub);
H
hjxilinx 已提交
2087
    
H
hjxilinx 已提交
2088
    // launch subquery for each vnode, so the subquery index equals to the vgroupIndex.
H
hjxilinx 已提交
2089
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, table_index);
H
hjxilinx 已提交
2090
    pTableMetaInfo->vgroupIndex = trsupport->subqueryIndex;
H
hjxilinx 已提交
2091 2092 2093 2094 2095 2096 2097 2098
    
    pSql->pSubs[trsupport->subqueryIndex] = pNew;
  }
  
  return pNew;
}

void tscRetrieveDataRes(void *param, TAOS_RES *tres, int code) {
2099
  SRetrieveSupport *trsupport = (SRetrieveSupport *) param;
H
hjxilinx 已提交
2100
  
H
Haojun Liao 已提交
2101
  SSqlObj*  pParentSql = trsupport->pParentSql;
2102
  SSqlObj*  pSql = (SSqlObj *) tres;
2103

2104 2105
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
  assert(pSql->cmd.numOfClause == 1 && pQueryInfo->numOfTables == 1);
H
hjxilinx 已提交
2106
  
2107
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
S
TD-1732  
Shengliang Guan 已提交
2108
  SVgroupInfo* pVgroup = &pTableMetaInfo->vgroupList->vgroups[trsupport->subqueryIndex];
H
Haojun Liao 已提交
2109

H
Haojun Liao 已提交
2110
  // stable query killed or other subquery failed, all query stopped
H
Haojun Liao 已提交
2111
  if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
2112
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
H
Haojun Liao 已提交
2113
    tscError("%p query cancelled or failed, sub:%p, vgId:%d, orderOfSub:%d, code:%s, global code:%s",
H
Haojun Liao 已提交
2114 2115 2116 2117
        pParentSql, pSql, pVgroup->vgId, trsupport->subqueryIndex, tstrerror(code), tstrerror(pParentSql->res.code));

    tscHandleSubqueryError(param, tres, code);
    return;
H
hjxilinx 已提交
2118 2119 2120
  }
  
  /*
H
Haojun Liao 已提交
2121
   * if a subquery on a vnode failed, all retrieve operations from vnode that occurs later
2122
   * than this one are actually not necessary, we simply call the tscRetrieveFromDnodeCallBack
H
hjxilinx 已提交
2123 2124
   * function to abort current and remain retrieve process.
   *
2125
   * NOTE: thread safe is required.
H
hjxilinx 已提交
2126
   */
H
Haojun Liao 已提交
2127 2128
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(code == taos_errno(pSql));
2129

H
Haojun Liao 已提交
2130
    if (trsupport->numOfRetry++ < MAX_NUM_OF_SUBQUERY_RETRY) {
2131
      tscError("%p sub:%p failed code:%s, retry:%d", pParentSql, pSql, tstrerror(code), trsupport->numOfRetry);
H
Haojun Liao 已提交
2132
      if (tscReissueSubquery(trsupport, pSql, code) == TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
2133 2134
        return;
      }
2135
    } else {
H
Haojun Liao 已提交
2136
      tscError("%p sub:%p reach the max retry times, set global code:%s", pParentSql, pSql, tstrerror(code));
H
Haojun Liao 已提交
2137
      atomic_val_compare_exchange_32(&pParentSql->res.code, TSDB_CODE_SUCCESS, code);  // set global code and abort
2138
    }
H
Haojun Liao 已提交
2139 2140 2141 2142 2143

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

H
Haojun Liao 已提交
2144
  tscDebug("%p sub:%p query complete, ep:%s, vgId:%d, orderOfSub:%d, retrieve data", trsupport->pParentSql, pSql,
2145
             pVgroup->epAddr[0].fqdn, pVgroup->vgId, trsupport->subqueryIndex);
H
Haojun Liao 已提交
2146 2147 2148 2149 2150

  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 已提交
2151 2152 2153
  }
}

H
Haojun Liao 已提交
2154
static void multiVnodeInsertFinalize(void* param, TAOS_RES* tres, int numOfRows) {
H
hjxilinx 已提交
2155 2156
  SInsertSupporter *pSupporter = (SInsertSupporter *)param;
  SSqlObj* pParentObj = pSupporter->pSql;
H
Haojun Liao 已提交
2157

H
Haojun Liao 已提交
2158
  // record the total inserted rows
H
Haojun Liao 已提交
2159 2160
  if (numOfRows > 0) {
    pParentObj->res.numOfRows += numOfRows;
H
Haojun Liao 已提交
2161 2162
  }

H
Haojun Liao 已提交
2163
  if (taos_errno(tres) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2164 2165 2166 2167
    SSqlObj* pSql = (SSqlObj*) tres;
    assert(pSql != NULL && pSql->res.code == numOfRows);
    
    pParentObj->res.code = pSql->res.code;
H
hjxilinx 已提交
2168
  }
H
Haojun Liao 已提交
2169

S
Shengliang Guan 已提交
2170
  taosTFree(pSupporter);
H
Haojun Liao 已提交
2171

H
Haojun Liao 已提交
2172
  if (atomic_sub_fetch_32(&pParentObj->subState.numOfRemain, 1) > 0) {
H
hjxilinx 已提交
2173 2174 2175
    return;
  }
  
2176
  tscDebug("%p Async insertion completed, total inserted:%" PRId64, pParentObj, pParentObj->res.numOfRows);
H
Haojun Liao 已提交
2177

H
hjxilinx 已提交
2178 2179
  // restore user defined fp
  pParentObj->fp = pParentObj->fetchFp;
2180 2181

  // todo remove this parameter in async callback function definition.
H
hjxilinx 已提交
2182
  // all data has been sent to vnode, call user function
S
Shengliang Guan 已提交
2183
  int32_t v = (pParentObj->res.code != TSDB_CODE_SUCCESS) ? pParentObj->res.code : (int32_t)pParentObj->res.numOfRows;
2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
  (*pParentObj->fp)(pParentObj->param, pParentObj, v);
}

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

  SInsertSupporter* pSupporter = (SInsertSupporter*) pSql->param;
H
Haojun Liao 已提交
2198
  assert(pSupporter->index < pSupporter->pSql->subState.numOfSub);
2199 2200

  STableDataBlocks* pTableDataBlock = taosArrayGetP(pCmd->pDataBlocks, pSupporter->index);
H
Haojun Liao 已提交
2201 2202 2203 2204 2205
  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.
2206 2207 2208
  }

  return tscProcessSql(pSql);
H
hjxilinx 已提交
2209 2210 2211 2212
}

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

H
Haojun Liao 已提交
2215 2216
  pSql->subState.numOfSub = (uint16_t)taosArrayGetSize(pCmd->pDataBlocks);
  assert(pSql->subState.numOfSub > 0);
H
Haojun Liao 已提交
2217 2218

  pRes->code = TSDB_CODE_SUCCESS;
2219

H
Haojun Liao 已提交
2220 2221 2222
  // the number of already initialized subqueries
  int32_t numOfSub = 0;

H
Haojun Liao 已提交
2223 2224
  pSql->subState.numOfRemain = pSql->subState.numOfSub;
  pSql->pSubs = calloc(pSql->subState.numOfSub, POINTER_BYTES);
H
Haojun Liao 已提交
2225 2226 2227 2228
  if (pSql->pSubs == NULL) {
    goto _error;
  }

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

H
Haojun Liao 已提交
2231
  while(numOfSub < pSql->subState.numOfSub) {
H
Haojun Liao 已提交
2232
    SInsertSupporter* pSupporter = calloc(1, sizeof(SInsertSupporter));
H
Haojun Liao 已提交
2233 2234 2235 2236
    if (pSupporter == NULL) {
      goto _error;
    }

2237 2238 2239 2240
    pSupporter->pSql   = pSql;
    pSupporter->index  = numOfSub;

    SSqlObj *pNew = createSimpleSubObj(pSql, multiVnodeInsertFinalize, pSupporter, TSDB_SQL_INSERT);
H
hjxilinx 已提交
2241
    if (pNew == NULL) {
H
Haojun Liao 已提交
2242
      tscError("%p failed to malloc buffer for subObj, orderOfSub:%d, reason:%s", pSql, numOfSub, strerror(errno));
H
Haojun Liao 已提交
2243
      goto _error;
H
hjxilinx 已提交
2244
    }
2245 2246 2247
  
    /*
     * assign the callback function to fetchFp to make sure that the error process function can restore
H
Haojun Liao 已提交
2248
     * the callback function (multiVnodeInsertFinalize) correctly.
2249 2250
     */
    pNew->fetchFp = pNew->fp;
H
Haojun Liao 已提交
2251
    pSql->pSubs[numOfSub] = pNew;
H
Haojun Liao 已提交
2252

2253 2254
    STableDataBlocks* pTableDataBlock = taosArrayGetP(pCmd->pDataBlocks, numOfSub);
    pRes->code = tscCopyDataBlockToPayload(pNew, pTableDataBlock);
H
Haojun Liao 已提交
2255
    if (pRes->code == TSDB_CODE_SUCCESS) {
2256
      tscDebug("%p sub:%p create subObj success. orderOfSub:%d", pSql, pNew, numOfSub);
2257
      numOfSub++;
H
Haojun Liao 已提交
2258
    } else {
H
Haojun Liao 已提交
2259
      tscDebug("%p prepare submit data block failed in async insertion, vnodeIdx:%d, total:%d, code:%s", pSql, numOfSub,
H
Haojun Liao 已提交
2260
               pSql->subState.numOfSub, tstrerror(pRes->code));
H
Haojun Liao 已提交
2261
      goto _error;
H
Haojun Liao 已提交
2262
    }
H
hjxilinx 已提交
2263 2264
  }
  
H
Haojun Liao 已提交
2265
  if (numOfSub < pSql->subState.numOfSub) {
H
hjxilinx 已提交
2266
    tscError("%p failed to prepare subObj structure and launch sub-insertion", pSql);
2267
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
Haojun Liao 已提交
2268
    goto _error;
H
hjxilinx 已提交
2269
  }
H
Haojun Liao 已提交
2270

2271 2272
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);

H
Haojun Liao 已提交
2273 2274
  // use the local variable
  for (int32_t j = 0; j < numOfSub; ++j) {
H
hjxilinx 已提交
2275
    SSqlObj *pSub = pSql->pSubs[j];
2276
    tscDebug("%p sub:%p launch sub insert, orderOfSub:%d", pSql, pSub, j);
H
hjxilinx 已提交
2277 2278
    tscProcessSql(pSub);
  }
H
Haojun Liao 已提交
2279

H
hjxilinx 已提交
2280
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2281 2282 2283

  _error:
  return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
2284
}
H
hjxilinx 已提交
2285

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

H
Haojun Liao 已提交
2289
  SInternalField* pInfo = (SInternalField*) TARRAY_GET_ELEM(pQueryInfo->fieldsInfo.internalField, columnIndex);
H
Haojun Liao 已提交
2290 2291 2292
  assert(pInfo->pSqlExpr != NULL);

  *bytes = pInfo->pSqlExpr->resBytes;
H
Haojun Liao 已提交
2293
  char* pData = pRes->data + pInfo->pSqlExpr->offset * pRes->numOfRows + pRes->row * (*bytes);
H
Haojun Liao 已提交
2294 2295 2296 2297 2298 2299 2300 2301 2302 2303

  return pData;
}

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

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

  int32_t numOfRes = INT32_MAX;
H
Haojun Liao 已提交
2304
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
Haojun Liao 已提交
2305 2306
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
H
Haojun Liao 已提交
2307 2308 2309
      continue;
    }

S
Shengliang Guan 已提交
2310
    int32_t remain = (int32_t)(pSub->res.numOfRows - pSub->res.row);
H
Haojun Liao 已提交
2311
    numOfRes = (int32_t)(MIN(numOfRes, remain));
H
Haojun Liao 已提交
2312 2313
  }

H
Haojun Liao 已提交
2314 2315
  if (numOfRes == 0) {  // no result any more, free all subquery objects
    freeJoinSubqueryObj(pSql);
H
Haojun Liao 已提交
2316 2317 2318
    return;
  }

H
Haojun Liao 已提交
2319
  int32_t totalSize = tscGetResRowLength(pQueryInfo->exprList);
H
Haojun Liao 已提交
2320 2321 2322 2323 2324 2325 2326 2327 2328 2329

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

H
Haojun Liao 已提交
2330 2331 2332 2333 2334 2335 2336 2337
  pRes->data = pRes->pRsp;

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

  size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
  for(int32_t i = 0; i < numOfExprs; ++i) {
    SColumnIndex* pIndex = &pRes->pColumnIndex[i];
H
Haojun Liao 已提交
2338 2339
    SSqlRes*      pRes1 = &pSql->pSubs[pIndex->tableIndex]->res;
    SSqlCmd*      pCmd1 = &pSql->pSubs[pIndex->tableIndex]->cmd;
H
Haojun Liao 已提交
2340 2341 2342 2343 2344

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

    data += bytes * numOfRes;
H
Haojun Liao 已提交
2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
  }

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

    pSub->res.row += numOfRes;
    assert(pSub->res.row <= pSub->res.numOfRows);
H
Haojun Liao 已提交
2355 2356 2357 2358 2359 2360
  }

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

H
hjxilinx 已提交
2361
void tscBuildResFromSubqueries(SSqlObj *pSql) {
H
Haojun Liao 已提交
2362 2363
  SSqlRes* pRes = &pSql->res;

H
hjxilinx 已提交
2364 2365 2366 2367
  if (pRes->code != TSDB_CODE_SUCCESS) {
    tscQueueAsyncRes(pSql);
    return;
  }
H
Haojun Liao 已提交
2368 2369 2370 2371

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

H
hjxilinx 已提交
2372
    size_t numOfExprs = tscSqlExprNumOfExprs(pQueryInfo);
2373
    pRes->numOfCols =  (int16_t)numOfExprs;
H
Haojun Liao 已提交
2374

H
Haojun Liao 已提交
2375 2376 2377 2378
    pRes->tsrow  = calloc(numOfExprs, POINTER_BYTES);
    pRes->buffer = calloc(numOfExprs, POINTER_BYTES);
    pRes->length = calloc(numOfExprs, sizeof(int32_t));

H
Haojun Liao 已提交
2379 2380 2381 2382 2383 2384
    if (pRes->tsrow == NULL || pRes->buffer == NULL || pRes->length == NULL) {
      pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
      tscQueueAsyncRes(pSql);
      return;
    }

H
Haojun Liao 已提交
2385 2386 2387 2388
    tscRestoreSQLFuncForSTableQuery(pQueryInfo);
  }

  while (1) {
H
Haojun Liao 已提交
2389
    assert (pRes->row >= pRes->numOfRows);
H
Haojun Liao 已提交
2390 2391

    doBuildResFromSubqueries(pSql);
S
TD-1057  
Shengliang Guan 已提交
2392
    tsem_post(&pSql->rspSem);
H
Haojun Liao 已提交
2393
    return;
H
hjxilinx 已提交
2394 2395 2396 2397 2398 2399
  }
}

static void transferNcharData(SSqlObj *pSql, int32_t columnIndex, TAOS_FIELD *pField) {
  SSqlRes *pRes = &pSql->res;
  
H
Haojun Liao 已提交
2400
  if (pRes->tsrow[columnIndex] != NULL && pField->type == TSDB_DATA_TYPE_NCHAR) {
H
hjxilinx 已提交
2401 2402 2403 2404 2405 2406 2407 2408
    // 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);
    
2409 2410
    int32_t length = taosUcs4ToMbs(pRes->tsrow[columnIndex], pRes->length[columnIndex], pRes->buffer[columnIndex]);
    if ( length >= 0 ) {
2411
      pRes->tsrow[columnIndex] = (unsigned char*)pRes->buffer[columnIndex];
2412
      pRes->length[columnIndex] = length;
H
hjxilinx 已提交
2413
    } else {
B
Bomin Zhang 已提交
2414
      tscError("%p charset:%s to %s. val:%s convert failed.", pSql, DEFAULT_UNICODE_ENCODEC, tsCharset, (char*)pRes->tsrow[columnIndex]);
H
hjxilinx 已提交
2415
      pRes->tsrow[columnIndex] = NULL;
2416
      pRes->length[columnIndex] = 0;
H
hjxilinx 已提交
2417 2418 2419 2420
    }
  }
}

2421 2422 2423 2424 2425 2426 2427 2428
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 已提交
2429
    if (strncmp(name, pExpr->aliasName, sizeof(pExpr->aliasName) - 1) == 0) {
2430 2431 2432 2433 2434 2435 2436 2437 2438
      index = i;
      break;
    }
  }

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

2439
TAOS_ROW doSetResultRowData(SSqlObj *pSql, bool finalResult) {
H
hjxilinx 已提交
2440 2441
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
H
Haojun Liao 已提交
2442

H
hjxilinx 已提交
2443 2444
  assert(pRes->row >= 0 && pRes->row <= pRes->numOfRows);
  if (pRes->row >= pRes->numOfRows) {  // all the results has returned to invoker
S
Shengliang Guan 已提交
2445
    taosTFree(pRes->tsrow);
H
hjxilinx 已提交
2446 2447
    return pRes->tsrow;
  }
H
Haojun Liao 已提交
2448

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

H
Haojun Liao 已提交
2451 2452
  size_t size = tscNumOfFields(pQueryInfo);
  for (int i = 0; i < size; ++i) {
H
Haojun Liao 已提交
2453
    SInternalField* pSup = TARRAY_GET_ELEM(pQueryInfo->fieldsInfo.internalField, i);
H
hjxilinx 已提交
2454
    if (pSup->pSqlExpr != NULL) {
2455
      tscGetResultColumnChr(pRes, &pQueryInfo->fieldsInfo, i);
H
hjxilinx 已提交
2456
    }
H
Haojun Liao 已提交
2457

H
hjxilinx 已提交
2458
    // primary key column cannot be null in interval query, no need to check
2459
    if (i == 0 && pQueryInfo->interval.interval > 0) {
H
hjxilinx 已提交
2460 2461
      continue;
    }
H
Haojun Liao 已提交
2462

H
Haojun Liao 已提交
2463
    TAOS_FIELD *pField = TARRAY_GET_ELEM(pQueryInfo->fieldsInfo.internalField, i);
H
Haojun Liao 已提交
2464 2465 2466 2467
    if (pRes->tsrow[i] != NULL && pField->type == TSDB_DATA_TYPE_NCHAR) {
      transferNcharData(pSql, i, pField);
    }

H
hjxilinx 已提交
2468 2469
    // calculate the result from several other columns
    if (pSup->pArithExprInfo != NULL) {
2470
      if (pRes->pArithSup == NULL) {
H
Haojun Liao 已提交
2471
        pRes->pArithSup = (SArithmeticSupport*)calloc(1, sizeof(SArithmeticSupport));
2472
      }
H
Haojun Liao 已提交
2473

H
Haojun Liao 已提交
2474 2475 2476 2477 2478 2479
      pRes->pArithSup->offset     = 0;
      pRes->pArithSup->pArithExpr = pSup->pArithExprInfo;
      pRes->pArithSup->numOfCols  = (int32_t)tscSqlExprNumOfExprs(pQueryInfo);
      pRes->pArithSup->exprList   = pQueryInfo->exprList;
      pRes->pArithSup->data       = calloc(pRes->pArithSup->numOfCols, POINTER_BYTES);

2480 2481 2482 2483 2484 2485 2486 2487 2488
      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 已提交
2489

2490 2491
      tExprTreeCalcTraverse(pRes->pArithSup->pArithExpr->pExpr, 1, pRes->buffer[i], pRes->pArithSup,
          TSDB_ORDER_ASC, getArithemicInputSrc);
2492
      pRes->tsrow[i] = (unsigned char*)pRes->buffer[i];
H
hjxilinx 已提交
2493 2494
    }
  }
H
Haojun Liao 已提交
2495

H
hjxilinx 已提交
2496 2497 2498 2499
  pRes->row++;  // index increase one-step
  return pRes->tsrow;
}

H
Haojun Liao 已提交
2500
static UNUSED_FUNC bool tscHasRemainDataInSubqueryResultSet(SSqlObj *pSql) {
H
hjxilinx 已提交
2501 2502 2503 2504 2505 2506 2507
  bool     hasData = true;
  SSqlCmd *pCmd = &pSql->cmd;
  
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0)) {
    bool allSubqueryExhausted = true;
    
H
Haojun Liao 已提交
2508
    for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533
      if (pSql->pSubs[i] == NULL) {
        continue;
      }
      
      SSqlRes *pRes1 = &pSql->pSubs[i]->res;
      SSqlCmd *pCmd1 = &pSql->pSubs[i]->cmd;
      
      SQueryInfo *pQueryInfo1 = tscGetQueryInfoDetail(pCmd1, pCmd1->clauseIndex);
      assert(pQueryInfo1->numOfTables == 1);
      
      STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo1, 0);
      
      /*
       * if the global limitation is not reached, and current result has not exhausted, or next more vnodes are
       * available, goes on
       */
      if (pTableMetaInfo->vgroupIndex < pTableMetaInfo->vgroupList->numOfVgroups && pRes1->row < pRes1->numOfRows &&
          (!tscHasReachLimitation(pQueryInfo1, pRes1))) {
        allSubqueryExhausted = false;
        break;
      }
    }
    
    hasData = !allSubqueryExhausted;
  } else {  // otherwise, in case inner join, if any subquery exhausted, query completed.
H
Haojun Liao 已提交
2534
    for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
2535 2536 2537 2538 2539 2540 2541 2542
      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 已提交
2543
          tscIsProjectionQuery(pQueryInfo1)) || (pRes1->numOfRows == 0)) {
H
hjxilinx 已提交
2544 2545 2546 2547 2548 2549 2550 2551
        hasData = false;
        break;
      }
    }
  }
  
  return hasData;
}