tscSubquery.c 91.6 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
  tsBufDestroy(pSupporter1->pTSBuf);
D
fix bug  
dapan1121 已提交
191
  pSupporter1->pTSBuf = NULL;
H
Haojun Liao 已提交
192
  tsBufDestroy(pSupporter2->pTSBuf);
D
fix bug  
dapan1121 已提交
193 194
  pSupporter2->pTSBuf = NULL;
    
H
Haojun Liao 已提交
195
  TSKEY et = taosGetTimestampUs();
H
Haojun Liao 已提交
196
  tscDebug("%p input1:%" PRId64 ", input2:%" PRId64 ", final:%" PRId64 " in %d vnodes for secondary query after ts blocks "
H
Haojun Liao 已提交
197
           "intersecting, skey:%" PRId64 ", ekey:%" PRId64 ", numOfVnode:%d, elapsed time:%" PRId64 " us",
H
Haojun Liao 已提交
198 199
           pSql, numOfInput1, numOfInput2, output1->numOfTotal, output1->numOfGroups, win->skey, win->ekey,
           tsBufGetNumOfGroup(output1), et - st);
H
hjxilinx 已提交
200 201 202 203 204

  return output1->numOfTotal;
}

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

  pSupporter->pObj = pSql;

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

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

S
slguan 已提交
223
  taosGetTmpfilePath("join-", pSupporter->path);
H
hjxilinx 已提交
224

D
fix bug  
dapan1121 已提交
225 226
  // do NOT create file here to reduce crash generated file left issue
  pSupporter->f = NULL;
H
hjxilinx 已提交
227 228 229 230

  return pSupporter;
}

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

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

H
hjxilinx 已提交
244
  tscFieldInfoClear(&pSupporter->fieldsInfo);
H
hjxilinx 已提交
245

D
fix bug  
dapan1121 已提交
246 247 248 249 250 251 252
  if (pSupporter->pTSBuf != NULL) {
    tsBufDestroy(pSupporter->pTSBuf);
    pSupporter->pTSBuf = NULL;
  }

  unlink(pSupporter->path);
  
H
hjxilinx 已提交
253 254
  if (pSupporter->f != NULL) {
    fclose(pSupporter->f);
H
hjxilinx 已提交
255
    pSupporter->f = NULL;
H
hjxilinx 已提交
256 257
  }

D
fix bug  
dapan1121 已提交
258

259 260 261 262 263
  if (pSupporter->pVgroupTables != NULL) {
    taosArrayDestroy(pSupporter->pVgroupTables);
    pSupporter->pVgroupTables = NULL;
  }

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

  return false;
}

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

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

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

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

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

S
TD-1848  
Shengliang Guan 已提交
317
  tfree(list);
318 319 320 321 322
}

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

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

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

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

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

    taosArrayPush(pNew, &info);
  }

S
TD-1848  
Shengliang Guan 已提交
344
  tfree(list);
345 346 347 348 349
  TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_MULTITABLE_QUERY);

  return pNew;
}

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

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

H
hjxilinx 已提交
374 375
  bool success = true;
  
H
Haojun Liao 已提交
376
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
377 378 379 380 381
    SSqlObj *pPrevSub = pSql->pSubs[i];
    pSql->pSubs[i] = NULL;
    
    pSupporter = pPrevSub->param;
  
H
hjxilinx 已提交
382
    if (taosArrayGetSize(pSupporter->exprList) == 0) {
383
      tscDebug("%p subIndex: %d, no need to launch query, ignore it", pSql, i);
H
hjxilinx 已提交
384 385
    
      tscDestroyJoinSupporter(pSupporter);
386
      taos_free_result(pPrevSub);
H
hjxilinx 已提交
387 388 389 390 391 392
    
      pSql->pSubs[i] = NULL;
      continue;
    }
  
    SQueryInfo *pSubQueryInfo = tscGetQueryInfoDetail(&pPrevSub->cmd, 0);
H
Haojun Liao 已提交
393
    STSBuf     *pTsBuf = pSubQueryInfo->tsBuf;
H
hjxilinx 已提交
394 395 396
    pSubQueryInfo->tsBuf = NULL;
  
    // free result for async object will also free sqlObj
H
hjxilinx 已提交
397
    assert(tscSqlExprNumOfExprs(pSubQueryInfo) == 1); // ts_comp query only requires one resutl columns
H
hjxilinx 已提交
398 399
    taos_free_result(pPrevSub);
  
400
    SSqlObj *pNew = createSubqueryObj(pSql, (int16_t) i, tscJoinQueryCallback, pSupporter, TSDB_SQL_SELECT, NULL);
H
hjxilinx 已提交
401 402 403 404 405
    if (pNew == NULL) {
      tscDestroyJoinSupporter(pSupporter);
      success = false;
      break;
    }
B
Bomin Zhang 已提交
406

H
hjxilinx 已提交
407 408 409 410
    tscClearSubqueryInfo(&pNew->cmd);
    pSql->pSubs[i] = pNew;
  
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
H
Haojun Liao 已提交
411
    pQueryInfo->tsBuf = pTsBuf;  // transfer the ownership of timestamp comp-z data to the new created object
B
Bomin Zhang 已提交
412

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

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

H
hjxilinx 已提交
419 420 421
    pQueryInfo->colList = pSupporter->colList;
    pQueryInfo->exprList = pSupporter->exprList;
    pQueryInfo->fieldsInfo = pSupporter->fieldsInfo;
H
Haojun Liao 已提交
422
    pQueryInfo->groupbyExpr = pSupporter->groupInfo;
H
Haojun Liao 已提交
423

424
    assert(pNew->subState.numOfSub == 0 && pNew->cmd.numOfClause == 1 && pQueryInfo->numOfTables == 1);
H
hjxilinx 已提交
425
  
426
    tscFieldInfoUpdateOffset(pQueryInfo);
H
hjxilinx 已提交
427
  
428
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
Haojun Liao 已提交
429
    pTableMetaInfo->pVgroupTables = pSupporter->pVgroupTables;
H
Haojun Liao 已提交
430 431 432

    pSupporter->exprList = NULL;
    pSupporter->colList = NULL;
433
    pSupporter->pVgroupTables = NULL;
H
Haojun Liao 已提交
434 435
    memset(&pSupporter->fieldsInfo, 0, sizeof(SFieldInfo));
    memset(&pSupporter->groupInfo, 0, sizeof(SSqlGroupbyExpr));
H
Haojun Liao 已提交
436

