tscSql.c 24.2 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 "hash.h"
H
hjxilinx 已提交
17
#include "os.h"
H
hjxilinx 已提交
18
#include "qast.h"
H
hzcheng 已提交
19
#include "tcache.h"
H
hjxilinx 已提交
20
#include "tnote.h"
H
hzcheng 已提交
21
#include "trpc.h"
S
slguan 已提交
22
#include "tscLog.h"
H
hjxilinx 已提交
23
#include "tscSubquery.h"
H
hzcheng 已提交
24 25
#include "tscUtil.h"
#include "tsclient.h"
26
#include "ttokendef.h"
H
hjxilinx 已提交
27
#include "tutil.h"
H
hzcheng 已提交
28

29 30 31 32 33 34 35 36 37 38 39 40
static bool validImpl(const char* str, size_t maxsize) {
  if (str == NULL) {
    return false;
  }
  
  size_t len = strlen(str);
  if (len <= 0 || len > maxsize) {
    return false;
  }
  
  return true;
}
H
hzcheng 已提交
41

42
static bool validUserName(const char* user) {
B
Bomin Zhang 已提交
43
  return validImpl(user, TSDB_USER_LEN - 1);
44
}
S
slguan 已提交
45

46
static bool validPassword(const char* passwd) {
B
Bomin Zhang 已提交
47
  return validImpl(passwd, TSDB_PASSWORD_LEN - 1);
48
}
H
hzcheng 已提交
49

H
Haojun Liao 已提交
50
SSqlObj *taosConnectImpl(const char *ip, const char *user, const char *pass, const char *db, uint16_t port,
51 52 53 54
                       void (*fp)(void *, TAOS_RES *, int), void *param, void **taos) {
  taos_init();
  
  if (!validUserName(user)) {
55
    terrno = TSDB_CODE_TSC_INVALID_USER_LENGTH;
H
hzcheng 已提交
56 57 58
    return NULL;
  }

59
  if (!validPassword(pass)) {
60
    terrno = TSDB_CODE_TSC_INVALID_PASS_LENGTH;
H
hzcheng 已提交
61 62
    return NULL;
  }
63 64 65

  if (ip) {
    if (tscSetMgmtIpListFromCfg(ip, NULL) < 0) return NULL;
66
    if (port) tscMgmtIpSet.ipSet.port[0] = port;
67 68
  } 
 
69 70
  void *pDnodeConn = NULL;
  if (tscInitRpc(user, pass, &pDnodeConn) != 0) {
71
    terrno = TSDB_CODE_RPC_NETWORK_UNAVAIL;
S
slguan 已提交
72 73
    return NULL;
  }
74
 
75
  STscObj *pObj = (STscObj *)calloc(1, sizeof(STscObj));
S
slguan 已提交
76
  if (NULL == pObj) {
77
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
78
    rpcClose(pDnodeConn);
S
slguan 已提交
79 80
    return NULL;
  }
H
hjxilinx 已提交
81

H
hzcheng 已提交
82 83
  pObj->signature = pObj;

B
Bomin Zhang 已提交
84
  tstrncpy(pObj->user, user, sizeof(pObj->user));
S
slguan 已提交
85
  taosEncryptPass((uint8_t *)pass, strlen(pass), pObj->pass);
H
hzcheng 已提交
86 87 88 89

  if (db) {
    int32_t len = strlen(db);
    /* db name is too long */
B
Bomin Zhang 已提交
90
    if (len >= TSDB_DB_NAME_LEN) {
91
      terrno = TSDB_CODE_TSC_INVALID_DB_LENGTH;
92 93
      rpcClose(pDnodeConn);
      free(pObj);
H
hzcheng 已提交
94 95 96
      return NULL;
    }

B
Bomin Zhang 已提交
97 98
    char tmp[TSDB_DB_NAME_LEN] = {0};
    tstrncpy(tmp, db, sizeof(tmp));
H
hzcheng 已提交
99 100

    strdequote(tmp);
S
slguan 已提交
101
    strtolower(pObj->db, tmp);
H
hzcheng 已提交
102 103 104 105
  }

  pthread_mutex_init(&pObj->mutex, NULL);

106
  SSqlObj *pSql = (SSqlObj *)calloc(1, sizeof(SSqlObj));
S
slguan 已提交
107
  if (NULL == pSql) {
108
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
109
    rpcClose(pDnodeConn);
S
slguan 已提交
110 111 112
    free(pObj);
    return NULL;
  }
H
hjxilinx 已提交
113

H
hzcheng 已提交
114 115
  pSql->pTscObj = pObj;
  pSql->signature = pSql;
116
  pSql->maxRetry = TSDB_MAX_REPLICA;
S
slguan 已提交
117
  tsem_init(&pSql->rspSem, 0, 0);
H
hjxilinx 已提交
118
  
119 120
  pObj->pDnodeConn = pDnodeConn;
  
H
hzcheng 已提交
121 122 123 124 125 126 127
  pSql->fp = fp;
  pSql->param = param;
  if (taos != NULL) {
    *taos = pObj;
  }

  pSql->cmd.command = TSDB_SQL_CONNECT;
128
  if (TSDB_CODE_SUCCESS != tscAllocPayload(&pSql->cmd, TSDB_DEFAULT_PAYLOAD_SIZE)) {
129
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
130
    rpcClose(pDnodeConn);
S
slguan 已提交
131 132 133 134
    free(pSql);
    free(pObj);
    return NULL;
  }
H
hzcheng 已提交
135

136
  tsInsertHeadSize = sizeof(SMsgDesc) + sizeof(SSubmitMsg);
H
Haojun Liao 已提交
137
  return pSql;
H
hzcheng 已提交
138 139
}

