parserUtil.c 58.4 KB
Newer Older
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/>.
 */
15

16 17 18 19
#include "parserUtil.h"
#include <tglobal.h>
#include <ttime.h>
#include "function.h"
20
#include "parser.h"
21 22
#include "parserInt.h"
#include "queryInfoUtil.h"
23
#include "taoserror.h"
24
#include "tbuffer.h"
25 26
#include "thash.h"
#include "tmsg.h"
27
#include "tmsgtype.h"
28 29
#include "ttypes.h"
#include "tutil.h"
30 31 32 33 34 35 36 37 38 39

typedef struct STableFilterCond {
  uint64_t uid;
  int16_t  idx;  //table index
  int32_t  len;  // length of tag query condition data
  char *   cond;
} STableFilterCond;

static STableMetaInfo* addTableMetaInfo(SQueryStmtInfo* pQueryInfo, SName* name, STableMeta* pTableMeta,
                                        SVgroupsInfo* vgroupList, SArray* pTagCols, SArray* pVgroupTables);
40

41
int32_t parserValidateIdToken(SToken* pToken) {
42 43 44 45
  if (pToken == NULL || pToken->z == NULL || pToken->type != TK_ID) {
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

46 47 48 49 50
  // it is a token quoted with escape char '`'
  if (pToken->z[0] == TS_ESCAPE_CHAR && pToken->z[pToken->n - 1] == TS_ESCAPE_CHAR) {
    return TSDB_CODE_SUCCESS;
  }

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
  char* sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true);
  if (sep == NULL) {  // It is a single part token, not a complex type
    if (isNumber(pToken)) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    strntolower(pToken->z, pToken->z, pToken->n);
  } else {  // two part
    int32_t oldLen = pToken->n;
    char*   pStr = pToken->z;

    if (pToken->type == TK_SPACE) {
      pToken->n = (uint32_t)strtrim(pToken->z);
    }

    pToken->n = tGetToken(pToken->z, &pToken->type);
    if (pToken->z[pToken->n] != TS_PATH_DELIMITER[0]) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    if (pToken->type != TK_ID) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    int32_t firstPartLen = pToken->n;

    pToken->z = sep + 1;
    pToken->n = (uint32_t)(oldLen - (sep - pStr) - 1);
    int32_t len = tGetToken(pToken->z, &pToken->type);
    if (len != pToken->n || pToken->type != TK_ID) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

    // re-build the whole name string
    if (pStr[firstPartLen] == TS_PATH_DELIMITER[0]) {
      // first part do not have quote do nothing
    } else {
      pStr[firstPartLen] = TS_PATH_DELIMITER[0];
      memmove(&pStr[firstPartLen + 1], pToken->z, pToken->n);
      uint32_t offset = (uint32_t)(pToken->z - (pStr + firstPartLen + 1));
      memset(pToken->z + pToken->n - offset, ' ', offset);
    }

    pToken->n += (firstPartLen + sizeof(TS_PATH_DELIMITER[0]));
    pToken->z = pStr;

    strntolower(pToken->z, pToken->z, pToken->n);
  }

  return TSDB_CODE_SUCCESS;
101 102
}

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
int32_t parserValidatePassword(SToken* pToken, SMsgBuf* pMsgBuf) {
  const char* msg1 = "password can not be empty";
  const char* msg2 = "name or password too long";
  const char* msg3 = "password needs single quote marks enclosed";

  if (pToken->type != TK_STRING) {
    return buildInvalidOperationMsg(pMsgBuf, msg3);
  }

  strdequote(pToken->z);

  pToken->n = (uint32_t)strtrim(pToken->z);  // trim space before and after passwords
  if (pToken->n <= 0) {
    return buildInvalidOperationMsg(pMsgBuf, msg1);
  }

  if (pToken->n >= TSDB_USET_PASSWORD_LEN) {
    return buildInvalidOperationMsg(pMsgBuf, msg2);
  }

  return TSDB_CODE_SUCCESS;
}

