tscSql.c 34.9 KB
Newer Older
H
hzcheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * 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
hjxilinx 已提交
16
#include <tast.h>
H
hjxilinx 已提交
17
#include "hash.h"
H
hjxilinx 已提交
18
#include "os.h"
H
hzcheng 已提交
19 20
#include "tcache.h"
#include "tlog.h"
H
hjxilinx 已提交
21
#include "tnote.h"
H
hzcheng 已提交
22
#include "trpc.h"
S
slguan 已提交
23
#include "tscJoinProcess.h"
H
hzcheng 已提交
24
#include "tscProfile.h"
H
hjxilinx 已提交
25
#include "tscSQLParser.h"
H
hzcheng 已提交
26 27 28
#include "tscSecondaryMerge.h"
#include "tscUtil.h"
#include "tsclient.h"
S
slguan 已提交
29
#include "tscompression.h"
H
hzcheng 已提交
30 31 32 33
#include "tsocket.h"
#include "ttimer.h"
#include "tutil.h"

H
hjxilinx 已提交
34 35
TAOS *taos_connect_imp(const char *ip, const char *user, const char *pass, const char *db, uint16_t port,
                       void (*fp)(void *, TAOS_RES *, int), void *param, void **taos) {
H
hzcheng 已提交
36 37
  STscObj *pObj;

S
slguan 已提交
38

H
hzcheng 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
  taos_init();

  if (user == NULL) {
    globalCode = TSDB_CODE_INVALID_ACCT;
    return NULL;
  } else {
    size_t len = strlen(user);
    if (len <= 0 || len > TSDB_USER_LEN) {
      globalCode = TSDB_CODE_INVALID_ACCT;
      return NULL;
    }
  }

  if (pass == NULL) {
    globalCode = TSDB_CODE_INVALID_PASS;
    return NULL;
  } else {
    size_t len = strlen(pass);
    if (len <= 0 || len > TSDB_KEY_LEN) {
      globalCode = TSDB_CODE_INVALID_PASS;
      return NULL;
    }
  }

S
slguan 已提交
63 64 65 66 67
  if (tscInitRpc(user, pass) != 0) {
    globalCode = TSDB_CODE_NETWORK_UNAVAIL;
    return NULL;
  }

S
slguan 已提交
68
  if (ip && ip[0]) {
S
slguan 已提交
69
    tscMgmtIpList.inUse = 0;
S
slguan 已提交
70
    tscMgmtIpList.port = tsMnodeShellPort;
S
slguan 已提交
71
    tscMgmtIpList.numOfIps = 1;
S
slguan 已提交
72
    tscMgmtIpList.ip[0] = inet_addr(ip);
S
slguan 已提交
73 74 75 76 77 78 79

    if (tsMasterIp[0] && strcmp(ip, tsMasterIp) != 0) {
      tscMgmtIpList.numOfIps = 2;
      tscMgmtIpList.ip[1] = inet_addr(tsMasterIp);
    }

    if (tsSecondIp[0] && strcmp(tsSecondIp, tsMasterIp) != 0) {
S
slguan 已提交
80 81 82
      tscMgmtIpList.numOfIps = 3;
      tscMgmtIpList.ip[2] = inet_addr(tsSecondIp);
    }
S
slguan 已提交
83
  }
H
hzcheng 已提交
84

S
slguan 已提交
85
  tscMgmtIpList.port = port ? port : tsMnodeShellPort;
S
slguan 已提交
86

H
hzcheng 已提交
87
  pObj = (STscObj *)malloc(sizeof(STscObj));
S
slguan 已提交
88 89 90 91
  if (NULL == pObj) {
    globalCode = TSDB_CODE_CLI_OUT_OF_MEMORY;
    return NULL;
  }
H
hjxilinx 已提交
92

H
hzcheng 已提交
93 94 95 96
  memset(pObj, 0, sizeof(STscObj));
  pObj->signature = pObj;

  strncpy(pObj->user, user, TSDB_USER_LEN);
S
slguan 已提交
97
  taosEncryptPass((uint8_t *)pass, strlen(pass), pObj->pass);
S
slguan 已提交
98
  pObj->mgmtPort = port ? port : tsMnodeShellPort;
H
hzcheng 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112

  if (db) {
    int32_t len = strlen(db);
    /* db name is too long */
    if (len > TSDB_DB_NAME_LEN) {
      free(pObj);
      globalCode = TSDB_CODE_INVALID_DB;
      return NULL;
    }

    char tmp[TSDB_DB_NAME_LEN + 1] = {0};
    strcpy(tmp, db);

    strdequote(tmp);
S
slguan 已提交
113
    strtolower(pObj->db, tmp);
H
hzcheng 已提交
114 115 116 117 118
  }

  pthread_mutex_init(&pObj->mutex, NULL);

  SSqlObj *pSql = (SSqlObj *)malloc(sizeof(SSqlObj));
S
slguan 已提交
119 120 121 122 123
  if (NULL == pSql) {
    globalCode = TSDB_CODE_CLI_OUT_OF_MEMORY;
    free(pObj);
    return NULL;
  }
H
hjxilinx 已提交
124

H
hzcheng 已提交
125 126 127
  memset(pSql, 0, sizeof(SSqlObj));
  pSql->pTscObj = pObj;
  pSql->signature = pSql;
S
slguan 已提交
128 129
  tsem_init(&pSql->rspSem, 0, 0);
  tsem_init(&pSql->emptyRspSem, 0, 1);
H
hzcheng 已提交
130 131 132 133 134 135 136 137
  pObj->pSql = pSql;
  pSql->fp = fp;
  pSql->param = param;
  if (taos != NULL) {
    *taos = pObj;
  }

  pSql->cmd.command = TSDB_SQL_CONNECT;
138
  if (TSDB_CODE_SUCCESS != tscAllocPayload(&pSql->cmd, TSDB_DEFAULT_PAYLOAD_SIZE)) {
S
slguan 已提交
139 140 141 142 143
    globalCode = TSDB_CODE_CLI_OUT_OF_MEMORY;
    free(pSql);
    free(pObj);
    return NULL;
  }
H
hzcheng 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159

  pSql->res.code = tscProcessSql(pSql);
  if (fp != NULL) {
    tscTrace("%p DB async connection is opening", pObj);
    return pObj;
  }

  if (pSql->res.code) {
    taos_close(pObj);
    return NULL;
  }

  tscTrace("%p DB connection is opened", pObj);
  return pObj;
}

L
lihui 已提交
160
TAOS *taos_connect(const char *ip, const char *user, const char *pass, const char *db, uint16_t port) {
161
  if (ip == NULL || (ip != NULL && (strcmp("127.0.0.1", ip) == 0 || strcasecmp("localhost", ip) == 0))) {
S
slguan 已提交
162
    ip = tsMasterIp;
H
hzcheng 已提交
163 164 165 166 167
  }
  tscTrace("try to create a connection to %s", ip);

  void *taos = taos_connect_imp(ip, user, pass, db, port, NULL, NULL, NULL);
  if (taos != NULL) {
H
hjxilinx 已提交
168
    STscObj *pObj = (STscObj *)taos;
H
hjliao 已提交
169

S
slguan 已提交
170
    // version compare only requires the first 3 segments of the version string
S
slguan 已提交
171 172 173
    int code = taosCheckVersion(version, taos_get_server_info(taos), 3);
    if (code != 0) {
      pObj->pSql->res.code = code;
S
slguan 已提交
174
      taos_close(taos);
S
slguan 已提交
175 176
      return NULL;
    }
H
hzcheng 已提交
177 178 179 180 181
  }

  return taos;
}