H
hjxilinx 已提交
437 438 439 440 441
    /*
     * 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;
442
    pQueryInfo->limit = pSupporter->limit;
H
Haojun Liao 已提交
443 444 445 446 447

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

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

H
Haojun Liao 已提交
450
    if ((pExpr->colInfo.colId != PRIMARYKEY_TIMESTAMP_COL_INDEX) ||
H
Haojun Liao 已提交
451 452 453 454 455
        (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 已提交
456
      tscPrintSelectClause(pNew, 0);
457
      tscFieldInfoUpdateOffset(pQueryInfo);
H
Haojun Liao 已提交
458 459 460 461

      pExpr = tscSqlExprGet(pQueryInfo, 0);
    }

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

467
      // set the tag column id for executor to extract correct tag value
468
      pExpr->param[0] = (tVariant) {.i64 = colId, .nType = TSDB_DATA_TYPE_BIGINT, .nLen = sizeof(int64_t)};
H
Haojun Liao 已提交
469
      pExpr->numOfParams = 1;
H
Haojun Liao 已提交
470 471
    }

472 473 474 475 476 477 478 479
    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 已提交
480 481 482
      }
    }

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

H
Haojun Liao 已提交
504
    tscDoQuery(pSql->pSubs[i]);
H
hjxilinx 已提交
505 506 507 508 509
  }

  return TSDB_CODE_SUCCESS;
}

H
hjxilinx 已提交
510
void freeJoinSubqueryObj(SSqlObj* pSql) {
H
Haojun Liao 已提交
511
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
512 513 514 515 516
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
      continue;
    }
    
517
    SJoinSupporter* p = pSub->param;
H
hjxilinx 已提交
518
    tscDestroyJoinSupporter(p);
H
hjxilinx 已提交
519

H
hjxilinx 已提交
520 521
    if (pSub->res.code == TSDB_CODE_SUCCESS) {
      taos_free_result(pSub);
H
hjxilinx 已提交
522 523 524
    }
  }

H
Haojun Liao 已提交
525
  pSql->subState.numOfSub = 0;
H
hjxilinx 已提交
526 527
}

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

H
Haojun Liao 已提交
531
  if (atomic_sub_fetch_32(&pSqlObj->subState.numOfRemain, 1) <= 0) {
532
    tscError("%p all subquery return and query failed, global code:%s", pSqlObj, tstrerror(pSqlObj->res.code));
H
hjxilinx 已提交
533
    freeJoinSubqueryObj(pSqlObj);
H
hjxilinx 已提交
534
  }
D
fix bug  
dapan1121 已提交
535

D
TD-2516  
dapan1121 已提交
536
  //tscDestroyJoinSupporter(pSupporter);
H
hjxilinx 已提交
537 538 539
}

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


H
hjxilinx 已提交
545 546
}

H
Haojun Liao 已提交
547 548 549
int32_t tidTagsCompar(const void* p1, const void* p2) {
  const STidTags* t1 = (const STidTags*) (p1);
  const STidTags* t2 = (const STidTags*) (p2);
550 551
  
  if (t1->vgId != t2->vgId) {
weixin_48148422's avatar
weixin_48148422 已提交
552 553
    return (t1->vgId > t2->vgId) ? 1 : -1;
  }
554

H
Haojun Liao 已提交
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
  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;
574
  }
H
Haojun Liao 已提交
575

H
Haojun Liao 已提交
576
  return memcmp(tag1->data, tag2->data, tag1->len);
577 578
}

H
Haojun Liao 已提交
579
void tscBuildVgroupTableInfo(SSqlObj* pSql, STableMetaInfo* pTableMetaInfo, SArray* tables) {
H
Haojun Liao 已提交
580 581
  SArray*   result = taosArrayInit(4, sizeof(SVgroupTableInfo));
  SArray*   vgTables = NULL;
weixin_48148422's avatar
weixin_48148422 已提交
582 583
  STidTags* prev = NULL;

H
Haojun Liao 已提交
584 585 586
  size_t numOfTables = taosArrayGetSize(tables);
  for (size_t i = 0; i < numOfTables; i++) {
    STidTags* tt = taosArrayGet(tables, i);
weixin_48148422's avatar
weixin_48148422 已提交
587

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

H
Haojun Liao 已提交
591 592 593
      SVgroupTableInfo info = {{0}};
      for (int32_t m = 0; m < pvg->numOfVgroups; ++m) {
        if (tt->vgId == pvg->vgroups[m].vgId) {
S
TD-1732  
Shengliang Guan 已提交
594
          tscSVgroupInfoCopy(&info.vgInfo, &pvg->vgroups[m]);
595 596 597
          break;
        }
      }
598
      assert(info.vgInfo.numOfEps != 0);
weixin_48148422's avatar
weixin_48148422 已提交
599

H
Haojun Liao 已提交
600
      vgTables = taosArrayInit(4, sizeof(STableIdInfo));
weixin_48148422's avatar
weixin_48148422 已提交
601
      info.itemList = vgTables;
H
Haojun Liao 已提交
602 603 604

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

H
Haojun Liao 已提交
608
      taosArrayPush(result, &info);
609
    }
weixin_48148422's avatar
weixin_48148422 已提交
610

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

H
Haojun Liao 已提交
614
    tscTrace("%p tid:%d, uid:%"PRIu64",vgId:%d added", pSql, tt->tid, tt->uid, tt->vgId);
weixin_48148422's avatar
weixin_48148422 已提交
615
    prev = tt;
616
  }
weixin_48148422's avatar
weixin_48148422 已提交
617 618

  pTableMetaInfo->pVgroupTables = result;
H
Haojun Liao 已提交
619
  pTableMetaInfo->vgroupIndex = 0;
H
Haojun Liao 已提交
620 621 622

  if (taosArrayGetSize(result) > 0) {
    SVgroupTableInfo* g = taosArrayGet(result, taosArrayGetSize(result) - 1);
P
plum-lihui 已提交
623
    tscDebug("%p vgId:%d, tables:%"PRIzu, pSql, g->vgInfo.vgId, taosArrayGetSize(g->itemList));
H
Haojun Liao 已提交
624
  }
625 626 627 628 629 630
}

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

632
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
Haojun Liao 已提交
633 634
  assert(pQueryInfo->numOfTables == 1);

635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
  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 已提交
650 651
  if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
    SSqlExpr *pExpr = tscSqlExprGet(pQueryInfo, 0);
652
    int16_t tagColId = tscGetJoinTagColIdByUid(&pSupporter->tagCond, pTableMetaInfo->pTableMeta->id.uid);
653
    pExpr->param->i64 = tagColId;
H
Haojun Liao 已提交
654 655 656
    pExpr->numOfParams = 1;
  }

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

H
Haojun Liao 已提交
682
static bool checkForDuplicateTagVal(SSchema* pColSchema, SJoinSupporter* p1, SSqlObj* pPSqlObj) {
H
Haojun Liao 已提交
683 684 685
  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);
686
    assert(prev->vgId >= 1 && p->vgId >= 1);
H
Haojun Liao 已提交
687 688

    if (doCompare(prev->tag, p->tag, pColSchema->type, pColSchema->bytes) == 0) {
H
Haojun Liao 已提交
689 690
      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 已提交
691 692 693 694 695 696 697
      return false;
    }
  }

  return true;
}

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

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

H
Haojun Liao 已提交
704 705 706
  // 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 已提交
707 708

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

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

H
Haojun Liao 已提交
713
  // int16_t for padding
H
Haojun Liao 已提交
714 715 716
  int32_t size = p1->tagSize - sizeof(int16_t);
  *s1 = taosArrayInit(p1->num, size);
  *s2 = taosArrayInit(p2->num, size);
H
Haojun Liao 已提交
717

H
Haojun Liao 已提交
718
  if (!(checkForDuplicateTagVal(pColSchema, p1, pParentSql) && checkForDuplicateTagVal(pColSchema, p2, pParentSql))) {
719
    return TSDB_CODE_QRY_DUP_JOIN_KEY;
H
Haojun Liao 已提交
720 721 722 723 724 725
  }

  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);
726
    assert(pp1->tid != 0 && pp2->tid != 0);
H
Haojun Liao 已提交
727 728 729

    int32_t ret = doCompare(pp1->tag, pp2->tag, pColSchema->type, pColSchema->bytes);
    if (ret == 0) {
730
      tscDebug("%p tag matched, vgId:%d, val:%d, tid:%d, uid:%"PRIu64", tid:%d, uid:%"PRIu64, pParentSql, pp1->vgId,
H
Haojun Liao 已提交
731 732 733 734 735 736 737 738 739 740 741 742
               *(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++;
    }
  }
743

H
Haojun Liao 已提交
744 745 746 747 748 749 750 751
  // 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 已提交
752 753 754 755 756 757 758 759 760 761 762 763
#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 已提交
764
  tscDebug("%p tags match complete, result: %"PRIzu", %"PRIzu, pParentSql, t1, t2);
765
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
766 767
}

H
Haojun Liao 已提交
768
static void tidTagRetrieveCallback(void* param, TAOS_RES* tres, int32_t numOfRows) {
769
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
770

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

H
hjxilinx 已提交
773 774
  SSqlObj* pSql = (SSqlObj*)tres;
  SSqlCmd* pCmd = &pSql->cmd;
H
Haojun Liao 已提交
775 776 777
  SSqlRes* pRes = &pSql->res;

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

H
Haojun Liao 已提交
780 781 782
  // check for the error code firstly
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    // todo retry if other subqueries are not failed
H
Haojun Liao 已提交
783

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

H
Haojun Liao 已提交
787 788
    pParentSql->res.code = numOfRows;
    quitAllSubquery(pParentSql, pSupporter);
H
Haojun Liao 已提交
789

H
Haojun Liao 已提交
790
    tscAsyncResultOnError(pParentSql);
H
Haojun Liao 已提交
791 792
    return;
  }
H
Haojun Liao 已提交
793

H
Haojun Liao 已提交
794 795
  // keep the results in memory
  if (numOfRows > 0) {
796
    size_t validLen = (size_t)(pSupporter->tagSize * pRes->numOfRows);
H
Haojun Liao 已提交
797
    size_t length = pSupporter->totalLen + validLen;
H
Haojun Liao 已提交
798

H
Haojun Liao 已提交
799 800 801 802
    // todo handle memory error
    char* tmp = realloc(pSupporter->pIdTagList, length);
    if (tmp == NULL) {
      tscError("%p failed to malloc memory", pSql);
H
Haojun Liao 已提交
803

H
Haojun Liao 已提交
804 805
      pParentSql->res.code = TAOS_SYSTEM_ERROR(errno);
      quitAllSubquery(pParentSql, pSupporter);
H
Haojun Liao 已提交
806

H
Haojun Liao 已提交
807
      tscAsyncResultOnError(pParentSql);
H
Haojun Liao 已提交
808 809
      return;
    }
H
Haojun Liao 已提交
810

H
Haojun Liao 已提交
811
    pSupporter->pIdTagList = tmp;
H
Haojun Liao 已提交
812

H
Haojun Liao 已提交
813
    memcpy(pSupporter->pIdTagList + pSupporter->totalLen, pRes->data, validLen);
S
Shengliang Guan 已提交
814 815
    pSupporter->totalLen += (int32_t)validLen;
    pSupporter->num += (int32_t)pRes->numOfRows;
H
Haojun Liao 已提交
816

H
Haojun Liao 已提交
817 818 819 820 821 822
    // query not completed, continue to retrieve tid + tag tuples
    if (!pRes->completed) {
      taos_fetch_rows_a(tres, tidTagRetrieveCallback, param);
      return;
    }
  }
H
Haojun Liao 已提交
823

H
Haojun Liao 已提交
824 825 826 827
  // 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 已提交
828

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

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

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

H
Haojun Liao 已提交
839 840 841 842 843
    // set the callback function
    pSql->fp = tscJoinQueryCallback;
    tscProcessSql(pSql);
    return;
  }
H
Haojun Liao 已提交
844

H
Haojun Liao 已提交
845 846
  // 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 已提交
847
  if (atomic_sub_fetch_32(&pParentSql->subState.numOfRemain, 1) > 0) {
H
Haojun Liao 已提交
848 849
    return;
  }
H
Haojun Liao 已提交
850

H
Haojun Liao 已提交
851
  SArray *s1 = NULL, *s2 = NULL;
852 853 854 855
  int32_t code = getIntersectionOfTableTuple(pQueryInfo, pParentSql, &s1, &s2);
  if (code != TSDB_CODE_SUCCESS) {
    freeJoinSubqueryObj(pParentSql);
    pParentSql->res.code = code;
H
Haojun Liao 已提交
856
    tscAsyncResultOnError(pParentSql);
857 858 859

    taosArrayDestroy(s1);
    taosArrayDestroy(s2);
860 861 862
    return;
  }

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

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

869 870
    // set no result command
    pParentSql->cmd.command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
H
Haojun Liao 已提交
871 872
    assert(pParentSql->fp != tscJoinQueryCallback);

H
Haojun Liao 已提交
873
    (*pParentSql->fp)(pParentSql->param, pParentSql, 0);
B
Bomin Zhang 已提交
874 875 876 877
  } else {
    // proceed to for ts_comp query
    SSqlCmd* pSubCmd1 = &pParentSql->pSubs[0]->cmd;
    SSqlCmd* pSubCmd2 = &pParentSql->pSubs[1]->cmd;
H
Haojun Liao 已提交
878

B
Bomin Zhang 已提交
879 880 881
    SQueryInfo*     pQueryInfo1 = tscGetQueryInfoDetail(pSubCmd1, 0);
    STableMetaInfo* pTableMetaInfo1 = tscGetMetaInfo(pQueryInfo1, 0);
    tscBuildVgroupTableInfo(pParentSql, pTableMetaInfo1, s1);
H
Haojun Liao 已提交
882

B
Bomin Zhang 已提交
883 884 885
    SQueryInfo*     pQueryInfo2 = tscGetQueryInfoDetail(pSubCmd2, 0);
    STableMetaInfo* pTableMetaInfo2 = tscGetMetaInfo(pQueryInfo2, 0);
    tscBuildVgroupTableInfo(pParentSql, pTableMetaInfo2, s2);
H
Haojun Liao 已提交
886

H
Haojun Liao 已提交
887
    SSqlObj* psub1 = pParentSql->pSubs[0];
H
Haojun Liao 已提交
888
    ((SJoinSupporter*)psub1->param)->pVgroupTables =  tscVgroupTableInfoClone(pTableMetaInfo1->pVgroupTables);
H
Haojun Liao 已提交
889 890

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

H
Haojun Liao 已提交
893 894
    pParentSql->subState.numOfSub = 2;
    pParentSql->subState.numOfRemain = pParentSql->subState.numOfSub;
H
Haojun Liao 已提交
895

H
Haojun Liao 已提交
896
    for (int32_t m = 0; m < pParentSql->subState.numOfSub; ++m) {
B
Bomin Zhang 已提交
897 898 899
      SSqlObj* sub = pParentSql->pSubs[m];
      issueTSCompQuery(sub, sub->param, pParentSql);
    }
H
Haojun Liao 已提交
900
  }
B
Bomin Zhang 已提交
901 902 903

  taosArrayDestroy(s1);
  taosArrayDestroy(s2);
H
Haojun Liao 已提交
904
}
H
Haojun Liao 已提交
905

H
Haojun Liao 已提交
906 907
static void tsCompRetrieveCallback(void* param, TAOS_RES* tres, int32_t numOfRows) {
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
908

H
Haojun Liao 已提交
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
  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);

H
Haojun Liao 已提交
927
    tscAsyncResultOnError(pParentSql);
928 929
    return;
  }
H
Haojun Liao 已提交
930

H
Haojun Liao 已提交
931
  if (numOfRows > 0) {  // write the compressed timestamp to disk file
D
fix bug  
dapan1121 已提交
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
    if(pSupporter->f == NULL) {
      pSupporter->f = fopen(pSupporter->path, "w");

      if (pSupporter->f == NULL) {
        tscError("%p failed to create tmp file:%s, reason:%s", pSql, pSupporter->path, strerror(errno));
        
        pParentSql->res.code = TAOS_SYSTEM_ERROR(errno);

        quitAllSubquery(pParentSql, pSupporter);
        
        tscAsyncResultOnError(pParentSql);

        return;
      }
    }
      
948
    fwrite(pRes->data, (size_t)pRes->numOfRows, 1, pSupporter->f);
H
Haojun Liao 已提交
949 950 951 952 953 954 955 956
    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);
D
fix bug  
dapan1121 已提交
957 958 959

      quitAllSubquery(pParentSql, pSupporter);
      
H
Haojun Liao 已提交
960
      tscAsyncResultOnError(pParentSql);
H
Haojun Liao 已提交
961

H
hjxilinx 已提交
962 963
      return;
    }
964

H
Haojun Liao 已提交
965
    if (pSupporter->pTSBuf == NULL) {
966
      tscDebug("%p create tmp file for ts block:%s, size:%d bytes", pSql, pBuf->path, numOfRows);
H
Haojun Liao 已提交
967 968 969
      pSupporter->pTSBuf = pBuf;
    } else {
      assert(pQueryInfo->numOfTables == 1);  // for subquery, only one
H
Haojun Liao 已提交
970
      tsBufMerge(pSupporter->pTSBuf, pBuf);
H
Haojun Liao 已提交
971
      tsBufDestroy(pBuf);
H
Haojun Liao 已提交
972
    }
H
hjxilinx 已提交
973

H
Haojun Liao 已提交
974 975
    // continue to retrieve ts-comp data from vnode
    if (!pRes->completed) {
S
slguan 已提交
976
      taosGetTmpfilePath("ts-join", pSupporter->path);
H
Haojun Liao 已提交
977
      pSupporter->f = fopen(pSupporter->path, "w");
H
Haojun Liao 已提交
978
      pRes->row = pRes->numOfRows;
H
hjxilinx 已提交
979

H
Haojun Liao 已提交
980 981
      taos_fetch_rows_a(tres, tsCompRetrieveCallback, param);
      return;
H
hjxilinx 已提交
982
    }
H
Haojun Liao 已提交
983
  }
H
Haojun Liao 已提交
984

H
Haojun Liao 已提交
985 986
  if (hasMoreVnodesToTry(pSql)) {
    STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
Haojun Liao 已提交
987

H
Haojun Liao 已提交
988 989 990
    int32_t totalVgroups = pTableMetaInfo->vgroupList->numOfVgroups;
    pTableMetaInfo->vgroupIndex += 1;
    assert(pTableMetaInfo->vgroupIndex < totalVgroups);
H
Haojun Liao 已提交
991

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

H
Haojun Liao 已提交
996 997
    pCmd->command = TSDB_SQL_SELECT;
    tscResetForNextRetrieve(&pSql->res);
H
Haojun Liao 已提交
998

H
Haojun Liao 已提交
999
    assert(pSupporter->f == NULL);
S
slguan 已提交
1000
    taosGetTmpfilePath("ts-join", pSupporter->path);
H
Haojun Liao 已提交
1001 1002 1003
    
    // TODO check for failure
    pSupporter->f = fopen(pSupporter->path, "w");
H
Haojun Liao 已提交
1004
    pRes->row = pRes->numOfRows;
H
Haojun Liao 已提交
1005

H
Haojun Liao 已提交
1006 1007 1008 1009 1010
    // set the callback function
    pSql->fp = tscJoinQueryCallback;
    tscProcessSql(pSql);
    return;
  }
H
Haojun Liao 已提交
1011

H
Haojun Liao 已提交
1012
  if (atomic_sub_fetch_32(&pParentSql->subState.numOfRemain, 1) > 0) {
H
Haojun Liao 已提交
1013 1014
    return;
  }
H
hjxilinx 已提交
1015

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

H
Haojun Liao 已提交
1018 1019 1020
  // proceeds to launched secondary query to retrieve final data
  SJoinSupporter* p1 = pParentSql->pSubs[0]->param;
  SJoinSupporter* p2 = pParentSql->pSubs[1]->param;
H
Haojun Liao 已提交
1021

H
Haojun Liao 已提交
1022 1023 1024
  STimeWindow win = TSWINDOW_INITIALIZER;
  int64_t num = doTSBlockIntersect(pParentSql, p1, p2, &win);
  if (num <= 0) {  // no result during ts intersect
1025
    tscDebug("%p no results generated in ts intersection, free all sub SqlObj and quit", pParentSql);
H
Haojun Liao 已提交
1026
    freeJoinSubqueryObj(pParentSql);
1027 1028 1029

    // set no result command
    pParentSql->cmd.command = TSDB_SQL_RETRIEVE_EMPTY_RESULT;
H
Haojun Liao 已提交
1030
    (*pParentSql->fp)(pParentSql->param, pParentSql, 0);
H
Haojun Liao 已提交
1031 1032 1033 1034 1035 1036
    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 已提交
1037 1038

  //update the vgroup that involved in real data query
H
Haojun Liao 已提交
1039
  tscLaunchRealSubqueries(pParentSql);
H
Haojun Liao 已提交
1040
}
H
Haojun Liao 已提交
1041

H
Haojun Liao 已提交
1042 1043
static void joinRetrieveFinalResCallback(void* param, TAOS_RES* tres, int numOfRows) {
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
1044

H
Haojun Liao 已提交
1045
  SSqlObj* pParentSql = pSupporter->pObj;
H
Haojun Liao 已提交
1046

H
Haojun Liao 已提交
1047 1048 1049
  SSqlObj* pSql = (SSqlObj*)tres;
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;
H
Haojun Liao 已提交
1050

H
Haojun Liao 已提交
1051 1052 1053
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(numOfRows == taos_errno(pSql));
H
hjxilinx 已提交
1054

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

H
Haojun Liao 已提交
1058
    tscAsyncResultOnError(pParentSql);
H
Haojun Liao 已提交
1059
    return;
H
Haojun Liao 已提交
1060
  }
H
Haojun Liao 已提交
1061

H
Haojun Liao 已提交
1062 1063 1064
  if (numOfRows >= 0) {
    pRes->numOfTotal += pRes->numOfRows;
  }
H
Haojun Liao 已提交
1065

H
Haojun Liao 已提交
1066
  SSubqueryState* pState = &pParentSql->subState;
H
Haojun Liao 已提交
1067 1068 1069
  if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) && numOfRows == 0) {
    STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
    assert(pQueryInfo->numOfTables == 1);
H
Haojun Liao 已提交
1070

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

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

H
Haojun Liao 已提交
1084 1085
      tscProcessSql(pSql);
      return;
H
Haojun Liao 已提交
1086 1087
    } else {
      tscDebug("%p no result in current subquery anymore", pSql);
H
Haojun Liao 已提交
1088 1089 1090
    }
  }

1091
  assert(pState->numOfRemain > 0);
H
Haojun Liao 已提交
1092 1093
  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 已提交
1094 1095 1096
    return;
  }

H
Haojun Liao 已提交
1097
  tscDebug("%p all %d secondary subqueries retrieval completed, code:%d", tres, pState->numOfSub, pParentSql->res.code);
H
Haojun Liao 已提交
1098 1099 1100 1101 1102 1103 1104

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

  // update the records for each subquery in parent sql object.
1105
  bool stableQuery = tscIsTwoStageSTableQuery(pQueryInfo, 0);
H
Haojun Liao 已提交
1106
  for (int32_t i = 0; i < pState->numOfSub; ++i) {
H
Haojun Liao 已提交
1107
    if (pParentSql->pSubs[i] == NULL) {
H
Haojun Liao 已提交
1108
      tscDebug("%p %p sub:%d not retrieve data", pParentSql, NULL, i);
H
Haojun Liao 已提交
1109
      continue;
H
hjxilinx 已提交
1110
    }
H
Haojun Liao 已提交
1111 1112

    SSqlRes* pRes1 = &pParentSql->pSubs[i]->res;
H
Haojun Liao 已提交
1113 1114

    if (pRes1->row > 0 && pRes1->numOfRows > 0) {
H
Haojun Liao 已提交
1115
      tscDebug("%p sub:%p index:%d numOfRows:%d total:%"PRId64 " (not retrieve)", pParentSql, pParentSql->pSubs[i], i,
H
Haojun Liao 已提交
1116 1117 1118
               pRes1->numOfRows, pRes1->numOfTotal);
      assert(pRes1->row < pRes1->numOfRows);
    } else {
1119
      if (!stableQuery) {
1120 1121 1122
        pRes1->numOfClauseTotal += pRes1->numOfRows;
      }

H
Haojun Liao 已提交
1123
      tscDebug("%p sub:%p index:%d numOfRows:%d total:%"PRId64, pParentSql, pParentSql->pSubs[i], i,
H
Haojun Liao 已提交
1124 1125
               pRes1->numOfRows, pRes1->numOfTotal);
    }
H
hjxilinx 已提交
1126
  }
H
Haojun Liao 已提交
1127 1128 1129

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

1132
void tscFetchDatablockForSubquery(SSqlObj* pSql) {
H
Haojun Liao 已提交
1133
  assert(pSql->subState.numOfSub >= 1);
H
hjxilinx 已提交
1134
  
H
hjxilinx 已提交
1135
  int32_t numOfFetch = 0;
H
Haojun Liao 已提交
1136 1137
  bool    hasData = true;
  bool    reachLimit = false;
H
Haojun Liao 已提交
1138 1139

  // if the subquery is NULL, it does not involved in the final result generation
H
Haojun Liao 已提交
1140
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
1141 1142
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
H
hjxilinx 已提交
1143 1144
      continue;
    }
H
Haojun Liao 已提交
1145

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

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

H
Haojun Liao 已提交
1150 1151
    if (!tscHasReachLimitation(pQueryInfo, pRes)) {
      if (pRes->row >= pRes->numOfRows) {
H
Haojun Liao 已提交
1152
        // no data left in current result buffer
H
Haojun Liao 已提交
1153 1154
        hasData = false;

H
Haojun Liao 已提交
1155 1156
        // 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 已提交
1157 1158
        if (!pRes->completed) {
          numOfFetch++;
H
Haojun Liao 已提交
1159
        }
H
hjxilinx 已提交
1160
      }
H
Haojun Liao 已提交
1161 1162
    } else {  // has reach the limitation, no data anymore
      if (pRes->row >= pRes->numOfRows) {
H
Haojun Liao 已提交
1163 1164
        reachLimit = true;
        hasData    = false;
H
Haojun Liao 已提交
1165 1166
        break;
      }
H
hjxilinx 已提交
1167
    }
H
Haojun Liao 已提交
1168
  }
H
hjxilinx 已提交
1169

H
hjxilinx 已提交
1170 1171 1172 1173
  // has data remains in client side, and continue to return data to app
  if (hasData) {
    tscBuildResFromSubqueries(pSql);
    return;
H
Haojun Liao 已提交
1174
  }
H
Haojun Liao 已提交
1175

H
Haojun Liao 已提交
1176 1177
  // If at least one subquery is completed in current vnode, try the next vnode in case of multi-vnode
  // super table projection query.
1178 1179 1180 1181 1182 1183 1184
  if (reachLimit) {
    pSql->res.completed = true;
    freeJoinSubqueryObj(pSql);

    if (pSql->res.code == TSDB_CODE_SUCCESS) {
      (*pSql->fp)(pSql->param, pSql, 0);
    } else {
H
Haojun Liao 已提交
1185
      tscAsyncResultOnError(pSql);
1186 1187 1188 1189 1190 1191
    }

    return;
  }

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

1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
    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 已提交
1207

H
Haojun Liao 已提交
1208
    // get the number of subquery that need to retrieve the next vnode.
1209
    if (orderedPrjQuery) {
1210
      for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
Haojun Liao 已提交
1211 1212
        SSqlObj* pSub = pSql->pSubs[i];
        if (pSub != NULL && pSub->res.row >= pSub->res.numOfRows && pSub->res.completed) {
H
Haojun Liao 已提交
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
          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);

1226 1227
      if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0) && pSub->res.row >= pSub->res.numOfRows &&
          pSub->res.completed) {
H
Haojun Liao 已提交
1228 1229 1230 1231 1232 1233
        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 已提交
1234
          numOfVgroups = (int32_t)taosArrayGetSize(pTableMetaInfo->pVgroupTables);
H
Haojun Liao 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
        } 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 已提交
1256 1257 1258 1259

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

H
hjxilinx 已提交
1260 1261 1262
    if (pSql->res.code == TSDB_CODE_SUCCESS) {
      (*pSql->fp)(pSql->param, pSql, 0);
    } else {
H
Haojun Liao 已提交
1263
      tscAsyncResultOnError(pSql);
H
hjxilinx 已提交
1264
    }
1265

H
hjxilinx 已提交
1266 1267 1268 1269
    return;
  }

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

H
Haojun Liao 已提交
1275
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
1276 1277 1278 1279
    SSqlObj* pSql1 = pSql->pSubs[i];
    if (pSql1 == NULL) {
      continue;
    }
H
Haojun Liao 已提交
1280

H
hjxilinx 已提交
1281 1282 1283
    SSqlRes* pRes1 = &pSql1->res;
    SSqlCmd* pCmd1 = &pSql1->cmd;

1284
    pSupporter = (SJoinSupporter*)pSql1->param;
H
hjxilinx 已提交
1285 1286 1287 1288 1289 1290 1291 1292

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

      tscResetForNextRetrieve(pRes1);
H
Haojun Liao 已提交
1297
      pSql1->fp = joinRetrieveFinalResCallback;
H
hjxilinx 已提交
1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313

      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 已提交
1314
  // the column transfer support struct has been built
H
hjxilinx 已提交
1315
  if (pRes->pColumnIndex != NULL) {
H
Haojun Liao 已提交
1316
    return;
H
hjxilinx 已提交
1317 1318 1319 1320
  }

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

S
Shengliang Guan 已提交
1321
  int32_t numOfExprs = (int32_t)tscSqlExprNumOfExprs(pQueryInfo);
H
Haojun Liao 已提交
1322
  pRes->pColumnIndex = calloc(1, sizeof(SColumnIndex) * numOfExprs);
H
Haojun Liao 已提交
1323 1324 1325 1326
  if (pRes->pColumnIndex == NULL) {
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return;
  }
H
Haojun Liao 已提交
1327 1328

  for (int32_t i = 0; i < numOfExprs; ++i) {
H
hjxilinx 已提交
1329 1330 1331 1332 1333
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, i);

    int32_t tableIndexOfSub = -1;
    for (int32_t j = 0; j < pQueryInfo->numOfTables; ++j) {
      STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, j);
1334
      if (pTableMetaInfo->pTableMeta->id.uid == pExpr->uid) {
H
hjxilinx 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
        tableIndexOfSub = j;
        break;
      }
    }

    assert(tableIndexOfSub >= 0 && tableIndexOfSub < pQueryInfo->numOfTables);
    
    SSqlCmd* pSubCmd = &pSql->pSubs[tableIndexOfSub]->cmd;
    SQueryInfo* pSubQueryInfo = tscGetQueryInfoDetail(pSubCmd, 0);
    
H
Haojun Liao 已提交
1345 1346
    size_t numOfSubExpr = taosArrayGetSize(pSubQueryInfo->exprList);
    for (int32_t k = 0; k < numOfSubExpr; ++k) {
H
hjxilinx 已提交
1347 1348 1349 1350 1351 1352 1353
      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 已提交
1354 1355 1356 1357

  // restore the offset value for super table query in case of final result.
  tscRestoreSQLFuncForSTableQuery(pQueryInfo);
  tscFieldInfoUpdateOffset(pQueryInfo);
H
hjxilinx 已提交
1358 1359 1360 1361
}

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

1363
  SJoinSupporter* pSupporter = (SJoinSupporter*)param;
H
Haojun Liao 已提交
1364
  SSqlObj* pParentSql = pSupporter->pObj;
D
fix bug  
dapan1121 已提交
1365
  
H
hjxilinx 已提交
1366
  // There is only one subquery and table for each subquery.
H
hjxilinx 已提交
1367
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
D
fix bug  
dapan1121 已提交
1368 1369
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);

H
hjxilinx 已提交
1370
  assert(pQueryInfo->numOfTables == 1 && pSql->cmd.numOfClause == 1);
H
hjxilinx 已提交
1371

H
Haojun Liao 已提交
1372 1373 1374 1375
  // 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);
H
Haojun Liao 已提交
1376
    tscAsyncResultOnError(pParentSql);
H
hjxilinx 已提交
1377

H
Haojun Liao 已提交
1378 1379
    return;
  }
H
hjxilinx 已提交
1380

H
Haojun Liao 已提交
1381 1382 1383
  // TODO here retry is required, not directly returns to client
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(taos_errno(pSql) == code);
H
hjxilinx 已提交
1384

1385
    tscError("%p abort query, code:%s, global code:%s", pSql, tstrerror(code), tstrerror(pParentSql->res.code));
H
Haojun Liao 已提交
1386 1387
    pParentSql->res.code = code;
    quitAllSubquery(pParentSql, pSupporter);
H
Haojun Liao 已提交
1388
    tscAsyncResultOnError(pParentSql);
H
Haojun Liao 已提交
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408

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

1409 1410 1411 1412 1413
  // 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 已提交
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
  }

  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 已提交
1430
    } else {
H
Haojun Liao 已提交
1431
      tscAsyncResultOnError(pParentSql);
H
hjxilinx 已提交
1432 1433 1434 1435 1436 1437 1438
    }
  }
}

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

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

H
Haojun Liao 已提交
1441
int32_t tscCreateJoinSubquery(SSqlObj *pSql, int16_t tableIndex, SJoinSupporter *pSupporter) {
H
hjxilinx 已提交
1442 1443 1444 1445
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  
  pSql->res.qhandle = 0x1;
H
Haojun Liao 已提交
1446 1447
  assert(pSql->res.numOfRows == 0);

H
hjxilinx 已提交
1448
  if (pSql->pSubs == NULL) {
H
Haojun Liao 已提交
1449
    pSql->pSubs = calloc(pSql->subState.numOfSub, POINTER_BYTES);
H
hjxilinx 已提交
1450
    if (pSql->pSubs == NULL) {
1451
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1452 1453 1454
    }
  }
  
1455
  SSqlObj *pNew = createSubqueryObj(pSql, tableIndex, tscJoinQueryCallback, pSupporter, TSDB_SQL_SELECT, NULL);
H
hjxilinx 已提交
1456
  if (pNew == NULL) {
1457
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1458 1459
  }
  
H
Haojun Liao 已提交
1460 1461
  pSql->pSubs[pSql->subState.numOfRemain++] = pNew;
  assert(pSql->subState.numOfRemain <= pSql->subState.numOfSub);
H
hjxilinx 已提交
1462 1463 1464 1465 1466 1467 1468 1469
  
  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);
    
1470 1471 1472 1473 1474 1475 1476
    // 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 已提交
1477 1478 1479 1480 1481 1482 1483
    pSupporter->colList = pNewQueryInfo->colList;
    pNewQueryInfo->colList = NULL;
    
    pSupporter->exprList = pNewQueryInfo->exprList;
    pNewQueryInfo->exprList = NULL;
    
    pSupporter->fieldsInfo = pNewQueryInfo->fieldsInfo;
H
hjxilinx 已提交
1484
  
H
hjxilinx 已提交
1485 1486
    // this data needs to be transfer to support struct
    memset(&pNewQueryInfo->fieldsInfo, 0, sizeof(SFieldInfo));
H
Haojun Liao 已提交
1487 1488 1489
    if (tscTagCondCopy(&pSupporter->tagCond, &pNewQueryInfo->tagCond) != 0) {
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
    }
H
Haojun Liao 已提交
1490

H
Haojun Liao 已提交
1491 1492 1493
    pSupporter->groupInfo = pNewQueryInfo->groupbyExpr;
    memset(&pNewQueryInfo->groupbyExpr, 0, sizeof(SSqlGroupbyExpr));

H
hjxilinx 已提交
1494
    pNew->cmd.numOfCols = 0;
1495
    pNewQueryInfo->interval.interval = 0;
H
Haojun Liao 已提交
1496 1497 1498 1499 1500
    pSupporter->limit = pNewQueryInfo->limit;

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

H
hjxilinx 已提交
1501 1502 1503
    // backup the data and clear it in the sqlcmd object
    memset(&pNewQueryInfo->groupbyExpr, 0, sizeof(SSqlGroupbyExpr));
    
H
hjxilinx 已提交
1504
    tscInitQueryInfo(pNewQueryInfo);
H
hjxilinx 已提交
1505 1506
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pNewQueryInfo, 0);
    
weixin_48148422's avatar
weixin_48148422 已提交
1507
    if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) { // return the tableId & tag
H
Haojun Liao 已提交
1508
      SColumnIndex colIndex = {0};
H
Haojun Liao 已提交
1509 1510 1511 1512

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

1513
      int32_t tagColId = tscGetJoinTagColIdByUid(pTagCond, pTableMetaInfo->pTableMeta->id.uid);
H
Haojun Liao 已提交
1514 1515 1516
      SSchema* s = tscGetColumnSchemaById(pTableMetaInfo->pTableMeta, tagColId);

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

H
Haojun Liao 已提交
1518
      int16_t bytes = 0;
H
Haojun Liao 已提交
1519
      int16_t type  = 0;
H
Haojun Liao 已提交
1520 1521
      int32_t inter = 0;

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

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

1528 1529
      // set get tags query type
      TSDB_QUERY_SET_TYPE(pNewQueryInfo->type, TSDB_QUERY_TYPE_TAG_FILTER_QUERY);
H
Haojun Liao 已提交
1530
      tscAddSpecialColumnForSelect(pNewQueryInfo, 0, TSDB_FUNC_TID_TAG, &colIndex, &s1, TSDB_COL_TAG);
1531
      size_t numOfCols = taosArrayGetSize(pNewQueryInfo->colList);
1532
  
1533
      tscDebug(
1534
          "%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%d, transfer to tid_tag query to retrieve (tableId, tags), "
S
TD-1057  
Shengliang Guan 已提交
1535
          "exprInfo:%" PRIzu ", colList:%" PRIzu ", fieldsInfo:%d, tagIndex:%d, name:%s",
1536
          pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
H
Haojun Liao 已提交
1537
          numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, colIndex.columnIndex, pNewQueryInfo->pTableMetaInfo[0]->name);
1538 1539
    } else {
      SSchema      colSchema = {.type = TSDB_DATA_TYPE_BINARY, .bytes = 1};
H
Haojun Liao 已提交
1540 1541
      SColumnIndex colIndex = {0, PRIMARYKEY_TIMESTAMP_COL_INDEX};
      tscAddSpecialColumnForSelect(pNewQueryInfo, 0, TSDB_FUNC_TS_COMP, &colIndex, &colSchema, TSDB_COL_NORMAL);
1542 1543 1544 1545

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

H
Haojun Liao 已提交
1546
      if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
1547
        int16_t tagColId = tscGetJoinTagColIdByUid(&pSupporter->tagCond, pTableMetaInfo->pTableMeta->id.uid);
1548
        pExpr->param->i64 = tagColId;
H
Haojun Liao 已提交
1549 1550
        pExpr->numOfParams = 1;
      }
1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567

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

1568
      tscDebug(
B
Bomin Zhang 已提交
1569
          "%p subquery:%p tableIndex:%d, vgroupIndex:%d, type:%u, transfer to ts_comp query to retrieve timestamps, "
S
TD-1057  
Shengliang Guan 已提交
1570
          "exprInfo:%" PRIzu ", colList:%" PRIzu ", fieldsInfo:%d, name:%s",
1571 1572 1573
          pSql, pNew, tableIndex, pTableMetaInfo->vgroupIndex, pNewQueryInfo->type, tscSqlExprNumOfExprs(pNewQueryInfo),
          numOfCols, pNewQueryInfo->fieldsInfo.numOfOutput, pNewQueryInfo->pTableMetaInfo[0]->name);
    }
H
hjxilinx 已提交
1574
  } else {
H
hjxilinx 已提交
1575
    assert(0);
H
hjxilinx 已提交
1576 1577 1578 1579
    SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
    pNewQueryInfo->type |= TSDB_QUERY_TYPE_SUBQUERY;
  }

H
Haojun Liao 已提交
1580
  return TSDB_CODE_SUCCESS;
H
hjxilinx 已提交
1581 1582
}

H
Haojun Liao 已提交
1583
void tscHandleMasterJoinQuery(SSqlObj* pSql) {
H
hjxilinx 已提交
1584
  SSqlCmd* pCmd = &pSql->cmd;
H
Haojun Liao 已提交
1585 1586
  SSqlRes* pRes = &pSql->res;

H
hjxilinx 已提交
1587 1588
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  assert((pQueryInfo->type & TSDB_QUERY_TYPE_SUBQUERY) == 0);
1589

H
Haojun Liao 已提交
1590
  int32_t code = TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1591
  pSql->subState.numOfSub = pQueryInfo->numOfTables;
H
Haojun Liao 已提交
1592

H
Haojun Liao 已提交
1593 1594
  bool hasEmptySub = false;

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

H
Haojun Liao 已提交
1598
    SJoinSupporter *pSupporter = tscCreateJoinSupporter(pSql, i);
H
hjxilinx 已提交
1599 1600 1601
    
    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 已提交
1602 1603
      code = TSDB_CODE_TSC_OUT_OF_MEMORY;
      goto _error;
H
hjxilinx 已提交
1604 1605
    }
    
H
Haojun Liao 已提交
1606
    code = tscCreateJoinSubquery(pSql, i, pSupporter);
H
hjxilinx 已提交
1607 1608
    if (code != TSDB_CODE_SUCCESS) {  // failed to create subquery object, quit query
      tscDestroyJoinSupporter(pSupporter);
H
Haojun Liao 已提交
1609 1610 1611 1612 1613 1614 1615
      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 已提交
1616 1617 1618
      break;
    }
  }
H
Haojun Liao 已提交
1619

H
Haojun Liao 已提交
1620 1621 1622 1623 1624
  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 已提交
1625
    for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
Haojun Liao 已提交
1626 1627
      SSqlObj* pSub = pSql->pSubs[i];
      if ((code = tscProcessSql(pSub)) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1628
        pSql->subState.numOfRemain = i - 1;  // the already sent request will continue and do not go to the error process routine
H
Haojun Liao 已提交
1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639
        break;
      }
    }

    pSql->cmd.command = TSDB_SQL_TABLE_JOIN_RETRIEVE;
  }

  return;

  _error:
  pRes->code = code;
H
Haojun Liao 已提交
1640
  tscAsyncResultOnError(pSql);
H
hjxilinx 已提交
1641 1642
}

H
Haojun Liao 已提交
1643 1644
static void doCleanupSubqueries(SSqlObj *pSql, int32_t numOfSubs) {
  assert(numOfSubs <= pSql->subState.numOfSub && numOfSubs >= 0);
H
hjxilinx 已提交
1645 1646 1647 1648 1649 1650 1651
  
  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 已提交
1652 1653
    tfree(pSupport->localBuffer);
    tfree(pSupport);
H
hjxilinx 已提交
1654
    
1655
    taos_free_result(pSub);
H
hjxilinx 已提交
1656 1657 1658
  }
}

D
TD-2516  
dapan1121 已提交
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
void tscLockByThread(int64_t *lockedBy) {
  int64_t tid = taosGetSelfPthreadId();
  int     i = 0;
  while (atomic_val_compare_exchange_64(lockedBy, 0, tid) != 0) {
    if (++i % 100 == 0) {
      sched_yield();
    }
  }
}

void tscUnlockByThread(int64_t *lockedBy) {
  int64_t tid = taosGetSelfPthreadId();
  if (atomic_val_compare_exchange_64(lockedBy, tid, 0) != tid) {
    assert(false);
  }
}



H
hjxilinx 已提交
1678 1679 1680 1681 1682
int32_t tscHandleMasterSTableQuery(SSqlObj *pSql) {
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;
  
  // pRes->code check only serves in launching metric sub-queries
1683
  if (pRes->code == TSDB_CODE_TSC_QUERY_CANCELLED) {
H
hjxilinx 已提交
1684
    pCmd->command = TSDB_SQL_RETRIEVE_LOCALMERGE;  // enable the abort of kill super table function.
H
hjxilinx 已提交
1685 1686 1687 1688
    return pRes->code;
  }
  
  tExtMemBuffer **  pMemoryBuf = NULL;
H
Haojun Liao 已提交
1689 1690
  tOrderDescriptor *pDesc  = NULL;
  SColumnModel     *pModel = NULL;
H
Haojun Liao 已提交
1691
  SColumnModel     *pFinalModel = NULL;
H
Haojun Liao 已提交
1692

H
Haojun Liao 已提交
1693
  pRes->qhandle = 0x1;  // hack the qhandle check
H
hjxilinx 已提交
1694
  
H
Haojun Liao 已提交
1695
  const uint32_t nBufferSize = (1u << 16u);  // 64KB
H
hjxilinx 已提交
1696
  
H
Haojun Liao 已提交
1697
  SQueryInfo     *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
1698
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
H
Haojun Liao 已提交
1699 1700
  SSubqueryState *pState = &pSql->subState;

H
Haojun Liao 已提交
1701 1702 1703 1704
  pState->numOfSub = 0;
  if (pTableMetaInfo->pVgroupTables == NULL) {
    pState->numOfSub = pTableMetaInfo->vgroupList->numOfVgroups;
  } else {
S
Shengliang Guan 已提交
1705
    pState->numOfSub = (int32_t)taosArrayGetSize(pTableMetaInfo->pVgroupTables);
H
Haojun Liao 已提交
1706 1707
  }

H
Haojun Liao 已提交
1708
  assert(pState->numOfSub > 0);
H
hjxilinx 已提交
1709
  
H
Haojun Liao 已提交
1710
  int32_t ret = tscLocalReducerEnvCreate(pSql, &pMemoryBuf, &pDesc, &pModel, &pFinalModel, nBufferSize);
H
hjxilinx 已提交
1711
  if (ret != 0) {
1712
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
Haojun Liao 已提交
1713
    tscAsyncResultOnError(pSql);
S
TD-1848  
Shengliang Guan 已提交
1714
    tfree(pMemoryBuf);
H
hjxilinx 已提交
1715
    return ret;
H
hjxilinx 已提交
1716 1717
  }
  
H
Haojun Liao 已提交
1718
  pSql->pSubs = calloc(pState->numOfSub, POINTER_BYTES);
H
Haojun Liao 已提交
1719

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

H
Haojun Liao 已提交
1722
  if (pSql->pSubs == NULL) {
S
TD-1848  
Shengliang Guan 已提交
1723
    tfree(pSql->pSubs);
H
Haojun Liao 已提交
1724
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
Haojun Liao 已提交
1725
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pFinalModel,pState->numOfSub);
H
Haojun Liao 已提交
1726

H
Haojun Liao 已提交
1727
    tscAsyncResultOnError(pSql);
H
Haojun Liao 已提交
1728 1729 1730
    return ret;
  }

H
Haojun Liao 已提交
1731
  pState->numOfRemain = pState->numOfSub;
H
hjxilinx 已提交
1732 1733 1734
  pRes->code = TSDB_CODE_SUCCESS;
  
  int32_t i = 0;
H
Haojun Liao 已提交
1735
  for (; i < pState->numOfSub; ++i) {
H
hjxilinx 已提交
1736 1737 1738 1739 1740 1741 1742 1743
    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 已提交
1744

H
hjxilinx 已提交
1745 1746 1747
    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 已提交
1748
      tfree(trs);
H
hjxilinx 已提交
1749 1750 1751
      break;
    }
    
H
Haojun Liao 已提交
1752 1753
    trs->subqueryIndex  = i;
    trs->pParentSql     = pSql;
H
hjxilinx 已提交
1754
    trs->pFinalColModel = pModel;
H
Haojun Liao 已提交
1755
    trs->pFFColModel    = pFinalModel;
H
Haojun Liao 已提交
1756

1757
    SSqlObj *pNew = tscCreateSTableSubquery(pSql, trs, NULL);
H
hjxilinx 已提交
1758 1759
    if (pNew == NULL) {
      tscError("%p failed to malloc buffer for subObj, orderOfSub:%d, reason:%s", pSql, i, strerror(errno));
S
TD-1848  
Shengliang Guan 已提交
1760 1761
      tfree(trs->localBuffer);
      tfree(trs);
H
hjxilinx 已提交
1762 1763 1764 1765 1766 1767 1768
      break;
    }
    
    // todo handle multi-vnode situation
    if (pQueryInfo->tsBuf) {
      SQueryInfo *pNewQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
      pNewQueryInfo->tsBuf = tsBufClone(pQueryInfo->tsBuf);
H
Haojun Liao 已提交
1769
      assert(pNewQueryInfo->tsBuf != NULL);
H
hjxilinx 已提交
1770 1771
    }
    
1772
    tscDebug("%p sub:%p create subquery success. orderOfSub:%d", pSql, pNew, trs->subqueryIndex);
H
hjxilinx 已提交
1773 1774
  }
  
H
Haojun Liao 已提交
1775
  if (i < pState->numOfSub) {
H
hjxilinx 已提交
1776
    tscError("%p failed to prepare subquery structure and launch subqueries", pSql);
1777
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
1778
    
H
Haojun Liao 已提交
1779
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pFinalModel, pState->numOfSub);
H
Haojun Liao 已提交
1780
    doCleanupSubqueries(pSql, i);
H
hjxilinx 已提交
1781 1782 1783
    return pRes->code;   // free all allocated resource
  }
  
1784
  if (pRes->code == TSDB_CODE_TSC_QUERY_CANCELLED) {
H
Haojun Liao 已提交
1785
    tscLocalReducerEnvDestroy(pMemoryBuf, pDesc, pModel, pFinalModel, pState->numOfSub);
H
Haojun Liao 已提交
1786
    doCleanupSubqueries(pSql, i);
H
hjxilinx 已提交
1787 1788 1789
    return pRes->code;
  }
  
H
Haojun Liao 已提交
1790
  for(int32_t j = 0; j < pState->numOfSub; ++j) {
H
hjxilinx 已提交
1791 1792 1793
    SSqlObj* pSub = pSql->pSubs[j];
    SRetrieveSupport* pSupport = pSub->param;
    
1794
    tscDebug("%p sub:%p launch subquery, orderOfSub:%d.", pSql, pSub, pSupport->subqueryIndex);
H
hjxilinx 已提交
1795 1796
    tscProcessSql(pSub);
  }
H
Haojun Liao 已提交
1797

H
hjxilinx 已提交
1798 1799 1800
  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
1801 1802
static void tscFreeRetrieveSup(SSqlObj *pSql) {
  SRetrieveSupport *trsupport = pSql->param;
1803

H
Haojun Liao 已提交
1804 1805 1806 1807 1808 1809 1810
  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 已提交
1811 1812
  tfree(trsupport->localBuffer);
  tfree(trsupport);
H
hjxilinx 已提交
1813 1814
}

1815
static void tscRetrieveFromDnodeCallBack(void *param, TAOS_RES *tres, int numOfRows);
1816
static void tscHandleSubqueryError(SRetrieveSupport *trsupport, SSqlObj *pSql, int numOfRows);
H
hjxilinx 已提交
1817

H
Haojun Liao 已提交
1818
static void tscAbortFurtherRetryRetrieval(SRetrieveSupport *trsupport, TAOS_RES *tres, int32_t code) {
H
hjxilinx 已提交
1819
// set no disk space error info
1820
  tscError("sub:%p failed to flush data to disk, reason:%s", tres, tstrerror(code));
H
Haojun Liao 已提交
1821
  SSqlObj* pParentSql = trsupport->pParentSql;
H
Haojun Liao 已提交
1822 1823

  pParentSql->res.code = code;
H
hjxilinx 已提交
1824
  trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
H
Haojun Liao 已提交
1825
  tscHandleSubqueryError(trsupport, tres, pParentSql->res.code);
H
hjxilinx 已提交
1826 1827
}

H
Haojun Liao 已提交
1828 1829 1830 1831 1832 1833 1834 1835
/*
 * 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 已提交
1836 1837
  STableMetaInfo* pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
  SVgroupInfo* pVgroup = &pTableMetaInfo->vgroupList->vgroups[0];
H
Haojun Liao 已提交
1838 1839 1840 1841 1842

  tExtMemBufferClear(trsupport->pExtMemBuffer[subqueryIndex]);

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

1846
  SSqlObj *pNew = tscCreateSTableSubquery(trsupport->pParentSql, trsupport, pSql);
H
Haojun Liao 已提交
1847
  if (pNew == NULL) {
1848 1849
    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 已提交
1850

1851
    pParentSql->res.code = terrno;
H
Haojun Liao 已提交
1852 1853 1854 1855 1856
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;

    return pParentSql->res.code;
  }

1857 1858 1859 1860 1861
  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 已提交
1862 1863 1864
    return ret;
  } else {
    return ret;
1865
  }
H
Haojun Liao 已提交
1866 1867
}

1868
void tscHandleSubqueryError(SRetrieveSupport *trsupport, SSqlObj *pSql, int numOfRows) {
H
Haojun Liao 已提交
1869 1870 1871 1872 1873
  // it has been freed already
  if (pSql->param != trsupport || pSql->param == NULL) {
    return;
  }

H
Haojun Liao 已提交
1874
  SSqlObj *pParentSql = trsupport->pParentSql;
H
hjxilinx 已提交
1875 1876 1877
  int32_t  subqueryIndex = trsupport->subqueryIndex;
  
  assert(pSql != NULL);
H
Haojun Liao 已提交
1878

H
Haojun Liao 已提交
1879 1880
  SSubqueryState* pState = &pParentSql->subState;
  assert(pState->numOfRemain <= pState->numOfSub && pState->numOfRemain >= 0);
H
Haojun Liao 已提交
1881

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

H
hjxilinx 已提交
1885 1886
    /*
     * kill current sub-query connection, which may retrieve data from vnodes;
1887
     * Here we get: pPObj->res.code == TSDB_CODE_TSC_QUERY_CANCELLED
H
hjxilinx 已提交
1888 1889 1890
     */
    pSql->res.numOfRows = 0;
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;  // disable retry efforts
1891 1892
    tscDebug("%p query is cancelled, sub:%p, orderOfSub:%d abort retrieve, code:%s", pParentSql, pSql,
             subqueryIndex, tstrerror(pParentSql->res.code));