140
static void syncConnCallback(void *param, TAOS_RES *tres, int code) {
H
Haojun Liao 已提交
141 142
  SSqlObj *pSql = (SSqlObj *) tres;
  assert(pSql != NULL);
H
hjxilinx 已提交
143
  
H
Haojun Liao 已提交
144
  sem_post(&pSql->rspSem);
145 146
}

L
lihui 已提交
147
TAOS *taos_connect(const char *ip, const char *user, const char *pass, const char *db, uint16_t port) {
148
  tscDebug("try to create a connection to %s:%u, user:%s db:%s", ip, port, user, db);
S
Shengliang Guan 已提交
149 150
  if (user == NULL) user = TSDB_DEFAULT_USER;
  if (pass == NULL) pass = TSDB_DEFAULT_PASS;
H
hzcheng 已提交
151

H
Haojun Liao 已提交
152 153 154
  STscObj* pObj = NULL;
  SSqlObj *pSql = taosConnectImpl(ip, user, pass, db, port, syncConnCallback, NULL, (void**) &pObj);
  if (pSql != NULL) {
155
    pSql->fp = syncConnCallback;
H
Haojun Liao 已提交
156
    pSql->param = pSql;
157 158 159 160 161
    
    tscProcessSql(pSql);
    sem_wait(&pSql->rspSem);
    
    if (pSql->res.code != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
162
      terrno = pSql->res.code;
H
Haojun Liao 已提交
163
      taos_free_result(pSql);
164 165 166 167
      taos_close(pObj);
      return NULL;
    }
    
168
    tscDebug("%p DB connection is opening, dnodeConn:%p", pObj, pObj->pDnodeConn);
H
Haojun Liao 已提交
169 170
    taos_free_result(pSql);
  
S
slguan 已提交
171
    // version compare only requires the first 3 segments of the version string
172
    int code = taosCheckVersion(version, taos_get_server_info(pObj), 3);
S
slguan 已提交
173
    if (code != 0) {
H
hjxilinx 已提交
174
      terrno = code;
175
      taos_close(pObj);
S
slguan 已提交
176
      return NULL;
177 178
    } else {
      return pObj;
S
slguan 已提交
179
    }
H
hzcheng 已提交
180 181
  }

182
  return NULL;
H
hzcheng 已提交
183
}
dengyihao's avatar
dengyihao 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196
TAOS *taos_connect_c(const char *ip, uint8_t ipLen, const char *user, uint8_t userLen, 
    const char *pass, uint8_t passLen, const char *db, uint8_t dbLen, uint16_t port) {
    char ipBuf[TSDB_EP_LEN] = {0};
    char userBuf[TSDB_USER_LEN] = {0};
    char passBuf[TSDB_PASSWORD_LEN] = {0};
    char dbBuf[TSDB_DB_NAME_LEN] = {0};
    strncpy(ipBuf,   ip,   MIN(TSDB_EP_LEN - 1,     ipLen)); 
    strncpy(userBuf, user, MIN(TSDB_USER_LEN - 1,    userLen)); 
    strncpy(passBuf, pass, MIN(TSDB_PASSWORD_LEN - 1,passLen)); 
    strncpy(dbBuf,   db,   MIN(TSDB_DB_NAME_LEN - 1, dbLen)); 
    return taos_connect(ipBuf, userBuf, passBuf, dbBuf, port);  
}

H
hzcheng 已提交
197

L
lihui 已提交
198
TAOS *taos_connect_a(char *ip, char *user, char *pass, char *db, uint16_t port, void (*fp)(void *, TAOS_RES *, int),
H
hzcheng 已提交
199
                     void *param, void **taos) {
H
Haojun Liao 已提交
200 201
  SSqlObj* pSql = taosConnectImpl(ip, user, pass, db, port, fp, param, taos);
  if (pSql == NULL) {
202 203 204 205
    return NULL;
  }
  
  pSql->res.code = tscProcessSql(pSql);
206
  tscDebug("%p DB async connection is opening", taos);
H
Haojun Liao 已提交
207
  return taos;
H
hzcheng 已提交
208 209 210 211 212
}

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

H
hjxilinx 已提交
213 214 215
  if (pObj == NULL || pObj->signature != pObj)  {
    return;
  }
H
hzcheng 已提交
216 217 218 219 220 221 222 223

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

