tscSubquery.c 90.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
TD-1848  
Shengliang Guan 已提交
258
  tfree(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

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

S
TD-1848  
Shengliang Guan 已提交
311
  tfree(list);
312 313 314 315 316
}

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

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

S
TD-1848  
Shengliang Guan 已提交
338
  tfree(list);
339 340 341 342 343
  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
    
      pSql->pSubs[i] = NULL;
      continue;
    }
  
    SQueryInfo *pSubQueryInfo = tscGetQueryInfoDetail(&pPrevSub->cmd, 0);
H
Haojun Liao 已提交
387
    STSBuf     *pTsBuf = pSubQueryInfo->tsBuf;
H
hjxilinx 已提交
388 389 390
    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
    tscClearSubqueryInfo(&pNew->cmd);
    pSql->pSubs[i] = pNew;
  
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
H
Haojun Liao 已提交
405
    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

      if (taosArrayGetSize(result) > 0) {
        SVgroupTableInfo* prevGroup = taosArrayGet(result, taosArrayGetSize(result) - 1);
P
plum-lihui 已提交
597
        tscDebug("%p vgId:%d, tables:%"PRIzu, pSql, prevGroup->vgInfo.vgId, taosArrayGetSize(prevGroup->itemList));
H
Haojun Liao 已提交
598 599
      }

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

  if (taosArrayGetSize(result) > 0) {
    SVgroupTableInfo* g = taosArrayGet(result, taosArrayGetSize(result) - 1);
P
plum-lihui 已提交
615
    tscDebug("%p vgId:%d, tables:%"PRIzu, pSql, g->vgInfo.vgId, taosArrayGetSize(g->itemList));
H
Haojun Liao 已提交
616
  }
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

P
plum-lihui 已提交
756
  tscDebug("%p tags match complete, result: %"PRIzu", %"PRIzu, 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");
H
Haojun Liao 已提交
951
      pRes->row = 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");
H
Haojun Liao 已提交
977
    pRes->row = 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

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

H
Haojun Liao 已提交
1096
      tscDebug("%p sub:%p index:%d numOfRows:%d total:%"PRId64, pParentSql, pParentSql->pSubs[i], i,
H
Haojun Liao 已提交
1097 1098
               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
TD-1848  
Shengliang Guan 已提交
1627 1628
    tfree(pSupport->localBuffer);
    tfree(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
    return pRes->code;
  }
  
  tExtMemBuffer **  pMemoryBuf = NULL;
H
Haojun Liao 已提交
1645 1646
  tOrderDescriptor *pDesc  = NULL;
  SColumnModel     *pModel = NULL;
H
Haojun Liao 已提交
1647
  SColumnModel     *pFinalModel = NULL;
H
Haojun Liao 已提交
1648

H
Haojun Liao 已提交
1649
  pRes->qhandle = 0x1;  // hack the qhandle check
H
hjxilinx 已提交
1650
  
H
Haojun Liao 已提交
1651
  const uint32_t nBufferSize = (1u << 16u);  // 64KB
H
hjxilinx 已提交
1652
  
H
Haojun Liao 已提交
1653
  SQueryInfo     *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
1654
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
Haojun Liao 已提交
1655 1656
  SSubqueryState *pState = &pSql->subState;

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

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

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

H
Haojun Liao 已提交
1678
  if (pSql->pSubs == NULL) {
S
TD-1848  
Shengliang Guan 已提交
1679
    tfree(pSql->pSubs);
H
Haojun Liao 已提交
1680
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
Haojun Liao 已提交
1681
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pFinalModel,pState->numOfSub);
H
Haojun Liao 已提交
1682 1683 1684 1685 1686

    tscQueueAsyncRes(pSql);
    return ret;
  }

H
Haojun Liao 已提交
1687
  pState->numOfRemain = pState->numOfSub;
H
hjxilinx 已提交
1688 1689 1690
  pRes->code = TSDB_CODE_SUCCESS;
  
  int32_t i = 0;
H
Haojun Liao 已提交
1691
  for (; i < pState->numOfSub; ++i) {
H
hjxilinx 已提交
1692 1693 1694 1695 1696 1697 1698 1699
    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 已提交
1700

H
hjxilinx 已提交
1701 1702 1703
    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
TD-1848  
Shengliang Guan 已提交
1704
      tfree(trs);
H
hjxilinx 已提交
1705 1706 1707
      break;
    }
    
H
Haojun Liao 已提交
1708 1709
    trs->subqueryIndex  = i;
    trs->pParentSql     = pSql;
H
hjxilinx 已提交
1710
    trs->pFinalColModel = pModel;
H
Haojun Liao 已提交
1711
    trs->pFFColModel    = pFinalModel;
H
Haojun Liao 已提交
1712

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

H
hjxilinx 已提交
1754 1755 1756
  return TSDB_CODE_SUCCESS;
}

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