H
hjxilinx 已提交
1893
  }
H
Haojun Liao 已提交
1894

H
hjxilinx 已提交
1895
  if (numOfRows >= 0) {  // current query is successful, but other sub query failed, still abort current query.
1896
    tscDebug("%p sub:%p retrieve numOfRows:%d,orderOfSub:%d", pParentSql, pSql, numOfRows, subqueryIndex);
1897 1898
    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 已提交
1899
  } else {
H
Haojun Liao 已提交
1900
    if (trsupport->numOfRetry++ < MAX_NUM_OF_SUBQUERY_RETRY && pParentSql->res.code == TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1901
      if (tscReissueSubquery(trsupport, pSql, numOfRows) == TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1902 1903 1904
        return;
      }
    } else {  // reach the maximum retry count, abort
H
Haojun Liao 已提交
1905 1906 1907
      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 已提交
1908 1909
    }
  }
H
Haojun Liao 已提交
1910

H
Haojun Liao 已提交
1911 1912
  int32_t remain = -1;
  if ((remain = atomic_sub_fetch_32(&pState->numOfRemain, 1)) > 0) {
1913
    tscDebug("%p sub:%p orderOfSub:%d freed, finished subqueries:%d", pParentSql, pSql, trsupport->subqueryIndex,
H
Haojun Liao 已提交
1914
        pState->numOfSub - remain);
H
Haojun Liao 已提交
1915

H
Haojun Liao 已提交
1916
    tscFreeRetrieveSup(pSql);
S
Shengliang Guan 已提交
1917
    return;
H
hjxilinx 已提交
1918 1919 1920
  }
  
  // all subqueries are failed