H
Hui Li 已提交
224
void waitForQueryRsp(void *param, TAOS_RES *tres, int code) {
H
Hui Li 已提交
225
  assert(tres != NULL);
H
[td-99]  
hjxilinx 已提交
226
  
H
Haojun Liao 已提交
227
  SSqlObj *pSql = (SSqlObj *) tres;
H
[td-99]  
hjxilinx 已提交
228
  sem_post(&pSql->rspSem);
229 230
}

231 232 233 234 235
static void waitForRetrieveRsp(void *param, TAOS_RES *tres, int numOfRows) {
  SSqlObj* pSql = (SSqlObj*) tres;
  sem_post(&pSql->rspSem);
}

H
Haojun Liao 已提交
236
TAOS_RES* taos_query(TAOS *taos, const char *sqlstr) {
S
slguan 已提交
237 238
  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) {
239
    terrno = TSDB_CODE_TSC_DISCONNECTED;
H
Haojun Liao 已提交
240
    return NULL;
S
slguan 已提交
241
  }
242
  
H
Haojun Liao 已提交
243 244 245
  int32_t sqlLen = strlen(sqlstr);
  if (sqlLen > tsMaxSQLStringLen) {
    tscError("sql string exceeds max length:%d", tsMaxSQLStringLen);
246
    terrno = TSDB_CODE_TSC_INVALID_SQL;
H
Haojun Liao 已提交
247 248 249 250 251
    return NULL;
  }
  
  taosNotePrintTsc(sqlstr);
  
H
Haojun Liao 已提交
252 253 254
  SSqlObj* pSql = calloc(1, sizeof(SSqlObj));
  if (pSql == NULL) {
    tscError("failed to malloc sqlObj");
255
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
Haojun Liao 已提交
256 257 258
    return NULL;
  }
  
H
[TD-98]  
hjxilinx 已提交
259
  doAsyncQuery(pObj, pSql, waitForQueryRsp, taos, sqlstr, sqlLen);
S
slguan 已提交
260

261
  // wait for the callback function to post the semaphore
H
Haojun Liao 已提交
262
  tsem_wait(&pSql->rspSem);
H
Haojun Liao 已提交
263
  return pSql;
H
hzcheng 已提交
264
}
dengyihao's avatar
dengyihao 已提交
265
TAOS_RES* taos_query_c(TAOS *taos, const char *sqlstr, uint32_t sqlLen) {
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) {
    terrno = TSDB_CODE_TSC_DISCONNECTED;
    return NULL;
  }
  
  if (sqlLen > tsMaxSQLStringLen) {
    tscError("sql string exceeds max length:%d", tsMaxSQLStringLen);
    terrno = TSDB_CODE_TSC_INVALID_SQL;
    return NULL;
  }
  
  SSqlObj* pSql = calloc(1, sizeof(SSqlObj));
  if (pSql == NULL) {
    tscError("failed to malloc sqlObj");
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return NULL;
  }
  
  doAsyncQuery(pObj, pSql, waitForQueryRsp, taos, sqlstr, sqlLen);

  tsem_wait(&pSql->rspSem);
  return pSql; 
dengyihao's avatar
dengyihao 已提交
289
}
H
hzcheng 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302
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;

H
hjxilinx 已提交
303
  int32_t num = 0;
304
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
305
  if (pQueryInfo == NULL) {
H
hjxilinx 已提交
306
    return num;
307
  }
308

H
hjxilinx 已提交
309 310 311 312 313 314 315 316 317
  size_t numOfCols = tscNumOfFields(pQueryInfo);
  for(int32_t i = 0; i < numOfCols; ++i) {
    SFieldSupInfo* pInfo = taosArrayGet(pQueryInfo->fieldsInfo.pSupportInfo, i);
    if (pInfo->visible) {
      num++;
    }
  }
  
  return num;
H
hzcheng 已提交
318 319
}

H
Haojun Liao 已提交
320 321 322
int taos_field_count(TAOS_RES *tres) {
  SSqlObj* pSql = (SSqlObj*) tres;
  if (pSql == NULL || pSql->signature != pSql) return 0;
H
hzcheng 已提交
323

H
Haojun Liao 已提交
324
  return taos_num_fields(pSql);
H
hzcheng 已提交
325 326
}

H
Haojun Liao 已提交
327 328 329
int taos_affected_rows(TAOS_RES *tres) {
  SSqlObj* pSql = (SSqlObj*) tres;
  if (pSql == NULL || pSql->signature != pSql) return 0;
H
hzcheng 已提交
330

H
Haojun Liao 已提交
331
  return (pSql->res.numOfRows);
H
hzcheng 已提交
332 333 334 335 336
}

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

  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
H
hjxilinx 已提交
339
  if (pQueryInfo == NULL) {
sangshuduo's avatar
sangshuduo 已提交
340
    return NULL;
H
hjxilinx 已提交
341 342 343 344 345 346 347 348
  }
  
  size_t numOfCols = tscNumOfFields(pQueryInfo);
  if (numOfCols == 0) {
    return NULL;
  }
  
  return pQueryInfo->fieldsInfo.pFields->pData;