H
Haojun Liao 已提交
1760 1761 1762 1763 1764 1765 1766
  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);
S
TD-1848  
Shengliang Guan 已提交
1767 1768
  tfree(trsupport->localBuffer);
  tfree(trsupport);
H
hjxilinx 已提交
1769 1770
}

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

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

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

H
Haojun Liao 已提交
1784 1785 1786 1787 1788 1789 1790 1791
/*
 * 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 已提交
1792 1793
  STableMetaInfo* pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
  SVgroupInfo* pVgroup = &pTableMetaInfo->vgroupList->vgroups[0];
H
Haojun Liao 已提交
1794 1795 1796 1797 1798

  tExtMemBufferClear(trsupport->pExtMemBuffer[subqueryIndex]);

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

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

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

    return pParentSql->res.code;
  }

1813 1814 1815 1816 1817
  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 已提交
1818 1819 1820
    return ret;
  } else {
    return ret;
1821
  }
H
Haojun Liao 已提交
1822 1823
}

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

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

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

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

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

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

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

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

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

H
hjxilinx 已提交
1886
  // in case of second stage join subquery, invoke its callback function instead of regular QueueAsyncRes
1887 1888 1889 1890 1891 1892 1893 1894 1895
  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 已提交
1896 1897
}

1898 1899
static void tscAllDataRetrievedFromDnode(SRetrieveSupport *trsupport, SSqlObj* pSql) {
  int32_t           idx = trsupport->subqueryIndex;
H
Haojun Liao 已提交
1900
  SSqlObj *         pParentSql = trsupport->pParentSql;
1901 1902
  tOrderDescriptor *pDesc = trsupport->pOrderDescriptor;
  
H
Haojun Liao 已提交
1903
  SSubqueryState* pState = &pParentSql->subState;
1904 1905
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
  
1906 1907
  STableMetaInfo* pTableMetaInfo = pQueryInfo->pTableMetaInfo[0];
  
1908
  // data in from current vnode is stored in cache and disk
S
Shengliang Guan 已提交
1909
  uint32_t numOfRowsFromSubquery = (uint32_t)(trsupport->pExtMemBuffer[idx]->numOfTotalElems + trsupport->localBuffer->num);
H
Haojun Liao 已提交
1910 1911 1912
  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);
1913 1914 1915 1916
  
  tColModelCompact(pDesc->pColumnModel, trsupport->localBuffer, pDesc->pColumnModel->capacity);

#ifdef _DEBUG_VIEW
1917
  printf("%" PRIu64 " rows data flushed to disk:\n", trsupport->localBuffer->num);
1918 1919
    SSrcColumnInfo colInfo[256] = {0};
    tscGetSrcColumnInfo(colInfo, pQueryInfo);
1920 1921
    tColModelDisplayEx(pDesc->pColumnModel, trsupport->localBuffer->data, trsupport->localBuffer->num,
                       trsupport->localBuffer->num, colInfo);
1922 1923
#endif
  
H
Haojun Liao 已提交
1924 1925 1926
  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 已提交
1927 1928
    tscAbortFurtherRetryRetrieval(trsupport, pSql, TSDB_CODE_TSC_NO_DISKSPACE);
    return;
1929 1930 1931
  }
  
  // each result for a vnode is ordered as an independant list,
H
Haojun Liao 已提交
1932
  // then used as an input of loser tree for disk-based merge
1933 1934
  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 已提交
1935 1936
    tscAbortFurtherRetryRetrieval(trsupport, pSql, code);
    return;
1937 1938
  }
  
H
Haojun Liao 已提交
1939
  int32_t remain = -1;
H
Haojun Liao 已提交
1940
  if ((remain = atomic_sub_fetch_32(&pParentSql->subState.numOfRemain, 1)) > 0) {
H
Haojun Liao 已提交
1941
    tscDebug("%p sub:%p orderOfSub:%d freed, finished subqueries:%d", pParentSql, pSql, trsupport->subqueryIndex,
H
Haojun Liao 已提交
1942
        pState->numOfSub - remain);
H
Haojun Liao 已提交
1943

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

1966 1967 1968 1969 1970 1971 1972
  // 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);
  }
1973 1974 1975
}

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

  // this query has been freed already
H
hjxilinx 已提交
1980
  SRetrieveSupport *trsupport = (SRetrieveSupport *)param;
H
Haojun Liao 已提交
1981 1982 1983 1984 1985 1986
  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 已提交
1987
  tOrderDescriptor *pDesc = trsupport->pOrderDescriptor;
H
Haojun Liao 已提交
1988
  int32_t           idx   = trsupport->subqueryIndex;
H
Haojun Liao 已提交
1989
  SSqlObj *         pParentSql = trsupport->pParentSql;
H
Haojun Liao 已提交
1990

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

  if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
1999
    tscDebug("%p query cancelled/failed, sub:%p, vgId:%d, orderOfSub:%d, code:%s, global code:%s",
H
Haojun Liao 已提交
2000 2001 2002 2003 2004 2005 2006 2007 2008
             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 已提交
2009 2010 2011 2012
    if (numOfRows == TSDB_CODE_TSC_QUERY_CANCELLED) {
      trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
    }

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

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

    tscHandleSubqueryError(param, tres, numOfRows);
    return;
H
hjxilinx 已提交
2026 2027 2028 2029 2030 2031 2032 2033 2034
  }
  
  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);
    
H
Haojun Liao 已提交
2035
    tscDebug("%p sub:%p retrieve numOfRows:%d totalNumOfRows:%" PRIu64 " from ep:%s, orderOfSub:%d", pParentSql, pSql,
2036
             pRes->numOfRows, pState->numOfRetrievedRows, pSql->epSet.fqdn[pSql->epSet.inUse], idx);
2037

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

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

    tscGetSrcColumnInfo(colInfo, pQueryInfo);
    tColModelDisplayEx(pDesc->pColumnModel, pRes->data, pRes->numOfRows, pRes->numOfRows, colInfo);
#endif
2052
    
H
Haojun Liao 已提交
2053 2054 2055 2056
    // 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 已提交
2057 2058
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_NO_DISKSPACE);
      return;
H
hjxilinx 已提交
2059 2060 2061
    }
    
    int32_t ret = saveToBuffer(trsupport->pExtMemBuffer[idx], pDesc, trsupport->localBuffer, pRes->data,
H
Haojun Liao 已提交
2062
                               pRes->numOfRows, pQueryInfo->groupbyExpr.orderType);
2063
    if (ret != 0) { // set no disk space error info, and abort retry
2064
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_NO_DISKSPACE);
2065 2066 2067 2068
    } else if (pRes->completed) {
      tscAllDataRetrievedFromDnode(trsupport, pSql);
    } else { // continue fetch data from dnode
      taos_fetch_rows_a(tres, tscRetrieveFromDnodeCallBack, param);
H
hjxilinx 已提交
2069
    }
2070
    
2071 2072
  } else { // all data has been retrieved to client
    tscAllDataRetrievedFromDnode(trsupport, pSql);
H
hjxilinx 已提交
2073 2074 2075
  }
}

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

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

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

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

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

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

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

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

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

  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 已提交
2149 2150 2151
  }
}

2152 2153
static bool needRetryInsert(SSqlObj* pParentObj, int32_t numOfSub) {
  if (pParentObj->retry > pParentObj->maxRetry) {
H
Haojun Liao 已提交
2154
    tscError("%p max retry reached, abort the retry effort", pParentObj);
2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
    return false;
  }

  for (int32_t i = 0; i < numOfSub; ++i) {
    int32_t code = pParentObj->pSubs[i]->res.code;
    if (code == TSDB_CODE_SUCCESS) {
      continue;
    }

    if (code != TSDB_CODE_TDB_TABLE_RECONFIGURE && code != TSDB_CODE_TDB_INVALID_TABLE_ID &&
        code != TSDB_CODE_VND_INVALID_VGROUP_ID && code != TSDB_CODE_RPC_NETWORK_UNAVAIL &&
        code != TSDB_CODE_APP_NOT_READY) {
      pParentObj->res.code = code;
      return false;
    }
  }

  return true;
}

H
Haojun Liao 已提交
2175 2176 2177 2178 2179 2180 2181 2182 2183
static void doFreeInsertSupporter(SSqlObj* pSqlObj) {
  assert(pSqlObj != NULL && pSqlObj->subState.numOfSub > 0);

  for(int32_t i = 0; i < pSqlObj->subState.numOfSub; ++i) {
    SSqlObj* pSql = pSqlObj->pSubs[i];
    tfree(pSql->param);
  }
}

H
Haojun Liao 已提交
2184
static void multiVnodeInsertFinalize(void* param, TAOS_RES* tres, int numOfRows) {
H
hjxilinx 已提交
2185 2186
  SInsertSupporter *pSupporter = (SInsertSupporter *)param;
  SSqlObj* pParentObj = pSupporter->pSql;
H
Haojun Liao 已提交
2187

H
Haojun Liao 已提交
2188
  // record the total inserted rows
H
Haojun Liao 已提交
2189 2190
  if (numOfRows > 0) {
    pParentObj->res.numOfRows += numOfRows;
H
Haojun Liao 已提交
2191 2192
  }

H
Haojun Liao 已提交
2193
  if (taos_errno(tres) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2194 2195 2196 2197
    SSqlObj* pSql = (SSqlObj*) tres;
    assert(pSql != NULL && pSql->res.code == numOfRows);
    
    pParentObj->res.code = pSql->res.code;
H
Haojun Liao 已提交
2198

2199 2200 2201 2202 2203
    // set the flag in the parent sqlObj
    if (pSql->cmd.submitSchema) {
      pParentObj->cmd.submitSchema = 1;
    }
  }
H
Haojun Liao 已提交
2204

H
Haojun Liao 已提交
2205
  if (atomic_sub_fetch_32(&pParentObj->subState.numOfRemain, 1) > 0) {
H
hjxilinx 已提交
2206 2207
    return;
  }
H
Haojun Liao 已提交
2208

H
hjxilinx 已提交
2209 2210
  // restore user defined fp
  pParentObj->fp = pParentObj->fetchFp;
2211
  int32_t numOfSub = pParentObj->subState.numOfSub;
2212
  doFreeInsertSupporter(pParentObj);
2213 2214 2215 2216 2217 2218 2219 2220 2221

  if (pParentObj->res.code == TSDB_CODE_SUCCESS) {
    tscDebug("%p Async insertion completed, total inserted:%d", pParentObj, pParentObj->res.numOfRows);

    // todo remove this parameter in async callback function definition.
    // all data has been sent to vnode, call user function
    int32_t v = (pParentObj->res.code != TSDB_CODE_SUCCESS) ? pParentObj->res.code : (int32_t)pParentObj->res.numOfRows;
    (*pParentObj->fp)(pParentObj->param, pParentObj, v);
  } else {
2222 2223 2224 2225
    if (!needRetryInsert(pParentObj, numOfSub)) {
      tscQueueAsyncRes(pParentObj);
      return;
    }
2226

2227
    int32_t numOfFailed = 0;
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249
    for(int32_t i = 0; i < numOfSub; ++i) {
      SSqlObj* pSql = pParentObj->pSubs[i];
      if (pSql->res.code != TSDB_CODE_SUCCESS) {
        numOfFailed += 1;

        // clean up tableMeta in cache
        tscFreeQueryInfo(&pSql->cmd, true);
        SQueryInfo* pQueryInfo = tscGetQueryInfoDetailSafely(&pSql->cmd, 0);
        STableMetaInfo* pMasterTableMetaInfo = tscGetTableMetaInfoFromCmd(&pParentObj->cmd, pSql->cmd.clauseIndex, 0);
        tscAddTableMetaInfo(pQueryInfo, pMasterTableMetaInfo->name, NULL, NULL, NULL, NULL);

        tscDebug("%p, failed sub:%d, %p", pParentObj, i, pSql);
      }
    }

    tscError("%p Async insertion completed, total inserted:%d rows, numOfFailed:%d, numOfTotal:%d", pParentObj,
             pParentObj->res.numOfRows, numOfFailed, numOfSub);

    tscDebug("%p cleanup %d tableMeta in cache", pParentObj, pParentObj->cmd.numOfTables);
    for(int32_t i = 0; i < pParentObj->cmd.numOfTables; ++i) {
      taosCacheRelease(tscMetaCache, (void**)&(pParentObj->cmd.pTableMetaList[i]), true);
    }
2250

2251 2252 2253 2254 2255
    pParentObj->cmd.parseFinished = false;
    pParentObj->subState.numOfRemain = numOfFailed;

    tscResetSqlCmdObj(&pParentObj->cmd, false);

H
Haojun Liao 已提交
2256 2257 2258
    // in case of insert, redo parsing the sql string and build new submit data block for two reasons:
    // 1. the table Id(tid & uid) may have been update, the submit block needs to be updated accordingly.
    // 2. vnode may need the schema information along with submit block to update its local table schema.
2259
    tscDebug("%p re-parse sql to generate submit data, retry:%d", pParentObj, pParentObj->retry++);
2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
    int32_t code = tsParseSql(pParentObj, true);
    if (code == TSDB_CODE_TSC_ACTION_IN_PROGRESS) return;

    if (code != TSDB_CODE_SUCCESS) {
      pParentObj->res.code = code;
      tscQueueAsyncRes(pParentObj);
      return;
    }

    tscDoQuery(pParentObj);
  }
2271 2272 2273 2274 2275 2276 2277
}

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

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

2285
  STableDataBlocks* pTableDataBlock = taosArrayGetP(pParent->cmd.pDataBlocks, pSupporter->index);
H
Haojun Liao 已提交
2286 2287 2288 2289 2290
  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.
2291 2292 2293
  }

  return tscProcessSql(pSql);
H
hjxilinx 已提交
2294 2295 2296 2297
}

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

2300 2301 2302 2303
  // it is the failure retry insert
  if (pSql->pSubs != NULL) {
    for(int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
      SSqlObj* pSub = pSql->pSubs[i];
2304 2305 2306
      SInsertSupporter* pSup = calloc(1, sizeof(SInsertSupporter));
      pSup->index = i;
      pSup->pSql = pSql;
2307

2308
      pSub->param = pSup;
2309 2310 2311 2312 2313 2314 2315 2316 2317
      tscDebug("%p sub:%p launch sub insert, orderOfSub:%d", pSql, pSub, i);
      if (pSub->res.code != TSDB_CODE_SUCCESS) {
        tscHandleInsertRetry(pSql, pSub);
      }
    }

    return TSDB_CODE_SUCCESS;
  }

H
Haojun Liao 已提交
2318 2319
  pSql->subState.numOfSub = (uint16_t)taosArrayGetSize(pCmd->pDataBlocks);
  assert(pSql->subState.numOfSub > 0);
H
Haojun Liao 已提交
2320 2321

  pRes->code = TSDB_CODE_SUCCESS;
2322

H
Haojun Liao 已提交
2323 2324 2325
  // the number of already initialized subqueries
  int32_t numOfSub = 0;

H
Haojun Liao 已提交
2326 2327
  pSql->subState.numOfRemain = pSql->subState.numOfSub;
  pSql->pSubs = calloc(pSql->subState.numOfSub, POINTER_BYTES);
H
Haojun Liao 已提交
2328 2329 2330 2331
  if (pSql->pSubs == NULL) {
    goto _error;
  }

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

H
Haojun Liao 已提交
2334
  while(numOfSub < pSql->subState.numOfSub) {
H
Haojun Liao 已提交
2335
    SInsertSupporter* pSupporter = calloc(1, sizeof(SInsertSupporter));
H
Haojun Liao 已提交
2336 2337 2338 2339
    if (pSupporter == NULL) {
      goto _error;
    }

2340 2341 2342 2343
    pSupporter->pSql   = pSql;
    pSupporter->index  = numOfSub;

    SSqlObj *pNew = createSimpleSubObj(pSql, multiVnodeInsertFinalize, pSupporter, TSDB_SQL_INSERT);
H
hjxilinx 已提交
2344
    if (pNew == NULL) {
H
Haojun Liao 已提交
2345
      tscError("%p failed to malloc buffer for subObj, orderOfSub:%d, reason:%s", pSql, numOfSub, strerror(errno));
H
Haojun Liao 已提交
2346
      goto _error;
H
hjxilinx 已提交
2347
    }
2348 2349 2350
  
    /*
     * assign the callback function to fetchFp to make sure that the error process function can restore
H
Haojun Liao 已提交
2351
     * the callback function (multiVnodeInsertFinalize) correctly.
2352 2353
     */
    pNew->fetchFp = pNew->fp;