H
Haojun Liao 已提交
1921
  tscError("%p retrieve from %d vnode(s) completed,code:%s.FAILED.", pParentSql, pState->numOfSub,
H
Haojun Liao 已提交
1922 1923
      tstrerror(pParentSql->res.code));

H
hjxilinx 已提交
1924
  // release allocated resource
H
Haojun Liao 已提交
1925
  tscLocalReducerEnvDestroy(trsupport->pExtMemBuffer, trsupport->pOrderDescriptor, trsupport->pFinalColModel, trsupport->pFFColModel,
H
Haojun Liao 已提交
1926
                            pState->numOfSub);
H
hjxilinx 已提交
1927
  
H
Haojun Liao 已提交
1928
  tscFreeRetrieveSup(pSql);
1929

H
hjxilinx 已提交
1930
  // in case of second stage join subquery, invoke its callback function instead of regular QueueAsyncRes
1931 1932 1933 1934 1935 1936
  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) {
H
Haojun Liao 已提交
1937
      tscAsyncResultOnError(pParentSql);
1938 1939
    }
  }
H
hjxilinx 已提交
1940 1941
}

1942 1943
static void tscAllDataRetrievedFromDnode(SRetrieveSupport *trsupport, SSqlObj* pSql) {
  int32_t           idx = trsupport->subqueryIndex;
H
Haojun Liao 已提交
1944
  SSqlObj *         pParentSql = trsupport->pParentSql;
1945 1946
  tOrderDescriptor *pDesc = trsupport->pOrderDescriptor;
  
H
Haojun Liao 已提交
1947
  SSubqueryState* pState = &pParentSql->subState;
1948 1949
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
  
1950 1951
  STableMetaInfo* pTableMetaInfo = pQueryInfo->pTableMetaInfo[0];
  
1952
  // data in from current vnode is stored in cache and disk
S
Shengliang Guan 已提交
1953
  uint32_t numOfRowsFromSubquery = (uint32_t)(trsupport->pExtMemBuffer[idx]->numOfTotalElems + trsupport->localBuffer->num);
H
Haojun Liao 已提交
1954 1955 1956
  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);