L
lihui 已提交
182
TAOS *taos_connect_a(char *ip, char *user, char *pass, char *db, uint16_t port, void (*fp)(void *, TAOS_RES *, int),
H
hzcheng 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
                     void *param, void **taos) {
  return taos_connect_imp(ip, user, pass, db, port, fp, param, taos);
}

void taos_close(TAOS *taos) {
  STscObj *pObj = (STscObj *)taos;

  if (pObj == NULL) return;
  if (pObj->signature != pObj) return;

  if (pObj->pHb != NULL) {
    tscSetFreeHeatBeat(pObj);
  } else {
    tscCloseTscObj(pObj);
  }
}

H
hjxilinx 已提交
200
int taos_query_imp(STscObj *pObj, SSqlObj *pSql) {
H
hzcheng 已提交
201 202 203 204
  SSqlRes *pRes = &pSql->res;

  pRes->numOfRows = 1;
  pRes->numOfTotal = 0;
H
hjxilinx 已提交
205
  pRes->numOfTotalInCurrentClause = 0;
206

L
lihui 已提交
207 208
  pSql->asyncTblPos = NULL;
  if (NULL != pSql->pTableHashList) {
H
hjxilinx 已提交
209
    taosHashCleanup(pSql->pTableHashList);
L
lihui 已提交
210 211
    pSql->pTableHashList = NULL;
  }
H
hjxilinx 已提交
212

L
lihui 已提交
213
  tscDump("%p pObj:%p, SQL: %s", pSql, pObj, pSql->sqlstr);
H
hzcheng 已提交
214

215
  pRes->code = (uint8_t)tsParseSql(pSql, false);
H
hzcheng 已提交
216 217 218 219 220 221 222 223

  /*
   * set the qhandle to 0 before return in order to erase the qhandle value assigned in the previous successful query.
   * If qhandle is NOT set 0, the function of taos_free_result() will send message to server by calling tscProcessSql()
   * to free connection, which may cause segment fault, when the parse phrase is not even successfully executed.
   */
  pRes->qhandle = 0;

H
hjxilinx 已提交
224 225 226
  if (pRes->code == TSDB_CODE_SUCCESS) {
    tscDoQuery(pSql);
  }
H
hzcheng 已提交
227

H
hjxilinx 已提交
228 229 230 231 232
  if (pRes->code == TSDB_CODE_SUCCESS) {
    tscTrace("%p SQL result:%d, %s pObj:%p", pSql, pRes->code, taos_errstr(pObj), pObj);
  } else {
    tscError("%p SQL result:%d, %s pObj:%p", pSql, pRes->code, taos_errstr(pObj), pObj);
  }
H
hjxilinx 已提交
233

H
hzcheng 已提交
234 235 236 237 238 239 240
  if (pRes->code != TSDB_CODE_SUCCESS) {
    tscFreeSqlObjPartial(pSql);
  }

  return pRes->code;
}

241 242 243 244 245 246 247
static void syncQueryCallback(void *param, TAOS_RES *tres, int code) {
  STscObj *pObj = (STscObj *)param;
  assert(pObj != NULL && pObj->pSql != NULL);
  
  sem_post(&pObj->pSql->rspSem);
}

S
slguan 已提交
248 249 250 251 252 253
int taos_query(TAOS *taos, const char *sqlstr) {
  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) {
    globalCode = TSDB_CODE_DISCONNECTED;
    return TSDB_CODE_DISCONNECTED;
  }
254 255 256 257 258
  
  SSqlObj *pSql = (SSqlObj *)calloc(1, sizeof(SSqlObj));
  if (pSql == NULL) {
    tscError("failed to malloc sqlObj");
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
S
slguan 已提交
259
  }
260 261 262 263 264 265
  
  pObj->pSql = pSql;
  tsem_init(&pSql->rspSem, 0, 0);
  
  int32_t sqlLen = strlen(sqlstr);
  doAsyncQuery(pObj, pObj->pSql, syncQueryCallback, taos, sqlstr, sqlLen);
S
slguan 已提交
266

267 268 269 270
  // wait for the callback function to post the semaphore
  sem_wait(&pSql->rspSem);
  
  return pSql->res.code;
S
slguan 已提交
271 272
}

H
hzcheng 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
TAOS_RES *taos_use_result(TAOS *taos) {
  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) {
    globalCode = TSDB_CODE_DISCONNECTED;
    return NULL;
  }

  return pObj->pSql;
}

int taos_result_precision(TAOS_RES *res) {
  SSqlObj *pSql = (SSqlObj *)res;
  if (pSql == NULL || pSql->signature != pSql) return 0;

  return pSql->res.precision;
}

int taos_num_rows(TAOS_RES *res) { return 0; }

int taos_num_fields(TAOS_RES *res) {
  SSqlObj *pSql = (SSqlObj *)res;
  if (pSql == NULL || pSql->signature != pSql) return 0;

296
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
297 298 299
  if (pQueryInfo == NULL) {
    return 0;
  }
300

301
  SFieldInfo *pFieldsInfo = &pQueryInfo->fieldsInfo;
S
slguan 已提交
302
  return (pFieldsInfo->numOfOutputCols - pFieldsInfo->numOfHiddenCols);
H
hzcheng 已提交
303 304 305 306 307 308
}

int taos_field_count(TAOS *taos) {
  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) return 0;

S
slguan 已提交
309
  return taos_num_fields(pObj->pSql);
H
hzcheng 已提交
310 311 312 313 314 315 316 317 318 319 320 321
}

int taos_affected_rows(TAOS *taos) {
  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) return 0;

  return (pObj->pSql->res.numOfRows);
}

TAOS_FIELD *taos_fetch_fields(TAOS_RES *res) {
  SSqlObj *pSql = (SSqlObj *)res;
  if (pSql == NULL || pSql->signature != pSql) return 0;
322 323

  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
324
  return pQueryInfo->fieldsInfo.pFields;
H
hzcheng 已提交
325 326 327 328 329 330 331 332 333 334
}

int taos_retrieve(TAOS_RES *res) {
  if (res == NULL) return 0;
  SSqlObj *pSql = (SSqlObj *)res;
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
  if (pSql == NULL || pSql->signature != pSql) return 0;
  if (pRes->qhandle == 0) return 0;

S
slguan 已提交
335 336
  tscResetForNextRetrieve(pRes);

H
hzcheng 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
  if (pCmd->command < TSDB_SQL_LOCAL) {
    pCmd->command = (pCmd->command > TSDB_SQL_MGMT) ? TSDB_SQL_RETRIEVE : TSDB_SQL_FETCH;
  }
  tscProcessSql(pSql);

  return pRes->numOfRows;
}