H
Haojun Liao 已提交
2354
    pSql->pSubs[numOfSub] = pNew;
H
Haojun Liao 已提交
2355

2356 2357
    STableDataBlocks* pTableDataBlock = taosArrayGetP(pCmd->pDataBlocks, numOfSub);
    pRes->code = tscCopyDataBlockToPayload(pNew, pTableDataBlock);
H
Haojun Liao 已提交
2358
    if (pRes->code == TSDB_CODE_SUCCESS) {
2359
      tscDebug("%p sub:%p create subObj success. orderOfSub:%d", pSql, pNew, numOfSub);
2360
      numOfSub++;
H
Haojun Liao 已提交
2361
    } else {
H
Haojun Liao 已提交
2362
      tscDebug("%p prepare submit data block failed in async insertion, vnodeIdx:%d, total:%d, code:%s", pSql, numOfSub,
H
Haojun Liao 已提交
2363
               pSql->subState.numOfSub, tstrerror(pRes->code));
H
Haojun Liao 已提交
2364
      goto _error;
H
Haojun Liao 已提交
2365
    }
H
hjxilinx 已提交
2366 2367
  }
  
H
Haojun Liao 已提交
2368
  if (numOfSub < pSql->subState.numOfSub) {
H
hjxilinx 已提交
2369
    tscError("%p failed to prepare subObj structure and launch sub-insertion", pSql);
2370
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
Haojun Liao 已提交
2371
    goto _error;
H
hjxilinx 已提交
2372
  }