H
hzcheng 已提交
349 350 351 352 353 354 355 356 357 358
}

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 已提交
359 360
  tscResetForNextRetrieve(pRes);

H
hzcheng 已提交
361 362 363 364 365 366 367 368 369 370 371 372 373
  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;

H
Haojun Liao 已提交
374
  if (pRes->qhandle == 0 || pSql->signature != pSql) {
H
hzcheng 已提交
375 376 377 378 379
    *rows = NULL;
    return 0;
  }

  // Retrieve new block
S
slguan 已提交
380
  tscResetForNextRetrieve(pRes);
H
hzcheng 已提交
381 382 383 384 385 386 387 388 389 390
  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 已提交
391
  // secondary merge has handle this situation
H
hjxilinx 已提交
392
  if (pCmd->command != TSDB_SQL_RETRIEVE_LOCALMERGE) {
H
Haojun Liao 已提交
393
    pRes->numOfClauseTotal += pRes->numOfRows;
S
slguan 已提交
394 395
  }

396
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
sangshuduo's avatar
sangshuduo 已提交
397 398 399
  if (pQueryInfo == NULL)
    return 0;

H
hjxilinx 已提交
400
  assert(0);
H
hjxilinx 已提交
401
  for (int i = 0; i < pQueryInfo->fieldsInfo.numOfOutput; ++i) {
402
    tscGetResultColumnChr(pRes, &pQueryInfo->fieldsInfo, i);
H
hzcheng 已提交
403 404 405 406
  }

  *rows = pRes->tsrow;

407
  return (pQueryInfo->order.order == TSDB_ORDER_DESC) ? pRes->numOfRows : -pRes->numOfRows;
H
hzcheng 已提交
408 409 410 411 412
}

TAOS_ROW taos_fetch_row(TAOS_RES *res) {
  SSqlObj *pSql = (SSqlObj *)res;
  if (pSql == NULL || pSql->signature != pSql) {
413
    terrno = TSDB_CODE_TSC_DISCONNECTED;
H
hzcheng 已提交
414 415
    return NULL;
  }
416 417 418 419
  
  SSqlCmd *pCmd = &pSql->cmd;
  SSqlRes *pRes = &pSql->res;
  
H
hjxilinx 已提交
420 421 422
  if (pRes->qhandle == 0 ||
      pCmd->command == TSDB_SQL_RETRIEVE_EMPTY_RESULT ||
      pCmd->command == TSDB_SQL_INSERT) {
423
    return NULL;
424
  }
425
  
426 427
  // current data set are exhausted, fetch more data from node
  if (pRes->row >= pRes->numOfRows && (pRes->completed != true || hasMoreVnodesToTry(pSql)) &&
H
hjxilinx 已提交
428
      (pCmd->command == TSDB_SQL_RETRIEVE ||
H
hjxilinx 已提交
429
       pCmd->command == TSDB_SQL_RETRIEVE_LOCALMERGE ||
430
       pCmd->command == TSDB_SQL_TABLE_JOIN_RETRIEVE ||
H
hjxilinx 已提交
431 432 433
       pCmd->command == TSDB_SQL_FETCH ||
       pCmd->command == TSDB_SQL_SHOW ||
       pCmd->command == TSDB_SQL_SELECT ||
H
Haojun Liao 已提交
434 435 436 437 438 439
       pCmd->command == TSDB_SQL_DESCRIBE_TABLE ||
       pCmd->command == TSDB_SQL_SERV_STATUS ||
       pCmd->command == TSDB_SQL_CURRENT_DB ||
       pCmd->command == TSDB_SQL_SERV_VERSION ||
       pCmd->command == TSDB_SQL_CLI_VERSION ||
       pCmd->command == TSDB_SQL_CURRENT_USER )) {
H
[td-99]  
hjxilinx 已提交
440
    taos_fetch_rows_a(res, waitForRetrieveRsp, pSql->pTscObj);
441
    sem_wait(&pSql->rspSem);
H
hjxilinx 已提交
442
  }
H
Haojun Liao 已提交
443

H
hjxilinx 已提交
444
  return doSetResultRowData(pSql, true);
H
hzcheng 已提交
445 446 447
}