int taos_fetch_block_impl(TAOS_RES *res, TAOS_ROW *rows) {
  SSqlObj *pSql = (SSqlObj *)res;
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
  STscObj *pObj = pSql->pTscObj;

  if (pRes->qhandle == 0 || pObj->pSql != pSql) {
    *rows = NULL;
    return 0;
  }

  // Retrieve new block
S
slguan 已提交
357
  tscResetForNextRetrieve(pRes);
H
hzcheng 已提交
358 359 360 361 362 363 364 365 366 367
  if (pCmd->command < TSDB_SQL_LOCAL) {
    pCmd->command = (pCmd->command > TSDB_SQL_MGMT) ? TSDB_SQL_RETRIEVE : TSDB_SQL_FETCH;
  }

  tscProcessSql(pSql);
  if (pRes->numOfRows == 0) {
    *rows = NULL;
    return 0;
  }

S
slguan 已提交
368 369
  // secondary merge has handle this situation
  if (pCmd->command != TSDB_SQL_RETRIEVE_METRIC) {
H
hjxilinx 已提交
370
    pRes->numOfTotalInCurrentClause += pRes->numOfRows;
S
slguan 已提交
371 372
  }

373
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
374
  for (int i = 0; i < pQueryInfo->fieldsInfo.numOfOutputCols; ++i) {
H
hjxilinx 已提交
375
    pRes->tsrow[i] = TSC_GET_RESPTR_BASE(pRes, pQueryInfo, i);
H
hzcheng 已提交
376 377 378 379
  }

  *rows = pRes->tsrow;

380
  return (pQueryInfo->order.order == TSQL_SO_DESC) ? pRes->numOfRows : -pRes->numOfRows;
H
hzcheng 已提交
381 382
}

H
hjxilinx 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
static void transferNcharData(SSqlObj *pSql, int32_t columnIndex, TAOS_FIELD *pField) {
  SSqlRes *pRes = &pSql->res;

  if (isNull(pRes->tsrow[columnIndex], pField->type)) {
    pRes->tsrow[columnIndex] = NULL;
  } else if (pField->type == TSDB_DATA_TYPE_NCHAR) {
    // 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);

    if (taosUcs4ToMbs(pRes->tsrow[columnIndex], pField->bytes, pRes->buffer[columnIndex])) {
      pRes->tsrow[columnIndex] = pRes->buffer[columnIndex];
    } else {
      tscError("%p charset:%s to %s. val:%ls convert failed.", pSql, DEFAULT_UNICODE_ENCODEC, tsCharset, pRes->tsrow);
      pRes->tsrow[columnIndex] = NULL;
    }
  }
}

static char *getArithemicInputSrc(void *param, char *name, int32_t colId) {
  SArithmeticSupport *pSupport = (SArithmeticSupport *)param;
  SSqlFunctionExpr *  pExpr = pSupport->pExpr;

  int32_t index = -1;
  for (int32_t i = 0; i < pExpr->pBinExprInfo.numOfCols; ++i) {
    if (strcmp(name, pExpr->pBinExprInfo.pReqColumns[i].name) == 0) {
      index = i;
      break;
    }
  }

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

S
slguan 已提交
422
static void **doSetResultRowData(SSqlObj *pSql) {
H
hzcheng 已提交
423 424
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
H
hjxilinx 已提交
425

H
hjxilinx 已提交
426
  assert(pRes->row >= 0 && pRes->row <= pRes->numOfRows);
H
hjxilinx 已提交
427

H
hjxilinx 已提交
428 429 430 431
  if (pRes->row >= pRes->numOfRows) {  // all the results has returned to invoker
    tfree(pRes->tsrow);
    return pRes->tsrow;
  }
432

H
hjxilinx 已提交
433 434 435 436 437 438 439 440 441 442 443 444
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  
  //todo refactor move away
  for(int32_t k = 0; k < pQueryInfo->exprsInfo.numOfExprs; ++k) {
    SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, k);
    
    if (k > 0) {
      SSqlExpr* pPrev = tscSqlExprGet(pQueryInfo, k - 1);
      pExpr->offset = pPrev->offset + pPrev->resBytes;
    }
  }
  
S
slguan 已提交
445
  int32_t num = 0;
H
hjxilinx 已提交
446 447
  for (int i = 0; i < tscNumOfFields(pQueryInfo); ++i) {
    if (pQueryInfo->fieldsInfo.pSqlExpr[i] != NULL) {
H
hjxilinx 已提交
448 449 450 451
      SSqlExpr* pExpr = pQueryInfo->fieldsInfo.pSqlExpr[i];
      pRes->tsrow[i] = TSC_GET_RESPTR_BASE(pRes, pQueryInfo, i) + pExpr->resBytes * pRes->row;
    } else {
      assert(0);
H
hjxilinx 已提交
452
    }
S
slguan 已提交
453

H
hzcheng 已提交
454
    // primary key column cannot be null in interval query, no need to check
455
    if (i == 0 && pQueryInfo->intervalTime > 0) {
H
hzcheng 已提交
456 457 458
      continue;
    }

459
    TAOS_FIELD *pField = tscFieldInfoGetField(pQueryInfo, i);
H
hjxilinx 已提交
460
    transferNcharData(pSql, i, pField);
H
hzcheng 已提交
461

H
hjxilinx 已提交
462 463 464 465 466 467 468 469 470 471
    // calculate the result from serveral other columns
    if (pQueryInfo->fieldsInfo.pExpr != NULL && pQueryInfo->fieldsInfo.pExpr[i] != NULL) {
      SArithmeticSupport *sas = (SArithmeticSupport *)calloc(1, sizeof(SArithmeticSupport));
      sas->offset = 0;
      sas->pExpr = pQueryInfo->fieldsInfo.pExpr[i];
      
      sas->numOfCols = sas->pExpr->pBinExprInfo.numOfCols;
      
      if (pRes->buffer[i] == NULL) {
        pRes->buffer[i] = malloc(tscFieldInfoGetField(pQueryInfo, i)->bytes);
H
hzcheng 已提交
472
      }
H
hjxilinx 已提交
473
      
H
hjxilinx 已提交
474 475 476 477 478 479
      for(int32_t k = 0; k < sas->numOfCols; ++k) {
        int32_t columnIndex = sas->pExpr->pBinExprInfo.pReqColumns[k].colIdxInBuf;
        SSqlExpr* pExpr = tscSqlExprGet(pQueryInfo, columnIndex);
        
        sas->elemSize[k] = pExpr->resBytes;
        sas->data[k] = (pRes->data + pRes->numOfRows* pExpr->offset) + pRes->row*pExpr->resBytes;
H
hzcheng 已提交
480
      }
H
hjxilinx 已提交
481 482 483

      tSQLBinaryExprCalcTraverse(sas->pExpr->pBinExprInfo.pBinExpr, 1, pRes->buffer[i], sas, TSQL_SO_ASC, getArithemicInputSrc);
      pRes->tsrow[i] = pRes->buffer[i];
H
hjxilinx 已提交
484
      
H
hjxilinx 已提交
485
      free(sas); //todo optimization
H
hzcheng 已提交
486 487 488
    }
  }

489
  assert(num <= pQueryInfo->fieldsInfo.numOfOutputCols);
H
hjxilinx 已提交
490 491

  pRes->row++;  // index increase one-step
H
hzcheng 已提交
492 493 494
  return pRes->tsrow;
}