H
Haojun Liao 已提交
2373

2374 2375
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);

H
Haojun Liao 已提交
2376 2377
  // use the local variable
  for (int32_t j = 0; j < numOfSub; ++j) {
H
hjxilinx 已提交
2378
    SSqlObj *pSub = pSql->pSubs[j];
2379
    tscDebug("%p sub:%p launch sub insert, orderOfSub:%d", pSql, pSub, j);
H
hjxilinx 已提交
2380 2381
    tscProcessSql(pSub);
  }
H
Haojun Liao 已提交
2382

H
hjxilinx 已提交
2383
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2384 2385 2386

  _error:
  return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
2387
}
H
hjxilinx 已提交
2388

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

H
Haojun Liao 已提交
2392
  SInternalField* pInfo = (SInternalField*) TARRAY_GET_ELEM(pQueryInfo->fieldsInfo.internalField, columnIndex);
H
Haojun Liao 已提交
2393 2394 2395
  assert(pInfo->pSqlExpr != NULL);

  *bytes = pInfo->pSqlExpr->resBytes;
H
Haojun Liao 已提交
2396
  char* pData = pRes->data + pInfo->pSqlExpr->offset * pRes->numOfRows + pRes->row * (*bytes);
H
Haojun Liao 已提交
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406

  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 已提交