1957 1958 1959 1960
  
  tColModelCompact(pDesc->pColumnModel, trsupport->localBuffer, pDesc->pColumnModel->capacity);

#ifdef _DEBUG_VIEW
1961
  printf("%" PRIu64 " rows data flushed to disk:\n", trsupport->localBuffer->num);
1962 1963
    SSrcColumnInfo colInfo[256] = {0};
    tscGetSrcColumnInfo(colInfo, pQueryInfo);
1964 1965
    tColModelDisplayEx(pDesc->pColumnModel, trsupport->localBuffer->data, trsupport->localBuffer->num,
                       trsupport->localBuffer->num, colInfo);
1966 1967
#endif
  
H
Haojun Liao 已提交
1968 1969 1970
  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 已提交
1971 1972
    tscAbortFurtherRetryRetrieval(trsupport, pSql, TSDB_CODE_TSC_NO_DISKSPACE);
    return;
1973 1974 1975
  }
  
  // each result for a vnode is ordered as an independant list,
H
Haojun Liao 已提交
1976
  // then used as an input of loser tree for disk-based merge
1977 1978
  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 已提交
1979 1980
    tscAbortFurtherRetryRetrieval(trsupport, pSql, code);
    return;
1981 1982
  }
  
H
Haojun Liao 已提交
1983
  int32_t remain = -1;