H
hjxilinx 已提交
495 496
static bool tscHashRemainDataInSubqueryResultSet(SSqlObj *pSql) {
  bool     hasData = true;
S
slguan 已提交
497 498
  SSqlCmd *pCmd = &pSql->cmd;

499
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
500
  if (tscNonOrderedProjectionQueryOnSTable(pQueryInfo, 0)) {
H
hjxilinx 已提交
501
    bool allSubqueryExhausted = true;
S
slguan 已提交
502

H
hjxilinx 已提交
503
    for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
504 505 506 507
      if (pSql->pSubs[i] == NULL) {
        continue;
      }

H
hjxilinx 已提交
508 509 510
      SSqlRes *pRes1 = &pSql->pSubs[i]->res;
      SSqlCmd *pCmd1 = &pSql->pSubs[i]->cmd;

511 512 513
      SQueryInfo *    pQueryInfo1 = tscGetQueryInfoDetail(pCmd1, pCmd1->clauseIndex);
      SMeterMetaInfo *pMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo1, 0);

H
hjxilinx 已提交
514
      assert(pQueryInfo1->numOfTables == 1);
H
hjxilinx 已提交
515 516 517

      /*
       * if the global limitation is not reached, and current result has not exhausted, or next more vnodes are
518
       * available, goes on
H
hjxilinx 已提交
519 520
       */
      if (pMetaInfo->vnodeIndex < pMetaInfo->pMetricMeta->numOfVnodes && pRes1->row < pRes1->numOfRows &&
H
hjxilinx 已提交
521
          (!tscHasReachLimitation(pQueryInfo1, pRes1))) {
H
hjxilinx 已提交
522 523
        allSubqueryExhausted = false;
        break;
H
hjxilinx 已提交
524 525
      }
    }
S
slguan 已提交
526

H
hjxilinx 已提交
527 528
    hasData = !allSubqueryExhausted;
  } else {  // otherwise, in case inner join, if any subquery exhausted, query completed.
S
slguan 已提交
529
    for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
530 531 532
      if (pSql->pSubs[i] == 0) {
        continue;
      }
H
hjxilinx 已提交
533

534 535 536
      SSqlRes *   pRes1 = &pSql->pSubs[i]->res;
      SQueryInfo *pQueryInfo1 = tscGetQueryInfoDetail(&pSql->pSubs[i]->cmd, 0);

H
hjxilinx 已提交
537
      if ((pRes1->row >= pRes1->numOfRows && tscHasReachLimitation(pQueryInfo1, pRes1) &&
538 539
           tscProjectionQueryOnTable(pQueryInfo1)) ||
          (pRes1->numOfRows == 0)) {
S
slguan 已提交
540 541 542 543
        hasData = false;
        break;
      }
    }
H
hjxilinx 已提交
544 545 546 547
  }

  return hasData;
}
S
slguan 已提交
548

549
static void **tscBuildResFromSubqueries(SSqlObj *pSql) {
H
hjxilinx 已提交
550
  SSqlRes *pRes = &pSql->res;
S
slguan 已提交
551

H
hjxilinx 已提交
552
  while (1) {
553
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, pSql->cmd.clauseIndex);
S
slguan 已提交
554
    if (pRes->tsrow == NULL) {
H
hjxilinx 已提交
555
      pRes->tsrow = calloc(pQueryInfo->exprsInfo.numOfExprs, POINTER_BYTES);
S
slguan 已提交
556 557 558
    }

    bool success = false;
559 560 561 562 563 564 565 566 567

    int32_t numOfTableHasRes = 0;
    for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
      if (pSql->pSubs[i] != 0) {
        numOfTableHasRes++;
      }
    }

    if (numOfTableHasRes >= 2) {  // do merge result
S
slguan 已提交
568

H
hjxilinx 已提交
569 570 571 572
      success = (doSetResultRowData(pSql->pSubs[0]) != NULL) && (doSetResultRowData(pSql->pSubs[1]) != NULL);
      //        TSKEY key1 = *(TSKEY *)pRes1->tsrow[0];
      //        TSKEY key2 = *(TSKEY *)pRes2->tsrow[0];
      //        printf("first:%" PRId64 ", second:%" PRId64 "\n", key1, key2);
H
hjxilinx 已提交
573
    } else {  // only one subquery
574 575 576 577 578
      SSqlObj *pSub = pSql->pSubs[0];
      if (pSub == NULL) {
        pSub = pSql->pSubs[1];
      }

H
hjxilinx 已提交
579
      success = (doSetResultRowData(pSub) != NULL);
S
slguan 已提交
580 581
    }

H
hjxilinx 已提交
582
    if (success) {  // current row of final output has been built, return to app
583
      for (int32_t i = 0; i < pQueryInfo->exprsInfo.numOfExprs; ++i) {
S
slguan 已提交
584 585 586 587 588 589 590
        int32_t tableIndex = pRes->pColumnIndex[i].tableIndex;
        int32_t columnIndex = pRes->pColumnIndex[i].columnIndex;

        SSqlRes *pRes1 = &pSql->pSubs[tableIndex]->res;
        pRes->tsrow[i] = pRes1->tsrow[columnIndex];
      }

591
      pRes->numOfTotalInCurrentClause++;
H
hjxilinx 已提交
592

593
      break;
594
    } else {  // continue retrieve data from vnode
595
      if (!tscHashRemainDataInSubqueryResultSet(pSql)) {
596 597
        tscTrace("%p at least one subquery exhausted, free all other %d subqueries", pSql, pSql->numOfSubs - 1);
        SSubqueryState *pState = NULL;
598

599
        // free all sub sqlobj
600 601 602 603 604
        for (int32_t i = 0; i < pSql->numOfSubs; ++i) {
          SSqlObj *pChildObj = pSql->pSubs[i];
          if (pChildObj == NULL) {
            continue;
          }
H
hjxilinx 已提交
605

606 607
          SJoinSubquerySupporter *pSupporter = (SJoinSubquerySupporter *)pChildObj->param;
          pState = pSupporter->pState;
H
hjxilinx 已提交
608

609 610 611
          tscDestroyJoinSupporter(pChildObj->param);
          taos_free_result(pChildObj);
        }
H
hjxilinx 已提交
612

613 614 615
        free(pState);
        return NULL;
      }
H
hjxilinx 已提交
616

617 618 619 620
      tscFetchDatablockFromSubquery(pSql);
      if (pRes->code != TSDB_CODE_SUCCESS) {
        return NULL;
      }
H
hjxilinx 已提交
621 622 623
    }
  }

624
  return pRes->tsrow;
H
hjxilinx 已提交
625 626
}