int taos_fetch_block(TAOS_RES *res, TAOS_ROW *rows) {
H
hjxilinx 已提交
448
#if 0
H
hzcheng 已提交
449
  SSqlObj *pSql = (SSqlObj *)res;
H
hjxilinx 已提交
450
  SSqlCmd *pCmd = &pSql->cmd;
451
  SSqlRes *pRes = &pSql->res;
452

H
hzcheng 已提交
453 454 455
  int nRows = 0;

  if (pSql == NULL || pSql->signature != pSql) {
456
    terrno = TSDB_CODE_TSC_DISCONNECTED;
H
hzcheng 已提交
457 458 459 460
    *rows = NULL;
    return 0;
  }

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

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

469
    pSql->cmd.command = pQueryInfo->command;
H
hjxilinx 已提交
470
    pCmd->clauseIndex++;
471

H
Haojun Liao 已提交
472 473
    pRes->numOfTotal += pRes->numOfClauseTotal;
    pRes->numOfClauseTotal = 0;
474
    pRes->rspType = 0;
475

476 477
    pSql->numOfSubs = 0;
    tfree(pSql->pSubs);
478

H
hjxilinx 已提交
479
    assert(pSql->fp == NULL);
480

481
    tscDebug("%p try data in the next subclause:%d, total subclause:%d", pSql, pCmd->clauseIndex, pCmd->numOfClause);
H
hjxilinx 已提交
482
    tscProcessSql(pSql);
483

H
hjxilinx 已提交
484
    nRows = taos_fetch_block_impl(res, rows);
H
hzcheng 已提交
485
  }
486

H
hzcheng 已提交
487
  return nRows;
H
hjxilinx 已提交
488 489 490 491
#endif

  (*rows) = taos_fetch_row(res);
  return ((*rows) != NULL)? 1:0;
H
hzcheng 已提交
492 493
}

S
slguan 已提交
494
int taos_select_db(TAOS *taos, const char *db) {
495
  char sql[256] = {0};
H
hzcheng 已提交
496 497 498

  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) {
499 500
    terrno = TSDB_CODE_TSC_DISCONNECTED;
    return TSDB_CODE_TSC_DISCONNECTED;
H
hzcheng 已提交
501 502
  }

503
  snprintf(sql, tListLen(sql), "use %s", db);
H
Haojun Liao 已提交
504 505 506 507 508
  SSqlObj* pSql = taos_query(taos, sql);
  int32_t code = pSql->res.code;
  taos_free_result(pSql);
  
  return code;
H
hzcheng 已提交
509 510
}

H
Haojun Liao 已提交
511
// send free message to vnode to free qhandle and corresponding resources in vnode
H
Haojun Liao 已提交
512
static bool tscFreeQhandleInVnode(SSqlObj* pSql) {
H
Haojun Liao 已提交
513 514 515 516 517 518 519 520
  SSqlCmd* pCmd = &pSql->cmd;
  SSqlRes* pRes = &pSql->res;

  SQueryInfo* pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);

  if (pRes->code == TSDB_CODE_SUCCESS && pRes->completed == false && !tscIsTwoStageSTableQuery(pQueryInfo, 0) &&
      (pCmd->command == TSDB_SQL_SELECT ||
H
Haojun Liao 已提交
521 522 523 524
       pCmd->command == TSDB_SQL_SHOW ||
       pCmd->command == TSDB_SQL_RETRIEVE ||
       pCmd->command == TSDB_SQL_FETCH) &&
      (pSql->pStream == NULL && pTableMetaInfo->pTableMeta != NULL)) {
H
Haojun Liao 已提交
525 526

    pCmd->command = (pCmd->command > TSDB_SQL_MGMT) ? TSDB_SQL_RETRIEVE : TSDB_SQL_FETCH;
H
Haojun Liao 已提交
527
    tscDebug("%p send msg to dnode to free qhandle ASAP, command:%s, ", pSql, sqlCmd[pCmd->command]);
H
Haojun Liao 已提交
528
    tscProcessSql(pSql);
H
Haojun Liao 已提交
529
    return true;
H
Haojun Liao 已提交
530
  }
H
Haojun Liao 已提交
531 532

  return false;
H
Haojun Liao 已提交
533 534
}

H
Haojun Liao 已提交
535
void taos_free_result(TAOS_RES *res) {
H
hzcheng 已提交
536
  SSqlObj *pSql = (SSqlObj *)res;
H
Haojun Liao 已提交
537

H
Haojun Liao 已提交
538
  if (pSql == NULL || pSql->signature != pSql) {
539
    tscDebug("%p sqlObj has been freed", pSql);
H
Haojun Liao 已提交
540 541
    return;
  }
H
Haojun Liao 已提交
542
  
H
Haojun Liao 已提交
543
  // The semaphore can not be changed while freeing async sub query objects.
H
Haojun Liao 已提交
544
  SSqlRes *pRes = &pSql->res;
H
Haojun Liao 已提交
545 546
  if (pRes == NULL || pRes->qhandle == 0) {
    tscFreeSqlObj(pSql);
547
    tscDebug("%p SqlObj is freed by app, qhandle is null", pSql);
H
hzcheng 已提交
548 549 550
    return;
  }

H
Haojun Liao 已提交
551
  // set freeFlag to 1 in retrieve message if there are un-retrieved results data in node
552
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(&pSql->cmd, 0);
553
  if (pQueryInfo == NULL) {
H
Haojun Liao 已提交
554
    tscFreeSqlObj(pSql);
555
    tscDebug("%p SqlObj is freed by app", pSql);
556 557 558
    return;
  }

559
  pQueryInfo->type = TSDB_QUERY_TYPE_FREE_RESOURCE;
H
Haojun Liao 已提交
560 561
  if (!tscFreeQhandleInVnode(pSql)) {
    tscFreeSqlObj(pSql);
562
    tscDebug("%p sqlObj is freed by app", pSql);
H
hzcheng 已提交
563 564 565
  }
}