H
Haojun Liao 已提交
1984
  if ((remain = atomic_sub_fetch_32(&pParentSql->subState.numOfRemain, 1)) > 0) {
H
Haojun Liao 已提交
1985
    tscDebug("%p sub:%p orderOfSub:%d freed, finished subqueries:%d", pParentSql, pSql, trsupport->subqueryIndex,
H
Haojun Liao 已提交
1986
        pState->numOfSub - remain);
H
Haojun Liao 已提交
1987

H
Haojun Liao 已提交
1988
    tscFreeRetrieveSup(pSql);
S
Shengliang Guan 已提交
1989
    return;
1990 1991 1992 1993 1994
  }
  
  // all sub-queries are returned, start to local merge process
  pDesc->pColumnModel->capacity = trsupport->pExtMemBuffer[idx]->numOfElemsPerPage;
  
H
Haojun Liao 已提交
1995
  tscDebug("%p retrieve from %d vnodes completed.final NumOfRows:%" PRId64 ",start to build loser tree", pParentSql,
H
Haojun Liao 已提交
1996
           pState->numOfSub, pState->numOfRetrievedRows);
1997
  
H
Haojun Liao 已提交
1998
  SQueryInfo *pPQueryInfo = tscGetQueryInfoDetail(&pParentSql->cmd, 0);
1999 2000
  tscClearInterpInfo(pPQueryInfo);
  
H
Haojun Liao 已提交
2001
  tscCreateLocalReducer(trsupport->pExtMemBuffer, pState->numOfSub, pDesc, trsupport->pFinalColModel, trsupport->pFFColModel, pParentSql);
H
Haojun Liao 已提交
2002
  tscDebug("%p build loser tree completed", pParentSql);
2003
  
H
Haojun Liao 已提交
2004 2005 2006
  pParentSql->res.precision = pSql->res.precision;
  pParentSql->res.numOfRows = 0;
  pParentSql->res.row = 0;
2007
  
H
Haojun Liao 已提交
2008
  tscFreeRetrieveSup(pSql);
H
Haojun Liao 已提交
2009

2010 2011 2012 2013 2014
  // 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 {
H
Haojun Liao 已提交
2015
    tscAsyncResultOnError(pParentSql);
2016
  }
2017 2018 2019
}

static void tscRetrieveFromDnodeCallBack(void *param, TAOS_RES *tres, int numOfRows) {
H
Haojun Liao 已提交
2020 2021 2022 2023
  SSqlObj *pSql = (SSqlObj *)tres;
  assert(pSql != NULL);

  // this query has been freed already
H
hjxilinx 已提交
2024
  SRetrieveSupport *trsupport = (SRetrieveSupport *)param;
H
Haojun Liao 已提交
2025 2026 2027 2028 2029 2030
  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 已提交
2031
  tOrderDescriptor *pDesc = trsupport->pOrderDescriptor;
H
Haojun Liao 已提交
2032
  int32_t           idx   = trsupport->subqueryIndex;
H
Haojun Liao 已提交
2033
  SSqlObj *         pParentSql = trsupport->pParentSql;
H
Haojun Liao 已提交
2034

H
Haojun Liao 已提交
2035 2036
  SSubqueryState* pState = &pParentSql->subState;
  assert(pState->numOfRemain <= pState->numOfSub && pState->numOfRemain >= 0);
H
hjxilinx 已提交
2037
  
H
Haojun Liao 已提交
2038
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
S
TD-1732  
Shengliang Guan 已提交
2039
  SVgroupInfo  *pVgroup = &pTableMetaInfo->vgroupList->vgroups[0];
H
Haojun Liao 已提交
2040 2041 2042

  if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
2043
    tscDebug("%p query cancelled/failed, sub:%p, vgId:%d, orderOfSub:%d, code:%s, global code:%s",
H
Haojun Liao 已提交
2044 2045 2046 2047 2048 2049 2050 2051 2052
             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 已提交
2053 2054 2055 2056
    if (numOfRows == TSDB_CODE_TSC_QUERY_CANCELLED) {
      trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
    }

H
Haojun Liao 已提交
2057
    if (trsupport->numOfRetry++ < MAX_NUM_OF_SUBQUERY_RETRY) {
2058
      tscError("%p sub:%p failed code:%s, retry:%d", pParentSql, pSql, tstrerror(numOfRows), trsupport->numOfRetry);
H
Haojun Liao 已提交
2059 2060 2061 2062 2063

      if (tscReissueSubquery(trsupport, pSql, numOfRows) == TSDB_CODE_SUCCESS) {
        return;
      }
    } else {
H
Haojun Liao 已提交
2064
      tscDebug("%p sub:%p reach the max retry times, set global code:%s", pParentSql, pSql, tstrerror(numOfRows));
H
Haojun Liao 已提交
2065 2066 2067 2068 2069
      atomic_val_compare_exchange_32(&pParentSql->res.code, TSDB_CODE_SUCCESS, numOfRows);  // set global code and abort
    }

    tscHandleSubqueryError(param, tres, numOfRows);
    return;
H
hjxilinx 已提交
2070 2071 2072 2073 2074 2075 2076 2077 2078
  }
  
  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 已提交
2079
    tscDebug("%p sub:%p retrieve numOfRows:%d totalNumOfRows:%" PRIu64 " from ep:%s, orderOfSub:%d", pParentSql, pSql,
2080
             pRes->numOfRows, pState->numOfRetrievedRows, pSql->epSet.fqdn[pSql->epSet.inUse], idx);
2081

H
hjxilinx 已提交
2082
    if (num > tsMaxNumOfOrderedResults && tscIsProjectionQueryOnSTable(pQueryInfo, 0)) {
B
Bomin Zhang 已提交
2083
      tscError("%p sub:%p num of OrderedRes is too many, max allowed:%" PRId32 " , current:%" PRId64,
H
Haojun Liao 已提交
2084
               pParentSql, pSql, tsMaxNumOfOrderedResults, num);
S
Shengliang Guan 已提交
2085 2086
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_SORTED_RES_TOO_MANY);
      return;
H
hjxilinx 已提交
2087 2088 2089
    }

#ifdef _DEBUG_VIEW
2090
    printf("received data from vnode: %"PRIu64" rows\n", pRes->numOfRows);
H
hjxilinx 已提交
2091 2092 2093 2094 2095
    SSrcColumnInfo colInfo[256] = {0};

    tscGetSrcColumnInfo(colInfo, pQueryInfo);
    tColModelDisplayEx(pDesc->pColumnModel, pRes->data, pRes->numOfRows, pRes->numOfRows, colInfo);