S
slguan 已提交
627 628 629 630 631 632 633 634 635 636 637
TAOS_ROW taos_fetch_row_impl(TAOS_RES *res) {
  SSqlObj *pSql = (SSqlObj *)res;
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;

  if (pRes->qhandle == 0 || pCmd->command == TSDB_SQL_RETRIEVE_EMPTY_RESULT) {
    return NULL;
  }

  if (pCmd->command == TSDB_SQL_METRIC_JOIN_RETRIEVE) {
    tscFetchDatablockFromSubquery(pSql);
H
hjxilinx 已提交
638

S
slguan 已提交
639
    if (pRes->code == TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
640
      tscTrace("%p data from all subqueries have been retrieved to client", pSql);
641
      return tscBuildResFromSubqueries(pSql);
S
slguan 已提交
642
    } else {
H
hjxilinx 已提交
643
      tscTrace("%p retrieve data from subquery failed, code:%d", pSql, pRes->code);
S
slguan 已提交
644 645 646
      return NULL;
    }

H
hjxilinx 已提交
647 648 649 650 651 652 653
  } else if (pRes->row >= pRes->numOfRows) {
    /**
     * NOT a join query
     *
     * If the data block of current result set have been consumed already, try fetch next result
     * data block from virtual node.
     */
S
slguan 已提交
654 655 656 657 658 659
    tscResetForNextRetrieve(pRes);

    if (pCmd->command < TSDB_SQL_LOCAL) {
      pCmd->command = (pCmd->command > TSDB_SQL_MGMT) ? TSDB_SQL_RETRIEVE : TSDB_SQL_FETCH;
    }

660 661
    tscProcessSql(pSql);  // retrieve data from virtual node

H
hjxilinx 已提交
662
    // if failed to retrieve data from current virtual node, try next one if exists
H
hjxilinx 已提交
663
    if (hasMoreVnodesToTry(pSql)) {
664
      tscTryQueryNextVnode(pSql, NULL);
S
slguan 已提交
665 666
    }

667 668
    /*
     * local reducer has handle this case,
H
hjxilinx 已提交
669
     * so no need to add the pRes->numOfRows for super table query
670
     */
S
slguan 已提交
671
    if (pCmd->command != TSDB_SQL_RETRIEVE_METRIC) {
H
hjxilinx 已提交
672
      pRes->numOfTotalInCurrentClause += pRes->numOfRows;
S
slguan 已提交
673
    }
674 675 676 677

    if (pRes->numOfRows == 0) {
      return NULL;
    }
S
slguan 已提交
678 679
  }

H
hjxilinx 已提交
680
  return doSetResultRowData(pSql);
S
slguan 已提交
681 682
}

683 684 685 686 687 688 689 690 691 692
static void asyncFetchCallback(void *param, TAOS_RES *tres, int numOfRows) {
  SSqlObj* pSql = (SSqlObj*) tres;
  if (numOfRows < 0) {
    // set the error code
    pSql->res.code = -numOfRows;
  }
  
  sem_post(&pSql->rspSem);
}

H
hzcheng 已提交
693 694 695 696 697 698
TAOS_ROW taos_fetch_row(TAOS_RES *res) {
  SSqlObj *pSql = (SSqlObj *)res;
  if (pSql == NULL || pSql->signature != pSql) {
    globalCode = TSDB_CODE_DISCONNECTED;
    return NULL;
  }
699 700 701 702 703 704
  
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
  
  if (pRes->qhandle == 0 || pCmd->command == TSDB_SQL_RETRIEVE_EMPTY_RESULT || pCmd->command == TSDB_SQL_INSERT) {
    return NULL;
705
  }
706 707
  
  // current data are exhausted, fetch more data
H
hjxilinx 已提交
708 709
  if (pRes->data == NULL || (pRes->data != NULL && pRes->row >= pRes->numOfRows &&
      (pCmd->command == TSDB_SQL_RETRIEVE || pCmd->command == TSDB_SQL_RETRIEVE_METRIC || pCmd->command == TSDB_SQL_FETCH))) {
710
    taos_fetch_rows_a(res, asyncFetchCallback, pSql->pTscObj);
H
hjxilinx 已提交
711
    
712
    sem_wait(&pSql->rspSem);
H
hjxilinx 已提交
713
  }
714 715
  
  return doSetResultRowData(pSql);
H
hzcheng 已提交
716 717 718 719
}

int taos_fetch_block(TAOS_RES *res, TAOS_ROW *rows) {
  SSqlObj *pSql = (SSqlObj *)res;
H
hjxilinx 已提交
720
  SSqlCmd *pCmd = &pSql->cmd;
721
  SSqlRes *pRes = &pSql->res;
722

H
hzcheng 已提交
723 724 725 726 727 728 729 730
  int nRows = 0;

  if (pSql == NULL || pSql->signature != pSql) {
    globalCode = TSDB_CODE_DISCONNECTED;
    *rows = NULL;
    return 0;
  }

S
slguan 已提交
731
  // projection query on metric, pipeline retrieve data from vnode list,
S
slguan 已提交
732
  // instead of two-stage mergednodeProcessMsgFromShell free qhandle
H
hzcheng 已提交
733
  nRows = taos_fetch_block_impl(res, rows);
734

H
hjxilinx 已提交
735 736
  // current subclause is completed, try the next subclause
  while (rows == NULL && pCmd->clauseIndex < pCmd->numOfClause - 1) {
737 738
    SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);

739
    pSql->cmd.command = pQueryInfo->command;
H
hjxilinx 已提交
740
    pCmd->clauseIndex++;
741

742 743 744
    pRes->numOfTotal += pRes->numOfTotalInCurrentClause;
    pRes->numOfTotalInCurrentClause = 0;
    pRes->rspType = 0;
745

746 747
    pSql->numOfSubs = 0;
    tfree(pSql->pSubs);
748

H
hjxilinx 已提交
749
    assert(pSql->fp == NULL);
750

H
hjxilinx 已提交
751 752
    tscTrace("%p try data in the next subclause:%d, total subclause:%d", pSql, pCmd->clauseIndex, pCmd->numOfClause);
    tscProcessSql(pSql);
753

H
hjxilinx 已提交
754
    nRows = taos_fetch_block_impl(res, rows);
H
hzcheng 已提交
755
  }
756

H
hzcheng 已提交
757 758 759
  return nRows;
}

S
slguan 已提交
760
int taos_select_db(TAOS *taos, const char *db) {
761
  char sql[256] = {0};
H
hzcheng 已提交
762 763 764 765 766 767 768

  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) {
    globalCode = TSDB_CODE_DISCONNECTED;
    return TSDB_CODE_DISCONNECTED;
  }

769
  snprintf(sql, tListLen(sql), "use %s", db);
H
hzcheng 已提交
770 771 772
  return taos_query(taos, sql);
}