2407
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
Haojun Liao 已提交
2408 2409
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
H
Haojun Liao 已提交
2410 2411 2412
      continue;
    }

S
Shengliang Guan 已提交
2413
    int32_t remain = (int32_t)(pSub->res.numOfRows - pSub->res.row);
H
Haojun Liao 已提交
2414
    numOfRes = (int32_t)(MIN(numOfRes, remain));
H
Haojun Liao 已提交
2415 2416
  }

H
Haojun Liao 已提交
2417 2418
  if (numOfRes == 0) {  // no result any more, free all subquery objects
    freeJoinSubqueryObj(pSql);
H
Haojun Liao 已提交
2419 2420 2421
    return;
  }

H
Haojun Liao 已提交
2422
  int32_t rowSize = tscGetResRowLength(pQueryInfo->exprList);
H
Haojun Liao 已提交
2423

H
Haojun Liao 已提交
2424 2425
  assert(numOfRes * rowSize > 0);
  char* tmp = realloc(pRes->pRsp, numOfRes * rowSize + sizeof(tFilePage));
H
Haojun Liao 已提交
2426 2427 2428 2429 2430 2431 2432
  if (tmp == NULL) {
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return;
  } else {
    pRes->pRsp = tmp;
  }

H
Haojun Liao 已提交
2433 2434
  tFilePage* pFilePage = (tFilePage*) pRes->pRsp;
  pFilePage->num = numOfRes;