H
Haojun Liao 已提交
126
int32_t parserValidateNameToken(SToken* pToken) {
127
  if (pToken == NULL || pToken->z == NULL || pToken->type != TK_ID || pToken->n == 0) {
H
Haojun Liao 已提交
128 129 130 131 132
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

  // it is a token quoted with escape char '`'
  if (pToken->z[0] == TS_ESCAPE_CHAR && pToken->z[pToken->n - 1] == TS_ESCAPE_CHAR) {
133
    pToken->n = strdequote(pToken->z);
H
Haojun Liao 已提交
134 135 136 137 138 139 140 141 142 143 144 145
    return TSDB_CODE_SUCCESS;
  }

  char* sep = strnchr(pToken->z, TS_PATH_DELIMITER[0], pToken->n, true);
  if (sep != NULL) {  // It is a complex type, not allow
    return TSDB_CODE_TSC_INVALID_OPERATION;
  }

  strntolower(pToken->z, pToken->z, pToken->n);
  return TSDB_CODE_SUCCESS;
}

146 147
int32_t buildInvalidOperationMsg(SMsgBuf* pBuf, const char* msg) {
  strncpy(pBuf->buf, msg, pBuf->len);
148
  return TSDB_CODE_TSC_INVALID_OPERATION;
149 150
}

151
int32_t buildSyntaxErrMsg(SMsgBuf* pBuf, const char* additionalInfo, const char* sourceStr) {
152 153 154 155 156 157 158
  const char* msgFormat1 = "syntax error near \'%s\'";
  const char* msgFormat2 = "syntax error near \'%s\' (%s)";
  const char* msgFormat3 = "%s";

  const char* prefix = "syntax error";
  if (sourceStr == NULL) {
    assert(additionalInfo != NULL);
159
    snprintf(pBuf->buf, pBuf->len, msgFormat1, additionalInfo);
160 161 162 163 164 165 166
    return TSDB_CODE_TSC_SQL_SYNTAX_ERROR;
  }

  char buf[64] = {0};  // only extract part of sql string
  strncpy(buf, sourceStr, tListLen(buf) - 1);

  if (additionalInfo != NULL) {
167
    snprintf(pBuf->buf, pBuf->len, msgFormat2, buf, additionalInfo);
168 169
  } else {
    const char* msgFormat = (0 == strncmp(sourceStr, prefix, strlen(prefix))) ? msgFormat3 : msgFormat1;
170
    snprintf(pBuf->buf, pBuf->len, msgFormat, buf);
171 172 173
  }

  return TSDB_CODE_TSC_SQL_SYNTAX_ERROR;
174
}
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560

SCond* getSTableQueryCond(STagCond* pTagCond, uint64_t uid) {
  if (pTagCond->pCond == NULL) {
    return NULL;
  }

  size_t size = taosArrayGetSize(pTagCond->pCond);
  for (int32_t i = 0; i < size; ++i) {
    SCond* pCond = taosArrayGet(pTagCond->pCond, i);

    if (uid == pCond->uid) {
      return pCond;
    }
  }

  return NULL;
}

STableFilterCond* tsGetTableFilter(SArray* filters, uint64_t uid, int16_t idx) {
  if (filters == NULL) {
    return NULL;
  }

  size_t size = taosArrayGetSize(filters);
  for (int32_t i = 0; i < size; ++i) {
    STableFilterCond* cond = taosArrayGet(filters, i);

    if (uid == cond->uid && (idx >= 0 && cond->idx == idx)) {
      return cond;
    }
  }

  return NULL;
}

void setSTableQueryCond(STagCond* pTagCond, uint64_t uid, SBufferWriter* bw) {
  if (tbufTell(bw) == 0) {
    return;
  }

  SCond cond = {
      .uid = uid,
      .len = (int32_t)(tbufTell(bw)),
      .cond = NULL,
  };

  cond.cond = tbufGetData(bw, true);

  if (pTagCond->pCond == NULL) {
    pTagCond->pCond = taosArrayInit(3, sizeof(SCond));
  }

  taosArrayPush(pTagCond->pCond, &cond);
}

//typedef struct SJoinStatus {
//  SSDataBlock* pBlock;   // point to the upstream block
//  int32_t      index;
//  bool         completed;// current upstream is completed or not
//} SJoinStatus;

/*
static void createInputDataFilterInfo(SQueryStmtInfo* px, int32_t numOfCol1, int32_t* numOfFilterCols, SSingleColumnFilterInfo** pFilterInfo) {
  SColumnInfo* tableCols = calloc(numOfCol1, sizeof(SColumnInfo));
  for(int32_t i = 0; i < numOfCol1; ++i) {
    SColumn* pCol = taosArrayGetP(px->colList, i);
    if (pCol->info.flist.numOfFilters > 0) {
      (*numOfFilterCols) += 1;
    }

    tableCols[i] = pCol->info;
  }

  if ((*numOfFilterCols) > 0) {
    doCreateFilterInfo(tableCols, numOfCol1, (*numOfFilterCols), pFilterInfo, 0);
  }

  tfree(tableCols);
}
*/

//void destroyTableNameList(SInsertStatementParam* pInsertParam) {
//  if (pInsertParam->numOfTables == 0) {
//    assert(pInsertParam->pTableNameList == NULL);
//    return;
//  }
//
//  for(int32_t i = 0; i < pInsertParam->numOfTables; ++i) {
//    tfree(pInsertParam->pTableNameList[i]);
//  }
//
//  pInsertParam->numOfTables = 0;
//  tfree(pInsertParam->pTableNameList);
//}

//void tscDestroyBoundColumnInfo(SParsedDataColInfo* pColInfo) {
//  tfree(pColInfo->boundedColumns);
//  tfree(pColInfo->cols);
//  tfree(pColInfo->colIdxInfo);
//}
//
//void tscDestroyDataBlock(STableDataBlocks* pDataBlock, bool removeMeta) {
//  if (pDataBlock == NULL) {
//    return;
//  }
//
//  tfree(pDataBlock->pData);
//
//  if (removeMeta) {
//    char name[TSDB_TABLE_FNAME_LEN] = {0};
//    tNameExtractFullName(&pDataBlock->tableName, name);
//
//    taosHashRemove(tscTableMetaMap, name, strnlen(name, TSDB_TABLE_FNAME_LEN));
//  }
//
//  if (!pDataBlock->cloned) {
//    tfree(pDataBlock->params);
//
//    // free the refcount for metermeta
//    if (pDataBlock->pTableMeta != NULL) {
//      tfree(pDataBlock->pTableMeta);
//    }
//
//    tscDestroyBoundColumnInfo(&pDataBlock->boundColumnInfo);
//  }
//
//  tfree(pDataBlock);
//}

//SParamInfo* tscAddParamToDataBlock(STableDataBlocks* pDataBlock, char type, uint8_t timePrec, int16_t bytes,
//                                   uint32_t offset) {
//  uint32_t needed = pDataBlock->numOfParams + 1;
//  if (needed > pDataBlock->numOfAllocedParams) {
//    needed *= 2;
//    void* tmp = realloc(pDataBlock->params, needed * sizeof(SParamInfo));
//    if (tmp == NULL) {
//      return NULL;
//    }
//    pDataBlock->params = (SParamInfo*)tmp;
//    pDataBlock->numOfAllocedParams = needed;
//  }
//
//  SParamInfo* param = pDataBlock->params + pDataBlock->numOfParams;
//  param->idx = -1;
//  param->type = type;
//  param->timePrec = timePrec;
//  param->bytes = bytes;
//  param->offset = offset;
//
//  ++pDataBlock->numOfParams;
//  return param;
//}

//void*  tscDestroyBlockArrayList(SArray* pDataBlockList) {
//  if (pDataBlockList == NULL) {
//    return NULL;
//  }
//
//  size_t size = taosArrayGetSize(pDataBlockList);
//  for (int32_t i = 0; i < size; i++) {
//    void* d = taosArrayGetP(pDataBlockList, i);
//    tscDestroyDataBlock(d, false);
//  }
//
//  taosArrayDestroy(pDataBlockList);
//  return NULL;
//}


//void freeUdfInfo(SUdfInfo* pUdfInfo) {
//  if (pUdfInfo == NULL) {
//    return;
//  }
//
//  if (pUdfInfo->funcs[TSDB_UDF_FUNC_DESTROY]) {
//    (*(udfDestroyFunc)pUdfInfo->funcs[TSDB_UDF_FUNC_DESTROY])(&pUdfInfo->init);
//  }
//
//  tfree(pUdfInfo->name);
//
//  if (pUdfInfo->path) {
//    unlink(pUdfInfo->path);
//  }
//
//  tfree(pUdfInfo->path);
//
//  tfree(pUdfInfo->content);
//
//  taosCloseDll(pUdfInfo->handle);
//}

//void*  tscDestroyUdfArrayList(SArray* pUdfList) {
//  if (pUdfList == NULL) {
//    return NULL;
//  }
//
//  size_t size = taosArrayGetSize(pUdfList);
//  for (int32_t i = 0; i < size; i++) {
//    SUdfInfo* udf = taosArrayGet(pUdfList, i);
//    freeUdfInfo(udf);
//  }
//
//  taosArrayDestroy(pUdfList);
//  return NULL;
//}

//void* tscDestroyBlockHashTable(SHashObj* pBlockHashTable, bool removeMeta) {
//  if (pBlockHashTable == NULL) {
//    return NULL;
//  }
//
//  STableDataBlocks** p = taosHashIterate(pBlockHashTable, NULL);
//  while(p) {
//    tscDestroyDataBlock(*p, removeMeta);
//    p = taosHashIterate(pBlockHashTable, p);
//  }
//
//  taosHashCleanup(pBlockHashTable);
//  return NULL;
//}

/**
 * create the in-memory buffer for each table to keep the submitted data block
 * @param initialSize
 * @param rowSize
 * @param startOffset
 * @param name
 * @param dataBlocks
 * @return
 */
//int32_t tscCreateDataBlock(size_t defaultSize, int32_t rowSize, int32_t startOffset, SName* name,
//                           STableMeta* pTableMeta, STableDataBlocks** dataBlocks) {
//  STableDataBlocks* dataBuf = (STableDataBlocks*)calloc(1, sizeof(STableDataBlocks));
//  if (dataBuf == NULL) {
//    tscError("failed to allocated memory, reason:%s", strerror(errno));
//    return TSDB_CODE_TSC_OUT_OF_MEMORY;
//  }
//
//  dataBuf->nAllocSize = (uint32_t)defaultSize;
//  dataBuf->headerSize = startOffset;
//
//  // the header size will always be the startOffset value, reserved for the subumit block header
//  if (dataBuf->nAllocSize <= dataBuf->headerSize) {
//    dataBuf->nAllocSize = dataBuf->headerSize * 2;
//  }
//
//  //dataBuf->pData = calloc(1, dataBuf->nAllocSize);
//  dataBuf->pData = malloc(dataBuf->nAllocSize);
//  if (dataBuf->pData == NULL) {
//    tscError("failed to allocated memory, reason:%s", strerror(errno));
//    tfree(dataBuf);
//    return TSDB_CODE_TSC_OUT_OF_MEMORY;
//  }
//  memset(dataBuf->pData, 0, sizeof(SSubmitBlk));
//
//  //Here we keep the tableMeta to avoid it to be remove by other threads.
//  dataBuf->pTableMeta = tscTableMetaDup(pTableMeta);
//
//  SParsedDataColInfo* pColInfo = &dataBuf->boundColumnInfo;
//  SSchema* pSchema = getTableColumnSchema(dataBuf->pTableMeta);
//  tscSetBoundColumnInfo(pColInfo, pSchema, dataBuf->pTableMeta->tableInfo.numOfColumns);
//
//  dataBuf->ordered  = true;
//  dataBuf->prevTS   = INT64_MIN;
//  dataBuf->rowSize  = rowSize;
//  dataBuf->size     = startOffset;
//  dataBuf->tsSource = -1;
//  dataBuf->vgId     = dataBuf->pTableMeta->vgId;
//
//  tNameAssign(&dataBuf->tableName, name);
//
//  assert(defaultSize > 0 && pTableMeta != NULL && dataBuf->pTableMeta != NULL);
//
//  *dataBlocks = dataBuf;
//  return TSDB_CODE_SUCCESS;
//}
//
//int32_t tscGetDataBlockFromList(SHashObj* pHashList, int64_t id, int32_t size, int32_t startOffset, int32_t rowSize,
//                                SName* name, STableMeta* pTableMeta, STableDataBlocks** dataBlocks,
//                                SArray* pBlockList) {
//  *dataBlocks = NULL;
//  STableDataBlocks** t1 = (STableDataBlocks**)taosHashGet(pHashList, (const char*)&id, sizeof(id));
//  if (t1 != NULL) {
//    *dataBlocks = *t1;
//  }
//
//  if (*dataBlocks == NULL) {
//    int32_t ret = tscCreateDataBlock((size_t)size, rowSize, startOffset, name, pTableMeta, dataBlocks);
//    if (ret != TSDB_CODE_SUCCESS) {
//      return ret;
//    }
//
//    taosHashPut(pHashList, (const char*)&id, sizeof(int64_t), (char*)dataBlocks, POINTER_BYTES);
//    if (pBlockList) {
//      taosArrayPush(pBlockList, dataBlocks);
//    }
//  }
//
//  return TSDB_CODE_SUCCESS;
//}
//
//// Erase the empty space reserved for binary data
//static int trimDataBlock(void* pDataBlock, STableDataBlocks* pTableDataBlock, SInsertStatementParam* insertParam,
//                         SBlockKeyTuple* blkKeyTuple) {
//  // TODO: optimize this function, handle the case while binary is not presented
//  STableMeta*     pTableMeta = pTableDataBlock->pTableMeta;
//  STableComInfo   tinfo = tscGetTableInfo(pTableMeta);
//  SSchema*        pSchema = getTableColumnSchema(pTableMeta);
//
//  SSubmitBlk* pBlock = pDataBlock;
//  memcpy(pDataBlock, pTableDataBlock->pData, sizeof(SSubmitBlk));
//  pDataBlock = (char*)pDataBlock + sizeof(SSubmitBlk);
//
//  int32_t flen = 0;  // original total length of row
//
//  // schema needs to be included into the submit data block
//  if (insertParam->schemaAttached) {
//    int32_t numOfCols = tscGetNumOfColumns(pTableDataBlock->pTableMeta);
//    for(int32_t j = 0; j < numOfCols; ++j) {
//      STColumn* pCol = (STColumn*) pDataBlock;
//      pCol->colId = htons(pSchema[j].colId);
//      pCol->type  = pSchema[j].type;
//      pCol->bytes = htons(pSchema[j].bytes);
//      pCol->offset = 0;
//
//      pDataBlock = (char*)pDataBlock + sizeof(STColumn);
//      flen += TYPE_BYTES[pSchema[j].type];
//    }
//
//    int32_t schemaSize = sizeof(STColumn) * numOfCols;
//    pBlock->schemaLen = schemaSize;
//  } else {
//    if (IS_RAW_PAYLOAD(insertParam->payloadType)) {
//      for (int32_t j = 0; j < tinfo.numOfColumns; ++j) {
//        flen += TYPE_BYTES[pSchema[j].type];
//      }
//    }
//    pBlock->schemaLen = 0;
//  }
//
//  char* p = pTableDataBlock->pData + sizeof(SSubmitBlk);
//  pBlock->dataLen = 0;
//  int32_t numOfRows = htons(pBlock->numOfRows);
//
//  if (IS_RAW_PAYLOAD(insertParam->payloadType)) {
//    for (int32_t i = 0; i < numOfRows; ++i) {
//      SMemRow memRow = (SMemRow)pDataBlock;
//      memRowSetType(memRow, SMEM_ROW_DATA);
//      SDataRow trow = memRowDataBody(memRow);
//      dataRowSetLen(trow, (uint16_t)(TD_DATA_ROW_HEAD_SIZE + flen));
//      dataRowSetVersion(trow, pTableMeta->sversion);
//
//      int toffset = 0;
//      for (int32_t j = 0; j < tinfo.numOfColumns; j++) {
//        tdAppendColVal(trow, p, pSchema[j].type, toffset);
//        toffset += TYPE_BYTES[pSchema[j].type];
//        p += pSchema[j].bytes;
//      }
//
//      pDataBlock = (char*)pDataBlock + memRowTLen(memRow);
//      pBlock->dataLen += memRowTLen(memRow);
//    }
//  } else {
//    for (int32_t i = 0; i < numOfRows; ++i) {
//      char* payload = (blkKeyTuple + i)->payloadAddr;
//      if (isNeedConvertRow(payload)) {
//        convertSMemRow(pDataBlock, payload, pTableDataBlock);
//        TDRowTLenT rowTLen = memRowTLen(pDataBlock);
//        pDataBlock = POINTER_SHIFT(pDataBlock, rowTLen);
//        pBlock->dataLen += rowTLen;
//      } else {
//        TDRowTLenT rowTLen = memRowTLen(payload);
//        memcpy(pDataBlock, payload, rowTLen);
//        pDataBlock = POINTER_SHIFT(pDataBlock, rowTLen);
//        pBlock->dataLen += rowTLen;
//      }
//    }
//  }
//
//  int32_t len = pBlock->dataLen + pBlock->schemaLen;
//  pBlock->dataLen = htonl(pBlock->dataLen);
//  pBlock->schemaLen = htonl(pBlock->schemaLen);
//
//  return len;
//}

561 562 563
TAOS_FIELD createField(const SSchema* pSchema) {
  TAOS_FIELD f = { .type = pSchema->type, .bytes = pSchema->bytes, };
  tstrncpy(f.name, pSchema->name, sizeof(f.name));
564 565 566
  return f;
}

567 568 569 570 571 572 573 574
void setColumn(SColumn* pColumn, uint64_t uid, const char* tableName, int8_t flag, const SSchema* pSchema) {
  pColumn->uid  = uid;
  pColumn->flag = flag;
  pColumn->info.colId = pSchema->colId;
  pColumn->info.bytes = pSchema->bytes;
  pColumn->info.type  = pSchema->type;

  if (tableName != NULL) {
H
Haojun Liao 已提交
575 576 577
    char n[TSDB_COL_NAME_LEN + 1 + TSDB_TABLE_NAME_LEN] = {0};
    snprintf(n, tListLen(n), "%s.%s", tableName, pSchema->name);
    tstrncpy(pColumn->name, n, tListLen(pColumn->name));
578 579 580 581 582
  } else {
    tstrncpy(pColumn->name, pSchema->name, tListLen(pColumn->name));
  }
}

583 584 585 586 587 588 589 590 591
SColumn createColumn(uint64_t uid, const char* tableName, int8_t flag, const SSchema* pSchema) {
  SColumn c;
  c.uid = uid;
  c.flag = flag;
  c.info.colId = pSchema->colId;
  c.info.bytes = pSchema->bytes;
  c.info.type = pSchema->type;

  if (tableName != NULL) {
H
Haojun Liao 已提交
592 593 594 595
    char n[TSDB_COL_NAME_LEN + 1 + TSDB_TABLE_NAME_LEN] = {0};
    snprintf(n, tListLen(n), "%s.%s", tableName, pSchema->name);

    tstrncpy(c.name, n, tListLen(c.name));
596 597 598 599 600 601 602
  } else {
    tstrncpy(c.name, pSchema->name, tListLen(c.name));
  }

  return c;
}

603
void addIntoSourceParam(SSourceParam* pSourceParam, tExprNode* pNode, SColumn* pColumn) {
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
  assert(pSourceParam != NULL);
  pSourceParam->num += 1;

  if (pSourceParam->pExprNodeList != NULL) {
    assert(pNode != NULL && pColumn == NULL);
    if (pSourceParam->pExprNodeList == NULL) {
      pSourceParam->pExprNodeList = taosArrayInit(4, POINTER_BYTES);
    }

    taosArrayPush(pSourceParam->pExprNodeList, &pNode);
  } else {
    assert(pColumn != NULL);
    if (pSourceParam->pColumnList == NULL) {
      pSourceParam->pColumnList = taosArrayInit(4, POINTER_BYTES);
    }

    taosArrayPush(pSourceParam->pColumnList, &pColumn);
  }
}

624 625 626 627
int32_t getNumOfFields(SFieldInfo* pFieldInfo) {
  return pFieldInfo->numOfOutput;
}

628 629 630 631 632 633 634 635 636 637
SInternalField* appendFieldInfo(SFieldInfo* pFieldInfo, TAOS_FIELD* pField) {
  assert(pFieldInfo != NULL);
  pFieldInfo->numOfOutput++;

  struct SInternalField info = { .pExpr = NULL, .visible = true };

  info.field = *pField;
  return taosArrayPush(pFieldInfo->internalField, &info);
}

638
SInternalField* insertFieldInfo(SFieldInfo* pFieldInfo, int32_t index, SSchema* pSchema) {
639 640 641
  pFieldInfo->numOfOutput++;
  struct SInternalField info = { .pExpr = NULL, .visible = true };

642 643 644 645
  info.field.type = pSchema->type;
  info.field.bytes = pSchema->bytes;
  tstrncpy(info.field.name, pSchema->name, tListLen(pSchema->name));

646 647 648 649 650 651 652
  return taosArrayInsert(pFieldInfo->internalField, index, &info);
}

void fieldInfoUpdateOffset(SQueryStmtInfo* pQueryInfo) {
  int32_t offset = 0;
  size_t numOfExprs = getNumOfExprs(pQueryInfo);

H
Haojun Liao 已提交
653
  SArray* pList = getCurrentExprList(pQueryInfo);
654
  for (int32_t i = 0; i < numOfExprs; ++i) {
H
Haojun Liao 已提交
655
    SExprInfo* p = taosArrayGetP(pList, i);
656

657 658
//    p->base.offset = offset;
    offset += p->base.resSchema.bytes;
659 660 661
  }
}

662
SInternalField* getInternalField(SFieldInfo* pFieldInfo, int32_t index) {
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
  assert(index < pFieldInfo->numOfOutput);
  return TARRAY_GET_ELEM(pFieldInfo->internalField, index);
}

TAOS_FIELD* getFieldInfo(SFieldInfo* pFieldInfo, int32_t index) {
  assert(index < pFieldInfo->numOfOutput);
  return &((SInternalField*)TARRAY_GET_ELEM(pFieldInfo->internalField, index))->field;
}

int32_t fieldInfoCompare(const SFieldInfo* pFieldInfo1, const SFieldInfo* pFieldInfo2, int32_t *diffSize) {
  assert(pFieldInfo1 != NULL && pFieldInfo2 != NULL);

  if (pFieldInfo1->numOfOutput != pFieldInfo2->numOfOutput) {
    return pFieldInfo1->numOfOutput - pFieldInfo2->numOfOutput;
  }

  for (int32_t i = 0; i < pFieldInfo1->numOfOutput; ++i) {
    TAOS_FIELD* pField1 = getFieldInfo((SFieldInfo*) pFieldInfo1, i);
    TAOS_FIELD* pField2 = getFieldInfo((SFieldInfo*) pFieldInfo2, i);

    if (pField1->type != pField2->type ||
        strcasecmp(pField1->name, pField2->name) != 0) {
      return 1;
    }

    if (pField1->bytes != pField2->bytes) {
      *diffSize = 1;

      if (pField2->bytes > pField1->bytes) {
        assert(IS_VAR_DATA_TYPE(pField1->type));
        pField1->bytes = pField2->bytes;
      }
    }
  }

  return 0;
}

int32_t getFieldInfoSize(const SFieldInfo* pFieldInfo1, const SFieldInfo* pFieldInfo2) {
  assert(pFieldInfo1 != NULL && pFieldInfo2 != NULL);

  for (int32_t i = 0; i < pFieldInfo1->numOfOutput; ++i) {
    TAOS_FIELD* pField1 = getFieldInfo((SFieldInfo*) pFieldInfo1, i);
    TAOS_FIELD* pField2 = getFieldInfo((SFieldInfo*) pFieldInfo2, i);

    pField2->bytes = pField1->bytes;
  }

  return 0;
}

static void destroyFilterInfo(SColumnFilterList* pFilterList) {
  if (pFilterList->filterInfo == NULL) {
    pFilterList->numOfFilters = 0;
    return;
  }

  for(int32_t i = 0; i < pFilterList->numOfFilters; ++i) {
    if (pFilterList->filterInfo[i].filterstr) {
      tfree(pFilterList->filterInfo[i].pz);
    }
  }

  tfree(pFilterList->filterInfo);
  pFilterList->numOfFilters = 0;
}

void cleanupFieldInfo(SFieldInfo* pFieldInfo) {
  if (pFieldInfo == NULL) {
    return;
  }

  if (pFieldInfo->internalField != NULL) {
    size_t num = taosArrayGetSize(pFieldInfo->internalField);
    for (int32_t i = 0; i < num; ++i) {
//      SInternalField* pfield = taosArrayGet(pFieldInfo->internalField, i);
//      if (pfield->pExpr != NULL && pfield->pExpr->pExpr != NULL) {
//        sqlExprDestroy(pfield->pExpr);
//      }
    }
  }

  taosArrayDestroy(pFieldInfo->internalField);
//  tfree(pFieldInfo->final);

  memset(pFieldInfo, 0, sizeof(SFieldInfo));
}

void copyFieldInfo(SFieldInfo* pFieldInfo, const SFieldInfo* pSrc, const SArray* pExprList) {
  assert(pFieldInfo != NULL && pSrc != NULL && pExprList != NULL);
  pFieldInfo->numOfOutput = pSrc->numOfOutput;

  if (pSrc->final != NULL) {
    pFieldInfo->final = calloc(pSrc->numOfOutput, sizeof(TAOS_FIELD));
    memcpy(pFieldInfo->final, pSrc->final, sizeof(TAOS_FIELD) * pSrc->numOfOutput);
  }

  if (pSrc->internalField != NULL) {
    size_t num = taosArrayGetSize(pSrc->internalField);
    size_t numOfExpr = taosArrayGetSize(pExprList);

    for (int32_t i = 0; i < num; ++i) {
      SInternalField* pfield = taosArrayGet(pSrc->internalField, i);

      SInternalField p = {.visible = pfield->visible, .field = pfield->field};

      bool found = false;
770
      int32_t resColId = pfield->pExpr->base.resSchema.colId;
771 772
      for(int32_t j = 0; j < numOfExpr; ++j) {
        SExprInfo* pExpr = taosArrayGetP(pExprList, j);
773
        if (pExpr->base.resSchema.colId == resColId) {
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
          p.pExpr = pExpr;
          found = true;
          break;
        }
      }

      if (!found) {
        assert(pfield->pExpr->pExpr != NULL);
        p.pExpr = calloc(1, sizeof(SExprInfo));
        assignExprInfo(p.pExpr, pfield->pExpr);
      }

      taosArrayPush(pFieldInfo->internalField, &p);
    }
  }
}

// ignore the tbname columnIndex to be inserted into source list
int32_t columnExists(SArray* pColumnList, int32_t columnId, uint64_t uid) {
  size_t numOfCols = taosArrayGetSize(pColumnList);

  int32_t i = 0;
  while (i < numOfCols) {
    SColumn* pCol = taosArrayGetP(pColumnList, i);
798
    if ((pCol->info.colId != columnId) || (pCol->uid != uid)) {
799 800 801 802 803 804 805 806 807 808 809 810 811 812
      ++i;
      continue;
    } else {
      break;
    }
  }

  if (i >= numOfCols || numOfCols == 0) {
    return -1;
  }

  return i;
}

813 814
static int32_t doFindPosition(const SArray* pColumnList, uint64_t uid, const SSchema* pSchema) {
  int32_t i = 0;
815 816 817 818

  size_t numOfCols = taosArrayGetSize(pColumnList);
  while (i < numOfCols) {
    SColumn* pCol = taosArrayGetP(pColumnList, i);
819
    if (pCol->uid < uid) {
820
      i++;
821
      continue;
822 823
    }

824 825 826
    if (pCol->info.colId < pSchema->colId) {
      i++;
      continue;
827 828
    }

829 830
    break;
  }
831

832 833
  return i;
}
834

835 836 837
SColumn* columnListInsert(SArray* pColumnList, uint64_t uid, SSchema* pSchema, int32_t flag) {
  // ignore the tbname columnIndex to be inserted into source list
  assert(pSchema != NULL && pColumnList != NULL);
838

839 840 841 842 843 844
  int32_t  i = doFindPosition(pColumnList, uid, pSchema);
  size_t size = taosArrayGetSize(pColumnList);
  if (size > 0 && i < size) {
    SColumn* pCol = taosArrayGetP(pColumnList, i);
    if (pCol->uid == uid && pCol->info.colId == pSchema->colId) {
      return pCol;
845 846 847
    }
  }

848 849 850 851 852 853 854 855 856 857 858 859
  SColumn* b = calloc(1, sizeof(SColumn));
  if (b == NULL) {
    return NULL;
  }

  b->uid        = uid;
  b->flag       = flag;
  b->info.colId = pSchema->colId;
  b->info.bytes = pSchema->bytes;
  b->info.type  = pSchema->type;
  tstrncpy(b->name, pSchema->name, tListLen(b->name));
  taosArrayInsert(pColumnList, i, &b);
860

861
  return b;
862 863
}

864
SColumn* insertPrimaryTsColumn(SArray* pColumnList, const char* colName, uint64_t tableUid) {
865
  SSchema s = {.type = TSDB_DATA_TYPE_TIMESTAMP, .bytes = TSDB_KEYSIZE, .colId = PRIMARYKEY_TIMESTAMP_COL_ID};
866 867
  strncpy(s.name, colName, tListLen(s.name));

868
  return columnListInsert(pColumnList, tableUid, &s, TSDB_COL_NORMAL);
869 870
}

871 872 873 874 875 876 877 878 879 880 881 882 883 884
void columnCopy(SColumn* pDest, const SColumn* pSrc);

SColumn* columnClone(const SColumn* src) {
  assert(src != NULL);

  SColumn* dst = calloc(1, sizeof(SColumn));
  if (dst == NULL) {
    return NULL;
  }

  columnCopy(dst, src);
  return dst;
}

885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
SColumnFilterInfo* tFilterInfoDup(const SColumnFilterInfo* src, int32_t numOfFilters) {
  if (numOfFilters == 0 || src == NULL) {
    assert(src == NULL);
    return NULL;
  }

  SColumnFilterInfo* pFilter = calloc(1, numOfFilters * sizeof(SColumnFilterInfo));

  memcpy(pFilter, src, sizeof(SColumnFilterInfo) * numOfFilters);
  for (int32_t j = 0; j < numOfFilters; ++j) {
    if (pFilter[j].filterstr) {
      size_t len = (size_t) pFilter[j].len + 1 * TSDB_NCHAR_SIZE;
      pFilter[j].pz = (int64_t) calloc(1, len);

      memcpy((char*)pFilter[j].pz, (char*)src[j].pz, (size_t) pFilter[j].len);
    }
  }

  assert(src->filterstr == 0 || src->filterstr == 1);
  assert(!(src->lowerRelOptr == TSDB_RELATION_INVALID && src->upperRelOptr == TSDB_RELATION_INVALID));

  return pFilter;
}

909 910 911
void columnCopy(SColumn* pDest, const SColumn* pSrc) {
  destroyFilterInfo(&pDest->info.flist);

912
  pDest->uid = pSrc->uid;
913 914 915 916 917 918 919
  pDest->info.flist.numOfFilters = pSrc->info.flist.numOfFilters;
  pDest->info.flist.filterInfo   = tFilterInfoDup(pSrc->info.flist.filterInfo, pSrc->info.flist.numOfFilters);
  pDest->info.type        = pSrc->info.type;
  pDest->info.colId        = pSrc->info.colId;
  pDest->info.bytes      = pSrc->info.bytes;
}

920
void columnListCopyAll(SArray* dst, const SArray* src) {
921 922 923 924 925
  assert(src != NULL && dst != NULL);

  size_t num = taosArrayGetSize(src);
  for (int32_t i = 0; i < num; ++i) {
    SColumn* pCol = taosArrayGetP(src, i);
926 927
    SColumn* p = columnClone(pCol);
    taosArrayPush(dst, &p);
928 929 930
  }
}

931
void columnListCopy(SArray* dst, const SArray* src, uint64_t uid) {
932 933 934 935 936
  assert(src != NULL && dst != NULL);

  size_t num = taosArrayGetSize(src);
  for (int32_t i = 0; i < num; ++i) {
    SColumn* pCol = taosArrayGetP(src, i);
937

938
    if (pCol->uid == uid) {
939 940 941
      SColumn* p = columnClone(pCol);
      taosArrayPush(dst, &p);
    }
942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
  }
}

static void columnDestroy(SColumn* pCol) {
  destroyFilterInfo(&pCol->info.flist);
  free(pCol);
}

void columnListDestroy(SArray* pColumnList) {
  if (pColumnList == NULL) {
    return;
  }

  size_t num = taosArrayGetSize(pColumnList);
  for (int32_t i = 0; i < num; ++i) {
    SColumn* pCol = taosArrayGetP(pColumnList, i);
    columnDestroy(pCol);
  }

  taosArrayDestroy(pColumnList);
}

bool validateColumnId(STableMetaInfo* pTableMetaInfo, int32_t colId, int32_t numOfParams) {
  if (pTableMetaInfo->pTableMeta == NULL) {
    return false;
  }

  if (colId == TSDB_TBNAME_COLUMN_INDEX || (colId <= TSDB_UD_COLUMN_INDEX && numOfParams == 2)) {
    return true;
  }

  SSchema* pSchema = getTableColumnSchema(pTableMetaInfo->pTableMeta);
  STableComInfo tinfo = getTableInfo(pTableMetaInfo->pTableMeta);

  int32_t  numOfTotal = tinfo.numOfTags + tinfo.numOfColumns;

  for (int32_t i = 0; i < numOfTotal; ++i) {
    if (pSchema[i].colId == colId) {
      return true;
    }
  }

  return false;
}

int32_t tscTagCondCopy(STagCond* dest, const STagCond* src) {
  memset(dest, 0, sizeof(STagCond));

  if (src->tbnameCond.cond != NULL) {
    dest->tbnameCond.cond = strdup(src->tbnameCond.cond);
    if (dest->tbnameCond.cond == NULL) {
      return -1;
    }
  }

  dest->tbnameCond.uid = src->tbnameCond.uid;
  dest->tbnameCond.len = src->tbnameCond.len;

  dest->joinInfo.hasJoin = src->joinInfo.hasJoin;

  for (int32_t i = 0; i < TSDB_MAX_JOIN_TABLE_NUM; ++i) {
    if (src->joinInfo.joinTables[i]) {
      dest->joinInfo.joinTables[i] = calloc(1, sizeof(SJoinNode));

      memcpy(dest->joinInfo.joinTables[i], src->joinInfo.joinTables[i], sizeof(SJoinNode));

      if (src->joinInfo.joinTables[i]->tsJoin) {
        dest->joinInfo.joinTables[i]->tsJoin = taosArrayDup(src->joinInfo.joinTables[i]->tsJoin);
      }

      if (src->joinInfo.joinTables[i]->tagJoin) {
        dest->joinInfo.joinTables[i]->tagJoin = taosArrayDup(src->joinInfo.joinTables[i]->tagJoin);
      }
    }
  }


  dest->relType = src->relType;

  if (src->pCond == NULL) {
    return 0;
  }

  size_t s = taosArrayGetSize(src->pCond);
  dest->pCond = taosArrayInit(s, sizeof(SCond));

  for (int32_t i = 0; i < s; ++i) {
    SCond* pCond = taosArrayGet(src->pCond, i);

    SCond c = {0};
    c.len = pCond->len;
    c.uid = pCond->uid;

    if (pCond->len > 0) {
      assert(pCond->cond != NULL);
      c.cond = malloc(c.len);
      if (c.cond == NULL) {
        return -1;
      }

      memcpy(c.cond, pCond->cond, c.len);
    }

    taosArrayPush(dest->pCond, &c);
  }

  return 0;
}

int32_t tscColCondCopy(SArray** dest, const SArray* src, uint64_t uid, int16_t tidx) {
  if (src == NULL) {
    return 0;
  }

  size_t s = taosArrayGetSize(src);
  *dest = taosArrayInit(s, sizeof(SCond));

  for (int32_t i = 0; i < s; ++i) {
    STableFilterCond* pCond = taosArrayGet(src, i);
    STableFilterCond c = {0};

    if (tidx > 0) {
      if (!(pCond->uid == uid && pCond->idx == tidx)) {
        continue;
      }

      c.idx = 0;
    } else {
      c.idx = pCond->idx;
    }

    c.len = pCond->len;
    c.uid = pCond->uid;

    if (pCond->len > 0) {
      assert(pCond->cond != NULL);
      c.cond = malloc(c.len);
      if (c.cond == NULL) {
        return -1;
      }

      memcpy(c.cond, pCond->cond, c.len);
    }

    taosArrayPush(*dest, &c);
  }

  return 0;
}

void cleanupColumnCond(SArray** pCond) {
  if (*pCond == NULL) {
    return;
  }

  size_t s = taosArrayGetSize(*pCond);
  for (int32_t i = 0; i < s; ++i) {
    STableFilterCond* p = taosArrayGet(*pCond, i);
    tfree(p->cond);
  }

  taosArrayDestroy(*pCond);

  *pCond = NULL;
}

void cleanupTagCond(STagCond* pTagCond) {
  free(pTagCond->tbnameCond.cond);

  if (pTagCond->pCond != NULL) {
    size_t s = taosArrayGetSize(pTagCond->pCond);
    for (int32_t i = 0; i < s; ++i) {
      SCond* p = taosArrayGet(pTagCond->pCond, i);
      tfree(p->cond);
    }

    taosArrayDestroy(pTagCond->pCond);
  }

  for (int32_t i = 0; i < TSDB_MAX_JOIN_TABLE_NUM; ++i) {
    SJoinNode *node = pTagCond->joinInfo.joinTables[i];
    if (node == NULL) {
      continue;
    }

    if (node->tsJoin != NULL) {
      taosArrayDestroy(node->tsJoin);
    }

    if (node->tagJoin != NULL) {
      taosArrayDestroy(node->tagJoin);
    }

    tfree(node);
  }

  memset(pTagCond, 0, sizeof(STagCond));
}

//void tscGetSrcColumnInfo(SSrcColumnInfo* pColInfo, SQueryStmtInfo* pQueryInfo) {
//  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
//  SSchema*        pSchema = getTableColumnSchema(pTableMetaInfo->pTableMeta);
//
//  size_t numOfExprs = getNumOfExprs(pQueryInfo);
//  for (int32_t i = 0; i < numOfExprs; ++i) {
//    SExprInfo* pExpr = getExprInfo(pQueryInfo, i);
//    pColInfo[i].functionId = pExpr->base.functionId;
//
//    if (TSDB_COL_IS_TAG(pExpr->base.colInfo.flag)) {
//      SSchema* pTagSchema = tscGetTableTagSchema(pTableMetaInfo->pTableMeta);
//
//      int16_t index = pExpr->base.colInfo.colIndex;
//      pColInfo[i].type = (index != -1) ? pTagSchema[index].type : TSDB_DATA_TYPE_BINARY;
//    } else {
//      pColInfo[i].type = pSchema[pExpr->base.colInfo.colIndex].type;
//    }
//  }
//}

/**
 *
 * @param clauseIndex denote the index of the union sub clause, usually are 0, if no union query exists.
 * @param tableIndex  denote the table index for join query, where more than one table exists
 * @return
 */
X
Xiaoyu Wang 已提交
1167
STableMetaInfo* getMetaInfo(const SQueryStmtInfo* pQueryInfo, int32_t tableIndex) {
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
  assert(pQueryInfo != NULL);
  if (pQueryInfo->pTableMetaInfo == NULL) {
    assert(pQueryInfo->numOfTables == 0);
    return NULL;
  }

  assert(tableIndex >= 0 && tableIndex <= pQueryInfo->numOfTables && pQueryInfo->pTableMetaInfo != NULL);
  return pQueryInfo->pTableMetaInfo[tableIndex];
}

STableMetaInfo* getTableMetaInfoByUid(SQueryStmtInfo* pQueryInfo, uint64_t uid, int32_t* index) {
  int32_t k = -1;

  for (int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
    if (pQueryInfo->pTableMetaInfo[i]->pTableMeta->uid == uid) {
      k = i;
      break;
    }
  }

  if (index != NULL) {
    *index = k;
  }

  assert(k != -1);
  return getMetaInfo(pQueryInfo, k);
}

int32_t queryInfoCopy(SQueryStmtInfo* pQueryInfo, const SQueryStmtInfo* pSrc) {
  assert(pQueryInfo != NULL && pSrc != NULL);
  int32_t code = TSDB_CODE_SUCCESS;

  memcpy(&pQueryInfo->interval, &pSrc->interval, sizeof(pQueryInfo->interval));

  pQueryInfo->command        = pSrc->command;
  pQueryInfo->type           = pSrc->type;
  pQueryInfo->window         = pSrc->window;
  pQueryInfo->limit          = pSrc->limit;
  pQueryInfo->slimit         = pSrc->slimit;
  pQueryInfo->order          = pSrc->order;
  pQueryInfo->vgroupLimit    = pSrc->vgroupLimit;
  pQueryInfo->tsBuf          = NULL;
  pQueryInfo->fillType       = pSrc->fillType;
  pQueryInfo->fillVal        = NULL;
  pQueryInfo->numOfFillVal   = 0;;
  pQueryInfo->clauseLimit    = pSrc->clauseLimit;
  pQueryInfo->prjOffset      = pSrc->prjOffset;
  pQueryInfo->numOfTables    = 0;
  pQueryInfo->window         = pSrc->window;
  pQueryInfo->sessionWindow  = pSrc->sessionWindow;
  pQueryInfo->pTableMetaInfo = NULL;

  pQueryInfo->bufLen         = pSrc->bufLen;
//  pQueryInfo->orderProjectQuery = pSrc->orderProjectQuery;
//  pQueryInfo->arithmeticOnAgg   = pSrc->arithmeticOnAgg;
  pQueryInfo->buf            = malloc(pSrc->bufLen);
  if (pQueryInfo->buf == NULL) {
    code = TSDB_CODE_TSC_OUT_OF_MEMORY;
    goto _error;
  }

  if (pSrc->bufLen > 0) {
    memcpy(pQueryInfo->buf, pSrc->buf, pSrc->bufLen);
  }

  pQueryInfo->groupbyExpr = pSrc->groupbyExpr;
  if (pSrc->groupbyExpr.columnInfo != NULL) {
    pQueryInfo->groupbyExpr.columnInfo = taosArrayDup(pSrc->groupbyExpr.columnInfo);
    if (pQueryInfo->groupbyExpr.columnInfo == NULL) {
      code = TSDB_CODE_TSC_OUT_OF_MEMORY;
      goto _error;
    }
  }

  if (tscTagCondCopy(&pQueryInfo->tagCond, &pSrc->tagCond) != 0) {
    code = TSDB_CODE_TSC_OUT_OF_MEMORY;
    goto _error;
  }

  if (tscColCondCopy(&pQueryInfo->colCond, pSrc->colCond, 0, -1) != 0) {
    code = TSDB_CODE_TSC_OUT_OF_MEMORY;
    goto _error;
  }

  if (pSrc->fillType != TSDB_FILL_NONE) {
    pQueryInfo->fillVal = calloc(1, pSrc->fieldsInfo.numOfOutput * sizeof(int64_t));
    if (pQueryInfo->fillVal == NULL) {
      code = TSDB_CODE_TSC_OUT_OF_MEMORY;
      goto _error;
    }
    pQueryInfo->numOfFillVal = pSrc->fieldsInfo.numOfOutput;

    memcpy(pQueryInfo->fillVal, pSrc->fillVal, pSrc->fieldsInfo.numOfOutput * sizeof(int64_t));
  }

H
Haojun Liao 已提交
1263
  if (copyAllExprInfo(pQueryInfo->exprList[0], pSrc->exprList[0], true) != 0) {
1264 1265 1266 1267 1268
    code = TSDB_CODE_TSC_OUT_OF_MEMORY;
    goto _error;
  }

  columnListCopyAll(pQueryInfo->colList, pSrc->colList);
H
Haojun Liao 已提交
1269
  copyFieldInfo(&pQueryInfo->fieldsInfo, &pSrc->fieldsInfo, pQueryInfo->exprList[0]);
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366

  for(int32_t i = 0; i < pSrc->numOfTables; ++i) {
    STableMetaInfo* p1 = getMetaInfo((SQueryStmtInfo*) pSrc, i);

    STableMeta* pMeta = tableMetaDup(p1->pTableMeta);
    if (pMeta == NULL) {
      // todo handle the error
    }

    addTableMetaInfo(pQueryInfo, &p1->name, pMeta, p1->vgroupList, p1->tagColList, NULL);
  }

  SArray *pUdfInfo = NULL;
  if (pSrc->pUdfInfo) {
    pUdfInfo = taosArrayDup(pSrc->pUdfInfo);
  }

  pQueryInfo->pUdfInfo = pUdfInfo;

  _error:
  return code;
}

void clearAllTableMetaInfo(SQueryStmtInfo* pQueryInfo, bool removeMeta, uint64_t id) {
  for(int32_t i = 0; i < pQueryInfo->numOfTables; ++i) {
    STableMetaInfo* pTableMetaInfo = getMetaInfo(pQueryInfo, i);
    clearTableMetaInfo(pTableMetaInfo);
  }

  tfree(pQueryInfo->pTableMetaInfo);
}

STableMetaInfo* addTableMetaInfo(SQueryStmtInfo* pQueryInfo, SName* name, STableMeta* pTableMeta,
                                 SVgroupsInfo* vgroupList, SArray* pTagCols, SArray* pVgroupTables) {
  void* tmp = realloc(pQueryInfo->pTableMetaInfo, (pQueryInfo->numOfTables + 1) * POINTER_BYTES);
  if (tmp == NULL) {
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return NULL;
  }

  pQueryInfo->pTableMetaInfo = tmp;
  STableMetaInfo* pTableMetaInfo = calloc(1, sizeof(STableMetaInfo));

  if (pTableMetaInfo == NULL) {
    terrno = TSDB_CODE_TSC_OUT_OF_MEMORY;
    return NULL;
  }

  pQueryInfo->pTableMetaInfo[pQueryInfo->numOfTables] = pTableMetaInfo;

  if (name != NULL) {
    tNameAssign(&pTableMetaInfo->name, name);
  }

  pTableMetaInfo->pTableMeta = pTableMeta;

  if (vgroupList != NULL) {
//    pTableMetaInfo->vgroupList = vgroupInfoClone(vgroupList);
  }

  // TODO handle malloc failure
  pTableMetaInfo->tagColList = taosArrayInit(4, POINTER_BYTES);
  if (pTableMetaInfo->tagColList == NULL) {
    return NULL;
  }

  if (pTagCols != NULL && pTableMetaInfo->pTableMeta != NULL) {
    columnListCopy(pTableMetaInfo->tagColList, pTagCols, pTableMetaInfo->pTableMeta->uid);
  }

  pQueryInfo->numOfTables += 1;
  return pTableMetaInfo;
}

STableMetaInfo* addEmptyMetaInfo(SQueryStmtInfo* pQueryInfo) {
  return addTableMetaInfo(pQueryInfo, NULL, NULL, NULL, NULL, NULL);
}

SInternalField* getInternalFieldInfo(SFieldInfo* pFieldInfo, int32_t index) {
  assert(index < pFieldInfo->numOfOutput);
  return TARRAY_GET_ELEM(pFieldInfo->internalField, index);
}

int32_t getNumOfInternalField(SFieldInfo* pFieldInfo) {
  return (int32_t) taosArrayGetSize(pFieldInfo->internalField);
}

static void doSetSqlExprAndResultFieldInfo(SQueryStmtInfo* pNewQueryInfo, int64_t uid) {
  int32_t numOfOutput = (int32_t)getNumOfExprs(pNewQueryInfo);
  if (numOfOutput == 0) {
    return;
  }

  // set the field info in pNewQueryInfo object according to sqlExpr information
  for (int32_t i = 0; i < numOfOutput; ++i) {
    SExprInfo* pExpr = getExprInfo(pNewQueryInfo, i);

1367
    TAOS_FIELD f = createField(&pExpr->base.resSchema);
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
    SInternalField* pInfo1 = appendFieldInfo(&pNewQueryInfo->fieldsInfo, &f);
    pInfo1->pExpr = pExpr;
  }

  // update the pSqlExpr pointer in SInternalField according the field name
  // make sure the pSqlExpr point to the correct SqlExpr in pNewQueryInfo, not SqlExpr in pQueryInfo
  for (int32_t f = 0; f < pNewQueryInfo->fieldsInfo.numOfOutput; ++f) {
    TAOS_FIELD* field = getFieldInfo(&pNewQueryInfo->fieldsInfo, f);

    bool matched = false;
    for (int32_t k1 = 0; k1 < numOfOutput; ++k1) {
      SExprInfo* pExpr1 = getExprInfo(pNewQueryInfo, k1);

1381
      if (strcmp(field->name, pExpr1->base.resSchema.name) == 0) {  // establish link according to the result field name
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493
        SInternalField* pInfo = getInternalFieldInfo(&pNewQueryInfo->fieldsInfo, f);
        pInfo->pExpr = pExpr1;

        matched = true;
        break;
      }
    }

    assert(matched);
    (void)matched;
  }

//  updateFieldInfoOffset(pNewQueryInfo);
}

int16_t getJoinTagColIdByUid(STagCond* pTagCond, uint64_t uid) {
  int32_t i = 0;
  while (i < TSDB_MAX_JOIN_TABLE_NUM) {
    SJoinNode* node = pTagCond->joinInfo.joinTables[i];
    if (node && node->uid == uid) {
      return node->tagColId;
    }

    i++;
  }

  assert(0);
  return -1;
}

int16_t getTagColIndexById(STableMeta* pTableMeta, int16_t colId) {
  int32_t numOfTags = getNumOfTags(pTableMeta);

  SSchema* pSchema = getTableTagSchema(pTableMeta);
  for(int32_t i = 0; i < numOfTags; ++i) {
    if (pSchema[i].colId == colId) {
      return i;
    }
  }

  // can not reach here
  assert(0);
  return INT16_MIN;
}

bool isQueryWithLimit(SQueryStmtInfo* pQueryInfo) {
  while(pQueryInfo != NULL) {
    if (pQueryInfo->limit.limit > 0) {
      return true;
    }

    pQueryInfo = pQueryInfo->sibling;
  }

  return false;
}

SVgroupsInfo* vgroupInfoClone(SVgroupsInfo *vgroupList) {
  if (vgroupList == NULL) {
    return NULL;
  }

  size_t size = sizeof(SVgroupsInfo) + sizeof(SVgroupMsg) * vgroupList->numOfVgroups;
  SVgroupsInfo* pNew = malloc(size);
  if (pNew == NULL) {
    return NULL;
  }

  pNew->numOfVgroups = vgroupList->numOfVgroups;

  for(int32_t i = 0; i < vgroupList->numOfVgroups; ++i) {
    SVgroupMsg* pNewVInfo = &pNew->vgroups[i];

    SVgroupMsg* pvInfo = &vgroupList->vgroups[i];
    pNewVInfo->vgId = pvInfo->vgId;
    pNewVInfo->numOfEps = pvInfo->numOfEps;

    for(int32_t j = 0; j < pvInfo->numOfEps; ++j) {
      pNewVInfo->epAddr[j].port = pvInfo->epAddr[j].port;
      tstrncpy(pNewVInfo->epAddr[j].fqdn, pvInfo->epAddr[j].fqdn, TSDB_FQDN_LEN);
    }
  }

  return pNew;
}

void* vgroupInfoClear(SVgroupsInfo *vgroupList) {
  if (vgroupList == NULL) {
    return NULL;
  }

  tfree(vgroupList);
  return NULL;
}

int32_t copyTagData(STagData* dst, const STagData* src) {
  dst->dataLen = src->dataLen;
  tstrncpy(dst->name, src->name, tListLen(dst->name));

  if (dst->dataLen > 0) {
    dst->data = malloc(dst->dataLen);
    if (dst->data == NULL) {
      return -1;
    }

    memcpy(dst->data, src->data, dst->dataLen);
  }

  return 0;
}


1494
uint32_t getTableMetaSize(const STableMeta* pTableMeta) {
1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
  assert(pTableMeta != NULL);

  int32_t totalCols = 0;
  if (pTableMeta->tableInfo.numOfColumns >= 0) {
    totalCols = pTableMeta->tableInfo.numOfColumns + pTableMeta->tableInfo.numOfTags;
  }

  return sizeof(STableMeta) + totalCols * sizeof(SSchema);
}

uint32_t getTableMetaMaxSize() {
  return sizeof(STableMeta) + TSDB_MAX_COLUMNS * sizeof(SSchema);
}

1509
STableMeta* tableMetaDup(const STableMeta* pTableMeta) {
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
  assert(pTableMeta != NULL);
  size_t size = getTableMetaSize(pTableMeta);

  STableMeta* p = malloc(size);
  memcpy(p, pTableMeta, size);
  return p;
}

SVgroupsInfo* vgroupsInfoDup(SVgroupsInfo* pVgroupsInfo) {
  assert(pVgroupsInfo != NULL);

  size_t size = sizeof(SVgroupMsg) * pVgroupsInfo->numOfVgroups + sizeof(SVgroupsInfo);
  SVgroupsInfo* pInfo = calloc(1, size);
  pInfo->numOfVgroups = pVgroupsInfo->numOfVgroups;
  for (int32_t m = 0; m < pVgroupsInfo->numOfVgroups; ++m) {
    memcpy(&pInfo->vgroups[m], &pVgroupsInfo->vgroups[m], sizeof(SVgroupMsg));
  }

  return pInfo;
}

int32_t getNumOfOutput(SFieldInfo* pFieldInfo) {
  return pFieldInfo->numOfOutput;
}

int32_t getColFilterSerializeLen(SQueryStmtInfo* pQueryInfo) {
  int16_t numOfCols = (int16_t)taosArrayGetSize(pQueryInfo->colList);
  int32_t len = 0;

  for(int32_t i = 0; i < numOfCols; ++i) {
    SColumn* pCol = taosArrayGetP(pQueryInfo->colList, i);
    for (int32_t j = 0; j < pCol->info.flist.numOfFilters; ++j) {
      len += sizeof(SColumnFilterInfo);
      if (pCol->info.flist.filterInfo[j].filterstr) {
        len += (int32_t)pCol->info.flist.filterInfo[j].len + 1 * TSDB_NCHAR_SIZE;
      }
    }
  }
  return len;
}

int32_t getTagFilterSerializeLen(SQueryStmtInfo* pQueryInfo) {
  // serialize tag column query condition
  if (pQueryInfo->tagCond.pCond != NULL && taosArrayGetSize(pQueryInfo->tagCond.pCond) > 0) {
    STagCond* pTagCond = &pQueryInfo->tagCond;

    STableMetaInfo *pTableMetaInfo = getMetaInfo(pQueryInfo, 0);
    STableMeta * pTableMeta = pTableMetaInfo->pTableMeta;
    SCond *pCond = getSTableQueryCond(pTagCond, pTableMeta->uid);
    if (pCond != NULL && pCond->cond != NULL) {
      return pCond->len;
    }
  }
  return 0;
}

1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583
uint32_t convertRelationalOperator(SToken *pToken) {
  switch (pToken->type) {
    case TK_LT:
      return TSDB_RELATION_LESS;
    case TK_LE:
      return TSDB_RELATION_LESS_EQUAL;
    case TK_GT:
      return TSDB_RELATION_GREATER;
    case TK_GE:
      return TSDB_RELATION_GREATER_EQUAL;
    case TK_NE:
      return TSDB_RELATION_NOT_EQUAL;
    case TK_AND:
      return TSDB_RELATION_AND;
    case TK_OR:
      return TSDB_RELATION_OR;
    case TK_EQ:
      return TSDB_RELATION_EQUAL;
1584

1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
    case TK_PLUS:
      return TSDB_BINARY_OP_ADD;
    case TK_MINUS:
      return TSDB_BINARY_OP_SUBTRACT;
    case TK_STAR:
      return TSDB_BINARY_OP_MULTIPLY;
    case TK_SLASH:
    case TK_DIVIDE:
      return TSDB_BINARY_OP_DIVIDE;
    case TK_REM:
      return TSDB_BINARY_OP_REMAINDER;
    case TK_LIKE:
      return TSDB_RELATION_LIKE;
    case TK_MATCH:
      return TSDB_RELATION_MATCH;
    case TK_NMATCH:
      return TSDB_RELATION_NMATCH;
    case TK_ISNULL:
      return TSDB_RELATION_ISNULL;
    case TK_NOTNULL:
      return TSDB_RELATION_NOTNULL;
    case TK_IN:
      return TSDB_RELATION_IN;
    default: { return 0; }
  }
}

1612
bool isDclSqlStatement(SSqlInfo* pSqlInfo) {
H
Haojun Liao 已提交
1613 1614 1615 1616 1617 1618 1619
  int32_t type = pSqlInfo->type;
  return (type == TSDB_SQL_CREATE_USER || type == TSDB_SQL_CREATE_ACCT || type == TSDB_SQL_DROP_USER ||
          type == TSDB_SQL_DROP_ACCT || type == TSDB_SQL_SHOW);
}

bool isDdlSqlStatement(SSqlInfo* pSqlInfo) {
  int32_t type = pSqlInfo->type;
1620 1621 1622 1623 1624
  return (type == TSDB_SQL_CREATE_TABLE || type == TSDB_SQL_CREATE_DB || type == TSDB_SQL_DROP_DB);
}

bool isDqlSqlStatement(SSqlInfo* pSqlInfo) {
  return pSqlInfo->type == TSDB_SQL_SELECT;
1625 1626
}

1627 1628
static uint8_t TRUE_VALUE = (uint8_t)TSDB_TRUE;
static uint8_t FALSE_VALUE = (uint8_t)TSDB_FALSE;
1629

1630 1631 1632
static FORCE_INLINE int32_t toDouble(SToken *pToken, double *value, char **endPtr) {
  errno = 0;
  *value = strtold(pToken->z, endPtr);
1633

1634 1635 1636
  // not a valid integer number, return error
  if ((*endPtr - pToken->z) != pToken->n) {
    return TK_ILLEGAL;
1637 1638
  }

1639 1640
  return pToken->type;
}
1641

1642 1643 1644 1645
static bool isNullStr(SToken *pToken) {
  return (pToken->type == TK_NULL) || ((pToken->type == TK_STRING) && (pToken->n != 0) &&
                                       (strncasecmp(TSDB_DATA_NULL_STR_L, pToken->z, pToken->n) == 0));
}
1646

1647
static FORCE_INLINE int32_t checkAndTrimValue(SToken* pToken, uint32_t type, char* tmpTokenBuf, SMsgBuf* pMsgBuf) {
X
Xiaoyu Wang 已提交
1648 1649 1650
  if ((pToken->type != TK_NOW && pToken->type != TK_INTEGER && pToken->type != TK_STRING && pToken->type != TK_FLOAT && pToken->type != TK_BOOL &&
       pToken->type != TK_NULL && pToken->type != TK_HEX && pToken->type != TK_OCT && pToken->type != TK_BIN) ||
      (pToken->n == 0) || (pToken->type == TK_RP)) {
1651
    return buildSyntaxErrMsg(pMsgBuf, "invalid data or symbol", pToken->z);
1652 1653
  }

1654 1655
  if (IS_NUMERIC_TYPE(type) && pToken->n == 0) {
    return buildSyntaxErrMsg(pMsgBuf, "invalid numeric data", pToken->z);
1656 1657
  }

1658 1659 1660 1661
  // Remove quotation marks
  if (TK_STRING == type) {
    if (pToken->n >= TSDB_MAX_BYTES_PER_ROW) {
      return buildSyntaxErrMsg(pMsgBuf, "too long string", pToken->z);
1662 1663
    }

1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
    // delete escape character: \\, \', \"
    char delim = pToken->z[0];
    int32_t cnt = 0;
    int32_t j = 0;
    for (uint32_t k = 1; k < pToken->n - 1; ++k) {
      if (pToken->z[k] == '\\' || (pToken->z[k] == delim && pToken->z[k + 1] == delim)) {
        tmpTokenBuf[j] = pToken->z[k + 1];
        cnt++;
        j++;
        k++;
        continue;
      }
      tmpTokenBuf[j] = pToken->z[k];
      j++;
1678
    }
1679 1680 1681 1682

    tmpTokenBuf[j] = 0;
    pToken->z = tmpTokenBuf;
    pToken->n -= 2 + cnt;
1683 1684
  }

1685 1686
  return TSDB_CODE_SUCCESS;
}
1687

1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
static int parseTime(char **end, SToken *pToken, int16_t timePrec, int64_t *time, SMsgBuf* pMsgBuf) {
  int32_t   index = 0;
  SToken    sToken;
  int64_t   interval;
  int64_t   ts = 0;
  char* pTokenEnd = *end;

  if (pToken->type == TK_NOW) {
    ts = taosGetTimestamp(timePrec);
  } else if (pToken->type == TK_INTEGER) {
    bool isSigned = false;
    toInteger(pToken->z, pToken->n, 10, &ts, &isSigned);
  } else { // parse the RFC-3339/ISO-8601 timestamp format string
    if (taosParseTime(pToken->z, time, pToken->n, timePrec, tsDaylight) != TSDB_CODE_SUCCESS) {
      return buildSyntaxErrMsg(pMsgBuf, "invalid timestamp format", pToken->z);
    }
1704

1705
    return TSDB_CODE_SUCCESS;
1706 1707
  }

1708 1709 1710 1711 1712 1713 1714
  for (int k = pToken->n; pToken->z[k] != '\0'; k++) {
    if (pToken->z[k] == ' ' || pToken->z[k] == '\t') continue;
    if (pToken->z[k] == ',') {
      *end = pTokenEnd;
      *time = ts;
      return 0;
    }
1715

1716
    break;
1717 1718
  }

1719 1720 1721 1722 1723 1724 1725 1726
  /*
   * time expression:
   * e.g., now+12a, now-5h
   */
  SToken valueToken;
  index = 0;
  sToken = tStrGetToken(pTokenEnd, &index, false);
  pTokenEnd += index;
1727

1728 1729 1730 1731
  if (sToken.type == TK_MINUS || sToken.type == TK_PLUS) {
    index = 0;
    valueToken = tStrGetToken(pTokenEnd, &index, false);
    pTokenEnd += index;
1732

1733 1734 1735
    if (valueToken.n < 2) {
      return buildSyntaxErrMsg(pMsgBuf, "value expected in timestamp", sToken.z);
    }
1736

1737 1738
    char unit = 0;
    if (parseAbsoluteDuration(valueToken.z, valueToken.n, &interval, &unit, timePrec) != TSDB_CODE_SUCCESS) {
1739 1740 1741
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

1742 1743 1744 1745 1746 1747 1748
    if (sToken.type == TK_PLUS) {
      ts += interval;
    } else {
      ts = ts - interval;
    }

    *end = pTokenEnd;
1749 1750
  }

1751 1752 1753
  *time = ts;
  return TSDB_CODE_SUCCESS;
}
1754

1755 1756 1757 1758
int32_t parseValueToken(char** end, SToken* pToken, SSchema* pSchema, int16_t timePrec, char* tmpTokenBuf, _row_append_fn_t func, void* param, SMsgBuf* pMsgBuf) {
  int64_t iv;
  char   *endptr = NULL;
  bool    isSigned = false;
1759

1760 1761
  int32_t code = checkAndTrimValue(pToken, pSchema->type, tmpTokenBuf, pMsgBuf);
  if (code != TSDB_CODE_SUCCESS) {
1762 1763 1764
    return code;
  }

1765 1766 1767 1768 1769
  if (isNullStr(pToken)) {
    if (TSDB_DATA_TYPE_TIMESTAMP == pSchema->type && PRIMARYKEY_TIMESTAMP_COL_ID == pSchema->colId) {
      int64_t tmpVal = 0;
      return func(&tmpVal, pSchema->bytes, param);
    }
1770

1771
    return func(getNullValue(pSchema->type), 0, param);
1772 1773
  }

1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791
  switch (pSchema->type) {
    case TSDB_DATA_TYPE_BOOL: {
      if ((pToken->type == TK_BOOL || pToken->type == TK_STRING) && (pToken->n != 0)) {
        if (strncmp(pToken->z, "true", pToken->n) == 0) {
          return func(&TRUE_VALUE, pSchema->bytes, param);
        } else if (strncmp(pToken->z, "false", pToken->n) == 0) {
          return func(&FALSE_VALUE, pSchema->bytes, param);
        } else {
          return buildSyntaxErrMsg(pMsgBuf, "invalid bool data", pToken->z);
        }
      } else if (pToken->type == TK_INTEGER) {
        return func(((strtoll(pToken->z, NULL, 10) == 0) ? &FALSE_VALUE : &TRUE_VALUE), pSchema->bytes, param);
      } else if (pToken->type == TK_FLOAT) {
        return func(((strtod(pToken->z, NULL) == 0) ? &FALSE_VALUE : &TRUE_VALUE), pSchema->bytes, param);
      } else {
        return buildSyntaxErrMsg(pMsgBuf, "invalid bool data", pToken->z);
      }
    }
1792

1793
    case TSDB_DATA_TYPE_TINYINT: {
X
Xiaoyu Wang 已提交
1794
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &iv, &isSigned)) {
1795 1796 1797 1798
        return buildSyntaxErrMsg(pMsgBuf, "invalid tinyint data", pToken->z);
      } else if (!IS_VALID_TINYINT(iv)) {
        return buildSyntaxErrMsg(pMsgBuf, "tinyint data overflow", pToken->z);
      }
1799

1800 1801 1802
      uint8_t tmpVal = (uint8_t)iv;
      return func(&tmpVal, pSchema->bytes, param);
    }
1803

1804
    case TSDB_DATA_TYPE_UTINYINT:{
X
Xiaoyu Wang 已提交
1805
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &iv, &isSigned)) {
1806 1807 1808 1809 1810 1811 1812
        return buildSyntaxErrMsg(pMsgBuf, "invalid unsigned tinyint data", pToken->z);
      } else if (!IS_VALID_UTINYINT(iv)) {
        return buildSyntaxErrMsg(pMsgBuf, "unsigned tinyint data overflow", pToken->z);
      }
      uint8_t tmpVal = (uint8_t)iv;
      return func(&tmpVal, pSchema->bytes, param);
    }