H
hjxilinx 已提交
773
void taos_free_result_imp(TAOS_RES *res, int keepCmd) {
H
hzcheng 已提交
774 775 776 777 778 779 780 781 782
  if (res == NULL) return;

  SSqlObj *pSql = (SSqlObj *)res;
  SSqlRes *pRes = &pSql->res;
  SSqlCmd *pCmd = &pSql->cmd;

  tscTrace("%p start to free result", pSql);

  if (pSql->signature != pSql) return;
S
slguan 已提交
783

H
hzcheng 已提交
784 785 786 787
  if (pRes == NULL || pRes->qhandle == 0) {
    /* Query rsp is not received from vnode, so the qhandle is NULL */
    tscTrace("%p qhandle is null, abort free, fp:%p", pSql, pSql->fp);
    if (pSql->fp != NULL) {
788 789 790 791 792 793 794
      STscObj* pObj = pSql->pTscObj;
  
      if (pSql == pObj->pSql) {
        pObj->pSql = NULL;
        tscFreeSqlObj(pSql);
      }
      
H
hzcheng 已提交
795
      tscTrace("%p Async SqlObj is freed by app", pSql);
weixin_48148422's avatar
weixin_48148422 已提交
796 797
    } else if (keepCmd) {
      tscFreeSqlResult(pSql);
H
hzcheng 已提交
798 799 800 801 802 803
    } else {
      tscFreeSqlObjPartial(pSql);
    }
    return;
  }

S
slguan 已提交
804
  // set freeFlag to 1 in retrieve message if there are un-retrieved results
805
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
806 807 808 809 810
  if (pQueryInfo == NULL) {
    tscFreeSqlObjPartial(pSql);
    return;
  }

811
  pQueryInfo->type = TSDB_QUERY_TYPE_FREE_RESOURCE;
S
slguan 已提交
812

813
  SMeterMetaInfo *pMeterMetaInfo = tscGetMeterMetaInfoFromQueryInfo(pQueryInfo, 0);
H
hzcheng 已提交
814 815

  /*
S
slguan 已提交
816 817
   * case 1. Partial data have been retrieved from vnodes, but not all data has been retrieved yet.
   *         We need to recycle the connection by noticing the vnode return 0 results.
H
hzcheng 已提交
818
   * case 2. When the query response is received from vnodes and the numOfRows is set to 0, the user calls
S
slguan 已提交
819 820 821 822 823
   *         taos_free_result before the taos_fetch_row is called in non-stream computing,
   *         we need to recycle the connection.
   * case 3. If the query process is cancelled by user in stable query, tscProcessSql should not be called
   *         for each subquery. Because the failure of execution tsProcessSql may trigger the callback function
   *         be executed, and the retry efforts may result in double free the resources, e.g.,SRetrieveSupport
H
hzcheng 已提交
824 825 826 827
   */
  if (pRes->code != TSDB_CODE_QUERY_CANCELLED &&
      ((pRes->numOfRows > 0 && pCmd->command < TSDB_SQL_LOCAL) ||
       (pRes->code == TSDB_CODE_SUCCESS && pRes->numOfRows == 0 && pCmd->command == TSDB_SQL_SELECT &&
S
slguan 已提交
828
        pSql->pStream == NULL && pMeterMetaInfo->pMeterMeta != NULL))) {
H
hzcheng 已提交
829 830
    pCmd->command = (pCmd->command > TSDB_SQL_MGMT) ? TSDB_SQL_RETRIEVE : TSDB_SQL_FETCH;

H
hjxilinx 已提交
831
    tscTrace("%p code:%d, numOfRows:%d, command:%d", pSql, pRes->code, pRes->numOfRows, pCmd->command);
H
hjxilinx 已提交
832

S
slguan 已提交
833 834
    void *fp = pSql->fp;
    if (fp != NULL) {
H
hzcheng 已提交
835
      pSql->freed = 1;
S
slguan 已提交
836
    }
H
hzcheng 已提交
837

S
slguan 已提交
838 839 840 841 842 843 844
    tscProcessSql(pSql);

    /*
     *  If release connection msg is sent to vnode, the corresponding SqlObj for async query can not be freed instantly,
     *  since its free operation is delegated to callback function, which is tscProcessMsgFromServer.
     */
    if (fp == NULL) {
H
hzcheng 已提交
845
      /*
S
slguan 已提交
846 847 848 849 850 851 852 853
       * fp may be released here, so we cannot use the pSql->fp
       *
       * In case of handle sync model query, the main SqlObj cannot be freed.
       * So, we only free part attributes, including allocated resources and references on metermeta/metricmeta
       * data in cache.
       *
       * Then this object will be reused and no free operation is required.
       */
weixin_48148422's avatar
weixin_48148422 已提交
854 855 856 857 858 859 860
      if (keepCmd) {
        tscFreeSqlResult(pSql);
        tscTrace("%p sql result is freed by app while sql command is kept", pSql);
      } else {
        tscFreeSqlObjPartial(pSql);
        tscTrace("%p sql result is freed by app", pSql);
      }
861 862 863 864 865
    } else {  // for async release, remove its link
      STscObj* pObj = pSql->pTscObj;
      if (pObj->pSql == pSql) {
        pObj->pSql = NULL;
      }
H
hzcheng 已提交
866 867
    }
  } else {
S
slguan 已提交
868 869
    // if no free resource msg is sent to vnode, we free this object immediately.

H
hzcheng 已提交
870 871 872
    if (pSql->fp) {
      assert(pRes->numOfRows == 0 || (pCmd->command > TSDB_SQL_LOCAL));
      tscFreeSqlObj(pSql);
S
slguan 已提交
873
      tscTrace("%p Async sql result is freed by app", pSql);
weixin_48148422's avatar
weixin_48148422 已提交
874 875 876
    } else if (keepCmd) {
      tscFreeSqlResult(pSql);
      tscTrace("%p sql result is freed while sql command is kept", pSql);
H
hzcheng 已提交
877 878 879 880 881 882 883
    } else {
      tscFreeSqlObjPartial(pSql);
      tscTrace("%p sql result is freed", pSql);
    }
  }
}

H
hjxilinx 已提交
884
void taos_free_result(TAOS_RES *res) { taos_free_result_imp(res, 0); }
weixin_48148422's avatar
weixin_48148422 已提交
885

H
hzcheng 已提交
886 887 888 889 890 891
int taos_errno(TAOS *taos) {
  STscObj *pObj = (STscObj *)taos;
  int      code;

  if (pObj == NULL || pObj->signature != pObj) return globalCode;

S
slguan 已提交
892
  if ((int8_t)(pObj->pSql->res.code) == -1)
H
hzcheng 已提交
893 894 895 896 897 898 899
    code = TSDB_CODE_OTHERS;
  else
    code = pObj->pSql->res.code;

  return code;
}

H
hjxilinx 已提交
900
static bool validErrorCode(int32_t code) { return code >= TSDB_CODE_SUCCESS && code < TSDB_CODE_MAX_ERROR_CODE; }
H
hjxilinx 已提交
901 902 903 904 905

/*
 * In case of invalid sql error, additional information is attached to explain
 * why the sql is invalid
 */
H
hjxilinx 已提交
906
static bool hasAdditionalErrorInfo(int32_t code, SSqlCmd *pCmd) {
H
hjxilinx 已提交
907 908 909 910 911
  if (code != TSDB_CODE_INVALID_SQL) {
    return false;
  }

  size_t len = strlen(pCmd->payload);
H
hjxilinx 已提交
912 913

  char *z = NULL;
H
hjxilinx 已提交
914
  if (len > 0) {
H
hjxilinx 已提交
915
    z = strstr(pCmd->payload, "invalid SQL");
H
hjxilinx 已提交
916
  }
H
hjxilinx 已提交
917

H
hjxilinx 已提交
918 919 920
  return z != NULL;
}