#endif
2096
    
H
Haojun Liao 已提交
2097 2098 2099 2100
    // 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 已提交
2101 2102
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_NO_DISKSPACE);
      return;
H
hjxilinx 已提交
2103 2104 2105
    }
    
    int32_t ret = saveToBuffer(trsupport->pExtMemBuffer[idx], pDesc, trsupport->localBuffer, pRes->data,
H
Haojun Liao 已提交
2106
                               pRes->numOfRows, pQueryInfo->groupbyExpr.orderType);
2107
    if (ret != 0) { // set no disk space error info, and abort retry
2108
      tscAbortFurtherRetryRetrieval(trsupport, tres, TSDB_CODE_TSC_NO_DISKSPACE);
2109 2110 2111 2112
    } else if (pRes->completed) {
      tscAllDataRetrievedFromDnode(trsupport, pSql);
    } else { // continue fetch data from dnode
      taos_fetch_rows_a(tres, tscRetrieveFromDnodeCallBack, param);
H
hjxilinx 已提交
2113
    }
2114
    
2115 2116
  } else { // all data has been retrieved to client
    tscAllDataRetrievedFromDnode(trsupport, pSql);
H
hjxilinx 已提交
2117 2118 2119
  }
}

2120
static SSqlObj *tscCreateSTableSubquery(SSqlObj *pSql, SRetrieveSupport *trsupport, SSqlObj *prevSqlObj) {
H
hjxilinx 已提交
2121 2122
  const int32_t table_index = 0;
  
2123
  SSqlObj *pNew = createSubqueryObj(pSql, table_index, tscRetrieveDataRes, trsupport, TSDB_SQL_SELECT, prevSqlObj);
H
hjxilinx 已提交
2124 2125
  if (pNew != NULL) {  // the sub query of two-stage super table query
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pNew->cmd, 0);
2126

H
hjxilinx 已提交
2127
    pQueryInfo->type |= TSDB_QUERY_TYPE_STABLE_SUBQUERY;
H
Haojun Liao 已提交
2128
    assert(pQueryInfo->numOfTables == 1 && pNew->cmd.numOfClause == 1 && trsupport->subqueryIndex < pSql->subState.numOfSub);
H
hjxilinx 已提交
2129
    
H
hjxilinx 已提交
2130
    // launch subquery for each vnode, so the subquery index equals to the vgroupIndex.
H
hjxilinx 已提交
2131
    STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, table_index);
H
hjxilinx 已提交
2132
    pTableMetaInfo->vgroupIndex = trsupport->subqueryIndex;
H
hjxilinx 已提交
2133 2134 2135 2136 2137 2138 2139
    
    pSql->pSubs[trsupport->subqueryIndex] = pNew;
  }
  
  return pNew;
}

2140
// todo there is are race condition in this function, while cancel is called by user.
H
hjxilinx 已提交
2141
void tscRetrieveDataRes(void *param, TAOS_RES *tres, int code) {
2142 2143 2144 2145 2146 2147 2148
  // the param may be null, since it may be done by other query threads. and the asyncOnError may enter in this
  // function while kill query by a user.
  if (param == NULL) {
    assert(code != TSDB_CODE_SUCCESS);
    return;
  }

2149
  SRetrieveSupport *trsupport = (SRetrieveSupport *) param;
H
hjxilinx 已提交
2150
  
H
Haojun Liao 已提交
2151
  SSqlObj*  pParentSql = trsupport->pParentSql;
2152
  SSqlObj*  pSql = (SSqlObj *) tres;
2153

2154 2155
  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
  assert(pSql->cmd.numOfClause == 1 && pQueryInfo->numOfTables == 1);
H
hjxilinx 已提交
2156
  
2157
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
S
TD-1732  
Shengliang Guan 已提交
2158
  SVgroupInfo* pVgroup = &pTableMetaInfo->vgroupList->vgroups[trsupport->subqueryIndex];
H
Haojun Liao 已提交
2159

H
Haojun Liao 已提交
2160
  // stable query killed or other subquery failed, all query stopped
H
Haojun Liao 已提交
2161
  if (pParentSql->res.code != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
2162
    trsupport->numOfRetry = MAX_NUM_OF_SUBQUERY_RETRY;
H
Haojun Liao 已提交
2163
    tscError("%p query cancelled or failed, sub:%p, vgId:%d, orderOfSub:%d, code:%s, global code:%s",
H
Haojun Liao 已提交
2164 2165 2166 2167
        pParentSql, pSql, pVgroup->vgId, trsupport->subqueryIndex, tstrerror(code), tstrerror(pParentSql->res.code));

    tscHandleSubqueryError(param, tres, code);
    return;
H
hjxilinx 已提交
2168 2169 2170
  }
  
  /*
H
Haojun Liao 已提交
2171
   * if a subquery on a vnode failed, all retrieve operations from vnode that occurs later
2172
   * than this one are actually not necessary, we simply call the tscRetrieveFromDnodeCallBack
H
hjxilinx 已提交
2173 2174
   * function to abort current and remain retrieve process.
   *
2175
   * NOTE: thread safe is required.
H
hjxilinx 已提交
2176
   */
H
Haojun Liao 已提交
2177 2178
  if (taos_errno(pSql) != TSDB_CODE_SUCCESS) {
    assert(code == taos_errno(pSql));
2179

H
Haojun Liao 已提交
2180
    if (trsupport->numOfRetry++ < MAX_NUM_OF_SUBQUERY_RETRY) {
2181
      tscError("%p sub:%p failed code:%s, retry:%d", pParentSql, pSql, tstrerror(code), trsupport->numOfRetry);
H
Haojun Liao 已提交
2182
      if (tscReissueSubquery(trsupport, pSql, code) == TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
2183 2184
        return;
      }
2185
    } else {
H
Haojun Liao 已提交
2186
      tscError("%p sub:%p reach the max retry times, set global code:%s", pParentSql, pSql, tstrerror(code));
H
Haojun Liao 已提交
2187
      atomic_val_compare_exchange_32(&pParentSql->res.code, TSDB_CODE_SUCCESS, code);  // set global code and abort
2188
    }
H
Haojun Liao 已提交
2189 2190 2191 2192 2193

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

H
Haojun Liao 已提交
2194
  tscDebug("%p sub:%p query complete, ep:%s, vgId:%d, orderOfSub:%d, retrieve data", trsupport->pParentSql, pSql,
2195
             pVgroup->epAddr[0].fqdn, pVgroup->vgId, trsupport->subqueryIndex);
H
Haojun Liao 已提交
2196 2197 2198 2199 2200

  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 已提交
2201 2202 2203
  }
}

2204 2205
static bool needRetryInsert(SSqlObj* pParentObj, int32_t numOfSub) {
  if (pParentObj->retry > pParentObj->maxRetry) {
H
Haojun Liao 已提交
2206
    tscError("%p max retry reached, abort the retry effort", pParentObj);
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
    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 已提交
2227 2228 2229 2230 2231 2232 2233 2234 2235
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 已提交
2236
static void multiVnodeInsertFinalize(void* param, TAOS_RES* tres, int numOfRows) {
H
hjxilinx 已提交
2237 2238
  SInsertSupporter *pSupporter = (SInsertSupporter *)param;
  SSqlObj* pParentObj = pSupporter->pSql;
H
Haojun Liao 已提交
2239

H
Haojun Liao 已提交
2240
  // record the total inserted rows
H
Haojun Liao 已提交
2241 2242
  if (numOfRows > 0) {
    pParentObj->res.numOfRows += numOfRows;
H
Haojun Liao 已提交
2243 2244
  }

H
Haojun Liao 已提交
2245
  if (taos_errno(tres) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2246 2247 2248 2249
    SSqlObj* pSql = (SSqlObj*) tres;
    assert(pSql != NULL && pSql->res.code == numOfRows);
    
    pParentObj->res.code = pSql->res.code;
H
Haojun Liao 已提交
2250

2251 2252 2253 2254 2255
    // set the flag in the parent sqlObj
    if (pSql->cmd.submitSchema) {
      pParentObj->cmd.submitSchema = 1;
    }
  }
H
Haojun Liao 已提交
2256

H
Haojun Liao 已提交
2257
  if (atomic_sub_fetch_32(&pParentObj->subState.numOfRemain, 1) > 0) {
H
hjxilinx 已提交
2258 2259
    return;
  }
H
Haojun Liao 已提交
2260

H
hjxilinx 已提交
2261 2262
  // restore user defined fp
  pParentObj->fp = pParentObj->fetchFp;
2263
  int32_t numOfSub = pParentObj->subState.numOfSub;
2264
  doFreeInsertSupporter(pParentObj);
2265 2266 2267 2268 2269 2270 2271 2272 2273

  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 {
2274
    if (!needRetryInsert(pParentObj, numOfSub)) {
H
Haojun Liao 已提交
2275
      tscAsyncResultOnError(pParentObj);
2276 2277
      return;
    }
2278

2279
    int32_t numOfFailed = 0;
2280 2281 2282 2283 2284 2285
    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
2286
        tscFreeQueryInfo(&pSql->cmd);
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297
        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);

2298
    tscDebug("%p cleanup %d tableMeta in hashTable", pParentObj, pParentObj->cmd.numOfTables);
2299
    for(int32_t i = 0; i < pParentObj->cmd.numOfTables; ++i) {
2300 2301
      char* name = pParentObj->cmd.pTableNameList[i];
      taosHashRemove(tscTableMetaInfo, name, strnlen(name, TSDB_TABLE_FNAME_LEN));
2302
    }
2303

2304 2305 2306
    pParentObj->cmd.parseFinished = false;
    pParentObj->subState.numOfRemain = numOfFailed;

2307
    tscResetSqlCmdObj(&pParentObj->cmd);
2308

H
Haojun Liao 已提交
2309 2310 2311
    // 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.
S
TD-2475  
Shengliang Guan 已提交
2312 2313 2314
    tscDebug("%p re-parse sql to generate submit data, retry:%d", pParentObj, pParentObj->retry);
    pParentObj->retry++;

2315 2316 2317 2318 2319
    int32_t code = tsParseSql(pParentObj, true);
    if (code == TSDB_CODE_TSC_ACTION_IN_PROGRESS) return;

    if (code != TSDB_CODE_SUCCESS) {
      pParentObj->res.code = code;
H
Haojun Liao 已提交
2320
      tscAsyncResultOnError(pParentObj);
2321 2322 2323 2324 2325
      return;
    }

    tscDoQuery(pParentObj);
  }
2326 2327 2328 2329 2330 2331 2332
}

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

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

2340
  STableDataBlocks* pTableDataBlock = taosArrayGetP(pParent->cmd.pDataBlocks, pSupporter->index);
H
Haojun Liao 已提交
2341 2342 2343
  int32_t code = tscCopyDataBlockToPayload(pSql, pTableDataBlock);

  if ((pRes->code = code)!= TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2344
    tscAsyncResultOnError(pSql);
H
Haojun Liao 已提交
2345
    return code;  // here the pSql may have been released already.
2346 2347 2348
  }

  return tscProcessSql(pSql);
H
hjxilinx 已提交
2349 2350 2351 2352
}

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

2355 2356 2357 2358
  // 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];
2359 2360 2361
      SInsertSupporter* pSup = calloc(1, sizeof(SInsertSupporter));
      pSup->index = i;
      pSup->pSql = pSql;
2362

2363
      pSub->param = pSup;
2364 2365 2366 2367 2368 2369 2370 2371 2372
      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 已提交
2373 2374
  pSql->subState.numOfSub = (uint16_t)taosArrayGetSize(pCmd->pDataBlocks);
  assert(pSql->subState.numOfSub > 0);
H
Haojun Liao 已提交
2375 2376

  pRes->code = TSDB_CODE_SUCCESS;
2377

H
Haojun Liao 已提交
2378 2379 2380
  // the number of already initialized subqueries
  int32_t numOfSub = 0;

H
Haojun Liao 已提交
2381 2382
  pSql->subState.numOfRemain = pSql->subState.numOfSub;
  pSql->pSubs = calloc(pSql->subState.numOfSub, POINTER_BYTES);