1813

1814
    case TSDB_DATA_TYPE_SMALLINT: {
X
Xiaoyu Wang 已提交
1815
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &iv, &isSigned)) {
1816 1817 1818 1819 1820 1821 1822
        return buildSyntaxErrMsg(pMsgBuf, "invalid smallint data", pToken->z);
      } else if (!IS_VALID_SMALLINT(iv)) {
        return buildSyntaxErrMsg(pMsgBuf, "smallint data overflow", pToken->z);
      }
      int16_t tmpVal = (int16_t)iv;
      return func(&tmpVal, pSchema->bytes, param);
    }
1823

1824
    case TSDB_DATA_TYPE_USMALLINT: {
X
Xiaoyu Wang 已提交
1825
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &iv, &isSigned)) {
1826 1827 1828 1829 1830 1831 1832
        return buildSyntaxErrMsg(pMsgBuf, "invalid unsigned smallint data", pToken->z);
      } else if (!IS_VALID_USMALLINT(iv)) {
        return buildSyntaxErrMsg(pMsgBuf, "unsigned smallint data overflow", pToken->z);
      }
      uint16_t tmpVal = (uint16_t)iv;
      return func(&tmpVal, pSchema->bytes, param);
    }
1833

1834
    case TSDB_DATA_TYPE_INT: {
X
Xiaoyu Wang 已提交
1835
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &iv, &isSigned)) {
1836 1837 1838 1839 1840 1841
        return buildSyntaxErrMsg(pMsgBuf, "invalid int data", pToken->z);
      } else if (!IS_VALID_INT(iv)) {
        return buildSyntaxErrMsg(pMsgBuf, "int data overflow", pToken->z);
      }
      int32_t tmpVal = (int32_t)iv;
      return func(&tmpVal, pSchema->bytes, param);