H
Haojun Liao 已提交
2435

H
Haojun Liao 已提交
2436
  pRes->data = pFilePage->data;
H
Haojun Liao 已提交
2437
  char* data = pRes->data;
H
Haojun Liao 已提交
2438

H
Haojun Liao 已提交
2439 2440 2441 2442 2443
  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 已提交
2444 2445
    SSqlRes*      pRes1 = &pSql->pSubs[pIndex->tableIndex]->res;
    SSqlCmd*      pCmd1 = &pSql->pSubs[pIndex->tableIndex]->cmd;
H
Haojun Liao 已提交
2446 2447 2448 2449 2450

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

    data += bytes * numOfRes;
H
Haojun Liao 已提交
2451 2452 2453 2454 2455 2456 2457 2458 2459 2460
  }

  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 已提交
2461 2462 2463 2464
  }

  pRes->numOfRows = numOfRes;
  pRes->numOfClauseTotal += numOfRes;
H
Haojun Liao 已提交
2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475

  int32_t finalRowSize = 0;
  for(int32_t i = 0; i < tscNumOfFields(pQueryInfo); ++i) {
    TAOS_FIELD* pField = tscFieldInfoGetField(&pQueryInfo->fieldsInfo, i);
    finalRowSize += pField->bytes;
  }

  doArithmeticCalculate(pQueryInfo, pFilePage, rowSize, finalRowSize);

  pRes->data = pFilePage->data;
  tscSetResRawPtr(pRes, pQueryInfo);