H
[td-99]  
hjxilinx 已提交
566
// todo should not be used in async query
H
Haojun Liao 已提交
567 568
int taos_errno(TAOS_RES *tres) {
  SSqlObj *pSql = (SSqlObj *) tres;
H
hzcheng 已提交
569

H
Haojun Liao 已提交
570
  if (pSql == NULL || pSql->signature != pSql) {
H
[td-99]  
hjxilinx 已提交
571 572
    return terrno;
  }
H
hzcheng 已提交
573

H
Haojun Liao 已提交
574
  return pSql->res.code;
H
hzcheng 已提交
575 576
}

H
hjxilinx 已提交
577 578 579 580
/*
 * In case of invalid sql error, additional information is attached to explain
 * why the sql is invalid
 */
H
hjxilinx 已提交
581
static bool hasAdditionalErrorInfo(int32_t code, SSqlCmd *pCmd) {
582
  if (code != TSDB_CODE_TSC_INVALID_SQL) {
H
hjxilinx 已提交
583 584 585 586
    return false;
  }

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

  char *z = NULL;
H
hjxilinx 已提交
589
  if (len > 0) {
H
hjxilinx 已提交
590
    z = strstr(pCmd->payload, "invalid SQL");
H
hjxilinx 已提交
591
  }
H
hjxilinx 已提交
592

H
hjxilinx 已提交
593 594 595
  return z != NULL;
}

H
[td-99]  
hjxilinx 已提交
596
// todo should not be used in async model
H
Haojun Liao 已提交
597 598
char *taos_errstr(TAOS_RES *tres) {
  SSqlObj *pSql = (SSqlObj *) tres;
H
hzcheng 已提交
599

H
Haojun Liao 已提交
600 601 602
  if (pSql == NULL || pSql->signature != pSql) {
    return (char*) tstrerror(terrno);
  }
H
hzcheng 已提交
603

H
[td-32]  
hjxilinx 已提交
604
  if (hasAdditionalErrorInfo(pSql->res.code, &pSql->cmd)) {
H
hjxilinx 已提交
605
    return pSql->cmd.payload;
H
hzcheng 已提交
606
  } else {
H
[td-32]  
hjxilinx 已提交
607
    return (char*)tstrerror(pSql->res.code);
H
hzcheng 已提交
608 609 610 611 612
  }
}

void taos_config(int debug, char *log_path) {
  uDebugFlag = debug;
B
Bomin Zhang 已提交
613
  tstrncpy(tsLogDir, log_path, TSDB_FILENAME_LEN);
H
hzcheng 已提交
614 615 616 617 618 619 620 621 622 623
}

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

  if (pObj == NULL) return NULL;

  return pObj->sversion;
}

624 625 626 627 628 629 630 631 632
int* taos_fetch_lengths(TAOS_RES *res) {
  SSqlObj* pSql = (SSqlObj* ) res;
  if (pSql == NULL || pSql->signature != pSql) {
    return NULL;
  }
  
  return pSql->res.length;
}

H
hzcheng 已提交
633 634 635
char *taos_get_client_info() { return version; }

void taos_stop_query(TAOS_RES *res) {
636 637 638
  if (res == NULL) {
    return;
  }
H
hzcheng 已提交
639 640

  SSqlObj *pSql = (SSqlObj *)res;
641 642
  SSqlCmd *pCmd = &pSql->cmd;

H
hzcheng 已提交
643
  if (pSql->signature != pSql) return;
644
  tscDebug("%p start to cancel query", res);
H
hzcheng 已提交
645 646


647
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, pCmd->clauseIndex);
H
hjxilinx 已提交
648
  if (tscIsTwoStageSTableQuery(pQueryInfo, 0)) {
H
hjxilinx 已提交
649
    tscKillSTableQuery(pSql);
H
hzcheng 已提交
650 651
  }

dengyihao's avatar
dengyihao 已提交
652 653
  if (pSql->cmd.command < TSDB_SQL_LOCAL) {
    rpcCancelRequest(pSql->pRpcCtx);
H
hzcheng 已提交
654
  }
dengyihao's avatar
dengyihao 已提交
655 656
  pSql->res.code = TSDB_CODE_TSC_QUERY_CANCELLED;
  tscQueueAsyncRes(pSql);
H
hzcheng 已提交
657

658
  tscDebug("%p query is cancelled", res);