1842 1843
    }

1844
    case TSDB_DATA_TYPE_UINT: {
X
Xiaoyu Wang 已提交
1845
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &iv, &isSigned)) {
1846 1847 1848 1849 1850 1851
        return buildSyntaxErrMsg(pMsgBuf, "invalid unsigned int data", pToken->z);
      } else if (!IS_VALID_UINT(iv)) {
        return buildSyntaxErrMsg(pMsgBuf, "unsigned int data overflow", pToken->z);
      }
      uint32_t tmpVal = (uint32_t)iv;
      return func(&tmpVal, pSchema->bytes, param);
1852 1853
    }

1854
    case TSDB_DATA_TYPE_BIGINT: {
X
Xiaoyu Wang 已提交
1855
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &iv, &isSigned)) {
1856 1857 1858 1859 1860
        return buildSyntaxErrMsg(pMsgBuf, "invalid bigint data", pToken->z);
      } else if (!IS_VALID_BIGINT(iv)) {
        return buildSyntaxErrMsg(pMsgBuf, "bigint data overflow", pToken->z);
      }
      return func(&iv, pSchema->bytes, param);
1861 1862
    }

1863
    case TSDB_DATA_TYPE_UBIGINT: {
X
Xiaoyu Wang 已提交
1864
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &iv, &isSigned)) {
1865 1866 1867 1868 1869 1870 1871
        return buildSyntaxErrMsg(pMsgBuf, "invalid unsigned bigint data", pToken->z);
      } else if (!IS_VALID_UBIGINT((uint64_t)iv)) {
        return buildSyntaxErrMsg(pMsgBuf, "unsigned bigint data overflow", pToken->z);
      }
      uint64_t tmpVal = (uint64_t)iv;
      return func(&tmpVal, pSchema->bytes, param);
    }