H
Haojun Liao 已提交
2476 2477
}

H
hjxilinx 已提交
2478
void tscBuildResFromSubqueries(SSqlObj *pSql) {
H
Haojun Liao 已提交
2479 2480
  SSqlRes* pRes = &pSql->res;

H
hjxilinx 已提交
2481 2482 2483 2484
  if (pRes->code != TSDB_CODE_SUCCESS) {
    tscQueueAsyncRes(pSql);
    return;
  }
H
Haojun Liao 已提交
2485 2486 2487

  if (pRes->tsrow == NULL) {
    SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, pSql->cmd.clauseIndex);
H
Haojun Liao 已提交
2488
    pRes->numOfCols = (int16_t) tscSqlExprNumOfExprs(pQueryInfo);
H
Haojun Liao 已提交
2489

H
Haojun Liao 已提交
2490 2491 2492 2493
    pRes->tsrow  = calloc(pRes->numOfCols, POINTER_BYTES);
    pRes->urow   = calloc(pRes->numOfCols, POINTER_BYTES);
    pRes->buffer = calloc(pRes->numOfCols, POINTER_BYTES);
    pRes->length = calloc(pRes->numOfCols, sizeof(int32_t));
H
Haojun Liao 已提交
2494

H
Haojun Liao 已提交
2495 2496 2497 2498 2499 2500
    if (pRes->tsrow == NULL || pRes->buffer == NULL || pRes->length == NULL) {
      pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
      tscQueueAsyncRes(pSql);
      return;
    }

H
Haojun Liao 已提交
2501 2502 2503 2504
    tscRestoreSQLFuncForSTableQuery(pQueryInfo);
  }

  while (1) {
H
Haojun Liao 已提交
2505
    assert (pRes->row >= pRes->numOfRows);
H
Haojun Liao 已提交
2506 2507

    doBuildResFromSubqueries(pSql);
2508 2509 2510 2511 2512
    if (pRes->code == TSDB_CODE_SUCCESS) {
      (*pSql->fp)(pSql->param, pSql, pRes->numOfRows);
    } else {
      tscQueueAsyncRes(pSql);
    }
H
hjxilinx 已提交
2513 2514 2515
  }
}