H
Haojun Liao 已提交
2383 2384 2385 2386
  if (pSql->pSubs == NULL) {
    goto _error;
  }

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

H
Haojun Liao 已提交
2389
  while(numOfSub < pSql->subState.numOfSub) {
H
Haojun Liao 已提交
2390
    SInsertSupporter* pSupporter = calloc(1, sizeof(SInsertSupporter));
H
Haojun Liao 已提交
2391 2392 2393 2394
    if (pSupporter == NULL) {
      goto _error;
    }

2395 2396 2397 2398
    pSupporter->pSql   = pSql;
    pSupporter->index  = numOfSub;

    SSqlObj *pNew = createSimpleSubObj(pSql, multiVnodeInsertFinalize, pSupporter, TSDB_SQL_INSERT);
H
hjxilinx 已提交
2399
    if (pNew == NULL) {
H
Haojun Liao 已提交
2400
      tscError("%p failed to malloc buffer for subObj, orderOfSub:%d, reason:%s", pSql, numOfSub, strerror(errno));
H
Haojun Liao 已提交
2401
      goto _error;
H
hjxilinx 已提交
2402
    }
2403 2404 2405
  
    /*
     * assign the callback function to fetchFp to make sure that the error process function can restore
H
Haojun Liao 已提交
2406
     * the callback function (multiVnodeInsertFinalize) correctly.
2407 2408
     */
    pNew->fetchFp = pNew->fp;
H
Haojun Liao 已提交
2409
    pSql->pSubs[numOfSub] = pNew;
H
Haojun Liao 已提交
2410

2411 2412
    STableDataBlocks* pTableDataBlock = taosArrayGetP(pCmd->pDataBlocks, numOfSub);
    pRes->code = tscCopyDataBlockToPayload(pNew, pTableDataBlock);
H
Haojun Liao 已提交
2413
    if (pRes->code == TSDB_CODE_SUCCESS) {
2414
      tscDebug("%p sub:%p create subObj success. orderOfSub:%d", pSql, pNew, numOfSub);
2415
      numOfSub++;
H
Haojun Liao 已提交
2416
    } else {
H
Haojun Liao 已提交
2417
      tscDebug("%p prepare submit data block failed in async insertion, vnodeIdx:%d, total:%d, code:%s", pSql, numOfSub,
H
Haojun Liao 已提交
2418
               pSql->subState.numOfSub, tstrerror(pRes->code));
H
Haojun Liao 已提交
2419
      goto _error;
H
Haojun Liao 已提交
2420
    }
H
hjxilinx 已提交
2421 2422
  }
  
H
Haojun Liao 已提交
2423
  if (numOfSub < pSql->subState.numOfSub) {
H
hjxilinx 已提交
2424
    tscError("%p failed to prepare subObj structure and launch sub-insertion", pSql);
2425
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
Haojun Liao 已提交
2426
    goto _error;
H
hjxilinx 已提交
2427
  }
H
Haojun Liao 已提交
2428

2429 2430
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);

H
Haojun Liao 已提交
2431 2432
  // use the local variable
  for (int32_t j = 0; j < numOfSub; ++j) {
H
hjxilinx 已提交
2433
    SSqlObj *pSub = pSql->pSubs[j];
2434
    tscDebug("%p sub:%p launch sub insert, orderOfSub:%d", pSql, pSub, j);
H
hjxilinx 已提交
2435 2436
    tscProcessSql(pSub);
  }
H
Haojun Liao 已提交
2437

H
hjxilinx 已提交
2438
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
2439 2440 2441

  _error:
  return TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hjxilinx 已提交
2442
}
H
hjxilinx 已提交
2443

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

H
Haojun Liao 已提交
2447
  SInternalField* pInfo = (SInternalField*) TARRAY_GET_ELEM(pQueryInfo->fieldsInfo.internalField, columnIndex);
H
Haojun Liao 已提交
2448 2449 2450
  assert(pInfo->pSqlExpr != NULL);

  *bytes = pInfo->pSqlExpr->resBytes;
H
Haojun Liao 已提交
2451
  char* pData = pRes->data + pInfo->pSqlExpr->offset * pRes->numOfRows + pRes->row * (*bytes);
H
Haojun Liao 已提交
2452 2453 2454 2455 2456 2457 2458 2459 2460 2461

  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 已提交
2462
  for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
Haojun Liao 已提交
2463 2464
    SSqlObj* pSub = pSql->pSubs[i];
    if (pSub == NULL) {
H
Haojun Liao 已提交
2465 2466 2467
      continue;
    }

S
Shengliang Guan 已提交
2468
    int32_t remain = (int32_t)(pSub->res.numOfRows - pSub->res.row);
H
Haojun Liao 已提交
2469
    numOfRes = (int32_t)(MIN(numOfRes, remain));
H
Haojun Liao 已提交
2470 2471
  }

H
Haojun Liao 已提交
2472 2473
  if (numOfRes == 0) {  // no result any more, free all subquery objects
    freeJoinSubqueryObj(pSql);
H
Haojun Liao 已提交
2474 2475 2476
    return;
  }

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

H
Haojun Liao 已提交
2479 2480
  assert(numOfRes * rowSize > 0);
  char* tmp = realloc(pRes->pRsp, numOfRes * rowSize + sizeof(tFilePage));
H
Haojun Liao 已提交
2481 2482 2483 2484 2485 2486 2487
  if (tmp == NULL) {
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return;
  } else {
    pRes->pRsp = tmp;
  }

H
Haojun Liao 已提交
2488 2489
  tFilePage* pFilePage = (tFilePage*) pRes->pRsp;
  pFilePage->num = numOfRes;
H
Haojun Liao 已提交
2490

H
Haojun Liao 已提交
2491
  pRes->data = pFilePage->data;
H
Haojun Liao 已提交
2492
  char* data = pRes->data;
H
Haojun Liao 已提交
2493

H
Haojun Liao 已提交
2494 2495 2496 2497 2498
  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 已提交
2499 2500
    SSqlRes*      pRes1 = &pSql->pSubs[pIndex->tableIndex]->res;
    SSqlCmd*      pCmd1 = &pSql->pSubs[pIndex->tableIndex]->cmd;
H
Haojun Liao 已提交
2501 2502 2503 2504 2505

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

    data += bytes * numOfRes;
H
Haojun Liao 已提交
2506 2507 2508 2509 2510 2511 2512 2513 2514 2515
  }

  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 已提交
2516 2517 2518 2519
  }

  pRes->numOfRows = numOfRes;
  pRes->numOfClauseTotal += numOfRes;
H
Haojun Liao 已提交
2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530

  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 已提交
2531 2532
}

H
hjxilinx 已提交
2533
void tscBuildResFromSubqueries(SSqlObj *pSql) {
H
Haojun Liao 已提交
2534 2535
  SSqlRes* pRes = &pSql->res;

H
hjxilinx 已提交
2536
  if (pRes->code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
2537
    tscAsyncResultOnError(pSql);
H
hjxilinx 已提交
2538 2539
    return;
  }
H
Haojun Liao 已提交
2540 2541 2542

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

H
Haojun Liao 已提交
2545 2546 2547 2548
    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 已提交
2549

H
Haojun Liao 已提交
2550 2551
    if (pRes->tsrow == NULL || pRes->buffer == NULL || pRes->length == NULL) {
      pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
Haojun Liao 已提交
2552
      tscAsyncResultOnError(pSql);
H
Haojun Liao 已提交
2553 2554 2555
      return;
    }

H
Haojun Liao 已提交
2556 2557 2558
    tscRestoreSQLFuncForSTableQuery(pQueryInfo);
  }

H
Haojun Liao 已提交
2559 2560 2561 2562 2563
  assert (pRes->row >= pRes->numOfRows);
  doBuildResFromSubqueries(pSql);
  if (pRes->code == TSDB_CODE_SUCCESS) {
    (*pSql->fp)(pSql->param, pSql, pRes->numOfRows);
  } else {
H
Haojun Liao 已提交
2564
    tscAsyncResultOnError(pSql);
H
hjxilinx 已提交
2565 2566 2567
  }
}

2568
static UNUSED_FUNC void transferNcharData(SSqlObj *pSql, int32_t columnIndex, TAOS_FIELD *pField) {
H
hjxilinx 已提交
2569 2570
  SSqlRes *pRes = &pSql->res;
  
H
Haojun Liao 已提交
2571
  if (pRes->tsrow[columnIndex] != NULL && pField->type == TSDB_DATA_TYPE_NCHAR) {
H
hjxilinx 已提交
2572 2573 2574 2575 2576 2577 2578 2579
    // 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);
    
2580 2581
    int32_t length = taosUcs4ToMbs(pRes->tsrow[columnIndex], pRes->length[columnIndex], pRes->buffer[columnIndex]);
    if ( length >= 0 ) {
2582
      pRes->tsrow[columnIndex] = (unsigned char*)pRes->buffer[columnIndex];
2583
      pRes->length[columnIndex] = length;
H
hjxilinx 已提交
2584
    } else {
B
Bomin Zhang 已提交
2585
      tscError("%p charset:%s to %s. val:%s convert failed.", pSql, DEFAULT_UNICODE_ENCODEC, tsCharset, (char*)pRes->tsrow[columnIndex]);
H
hjxilinx 已提交
2586
      pRes->tsrow[columnIndex] = NULL;
2587
      pRes->length[columnIndex] = 0;
H
hjxilinx 已提交
2588 2589 2590 2591
    }
  }
}

H
Haojun Liao 已提交
2592
char *getArithmeticInputSrc(void *param, const char *name, int32_t colId) {
2593 2594 2595 2596 2597 2598 2599
  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 已提交
2600
    if (strncmp(name, pExpr->aliasName, sizeof(pExpr->aliasName) - 1) == 0) {
2601 2602 2603 2604 2605 2606 2607 2608 2609
      index = i;
      break;
    }
  }

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

2610
TAOS_ROW doSetResultRowData(SSqlObj *pSql) {
H
hjxilinx 已提交
2611 2612
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
H
Haojun Liao 已提交
2613

H
hjxilinx 已提交
2614 2615
  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 已提交
2616
    tfree(pRes->tsrow);
H
hjxilinx 已提交
2617 2618
    return pRes->tsrow;
  }
H
Haojun Liao 已提交
2619

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

H
Haojun Liao 已提交
2622 2623
  size_t size = tscNumOfFields(pQueryInfo);
  for (int i = 0; i < size; ++i) {
2624
    SInternalField* pInfo = (SInternalField*)TARRAY_GET_ELEM(pQueryInfo->fieldsInfo.internalField, i);
H
Haojun Liao 已提交
2625

H
Haojun Liao 已提交
2626
    int32_t type  = pInfo->field.type;
2627
    int32_t bytes = pInfo->field.bytes;
H
Haojun Liao 已提交
2628

2629 2630 2631 2632 2633
    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 已提交
2634
    }
H
Haojun Liao 已提交
2635

H
Haojun Liao 已提交
2636
    ((char**) pRes->urow)[i] += bytes;
H
hjxilinx 已提交
2637
  }
H
Haojun Liao 已提交
2638

H
hjxilinx 已提交
2639 2640 2641 2642
  pRes->row++;  // index increase one-step
  return pRes->tsrow;
}

H
Haojun Liao 已提交
2643
static UNUSED_FUNC bool tscHasRemainDataInSubqueryResultSet(SSqlObj *pSql) {
H
hjxilinx 已提交
2644 2645 2646 2647 2648 2649 2650
  bool     hasData = true;
  SSqlCmd *pCmd = &pSql->cmd;
  
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0)) {
    bool allSubqueryExhausted = true;
    
H
Haojun Liao 已提交
2651
    for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
      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 已提交
2677
    for (int32_t i = 0; i < pSql->subState.numOfSub; ++i) {
H
hjxilinx 已提交
2678 2679 2680 2681 2682 2683 2684 2685
      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 已提交
2686
          tscIsProjectionQuery(pQueryInfo1)) || (pRes1->numOfRows == 0)) {
H
hjxilinx 已提交
2687 2688 2689 2690 2691 2692 2693 2694
        hasData = false;
        break;
      }
    }
  }
  
  return hasData;
}