1872

1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883
    case TSDB_DATA_TYPE_FLOAT: {
      double dv;
      if (TK_ILLEGAL == toDouble(pToken, &dv, &endptr)) {
        return buildSyntaxErrMsg(pMsgBuf, "illegal float data", pToken->z);
      }
      if (((dv == HUGE_VAL || dv == -HUGE_VAL) && errno == ERANGE) || dv > FLT_MAX || dv < -FLT_MAX || isinf(dv) || isnan(dv)) {
        return buildSyntaxErrMsg(pMsgBuf, "illegal float data", pToken->z);
      }
      float tmpVal = (float)dv;
      return func(&tmpVal, pSchema->bytes, param);
    }
1884

1885 1886 1887 1888 1889 1890 1891 1892 1893 1894
    case TSDB_DATA_TYPE_DOUBLE: {
      double dv;
      if (TK_ILLEGAL == toDouble(pToken, &dv, &endptr)) {
        return buildSyntaxErrMsg(pMsgBuf, "illegal double data", pToken->z);
      }
      if (((dv == HUGE_VAL || dv == -HUGE_VAL) && errno == ERANGE) || isinf(dv) || isnan(dv)) {
        return buildSyntaxErrMsg(pMsgBuf, "illegal double data", pToken->z);
      }
      return func(&dv, pSchema->bytes, param);
    }