H
hzcheng 已提交
921
char *taos_errstr(TAOS *taos) {
H
hjxilinx 已提交
922 923
  STscObj *pObj = (STscObj *)taos;
  uint8_t  code;
H
hzcheng 已提交
924

S
slguan 已提交
925 926
  if (pObj == NULL || pObj->signature != pObj)
    return (char*)tstrerror(globalCode);
H
hzcheng 已提交
927

H
hjxilinx 已提交
928 929
  SSqlObj *pSql = pObj->pSql;

H
hjxilinx 已提交
930 931 932
  if (validErrorCode(pSql->res.code)) {
    code = pSql->res.code;
  } else {
H
hjxilinx 已提交
933
    code = TSDB_CODE_OTHERS;  // unknown error
H
hjxilinx 已提交
934
  }
H
hzcheng 已提交
935

H
hjxilinx 已提交
936 937
  if (hasAdditionalErrorInfo(code, &pSql->cmd)) {
    return pSql->cmd.payload;
H
hzcheng 已提交
938
  } else {
S
slguan 已提交
939
    return (char*)tstrerror(code);
H
hzcheng 已提交
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
  }
}

void taos_config(int debug, char *log_path) {
  uDebugFlag = debug;
  strcpy(logDir, log_path);
}

char *taos_get_server_info(TAOS *taos) {
  STscObj *pObj = (STscObj *)taos;

  if (pObj == NULL) return NULL;

  return pObj->sversion;
}

char *taos_get_client_info() { return version; }

void taos_stop_query(TAOS_RES *res) {
  if (res == NULL) return;

  SSqlObj *pSql = (SSqlObj *)res;
962 963
  SSqlCmd *pCmd = &pSql->cmd;

H
hzcheng 已提交
964 965 966 967 968
  if (pSql->signature != pSql) return;
  tscTrace("%p start to cancel query", res);

  pSql->res.code = TSDB_CODE_QUERY_CANCELLED;

969 970
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
  if (tscIsTwoStageMergeMetricQuery(pQueryInfo, 0)) {
H
hzcheng 已提交
971 972 973 974 975 976 977 978
    tscKillMetricQuery(pSql);
    return;
  }

  if (pSql->cmd.command >= TSDB_SQL_LOCAL) {
    return;
  }

S
slguan 已提交
979
  //taosStopRpcConn(pSql->thandle);
H
hzcheng 已提交
980 981 982 983 984 985
  tscTrace("%p query is cancelled", res);
}

int taos_print_row(char *str, TAOS_ROW row, TAOS_FIELD *fields, int num_fields) {
  int len = 0;
  for (int i = 0; i < num_fields; ++i) {
986 987 988 989
    if (i > 0) {
      str[len++] = ' ';
    }

H
hzcheng 已提交
990
    if (row[i] == NULL) {
991
      len += sprintf(str + len, "%s", TSDB_DATA_NULL_STR);
H
hzcheng 已提交
992 993 994 995 996
      continue;
    }

    switch (fields[i].type) {
      case TSDB_DATA_TYPE_TINYINT:
997
        len += sprintf(str + len, "%d", *((char *)row[i]));
H
hzcheng 已提交
998 999 1000
        break;

      case TSDB_DATA_TYPE_SMALLINT:
1001
        len += sprintf(str + len, "%d", *((short *)row[i]));
H
hzcheng 已提交
1002 1003 1004
        break;

      case TSDB_DATA_TYPE_INT:
1005
        len += sprintf(str + len, "%d", *((int *)row[i]));
H
hzcheng 已提交
1006 1007 1008
        break;

      case TSDB_DATA_TYPE_BIGINT:
1009
        len += sprintf(str + len, "%" PRId64, *((int64_t *)row[i]));
H
hzcheng 已提交
1010 1011
        break;

L
lihui 已提交
1012 1013
      case TSDB_DATA_TYPE_FLOAT: {
        float fv = 0;
L
lihui 已提交
1014
        fv = GET_FLOAT_VAL(row[i]);
1015
        len += sprintf(str + len, "%f", fv);
1016
      } break;
H
hzcheng 已提交
1017

1018
      case TSDB_DATA_TYPE_DOUBLE: {
L
lihui 已提交
1019
        double dv = 0;
L
lihui 已提交
1020
        dv = GET_DOUBLE_VAL(row[i]);
1021
        len += sprintf(str + len, "%lf", dv);
1022
      } break;
H
hzcheng 已提交
1023 1024

      case TSDB_DATA_TYPE_BINARY:
S
slguan 已提交
1025
      case TSDB_DATA_TYPE_NCHAR: {
H
hjxilinx 已提交
1026 1027 1028 1029 1030 1031 1032 1033
        size_t xlen = 0;
        for (xlen = 0; xlen <= fields[i].bytes; xlen++) {
          char c = ((char *)row[i])[xlen];
          if (c == 0) break;
          str[len++] = c;
        }
        str[len] = 0;
      } break;
H
hzcheng 已提交
1034 1035

      case TSDB_DATA_TYPE_TIMESTAMP:
1036
        len += sprintf(str + len, "%" PRId64, *((int64_t *)row[i]));
H
hzcheng 已提交
1037 1038 1039
        break;

      case TSDB_DATA_TYPE_BOOL:
1040
        len += sprintf(str + len, "%d", *((int8_t *)row[i]));
H
hzcheng 已提交
1041 1042 1043 1044 1045 1046 1047 1048
      default:
        break;
    }
  }

  return len;
}

S
slguan 已提交
1049
int taos_validate_sql(TAOS *taos, const char *sql) {
H
hzcheng 已提交
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) {
    globalCode = TSDB_CODE_DISCONNECTED;
    return TSDB_CODE_DISCONNECTED;
  }

  SSqlObj *pSql = pObj->pSql;
  SSqlRes *pRes = &pSql->res;

  pRes->numOfRows = 1;
  pRes->numOfTotal = 0;
H
hjxilinx 已提交
1061
  pRes->numOfTotalInCurrentClause = 0;
1062

H
hzcheng 已提交
1063 1064 1065
  tscTrace("%p Valid SQL: %s pObj:%p", pSql, sql, pObj);

  int32_t sqlLen = strlen(sql);
H
hjxilinx 已提交
1066
  if (sqlLen > tsMaxSQLStringLen) {
H
hzcheng 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
    tscError("%p sql too long", pSql);
    pRes->code = TSDB_CODE_INVALID_SQL;
    return pRes->code;
  }

  pSql->sqlstr = realloc(pSql->sqlstr, sqlLen + 1);
  if (pSql->sqlstr == NULL) {
    pRes->code = TSDB_CODE_CLI_OUT_OF_MEMORY;
    tscError("%p failed to malloc sql string buffer", pSql);
    tscTrace("%p Valid SQL result:%d, %s pObj:%p", pSql, pRes->code, taos_errstr(taos), pObj);
    return pRes->code;
  }