H
hzcheng 已提交
659 660 661 662 663
}

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) {
664 665 666 667
    if (i > 0) {
      str[len++] = ' ';
    }

H
hzcheng 已提交
668
    if (row[i] == NULL) {
669
      len += sprintf(str + len, "%s", TSDB_DATA_NULL_STR);
H
hzcheng 已提交
670 671 672 673 674
      continue;
    }

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

      case TSDB_DATA_TYPE_SMALLINT:
679
        len += sprintf(str + len, "%d", *((short *)row[i]));
H
hzcheng 已提交
680 681 682
        break;

      case TSDB_DATA_TYPE_INT:
683
        len += sprintf(str + len, "%d", *((int *)row[i]));
H
hzcheng 已提交
684 685 686
        break;

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

L
lihui 已提交
690 691
      case TSDB_DATA_TYPE_FLOAT: {
        float fv = 0;
L
lihui 已提交
692
        fv = GET_FLOAT_VAL(row[i]);
693
        len += sprintf(str + len, "%f", fv);
694
      } break;
H
hzcheng 已提交
695

696
      case TSDB_DATA_TYPE_DOUBLE: {
L
lihui 已提交
697
        double dv = 0;
L
lihui 已提交
698
        dv = GET_DOUBLE_VAL(row[i]);
699
        len += sprintf(str + len, "%lf", dv);
700
      } break;
H
hzcheng 已提交
701 702

      case TSDB_DATA_TYPE_BINARY:
S
slguan 已提交
703
      case TSDB_DATA_TYPE_NCHAR: {
H
hjxilinx 已提交
704
        size_t xlen = 0;
705
        for (xlen = 0; xlen < fields[i].bytes - VARSTR_HEADER_SIZE; xlen++) {
H
hjxilinx 已提交
706 707 708 709 710 711
          char c = ((char *)row[i])[xlen];
          if (c == 0) break;
          str[len++] = c;
        }
        str[len] = 0;
      } break;
H
hzcheng 已提交
712 713

      case TSDB_DATA_TYPE_TIMESTAMP:
714
        len += sprintf(str + len, "%" PRId64, *((int64_t *)row[i]));
H
hzcheng 已提交
715 716 717
        break;

      case TSDB_DATA_TYPE_BOOL:
718
        len += sprintf(str + len, "%d", *((int8_t *)row[i]));
H
hzcheng 已提交
719 720 721 722 723 724 725 726
      default:
        break;
    }
  }

  return len;
}

S
slguan 已提交
727
int taos_validate_sql(TAOS *taos, const char *sql) {
H
hzcheng 已提交
728 729
  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) {
730 731
    terrno = TSDB_CODE_TSC_DISCONNECTED;
    return TSDB_CODE_TSC_DISCONNECTED;
H
hzcheng 已提交
732 733
  }

H
Haojun Liao 已提交
734 735
  SSqlObj* pSql = calloc(1, sizeof(SSqlObj));
  
H
hzcheng 已提交
736
  SSqlRes *pRes = &pSql->res;
737 738
  SSqlCmd *pCmd = &pSql->cmd;
  
H
hzcheng 已提交
739
  pRes->numOfTotal = 0;
H
Haojun Liao 已提交
740
  pRes->numOfClauseTotal = 0;
741

742
  tscDebug("%p Valid SQL: %s pObj:%p", pSql, sql, pObj);
H
hzcheng 已提交
743 744

  int32_t sqlLen = strlen(sql);
H
hjxilinx 已提交
745
  if (sqlLen > tsMaxSQLStringLen) {
H
hzcheng 已提交
746
    tscError("%p sql too long", pSql);
747
    pRes->code = TSDB_CODE_TSC_INVALID_SQL;
B
Bomin Zhang 已提交
748
    tfree(pSql);
H
hzcheng 已提交
749 750 751 752 753
    return pRes->code;
  }

  pSql->sqlstr = realloc(pSql->sqlstr, sqlLen + 1);
  if (pSql->sqlstr == NULL) {
754
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hzcheng 已提交
755
    tscError("%p failed to malloc sql string buffer", pSql);
756
    tscDebug("%p Valid SQL result:%d, %s pObj:%p", pSql, pRes->code, taos_errstr(taos), pObj);
B
Bomin Zhang 已提交
757
    tfree(pSql);
H
hzcheng 已提交
758 759 760
    return pRes->code;
  }

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

763 764 765 766
  pCmd->curSql = NULL;
  if (NULL != pCmd->pTableList) {
    taosHashCleanup(pCmd->pTableList);
    pCmd->pTableList = NULL;
L
lihui 已提交
767 768
  }

769
  pRes->code = (uint8_t)tsParseSql(pSql, false);
H
hzcheng 已提交
770 771
  int code = pRes->code;

772
  tscDebug("%p Valid SQL result:%d, %s pObj:%p", pSql, pRes->code, taos_errstr(taos), pObj);
H
hzcheng 已提交
773 774 775 776
  taos_free_result(pSql);

  return code;
}
S
slguan 已提交
777