1895

1896 1897 1898 1899 1900
    case TSDB_DATA_TYPE_BINARY: {
      // Too long values will raise the invalid sql error message
      if (pToken->n + VARSTR_HEADER_SIZE > pSchema->bytes) {
        return buildSyntaxErrMsg(pMsgBuf, "string data overflow", pToken->z);
      }
1901

1902
      return func(pToken->z, pToken->n, param);
1903 1904
    }

1905 1906
    case TSDB_DATA_TYPE_NCHAR: {
      return func(pToken->z, pToken->n, param);
1907 1908
    }

1909 1910 1911 1912 1913
    case TSDB_DATA_TYPE_TIMESTAMP: {
      int64_t tmpVal;
      if (parseTime(end, pToken, timePrec, &tmpVal, pMsgBuf) != TSDB_CODE_SUCCESS) {
        return buildSyntaxErrMsg(pMsgBuf, "invalid timestamp", pToken->z);
      }
1914

1915 1916
      return func(&tmpVal, pSchema->bytes, param);
    }
1917 1918
  }

1919
  return TSDB_CODE_FAILED;
1920 1921
}

1922 1923
int32_t KvRowAppend(const void *value, int32_t len, void *param) {
  SKvParam* pa = (SKvParam*) param;
1924

1925 1926
  int32_t type  = pa->schema->type;
  int32_t colId = pa->schema->colId;
1927

1928 1929 1930 1931 1932 1933 1934 1935 1936
  if (TSDB_DATA_TYPE_BINARY == type) {
    STR_WITH_SIZE_TO_VARSTR(pa->buf, value, len);
    tdAddColToKVRow(pa->builder, colId, type, pa->buf);
  } else if (TSDB_DATA_TYPE_NCHAR == type) {
    // if the converted output len is over than pColumnModel->bytes, return error: 'Argument list too long'
    int32_t output = 0;
    if (!taosMbsToUcs4(value, len, varDataVal(pa->buf), pa->schema->bytes - VARSTR_HEADER_SIZE, &output)) {
      return TSDB_CODE_TSC_SQL_SYNTAX_ERROR;
    }
1937

1938 1939 1940 1941 1942
    varDataSetLen(pa->buf, output);
    tdAddColToKVRow(pa->builder, colId, type, pa->buf);
  } else {
    tdAddColToKVRow(pa->builder, colId, type, value);
  }
1943

1944
  return TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1945 1946
}