2516
static UNUSED_FUNC void transferNcharData(SSqlObj *pSql, int32_t columnIndex, TAOS_FIELD *pField) {
H
hjxilinx 已提交
2517 2518
  SSqlRes *pRes = &pSql->res;
  
H
Haojun Liao 已提交
2519
  if (pRes->tsrow[columnIndex] != NULL && pField->type == TSDB_DATA_TYPE_NCHAR) {
H
hjxilinx 已提交
2520 2521 2522 2523 2524 2525 2526 2527
    // 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);
    
2528 2529
    int32_t length = taosUcs4ToMbs(pRes->tsrow[columnIndex], pRes->length[columnIndex], pRes->buffer[columnIndex]);
    if ( length >= 0 ) {
2530
      pRes->tsrow[columnIndex] = (unsigned char*)pRes->buffer[columnIndex];
2531
      pRes->length[columnIndex] = length;
H
hjxilinx 已提交
2532
    } else {
B
Bomin Zhang 已提交
2533
      tscError("%p charset:%s to %s. val:%s convert failed.", pSql, DEFAULT_UNICODE_ENCODEC, tsCharset, (char*)pRes->tsrow[columnIndex]);
H
hjxilinx 已提交
2534
      pRes->tsrow[columnIndex] = NULL;
2535
      pRes->length[columnIndex] = 0;
H
hjxilinx 已提交
2536 2537 2538 2539
    }
  }
}

H
Haojun Liao 已提交
2540
char *getArithmeticInputSrc(void *param, const char *name, int32_t colId) {
2541 2542 2543 2544 2545 2546 2547
  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 已提交
2548
    if (strncmp(name, pExpr->aliasName, sizeof(pExpr->aliasName) - 1) == 0) {
2549 2550 2551 2552 2553 2554 2555 2556 2557
      index = i;
      break;
    }
  }

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

2558
TAOS_ROW doSetResultRowData(SSqlObj *pSql) {
H
hjxilinx 已提交
2559 2560
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
H
Haojun Liao 已提交
2561

H
hjxilinx 已提交
2562 2563
  assert(pRes->row >= 0 && pRes->row <= pRes->numOfRows);
  if (pRes->row >= pRes->numOfRows) {  // all the results has returned to invoker
S
TD-1848  
Shengliang Guan 已提交
2564
    tfree(pRes->tsrow);
H
hjxilinx 已提交
2565 2566
    return pRes->tsrow;
  }
H
Haojun Liao 已提交
2567

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

H
Haojun Liao 已提交
2570 2571
  size_t size = tscNumOfFields(pQueryInfo);
  for (int i = 0; i < size; ++i) {
2572
    SInternalField* pInfo = (SInternalField*)TARRAY_GET_ELEM(pQueryInfo->fieldsInfo.internalField, i);
H
Haojun Liao 已提交
2573

H
Haojun Liao 已提交
2574
    int32_t type  = pInfo->field.type;
2575
    int32_t bytes = pInfo->field.bytes;
H
Haojun Liao 已提交
2576

2577 2578 2579 2580 2581
    if (type != TSDB_DATA_TYPE_BINARY && type != TSDB_DATA_TYPE_NCHAR) {
      pRes->tsrow[i] = isNull(pRes->urow[i], type) ? NULL : pRes->urow[i];
    } else {
      pRes->tsrow[i] = isNull(pRes->urow[i], type) ? NULL : varDataVal(pRes->urow[i]);
      pRes->length[i] = varDataLen(pRes->urow[i]);
H
hjxilinx 已提交
2582
    }
H
Haojun Liao 已提交
2583

H
Haojun Liao 已提交
2584
    ((char**) pRes->urow)[i] += bytes;
H
hjxilinx 已提交
2585
  }
H
Haojun Liao 已提交
2586

H
hjxilinx 已提交
2587 2588 2589 2590
  pRes->row++;  // index increase one-step
  return pRes->tsrow;
}

H
Haojun Liao 已提交
2591
static UNUSED_FUNC bool tscHasRemainDataInSubqueryResultSet(SSqlObj *pSql) {
H
hjxilinx 已提交
2592 2593 2594 2595 2596 2597 2598
  bool     hasData = true;
  SSqlCmd *pCmd = &pSql->cmd;
  
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0)) {
    bool allSubqueryExhausted = true;
    
H
Haojun Liao 已提交
2599
    for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624
      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 已提交
2625
    for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
2626 2627 2628 2629 2630 2631 2632 2633
      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 已提交
2634
          tscIsProjectionQuery(pQueryInfo1)) || (pRes1->numOfRows == 0)) {
H
hjxilinx 已提交
2635 2636 2637 2638 2639 2640 2641 2642
        hasData = false;
        break;
      }
    }
  }
  
  return hasData;
}