S
slguan 已提交
1080
  strtolower(pSql->sqlstr, sql);
H
hzcheng 已提交
1081

L
lihui 已提交
1082 1083
  pSql->asyncTblPos = NULL;
  if (NULL != pSql->pTableHashList) {
H
hjxilinx 已提交
1084
    taosHashCleanup(pSql->pTableHashList);
L
lihui 已提交
1085 1086 1087
    pSql->pTableHashList = NULL;
  }

1088
  pRes->code = (uint8_t)tsParseSql(pSql, false);
H
hzcheng 已提交
1089 1090 1091 1092 1093 1094 1095
  int code = pRes->code;

  tscTrace("%p Valid SQL result:%d, %s pObj:%p", pSql, pRes->code, taos_errstr(taos), pObj);
  taos_free_result(pSql);

  return code;
}
S
slguan 已提交
1096

H
hjxilinx 已提交
1097
static int tscParseTblNameList(SSqlObj *pSql, const char *tblNameList, int32_t tblListLen) {
S
slguan 已提交
1098 1099 1100 1101 1102 1103 1104 1105
  // must before clean the sqlcmd object
  tscCleanSqlCmd(&pSql->cmd);

  SSqlCmd *pCmd = &pSql->cmd;

  pCmd->command = TSDB_SQL_MULTI_META;
  pCmd->count = 0;

S
slguan 已提交
1106
  int   code = TSDB_CODE_INVALID_TABLE_ID;
H
hjxilinx 已提交
1107
  char *str = (char *)tblNameList;
S
slguan 已提交
1108

1109 1110 1111
  SQueryInfo *pQueryInfo = NULL;
  tscGetQueryInfoDetailSafely(pCmd, pCmd->clauseIndex, &pQueryInfo);

1112
  SMeterMetaInfo *pMeterMetaInfo = tscAddEmptyMeterMetaInfo(pQueryInfo);
S
slguan 已提交
1113

H
hjxilinx 已提交
1114
  if ((code = tscAllocPayload(pCmd, tblListLen + 16)) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
1115 1116 1117 1118
    return code;
  }

  char *nextStr;
S
slguan 已提交
1119
  char  tblName[TSDB_TABLE_ID_LEN];
S
slguan 已提交
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
  int   payloadLen = 0;
  char *pMsg = pCmd->payload;
  while (1) {
    nextStr = strchr(str, ',');
    if (nextStr == NULL) {
      break;
    }

    memcpy(tblName, str, nextStr - str);
    int32_t len = nextStr - str;
    tblName[len] = '\0';

    str = nextStr + 1;

    strtrim(tblName);
    len = (uint32_t)strlen(tblName);
H
hjxilinx 已提交
1136

S
slguan 已提交
1137 1138 1139 1140 1141
    SSQLToken sToken = {.n = len, .type = TK_ID, .z = tblName};
    tSQLGetToken(tblName, &sToken.type);

    // Check if the table name available or not
    if (tscValidateName(&sToken) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
1142
      code = TSDB_CODE_INVALID_TABLE_ID;
S
slguan 已提交
1143 1144 1145 1146
      sprintf(pCmd->payload, "table name is invalid");
      return code;
    }

1147
    if ((code = setMeterID(pMeterMetaInfo, &sToken, pSql)) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
1148 1149 1150 1151
      return code;
    }

    if (++pCmd->count > TSDB_MULTI_METERMETA_MAX_NUM) {
S
slguan 已提交
1152
      code = TSDB_CODE_INVALID_TABLE_ID;
S
slguan 已提交
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
      sprintf(pCmd->payload, "tables over the max number");
      return code;
    }

    if (payloadLen + strlen(pMeterMetaInfo->name) + 128 >= pCmd->allocSize) {
      char *pNewMem = realloc(pCmd->payload, pCmd->allocSize + tblListLen);
      if (pNewMem == NULL) {
        code = TSDB_CODE_CLI_OUT_OF_MEMORY;
        sprintf(pCmd->payload, "failed to allocate memory");
        return code;
      }

      pCmd->payload = pNewMem;
      pCmd->allocSize = pCmd->allocSize + tblListLen;
      pMsg = pCmd->payload;
    }

    payloadLen += sprintf(pMsg + payloadLen, "%s,", pMeterMetaInfo->name);
  }

  *(pMsg + payloadLen) = '\0';
  pCmd->payloadLen = payloadLen + 1;

  return TSDB_CODE_SUCCESS;
}

int taos_load_table_info(TAOS *taos, const char *tableNameList) {
H
hjxilinx 已提交
1180
  const int32_t MAX_TABLE_NAME_LENGTH = 12 * 1024 * 1024;  // 12MB list
S
slguan 已提交
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191

  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) {
    globalCode = TSDB_CODE_DISCONNECTED;
    return TSDB_CODE_DISCONNECTED;
  }

  SSqlObj *pSql = pObj->pSql;
  SSqlRes *pRes = &pSql->res;

  pRes->numOfTotal = 0;  // the number of getting table meta from server
H
hjxilinx 已提交
1192
  pRes->numOfTotalInCurrentClause = 0;
1193

S
slguan 已提交
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
  pRes->code = 0;

  assert(pSql->fp == NULL);
  tscTrace("%p tableNameList: %s pObj:%p", pSql, tableNameList, pObj);

  int32_t tblListLen = strlen(tableNameList);
  if (tblListLen > MAX_TABLE_NAME_LENGTH) {
    tscError("%p tableNameList too long, length:%d, maximum allowed:%d", pSql, tblListLen, MAX_TABLE_NAME_LENGTH);
    pRes->code = TSDB_CODE_INVALID_SQL;
    return pRes->code;
  }

H
hjxilinx 已提交
1206
  char *str = calloc(1, tblListLen + 1);
S
slguan 已提交
1207 1208 1209 1210 1211 1212 1213
  if (str == NULL) {
    pRes->code = TSDB_CODE_CLI_OUT_OF_MEMORY;
    tscError("%p failed to malloc sql string buffer", pSql);
    return pRes->code;
  }

  strtolower(str, tableNameList);
H
hjxilinx 已提交
1214
  pRes->code = (uint8_t)tscParseTblNameList(pSql, str, tblListLen);
S
slguan 已提交
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236

  /*
   * set the qhandle to 0 before return in order to erase the qhandle value assigned in the previous successful query.
   * If qhandle is NOT set 0, the function of taos_free_result() will send message to server by calling tscProcessSql()
   * to free connection, which may cause segment fault, when the parse phrase is not even successfully executed.
   */
  pRes->qhandle = 0;
  free(str);

  if (pRes->code != TSDB_CODE_SUCCESS) {
    return pRes->code;
  }

  tscDoQuery(pSql);

  tscTrace("%p load multi metermeta result:%d %s pObj:%p", pSql, pRes->code, taos_errstr(taos), pObj);
  if (pRes->code != TSDB_CODE_SUCCESS) {
    tscFreeSqlObjPartial(pSql);
  }

  return pRes->code;
}