H
Haojun Liao 已提交
1947
int32_t createSName(SName* pName, SToken* pTableName, SParseContext* pParseCtx, SMsgBuf* pMsgBuf) {
H
Haojun Liao 已提交
1948
  const char* msg1 = "name too long";
1949
  const char* msg2 = "invalid database name";
H
Haojun Liao 已提交
1950 1951

  int32_t  code = TSDB_CODE_SUCCESS;
1952
  char* p  = strnchr(pTableName->z, TS_PATH_DELIMITER[0], pTableName->n, true);
H
Haojun Liao 已提交
1953 1954

  if (p != NULL) { // db has been specified in sql string so we ignore current db path
1955
    assert(*p == TS_PATH_DELIMITER[0]);
H
Haojun Liao 已提交
1956

1957 1958 1959 1960
    int32_t dbLen = p - pTableName->z;
    char name[TSDB_DB_FNAME_LEN] = {0};
    strncpy(name, pTableName->z, dbLen);
    dbLen = strdequote(name);
H
Haojun Liao 已提交
1961

1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972
    code = tNameSetDbName(pName, pParseCtx->acctId, name, dbLen);
    if (code != TSDB_CODE_SUCCESS) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }

    int32_t tbLen = pTableName->n - dbLen - 1;
    char tbname[TSDB_TABLE_FNAME_LEN] = {0};
    strncpy(tbname, p + 1, tbLen);
    /*tbLen = */strdequote(tbname);

    code = tNameFromString(pName, tbname, T_NAME_TABLE);
H
Haojun Liao 已提交
1973 1974 1975 1976 1977 1978 1979 1980
    if (code != 0) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }
  } else {  // get current DB name first, and then set it into path
    if (pTableName->n >= TSDB_TABLE_NAME_LEN) {
      return buildInvalidOperationMsg(pMsgBuf, msg1);
    }

1981
    assert(pTableName->n < TSDB_TABLE_FNAME_LEN);
H
Haojun Liao 已提交
1982 1983 1984

    char name[TSDB_TABLE_FNAME_LEN] = {0};
    strncpy(name, pTableName->z, pTableName->n);
1985 1986 1987 1988 1989 1990 1991
    strdequote(name);

    code = tNameSetDbName(pName, pParseCtx->acctId, pParseCtx->db, strlen(pParseCtx->db));
    if (code != TSDB_CODE_SUCCESS) {
      code = buildInvalidOperationMsg(pMsgBuf, msg2);
      return code;
    }
H
Haojun Liao 已提交
1992 1993 1994 1995 1996 1997 1998 1999 2000

    code = tNameFromString(pName, name, T_NAME_TABLE);
    if (code != 0) {
      code = buildInvalidOperationMsg(pMsgBuf, msg1);
    }
  }

  return code;
}