H
hjxilinx 已提交
778
static int tscParseTblNameList(SSqlObj *pSql, const char *tblNameList, int32_t tblListLen) {
S
slguan 已提交
779
  // must before clean the sqlcmd object
780
  tscResetSqlCmdObj(&pSql->cmd);
S
slguan 已提交
781 782 783 784 785 786

  SSqlCmd *pCmd = &pSql->cmd;

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

787
  int   code = TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
H
hjxilinx 已提交
788
  char *str = (char *)tblNameList;
S
slguan 已提交
789

790 791 792
  SQueryInfo *pQueryInfo = NULL;
  tscGetQueryInfoDetailSafely(pCmd, pCmd->clauseIndex, &pQueryInfo);

H
hjxilinx 已提交
793
  STableMetaInfo *pTableMetaInfo = tscAddEmptyMetaInfo(pQueryInfo);
S
slguan 已提交
794

H
hjxilinx 已提交
795
  if ((code = tscAllocPayload(pCmd, tblListLen + 16)) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
796 797 798 799
    return code;
  }

  char *nextStr;
S
slguan 已提交
800
  char  tblName[TSDB_TABLE_ID_LEN];
S
slguan 已提交
801 802 803 804 805 806 807 808 809 810 811 812 813
  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;
H
Haojun Liao 已提交
814
    len = strtrim(tblName);
H
hjxilinx 已提交
815

S
slguan 已提交
816 817 818 819 820
    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) {
821
      code = TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
S
slguan 已提交
822 823 824 825
      sprintf(pCmd->payload, "table name is invalid");
      return code;
    }

H
Haojun Liao 已提交
826
    if ((code = tscSetTableFullName(pTableMetaInfo, &sToken, pSql)) != TSDB_CODE_SUCCESS) {
S
slguan 已提交
827 828 829 830
      return code;
    }

    if (++pCmd->count > TSDB_MULTI_METERMETA_MAX_NUM) {
831
      code = TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
S
slguan 已提交
832 833 834 835
      sprintf(pCmd->payload, "tables over the max number");
      return code;
    }

H
hjxilinx 已提交
836
    if (payloadLen + strlen(pTableMetaInfo->name) + 128 >= pCmd->allocSize) {
S
slguan 已提交
837 838
      char *pNewMem = realloc(pCmd->payload, pCmd->allocSize + tblListLen);
      if (pNewMem == NULL) {
839
        code = TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
840 841 842 843 844 845 846 847 848
        sprintf(pCmd->payload, "failed to allocate memory");
        return code;
      }

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

H
hjxilinx 已提交
849
    payloadLen += sprintf(pMsg + payloadLen, "%s,", pTableMetaInfo->name);
S
slguan 已提交
850 851 852 853 854 855 856 857 858
  }

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

  return TSDB_CODE_SUCCESS;
}

int taos_load_table_info(TAOS *taos, const char *tableNameList) {
H
hjxilinx 已提交
859
  const int32_t MAX_TABLE_NAME_LENGTH = 12 * 1024 * 1024;  // 12MB list
S
slguan 已提交
860 861 862

  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) {
863 864
    terrno = TSDB_CODE_TSC_DISCONNECTED;
    return TSDB_CODE_TSC_DISCONNECTED;
S
slguan 已提交
865 866
  }

H
Haojun Liao 已提交
867
  SSqlObj* pSql = calloc(1, sizeof(SSqlObj));
S
slguan 已提交
868 869 870
  SSqlRes *pRes = &pSql->res;

  pRes->numOfTotal = 0;  // the number of getting table meta from server
H
Haojun Liao 已提交
871
  pRes->numOfClauseTotal = 0;
872

S
slguan 已提交
873 874 875
  pRes->code = 0;

  assert(pSql->fp == NULL);
876
  tscDebug("%p tableNameList: %s pObj:%p", pSql, tableNameList, pObj);
S
slguan 已提交
877 878 879 880

  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);
881
    pRes->code = TSDB_CODE_TSC_INVALID_SQL;
B
Bomin Zhang 已提交
882
    tfree(pSql);
S
slguan 已提交
883 884 885
    return pRes->code;
  }

H
hjxilinx 已提交
886
  char *str = calloc(1, tblListLen + 1);
S
slguan 已提交
887
  if (str == NULL) {
888
    pRes->code = TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
889
    tscError("%p failed to malloc sql string buffer", pSql);
B
Bomin Zhang 已提交
890
    tfree(pSql);
S
slguan 已提交
891 892 893 894
    return pRes->code;
  }

  strtolower(str, tableNameList);
H
hjxilinx 已提交
895
  pRes->code = (uint8_t)tscParseTblNameList(pSql, str, tblListLen);
S
slguan 已提交
896 897 898 899 900 901 902 903 904 905

  /*
   * 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) {
B
Bomin Zhang 已提交
906
    tscFreeSqlObj(pSql);
S
slguan 已提交
907 908 909 910 911
    return pRes->code;
  }

  tscDoQuery(pSql);

912
  tscDebug("%p load multi metermeta result:%d %s pObj:%p", pSql, pRes->code, taos_errstr(taos), pObj);
S
slguan 已提交
913
  if (pRes->code != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
914
    tscPartiallyFreeSqlObj(pSql);
S
slguan 已提交
915 916 917 918
  }

  return pRes->code;
}