clientSml.c 79.0 KB
Newer Older
wmmhello's avatar
wmmhello 已提交
1 2 3 4 5
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

X
Xiaoyu Wang 已提交
6 7 8 9 10
#include "cJSON.h"
#include "catalog.h"
#include "clientInt.h"
#include "osSemaphore.h"
#include "osThread.h"
wmmhello's avatar
wmmhello 已提交
11 12
#include "query.h"
#include "taos.h"
wmmhello's avatar
wmmhello 已提交
13
#include "taoserror.h"
X
Xiaoyu Wang 已提交
14
#include "tcommon.h"
wmmhello's avatar
wmmhello 已提交
15
#include "tdef.h"
X
Xiaoyu Wang 已提交
16
#include "tglobal.h"
wmmhello's avatar
wmmhello 已提交
17 18
#include "tlog.h"
#include "tmsg.h"
X
Xiaoyu Wang 已提交
19
#include "tname.h"
wmmhello's avatar
wmmhello 已提交
20 21
#include "ttime.h"
#include "ttypes.h"
wmmhello's avatar
wmmhello 已提交
22

wmmhello's avatar
wmmhello 已提交
23
//=================================================================================================
wmmhello's avatar
wmmhello 已提交
24 25 26 27 28 29 30

#define SPACE ' '
#define COMMA ','
#define EQUAL '='
#define QUOTE '"'
#define SLASH '\\'

X
Xiaoyu Wang 已提交
31 32 33 34 35 36 37
#define JUMP_SPACE(sql)  \
  while (*sql != '\0') { \
    if (*sql == SPACE)   \
      sql++;             \
    else                 \
      break;             \
  }
wmmhello's avatar
wmmhello 已提交
38
// comma ,
X
Xiaoyu Wang 已提交
39 40
#define IS_SLASH_COMMA(sql) (*(sql) == COMMA && *((sql)-1) == SLASH)
#define IS_COMMA(sql)       (*(sql) == COMMA && *((sql)-1) != SLASH)
wmmhello's avatar
wmmhello 已提交
41
// space
X
Xiaoyu Wang 已提交
42 43
#define IS_SLASH_SPACE(sql) (*(sql) == SPACE && *((sql)-1) == SLASH)
#define IS_SPACE(sql)       (*(sql) == SPACE && *((sql)-1) != SLASH)
wmmhello's avatar
wmmhello 已提交
44
// equal =
X
Xiaoyu Wang 已提交
45 46
#define IS_SLASH_EQUAL(sql) (*(sql) == EQUAL && *((sql)-1) == SLASH)
#define IS_EQUAL(sql)       (*(sql) == EQUAL && *((sql)-1) != SLASH)
wmmhello's avatar
wmmhello 已提交
47
// quote "
X
Xiaoyu Wang 已提交
48 49
#define IS_SLASH_QUOTE(sql) (*(sql) == QUOTE && *((sql)-1) == SLASH)
#define IS_QUOTE(sql)       (*(sql) == QUOTE && *((sql)-1) != SLASH)
wmmhello's avatar
wmmhello 已提交
50
// SLASH
X
Xiaoyu Wang 已提交
51
#define IS_SLASH_SLASH(sql) (*(sql) == SLASH && *((sql)-1) == SLASH)
wmmhello's avatar
wmmhello 已提交
52

X
Xiaoyu Wang 已提交
53 54
#define IS_SLASH_LETTER(sql) \
  (IS_SLASH_COMMA(sql) || IS_SLASH_SPACE(sql) || IS_SLASH_EQUAL(sql) || IS_SLASH_QUOTE(sql) || IS_SLASH_SLASH(sql))
wmmhello's avatar
wmmhello 已提交
55

X
Xiaoyu Wang 已提交
56
#define MOVE_FORWARD_ONE(sql, len) (memmove((void *)((sql)-1), (sql), len))
wmmhello's avatar
wmmhello 已提交
57

X
Xiaoyu Wang 已提交
58 59 60 61 62 63 64 65
#define PROCESS_SLASH(key, keyLen)           \
  for (int i = 1; i < keyLen; ++i) {         \
    if (IS_SLASH_LETTER(key + i)) {          \
      MOVE_FORWARD_ONE(key + i, keyLen - i); \
      i--;                                   \
      keyLen--;                              \
    }                                        \
  }
wmmhello's avatar
wmmhello 已提交
66

67 68 69
#define IS_INVALID_COL_LEN(len)   ((len) <= 0 || (len) >= TSDB_COL_NAME_LEN)
#define IS_INVALID_TABLE_LEN(len) ((len) <= 0 || (len) >= TSDB_TABLE_NAME_LEN)

70 71 72
#define OTD_JSON_SUB_FIELDS_NUM 2
#define OTD_JSON_FIELDS_NUM     4

X
Xiaoyu Wang 已提交
73 74 75 76
#define TS        "_ts"
#define TS_LEN    3
#define VALUE     "_value"
#define VALUE_LEN 6
77

X
Xiaoyu Wang 已提交
78 79
#define BINARY_ADD_LEN 2  // "binary"   2 means " "
#define NCHAR_ADD_LEN  3  // L"nchar"   3 means L" "
wmmhello's avatar
wmmhello 已提交
80 81

#define MAX_RETRY_TIMES 5
X
Xiaoyu Wang 已提交
82
#define LINE_BATCH      20000
wmmhello's avatar
wmmhello 已提交
83 84 85 86
//=================================================================================================
typedef TSDB_SML_PROTOCOL_TYPE SMLProtocolType;

typedef enum {
87 88 89
  SCHEMA_ACTION_NULL,
  SCHEMA_ACTION_COLUMN,
  SCHEMA_ACTION_TAG
wmmhello's avatar
wmmhello 已提交
90 91 92
} ESchemaAction;

typedef struct {
X
Xiaoyu Wang 已提交
93 94 95 96
  const char *measure;
  const char *tags;
  const char *cols;
  const char *timestamp;
wmmhello's avatar
wmmhello 已提交
97 98 99 100 101 102 103 104 105

  int32_t measureLen;
  int32_t measureTagsLen;
  int32_t tagsLen;
  int32_t colsLen;
  int32_t timestampLen;
} SSmlLineInfo;

typedef struct {
X
Xiaoyu Wang 已提交
106 107 108 109
  const char *sTableName;  // super table name
  int32_t     sTableNameLen;
  char        childTableName[TSDB_TABLE_NAME_LEN];
  uint64_t    uid;
wmmhello's avatar
wmmhello 已提交
110

X
Xiaoyu Wang 已提交
111
  SArray *tags;
wmmhello's avatar
wmmhello 已提交
112

113 114
  // if info->formatData is true, elements are SArray<SSmlKv*>.
  // if info->formatData is false, elements are SHashObj<cols key string, SSmlKv*> for find by key quickly
X
Xiaoyu Wang 已提交
115
  SArray *cols;
wmmhello's avatar
wmmhello 已提交
116 117 118
} SSmlTableInfo;

typedef struct {
X
Xiaoyu Wang 已提交
119 120
  SArray   *tags;     // save the origin order to create table
  SHashObj *tagHash;  // elements are <key, index in tags>
121

X
Xiaoyu Wang 已提交
122 123
  SArray   *cols;
  SHashObj *colHash;
124

wmmhello's avatar
wmmhello 已提交
125 126 127 128
  STableMeta *tableMeta;
} SSmlSTableMeta;

typedef struct {
X
Xiaoyu Wang 已提交
129 130
  int32_t len;
  char   *buf;
wmmhello's avatar
wmmhello 已提交
131 132
} SSmlMsgBuf;

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
typedef struct {
  int32_t code;
  int32_t lineNum;

  int32_t numOfSTables;
  int32_t numOfCTables;
  int32_t numOfCreateSTables;

  int64_t parseTime;
  int64_t schemaTime;
  int64_t insertBindTime;
  int64_t insertRpcTime;
  int64_t endTime;
} SSmlCostInfo;

X
Xiaoyu Wang 已提交
148 149 150
typedef struct {
  SRequestObj     *request;
  tsem_t           sem;
wmmhello's avatar
wmmhello 已提交
151 152 153
  TdThreadSpinlock lock;
} Params;

wmmhello's avatar
wmmhello 已提交
154
typedef struct {
X
Xiaoyu Wang 已提交
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
  int64_t id;
  Params *params;
  bool    isLast;

  SMLProtocolType protocol;
  int8_t          precision;
  bool dataFormat;  // true means that the name and order of keys in each line are the same(only for influx protocol)

  SHashObj *childTables;
  SHashObj *superTables;
  SHashObj *pVgHash;
  void     *exec;

  STscObj     *taos;
  SCatalog    *pCatalog;
  SRequestObj *pRequest;
  SQuery      *pQuery;

  SSmlCostInfo cost;
  int32_t      affectedRows;
  SSmlMsgBuf   msgBuf;
  SHashObj    *dumplicateKey;  // for dumplicate key
  SArray      *colsContainer;  // for cols parse, if dataFormat == false
wmmhello's avatar
wmmhello 已提交
178
} SSmlHandle;
wmmhello's avatar
wmmhello 已提交
179 180
//=================================================================================================

wmmhello's avatar
wmmhello 已提交
181
//=================================================================================================
182
static volatile int64_t linesSmlHandleId = 0;
X
Xiaoyu Wang 已提交
183 184
static int64_t          smlGenId() {
           int64_t id;
wmmhello's avatar
wmmhello 已提交
185

X
Xiaoyu Wang 已提交
186 187
           do {
             id = atomic_add_fetch_64(&linesSmlHandleId, 1);
wmmhello's avatar
wmmhello 已提交
188 189
  } while (id == 0);

X
Xiaoyu Wang 已提交
190
           return id;
wmmhello's avatar
wmmhello 已提交
191 192
}

193
static inline bool smlDoubleToInt64OverFlow(double num) {
X
Xiaoyu Wang 已提交
194
  if (num >= (double)INT64_MAX || num <= (double)INT64_MIN) return true;
195 196 197 198 199 200 201 202 203 204 205 206
  return false;
}

static inline bool smlCheckDuplicateKey(const char *key, int32_t keyLen, SHashObj *pHash) {
  void *val = taosHashGet(pHash, key, keyLen);
  if (val) {
    return true;
  }
  taosHashPut(pHash, key, keyLen, key, 1);
  return false;
}

X
Xiaoyu Wang 已提交
207
static int32_t smlBuildInvalidDataMsg(SSmlMsgBuf *pBuf, const char *msg1, const char *msg2) {
208 209 210 211 212 213 214 215
  if(pBuf->buf){
    memset(pBuf->buf, 0, pBuf->len);
    if (msg1) strncat(pBuf->buf, msg1, pBuf->len);
    int32_t left = pBuf->len - strlen(pBuf->buf);
    if (left > 2 && msg2) {
      strncat(pBuf->buf, ":", left - 1);
      strncat(pBuf->buf, msg2, left - 2);
    }
wmmhello's avatar
wmmhello 已提交
216
  }
wmmhello's avatar
wmmhello 已提交
217 218 219
  return TSDB_CODE_SML_INVALID_DATA;
}

X
Xiaoyu Wang 已提交
220
static int32_t smlGenerateSchemaAction(SSchema *colField, SHashObj *colHash, SSmlKv *kv, bool isTag,
221
                                       ESchemaAction *action, SSmlHandle *info) {
222
  uint16_t *index = (uint16_t *)taosHashGet(colHash, kv->key, kv->keyLen);
223 224
  if (index) {
    if (colField[*index].type != kv->type) {
X
Xiaoyu Wang 已提交
225 226
      uError("SML:0x%" PRIx64 " point type and db type mismatch. key: %s. point type: %d, db type: %d", info->id,
             kv->key, colField[*index].type, kv->type);
227 228 229
      return TSDB_CODE_TSC_INVALID_VALUE;
    }

X
Xiaoyu Wang 已提交
230 231 232 233
    if ((colField[*index].type == TSDB_DATA_TYPE_VARCHAR &&
         (colField[*index].bytes - VARSTR_HEADER_SIZE) < kv->length) ||
        (colField[*index].type == TSDB_DATA_TYPE_NCHAR &&
         ((colField[*index].bytes - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE < kv->length))) {
234
      if (isTag) {
235
        *action = SCHEMA_ACTION_TAG;
236
      } else {
237
        *action = SCHEMA_ACTION_COLUMN;
238 239 240 241
      }
    }
  } else {
    if (isTag) {
242
      *action = SCHEMA_ACTION_TAG;
243
    } else {
244
      *action = SCHEMA_ACTION_COLUMN;
245 246
    }
  }
wmmhello's avatar
wmmhello 已提交
247 248 249
  return 0;
}

wmmhello's avatar
wmmhello 已提交
250
static int32_t smlFindNearestPowerOf2(int32_t length, uint8_t type) {
wmmhello's avatar
wmmhello 已提交
251
  int32_t result = 1;
X
Xiaoyu Wang 已提交
252
  while (result <= length) {
wmmhello's avatar
wmmhello 已提交
253 254
    result *= 2;
  }
wmmhello's avatar
wmmhello 已提交
255 256 257 258 259
  if (type == TSDB_DATA_TYPE_BINARY && result > TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE){
    result = TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE;
  } else if (type == TSDB_DATA_TYPE_NCHAR && result > (TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE){
    result = (TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE;
  }
wmmhello's avatar
wmmhello 已提交
260

261 262 263 264
  if (type == TSDB_DATA_TYPE_NCHAR){
    result = result * TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE;
  }else if (type == TSDB_DATA_TYPE_BINARY){
    result = result + VARSTR_HEADER_SIZE;
wmmhello's avatar
wmmhello 已提交
265
  }
266
  return result;
wmmhello's avatar
wmmhello 已提交
267 268
}

X
Xiaoyu Wang 已提交
269
static int32_t smlProcessSchemaAction(SSmlHandle *info, SSchema *schemaField, SHashObj *schemaHash, SArray *cols,
270
                                      ESchemaAction *action, bool isTag) {
271 272
  int32_t code = TSDB_CODE_SUCCESS;
  for (int j = 0; j < taosArrayGetSize(cols); ++j) {
273
    if(j == 0 && !isTag) continue;
X
Xiaoyu Wang 已提交
274
    SSmlKv *kv = (SSmlKv *)taosArrayGetP(cols, j);
275
    code = smlGenerateSchemaAction(schemaField, schemaHash, kv, isTag, action, info);
X
Xiaoyu Wang 已提交
276
    if (code != TSDB_CODE_SUCCESS) {
277 278 279 280 281 282
      return code;
    }
  }
  return TSDB_CODE_SUCCESS;
}

283
static int32_t smlCheckMeta(SSchema *schema, int32_t length, SArray *cols, bool isTag) {
284
  SHashObj *hashTmp = taosHashInit(length, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
285 286
  int32_t i = 0;
  for ( ;i < length; i++) {
287 288 289
    taosHashPut(hashTmp, schema[i].name, strlen(schema[i].name), &i, SHORT_BYTES);
  }

290 291 292 293 294 295
  if (isTag){
    i = 0;
  } else {
    i = 1;
  }
  for (; i < taosArrayGetSize(cols); i++) {
X
Xiaoyu Wang 已提交
296 297
    SSmlKv *kv = (SSmlKv *)taosArrayGetP(cols, i);
    if (taosHashGet(hashTmp, kv->key, kv->keyLen) == NULL) {
298 299 300
      return -1;
    }
  }
301
  taosHashCleanup(hashTmp);
302 303 304
  return 0;
}

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
static int32_t getBytes(uint8_t type, int32_t length){
  if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
    return smlFindNearestPowerOf2(length, type);
  } else {
    return tDataTypes[type].bytes;
  }
}

static int32_t smlSendMetaMsg(SSmlHandle *info, SName *pName, SSmlSTableMeta *sTableData,
                              int32_t colVer, int32_t tagVer, int8_t source, uint64_t suid){
  SRequestObj*   pRequest = NULL;
  SMCreateStbReq pReq = {0};
  int32_t        code = TSDB_CODE_SUCCESS;
  SCmdMsgInfo    pCmdMsg = {0};

  code = buildRequest(info->taos->id, "", 0, NULL, false, &pRequest);
  if (code != TSDB_CODE_SUCCESS) {
    goto end;
  }

  if (!pRequest->pDb) {
    code = TSDB_CODE_PAR_DB_NOT_SPECIFIED;
    goto end;
  }

  pReq.colVer = colVer;
  pReq.tagVer = tagVer;
  pReq.source = source;
  pReq.commentLen = -1;
  pReq.igExists = true;
  pReq.suid = suid;
  tNameExtractFullName(pName, pReq.name);

  pReq.numOfColumns = taosArrayGetSize(sTableData->cols);
  pReq.numOfTags = taosArrayGetSize(sTableData->tags);

  pReq.pColumns = taosArrayInit(pReq.numOfColumns, sizeof(SField));
  for (int i = 0; i < pReq.numOfColumns; i++) {
    SSmlKv *kv = (SSmlKv *)taosArrayGetP(sTableData->cols, i);
    SField field = {0};
    field.type = kv->type;
    field.bytes = getBytes(kv->type, kv->length);
    memcpy(field.name, kv->key, kv->keyLen);
    taosArrayPush(pReq.pColumns, &field);
  }

  if (pReq.numOfTags == 0){
    pReq.numOfTags = 1;
    pReq.pTags = taosArrayInit(pReq.numOfTags, sizeof(SField));
    SField field = {0};
    field.type = TSDB_DATA_TYPE_NCHAR;
    field.bytes = 1;
    strcpy(field.name, tsSmlTagName);
    taosArrayPush(pReq.pTags, &field);
  }else{
    pReq.pTags = taosArrayInit(pReq.numOfTags, sizeof(SField));
    for (int i = 0; i < pReq.numOfTags; i++) {
      SSmlKv *kv = (SSmlKv *)taosArrayGetP(sTableData->tags, i);
      SField field = {0};
      field.type = kv->type;
      field.bytes = getBytes(kv->type, kv->length);
      memcpy(field.name, kv->key, kv->keyLen);
      taosArrayPush(pReq.pTags, &field);
    }
  }

  pCmdMsg.epSet = getEpSet_s(&info->taos->pAppInfo->mgmtEp);
  pCmdMsg.msgType = TDMT_MND_CREATE_STB;
  pCmdMsg.msgLen = tSerializeSMCreateStbReq(NULL, 0, &pReq);
  pCmdMsg.pMsg = taosMemoryMalloc(pCmdMsg.msgLen);
  if (NULL == pCmdMsg.pMsg) {
    tFreeSMCreateStbReq(&pReq);
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
  tSerializeSMCreateStbReq(pCmdMsg.pMsg, pCmdMsg.msgLen, &pReq);

  SQuery pQuery;
  pQuery.execMode = QUERY_EXEC_MODE_RPC;
  pQuery.pCmdMsg = &pCmdMsg;
  pQuery.msgType = pQuery.pCmdMsg->msgType;
  pQuery.stableQuery = true;

  launchQueryImpl(pRequest, &pQuery, true, NULL);

  if(pRequest->code == TSDB_CODE_SUCCESS){
    catalogRemoveTableMeta(info->pCatalog, pName);
  }
  code = pRequest->code;
  taosMemoryFree(pCmdMsg.pMsg);

end:
  destroyRequest(pRequest);
  tFreeSMCreateStbReq(&pReq);
  return code;
}

X
Xiaoyu Wang 已提交
402
static int32_t smlModifyDBSchemas(SSmlHandle *info) {
wmmhello's avatar
wmmhello 已提交
403
  int32_t code = 0;
X
Xiaoyu Wang 已提交
404
  SName   pName = {TSDB_TABLE_NAME_T, info->taos->acctId, {0}, {0}};
405
  strcpy(pName.dbname, info->pRequest->pDb);
wmmhello's avatar
wmmhello 已提交
406

D
dapan1121 已提交
407 408 409 410 411
  SRequestConnInfo conn = {0};
  conn.pTrans = info->taos->pAppInfo->pTransporter;
  conn.requestId = info->pRequest->requestId;
  conn.requestObjRefId = info->pRequest->self;
  conn.mgmtEps = getEpSet_s(&info->taos->pAppInfo->mgmtEp);
X
Xiaoyu Wang 已提交
412 413

  SSmlSTableMeta **tableMetaSml = (SSmlSTableMeta **)taosHashIterate(info->superTables, NULL);
wmmhello's avatar
wmmhello 已提交
414
  while (tableMetaSml) {
X
Xiaoyu Wang 已提交
415 416 417
    SSmlSTableMeta *sTableData = *tableMetaSml;
    STableMeta     *pTableMeta = NULL;
    bool            needCheckMeta = false;  // for multi thread
wmmhello's avatar
wmmhello 已提交
418

wmmhello's avatar
wmmhello 已提交
419
    size_t superTableLen = 0;
X
Xiaoyu Wang 已提交
420
    void  *superTable = taosHashGetKey(tableMetaSml, &superTableLen);
421
    memset(pName.tname, 0, TSDB_TABLE_NAME_LEN);
wmmhello's avatar
wmmhello 已提交
422
    memcpy(pName.tname, superTable, superTableLen);
wmmhello's avatar
wmmhello 已提交
423

D
dapan1121 已提交
424
    code = catalogGetSTableMeta(info->pCatalog, &conn, &pName, &pTableMeta);
wmmhello's avatar
wmmhello 已提交
425

426
    if (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_MND_STB_NOT_EXIST) {
427
      code = smlSendMetaMsg(info, &pName, sTableData, 1, 1, TD_REQ_FROM_APP, 0);
428
      if (code != TSDB_CODE_SUCCESS) {
429
        uError("SML:0x%" PRIx64 " smlSendMetaMsg failed. can not create %s", info->id, superTable);
430
        goto end;
wmmhello's avatar
wmmhello 已提交
431
      }
432
      info->cost.numOfCreateSTables++;
X
Xiaoyu Wang 已提交
433 434 435 436 437
    } else if (code == TSDB_CODE_SUCCESS) {
      SHashObj *hashTmp = taosHashInit(pTableMeta->tableInfo.numOfTags,
                                       taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
      for (uint16_t i = pTableMeta->tableInfo.numOfColumns;
           i < pTableMeta->tableInfo.numOfColumns + pTableMeta->tableInfo.numOfTags; i++) {
438 439
        taosHashPut(hashTmp, pTableMeta->schema[i].name, strlen(pTableMeta->schema[i].name), &i, SHORT_BYTES);
      }
wmmhello's avatar
wmmhello 已提交
440

441 442
      ESchemaAction action = SCHEMA_ACTION_NULL;
      code = smlProcessSchemaAction(info, pTableMeta->schema, hashTmp, sTableData->tags, &action, true);
443 444
      if (code != TSDB_CODE_SUCCESS) {
        taosHashCleanup(hashTmp);
445
        goto end;
446
      }
447 448 449 450 451 452 453 454 455 456 457 458
      if (action == SCHEMA_ACTION_TAG){
        code = smlSendMetaMsg(info, &pName, sTableData, pTableMeta->sversion, pTableMeta->tversion + 1, TD_REQ_FROM_TAOX, pTableMeta->uid);
        if (code != TSDB_CODE_SUCCESS) {
          uError("SML:0x%" PRIx64 " smlSendMetaMsg failed. can not create %s", info->id, superTable);
          goto end;
        }
      }

      code = catalogRefreshTableMeta(info->pCatalog, &conn, &pName, -1);
      if (code != TSDB_CODE_SUCCESS) {
        goto end;
      }
459 460

      taosHashClear(hashTmp);
461
      for (uint16_t i = 1; i < pTableMeta->tableInfo.numOfColumns; i++) {
462 463
        taosHashPut(hashTmp, pTableMeta->schema[i].name, strlen(pTableMeta->schema[i].name), &i, SHORT_BYTES);
      }
464 465
      action = SCHEMA_ACTION_NULL;
      code = smlProcessSchemaAction(info, pTableMeta->schema, hashTmp, sTableData->cols, &action, false);
466 467
      taosHashCleanup(hashTmp);
      if (code != TSDB_CODE_SUCCESS) {
468
        goto end;
wmmhello's avatar
wmmhello 已提交
469
      }
470 471 472 473 474 475 476
      if (action == SCHEMA_ACTION_COLUMN){
        code = smlSendMetaMsg(info, &pName, sTableData, pTableMeta->sversion + 1, pTableMeta->tversion, TD_REQ_FROM_TAOX, pTableMeta->uid);
        if (code != TSDB_CODE_SUCCESS) {
          uError("SML:0x%" PRIx64 " smlSendMetaMsg failed. can not create %s", info->id, superTable);
          goto end;
        }
      }
wmmhello's avatar
wmmhello 已提交
477

D
dapan1121 已提交
478
      code = catalogRefreshTableMeta(info->pCatalog, &conn, &pName, -1);
wmmhello's avatar
wmmhello 已提交
479
      if (code != TSDB_CODE_SUCCESS) {
480
        goto end;
wmmhello's avatar
wmmhello 已提交
481
      }
482
      needCheckMeta = true;
wmmhello's avatar
wmmhello 已提交
483
    } else {
X
Xiaoyu Wang 已提交
484
      uError("SML:0x%" PRIx64 " load table meta error: %s", info->id, tstrerror(code));
485
      goto end;
wmmhello's avatar
wmmhello 已提交
486
    }
X
Xiaoyu Wang 已提交
487
    if (pTableMeta) taosMemoryFree(pTableMeta);
488

D
dapan1121 已提交
489
    code = catalogGetSTableMeta(info->pCatalog, &conn, &pName, &pTableMeta);
490
    if (code != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
491
      uError("SML:0x%" PRIx64 " catalogGetSTableMeta failed. super table name %s", info->id, (char *)superTable);
492
      goto end;
493
    }
494

X
Xiaoyu Wang 已提交
495 496
    if (needCheckMeta) {
      code = smlCheckMeta(&(pTableMeta->schema[pTableMeta->tableInfo.numOfColumns]), pTableMeta->tableInfo.numOfTags,
497
                          sTableData->tags, true);
498
      if (code != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
499
        uError("SML:0x%" PRIx64 " check tag failed. super table name %s", info->id, (char *)superTable);
500 501
        goto end;
      }
502
      code = smlCheckMeta(&(pTableMeta->schema[0]), pTableMeta->tableInfo.numOfColumns, sTableData->cols, false);
503
      if (code != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
504
        uError("SML:0x%" PRIx64 " check cols failed. super table name %s", info->id, (char *)superTable);
505 506 507 508
        goto end;
      }
    }

509
    sTableData->tableMeta = pTableMeta;
wmmhello's avatar
wmmhello 已提交
510

X
Xiaoyu Wang 已提交
511
    tableMetaSml = (SSmlSTableMeta **)taosHashIterate(info->superTables, tableMetaSml);
wmmhello's avatar
wmmhello 已提交
512 513
  }
  return 0;
514 515

end:
D
dapan1121 已提交
516
  catalogRefreshTableMeta(info->pCatalog, &conn, &pName, 1);
517
  return code;
wmmhello's avatar
wmmhello 已提交
518 519
}

X
Xiaoyu Wang 已提交
520
static bool smlParseNumber(SSmlKv *kvVal, SSmlMsgBuf *msg) {
wmmhello's avatar
wmmhello 已提交
521
  const char *pVal = kvVal->value;
X
Xiaoyu Wang 已提交
522 523 524 525
  int32_t     len = kvVal->length;
  char       *endptr = NULL;
  double      result = taosStr2Double(pVal, &endptr);
  if (pVal == endptr) {
526
    smlBuildInvalidDataMsg(msg, "invalid data", pVal);
wmmhello's avatar
wmmhello 已提交
527 528 529
    return false;
  }

530
  int32_t left = len - (endptr - pVal);
X
Xiaoyu Wang 已提交
531
  if (left == 0 || (left == 3 && strncasecmp(endptr, "f64", left) == 0)) {
532 533
    kvVal->type = TSDB_DATA_TYPE_DOUBLE;
    kvVal->d = result;
X
Xiaoyu Wang 已提交
534 535
  } else if ((left == 3 && strncasecmp(endptr, "f32", left) == 0)) {
    if (!IS_VALID_FLOAT(result)) {
536 537
      smlBuildInvalidDataMsg(msg, "float out of range[-3.402823466e+38,3.402823466e+38]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
538
    }
539 540
    kvVal->type = TSDB_DATA_TYPE_FLOAT;
    kvVal->f = (float)result;
X
Xiaoyu Wang 已提交
541 542
  } else if ((left == 1 && *endptr == 'i') || (left == 3 && strncasecmp(endptr, "i64", left) == 0)) {
    if (smlDoubleToInt64OverFlow(result)) {
wmmhello's avatar
wmmhello 已提交
543 544
      errno = 0;
      int64_t tmp = taosStr2Int64(pVal, &endptr, 10);
X
Xiaoyu Wang 已提交
545
      if (errno == ERANGE) {
wmmhello's avatar
wmmhello 已提交
546 547 548 549 550 551
        smlBuildInvalidDataMsg(msg, "big int out of range[-9223372036854775808,9223372036854775807]", pVal);
        return false;
      }
      kvVal->type = TSDB_DATA_TYPE_BIGINT;
      kvVal->i = tmp;
      return true;
wmmhello's avatar
wmmhello 已提交
552
    }
553
    kvVal->type = TSDB_DATA_TYPE_BIGINT;
wmmhello's avatar
wmmhello 已提交
554
    kvVal->i = (int64_t)result;
wmmhello's avatar
wmmhello 已提交
555
  } else if ((left == 1 && *endptr == 'u') || (left == 3 && strncasecmp(endptr, "u64", left) == 0)) {
X
Xiaoyu Wang 已提交
556
    if (result >= (double)UINT64_MAX || result < 0) {
wmmhello's avatar
wmmhello 已提交
557 558
      errno = 0;
      uint64_t tmp = taosStr2UInt64(pVal, &endptr, 10);
X
Xiaoyu Wang 已提交
559
      if (errno == ERANGE || result < 0) {
wmmhello's avatar
wmmhello 已提交
560 561 562 563 564 565
        smlBuildInvalidDataMsg(msg, "unsigned big int out of range[0,18446744073709551615]", pVal);
        return false;
      }
      kvVal->type = TSDB_DATA_TYPE_UBIGINT;
      kvVal->u = tmp;
      return true;
566
    }
567
    kvVal->type = TSDB_DATA_TYPE_UBIGINT;
wmmhello's avatar
wmmhello 已提交
568
    kvVal->u = result;
X
Xiaoyu Wang 已提交
569 570
  } else if (left == 3 && strncasecmp(endptr, "i32", left) == 0) {
    if (!IS_VALID_INT(result)) {
571 572
      smlBuildInvalidDataMsg(msg, "int out of range[-2147483648,2147483647]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
573
    }
574 575
    kvVal->type = TSDB_DATA_TYPE_INT;
    kvVal->i = result;
X
Xiaoyu Wang 已提交
576 577
  } else if (left == 3 && strncasecmp(endptr, "u32", left) == 0) {
    if (!IS_VALID_UINT(result)) {
578 579
      smlBuildInvalidDataMsg(msg, "unsigned int out of range[0,4294967295]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
580
    }
581 582
    kvVal->type = TSDB_DATA_TYPE_UINT;
    kvVal->u = result;
X
Xiaoyu Wang 已提交
583 584
  } else if (left == 3 && strncasecmp(endptr, "i16", left) == 0) {
    if (!IS_VALID_SMALLINT(result)) {
585 586
      smlBuildInvalidDataMsg(msg, "small int our of range[-32768,32767]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
587
    }
588 589
    kvVal->type = TSDB_DATA_TYPE_SMALLINT;
    kvVal->i = result;
X
Xiaoyu Wang 已提交
590 591
  } else if (left == 3 && strncasecmp(endptr, "u16", left) == 0) {
    if (!IS_VALID_USMALLINT(result)) {
592 593
      smlBuildInvalidDataMsg(msg, "unsigned small int out of rang[0,65535]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
594
    }
595 596
    kvVal->type = TSDB_DATA_TYPE_USMALLINT;
    kvVal->u = result;
X
Xiaoyu Wang 已提交
597 598
  } else if (left == 2 && strncasecmp(endptr, "i8", left) == 0) {
    if (!IS_VALID_TINYINT(result)) {
599 600
      smlBuildInvalidDataMsg(msg, "tiny int out of range[-128,127]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
601
    }
602 603
    kvVal->type = TSDB_DATA_TYPE_TINYINT;
    kvVal->i = result;
X
Xiaoyu Wang 已提交
604 605
  } else if (left == 2 && strncasecmp(endptr, "u8", left) == 0) {
    if (!IS_VALID_UTINYINT(result)) {
606 607
      smlBuildInvalidDataMsg(msg, "unsigned tiny int out of range[0,255]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
608
    }
609 610
    kvVal->type = TSDB_DATA_TYPE_UTINYINT;
    kvVal->u = result;
X
Xiaoyu Wang 已提交
611
  } else {
612
    smlBuildInvalidDataMsg(msg, "invalid data", pVal);
wmmhello's avatar
wmmhello 已提交
613 614
    return false;
  }
615
  return true;
wmmhello's avatar
wmmhello 已提交
616 617
}

wmmhello's avatar
wmmhello 已提交
618
static bool smlParseBool(SSmlKv *kvVal) {
wmmhello's avatar
wmmhello 已提交
619
  const char *pVal = kvVal->value;
X
Xiaoyu Wang 已提交
620
  int32_t     len = kvVal->length;
621
  if ((len == 1) && (pVal[0] == 't' || pVal[0] == 'T')) {
wmmhello's avatar
wmmhello 已提交
622
    kvVal->i = true;
wmmhello's avatar
wmmhello 已提交
623 624 625
    return true;
  }

626
  if ((len == 1) && (pVal[0] == 'f' || pVal[0] == 'F')) {
wmmhello's avatar
wmmhello 已提交
627
    kvVal->i = false;
wmmhello's avatar
wmmhello 已提交
628 629 630
    return true;
  }

X
Xiaoyu Wang 已提交
631
  if ((len == 4) && !strncasecmp(pVal, "true", len)) {
wmmhello's avatar
wmmhello 已提交
632
    kvVal->i = true;
wmmhello's avatar
wmmhello 已提交
633 634
    return true;
  }
X
Xiaoyu Wang 已提交
635
  if ((len == 5) && !strncasecmp(pVal, "false", len)) {
wmmhello's avatar
wmmhello 已提交
636
    kvVal->i = false;
wmmhello's avatar
wmmhello 已提交
637 638 639 640 641
    return true;
  }
  return false;
}

wmmhello's avatar
wmmhello 已提交
642
static bool smlIsBinary(const char *pVal, uint16_t len) {
X
Xiaoyu Wang 已提交
643
  // binary: "abc"
wmmhello's avatar
wmmhello 已提交
644 645 646 647 648 649 650 651 652
  if (len < 2) {
    return false;
  }
  if (pVal[0] == '"' && pVal[len - 1] == '"') {
    return true;
  }
  return false;
}

wmmhello's avatar
wmmhello 已提交
653
static bool smlIsNchar(const char *pVal, uint16_t len) {
X
Xiaoyu Wang 已提交
654
  // nchar: L"abc"
wmmhello's avatar
wmmhello 已提交
655 656 657
  if (len < 3) {
    return false;
  }
X
Xiaoyu Wang 已提交
658
  if ((pVal[0] == 'l' || pVal[0] == 'L') && pVal[1] == '"' && pVal[len - 1] == '"') {
wmmhello's avatar
wmmhello 已提交
659 660 661 662 663
    return true;
  }
  return false;
}

664
static int64_t smlGetTimeValue(const char *value, int32_t len, int8_t type) {
X
Xiaoyu Wang 已提交
665
  char   *endPtr = NULL;
wafwerar's avatar
wafwerar 已提交
666
  int64_t tsInt64 = taosStr2Int64(value, &endPtr, 10);
X
Xiaoyu Wang 已提交
667
  if (value + len != endPtr) {
668
    return -1;
wmmhello's avatar
wmmhello 已提交
669
  }
670
  double ts = tsInt64;
671 672
  switch (type) {
    case TSDB_TIME_PRECISION_HOURS:
wmmhello's avatar
wmmhello 已提交
673 674
      ts *= NANOSECOND_PER_HOUR;
      tsInt64 *= NANOSECOND_PER_HOUR;
675 676
      break;
    case TSDB_TIME_PRECISION_MINUTES:
wmmhello's avatar
wmmhello 已提交
677 678
      ts *= NANOSECOND_PER_MINUTE;
      tsInt64 *= NANOSECOND_PER_MINUTE;
679 680
      break;
    case TSDB_TIME_PRECISION_SECONDS:
wmmhello's avatar
wmmhello 已提交
681 682
      ts *= NANOSECOND_PER_SEC;
      tsInt64 *= NANOSECOND_PER_SEC;
683 684
      break;
    case TSDB_TIME_PRECISION_MILLI:
wmmhello's avatar
wmmhello 已提交
685 686
      ts *= NANOSECOND_PER_MSEC;
      tsInt64 *= NANOSECOND_PER_MSEC;
687 688
      break;
    case TSDB_TIME_PRECISION_MICRO:
wmmhello's avatar
wmmhello 已提交
689 690
      ts *= NANOSECOND_PER_USEC;
      tsInt64 *= NANOSECOND_PER_USEC;
691 692 693 694 695
      break;
    case TSDB_TIME_PRECISION_NANO:
      break;
    default:
      ASSERT(0);
wmmhello's avatar
wmmhello 已提交
696
  }
X
Xiaoyu Wang 已提交
697
  if (ts >= (double)INT64_MAX || ts < 0) {
698
    return -1;
wmmhello's avatar
wmmhello 已提交
699 700
  }

701
  return tsInt64;
702 703 704 705 706 707
}

static int8_t smlGetTsTypeByLen(int32_t len) {
  if (len == TSDB_TIME_PRECISION_SEC_DIGITS) {
    return TSDB_TIME_PRECISION_SECONDS;
  } else if (len == TSDB_TIME_PRECISION_MILLI_DIGITS) {
708
    return TSDB_TIME_PRECISION_MILLI;
709 710
  } else {
    return -1;
wmmhello's avatar
wmmhello 已提交
711
  }
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
}

static int8_t smlGetTsTypeByPrecision(int8_t precision) {
  switch (precision) {
    case TSDB_SML_TIMESTAMP_HOURS:
      return TSDB_TIME_PRECISION_HOURS;
    case TSDB_SML_TIMESTAMP_MILLI_SECONDS:
      return TSDB_TIME_PRECISION_MILLI;
    case TSDB_SML_TIMESTAMP_NANO_SECONDS:
    case TSDB_SML_TIMESTAMP_NOT_CONFIGURED:
      return TSDB_TIME_PRECISION_NANO;
    case TSDB_SML_TIMESTAMP_MICRO_SECONDS:
      return TSDB_TIME_PRECISION_MICRO;
    case TSDB_SML_TIMESTAMP_SECONDS:
      return TSDB_TIME_PRECISION_SECONDS;
    case TSDB_SML_TIMESTAMP_MINUTES:
      return TSDB_TIME_PRECISION_MINUTES;
    default:
      return -1;
wmmhello's avatar
wmmhello 已提交
731
  }
732 733
}

X
Xiaoyu Wang 已提交
734 735
static int64_t smlParseInfluxTime(SSmlHandle *info, const char *data, int32_t len) {
  if (len == 0 || (len == 1 && data[0] == '0')) {
736
    return taosGetTimestampNs();
wmmhello's avatar
wmmhello 已提交
737 738
  }

739 740 741 742
  int8_t tsType = smlGetTsTypeByPrecision(info->precision);
  if (tsType == -1) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid timestamp precision", NULL);
    return -1;
wmmhello's avatar
wmmhello 已提交
743
  }
744 745

  int64_t ts = smlGetTimeValue(data, len, tsType);
X
Xiaoyu Wang 已提交
746
  if (ts == -1) {
747 748
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid timestamp", data);
    return -1;
wmmhello's avatar
wmmhello 已提交
749
  }
750 751 752
  return ts;
}

X
Xiaoyu Wang 已提交
753 754
static int64_t smlParseOpenTsdbTime(SSmlHandle *info, const char *data, int32_t len) {
  if (!data) {
755 756
    smlBuildInvalidDataMsg(&info->msgBuf, "timestamp can not be null", NULL);
    return -1;
wmmhello's avatar
wmmhello 已提交
757
  }
X
Xiaoyu Wang 已提交
758
  if (len == 1 && data[0] == '0') {
759 760
    return taosGetTimestampNs();
  }
761 762
  int8_t tsType = smlGetTsTypeByLen(len);
  if (tsType == -1) {
X
Xiaoyu Wang 已提交
763 764
    smlBuildInvalidDataMsg(&info->msgBuf,
                           "timestamp precision can only be seconds(10 digits) or milli seconds(13 digits)", data);
765 766 767
    return -1;
  }
  int64_t ts = smlGetTimeValue(data, len, tsType);
X
Xiaoyu Wang 已提交
768
  if (ts == -1) {
769 770 771 772 773 774
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid timestamp", data);
    return -1;
  }
  return ts;
}

X
Xiaoyu Wang 已提交
775
static int32_t smlParseTS(SSmlHandle *info, const char *data, int32_t len, SArray *cols) {
776
  int64_t ts = 0;
X
Xiaoyu Wang 已提交
777
  if (info->protocol == TSDB_SML_LINE_PROTOCOL) {
778
//    uError("SML:data:%s,len:%d", data, len);
779
    ts = smlParseInfluxTime(info, data, len);
X
Xiaoyu Wang 已提交
780
  } else if (info->protocol == TSDB_SML_TELNET_PROTOCOL) {
781
    ts = smlParseOpenTsdbTime(info, data, len);
X
Xiaoyu Wang 已提交
782
  } else {
783
    ASSERT(0);
784
  }
785

wmmhello's avatar
wmmhello 已提交
786
  if (ts == -1) return TSDB_CODE_INVALID_TIMESTAMP;
787 788 789

  // add ts to
  SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
X
Xiaoyu Wang 已提交
790
  if (!kv) {
791 792 793 794 795 796 797 798
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  kv->key = TS;
  kv->keyLen = TS_LEN;
  kv->i = ts;
  kv->type = TSDB_DATA_TYPE_TIMESTAMP;
  kv->length = (int16_t)tDataTypes[kv->type].bytes;
X
Xiaoyu Wang 已提交
799
  if (cols) taosArrayPush(cols, &kv);
800 801 802
  return TSDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
803
static int32_t smlParseValue(SSmlKv *pVal, SSmlMsgBuf *msg) {
X
Xiaoyu Wang 已提交
804
  // binary
wmmhello's avatar
wmmhello 已提交
805
  if (smlIsBinary(pVal->value, pVal->length)) {
806
    pVal->type = TSDB_DATA_TYPE_BINARY;
wmmhello's avatar
wmmhello 已提交
807
    pVal->length -= BINARY_ADD_LEN;
wmmhello's avatar
wmmhello 已提交
808 809 810
    if (pVal->length > TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE){
      return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
    }
811
    pVal->value += (BINARY_ADD_LEN - 1);
wmmhello's avatar
wmmhello 已提交
812
    return TSDB_CODE_SUCCESS;
813
  }
X
Xiaoyu Wang 已提交
814
  // nchar
wmmhello's avatar
wmmhello 已提交
815
  if (smlIsNchar(pVal->value, pVal->length)) {
816
    pVal->type = TSDB_DATA_TYPE_NCHAR;
wmmhello's avatar
wmmhello 已提交
817
    pVal->length -= NCHAR_ADD_LEN;
wmmhello's avatar
wmmhello 已提交
818 819 820
    if(pVal->length > (TSDB_MAX_NCHAR_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE){
      return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
    }
821
    pVal->value += (NCHAR_ADD_LEN - 1);
wmmhello's avatar
wmmhello 已提交
822
    return TSDB_CODE_SUCCESS;
823 824
  }

X
Xiaoyu Wang 已提交
825
  // bool
826 827 828
  if (smlParseBool(pVal)) {
    pVal->type = TSDB_DATA_TYPE_BOOL;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
wmmhello's avatar
wmmhello 已提交
829
    return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
830
  }
X
Xiaoyu Wang 已提交
831
  // number
832
  if (smlParseNumber(pVal, msg)) {
wmmhello's avatar
wmmhello 已提交
833
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
wmmhello's avatar
wmmhello 已提交
834
    return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
835 836
  }

wmmhello's avatar
wmmhello 已提交
837
  return TSDB_CODE_TSC_INVALID_VALUE;
wmmhello's avatar
wmmhello 已提交
838 839
}

X
Xiaoyu Wang 已提交
840 841
static int32_t smlParseInfluxString(const char *sql, SSmlLineInfo *elements, SSmlMsgBuf *msg) {
  if (!sql) return TSDB_CODE_SML_INVALID_DATA;
wmmhello's avatar
wmmhello 已提交
842
  JUMP_SPACE(sql)
X
Xiaoyu Wang 已提交
843
  if (*sql == COMMA) return TSDB_CODE_SML_INVALID_DATA;
wmmhello's avatar
wmmhello 已提交
844
  elements->measure = sql;
wmmhello's avatar
wmmhello 已提交
845

wmmhello's avatar
wmmhello 已提交
846
  // parse measure
wmmhello's avatar
wmmhello 已提交
847
  while (*sql != '\0') {
X
Xiaoyu Wang 已提交
848 849
    if ((sql != elements->measure) && IS_SLASH_LETTER(sql)) {
      MOVE_FORWARD_ONE(sql, strlen(sql) + 1);
wmmhello's avatar
wmmhello 已提交
850 851
      continue;
    }
X
Xiaoyu Wang 已提交
852
    if (IS_COMMA(sql)) {
wmmhello's avatar
wmmhello 已提交
853 854 855
      break;
    }

X
Xiaoyu Wang 已提交
856
    if (IS_SPACE(sql)) {
wmmhello's avatar
wmmhello 已提交
857 858
      break;
    }
wmmhello's avatar
wmmhello 已提交
859 860
    sql++;
  }
wmmhello's avatar
wmmhello 已提交
861
  elements->measureLen = sql - elements->measure;
X
Xiaoyu Wang 已提交
862
  if (IS_INVALID_TABLE_LEN(elements->measureLen)) {
863
    smlBuildInvalidDataMsg(msg, "measure is empty or too large than 192", NULL);
wmmhello's avatar
wmmhello 已提交
864
    return TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
wmmhello's avatar
wmmhello 已提交
865
  }
wmmhello's avatar
wmmhello 已提交
866

wmmhello's avatar
wmmhello 已提交
867
  // parse tag
X
Xiaoyu Wang 已提交
868
  if (*sql == SPACE) {
wmmhello's avatar
wmmhello 已提交
869
    elements->tagsLen = 0;
X
Xiaoyu Wang 已提交
870 871
  } else {
    if (*sql == COMMA) sql++;
wmmhello's avatar
wmmhello 已提交
872 873
    elements->tags = sql;
    while (*sql != '\0') {
X
Xiaoyu Wang 已提交
874
      if (IS_SPACE(sql)) {
wmmhello's avatar
wmmhello 已提交
875 876 877
        break;
      }
      sql++;
wmmhello's avatar
wmmhello 已提交
878
    }
wmmhello's avatar
wmmhello 已提交
879
    elements->tagsLen = sql - elements->tags;
880
  }
wmmhello's avatar
wmmhello 已提交
881
  elements->measureTagsLen = sql - elements->measure;
wmmhello's avatar
wmmhello 已提交
882

wmmhello's avatar
wmmhello 已提交
883 884 885
  // parse cols
  JUMP_SPACE(sql)
  elements->cols = sql;
wmmhello's avatar
wmmhello 已提交
886
  bool isInQuote = false;
wmmhello's avatar
wmmhello 已提交
887
  while (*sql != '\0') {
X
Xiaoyu Wang 已提交
888
    if (IS_QUOTE(sql)) {
wmmhello's avatar
wmmhello 已提交
889 890
      isInQuote = !isInQuote;
    }
X
Xiaoyu Wang 已提交
891
    if (!isInQuote && IS_SPACE(sql)) {
wmmhello's avatar
wmmhello 已提交
892 893 894 895
      break;
    }
    sql++;
  }
X
Xiaoyu Wang 已提交
896
  if (isInQuote) {
897 898 899
    smlBuildInvalidDataMsg(msg, "only one quote", elements->cols);
    return TSDB_CODE_SML_INVALID_DATA;
  }
wmmhello's avatar
wmmhello 已提交
900
  elements->colsLen = sql - elements->cols;
X
Xiaoyu Wang 已提交
901
  if (elements->colsLen == 0) {
wmmhello's avatar
wmmhello 已提交
902 903 904
    smlBuildInvalidDataMsg(msg, "cols is empty", NULL);
    return TSDB_CODE_SML_INVALID_DATA;
  }
wmmhello's avatar
wmmhello 已提交
905

wmmhello's avatar
wmmhello 已提交
906 907 908
  // parse timestamp
  JUMP_SPACE(sql)
  elements->timestamp = sql;
wmmhello's avatar
wmmhello 已提交
909
  while (*sql != '\0') {
X
Xiaoyu Wang 已提交
910
    if (*sql == SPACE) {
wmmhello's avatar
wmmhello 已提交
911 912 913 914
      break;
    }
    sql++;
  }
wmmhello's avatar
wmmhello 已提交
915
  elements->timestampLen = sql - elements->timestamp;
wmmhello's avatar
wmmhello 已提交
916 917 918 919

  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
920
static void smlParseTelnetElement(const char **sql, const char **data, int32_t *len) {
921
  while (**sql != '\0') {
X
Xiaoyu Wang 已提交
922
    if (**sql != SPACE && !(*data)) {
923
      *data = *sql;
X
Xiaoyu Wang 已提交
924
    } else if (**sql == SPACE && *data) {
925 926 927 928 929 930 931
      *len = *sql - *data;
      break;
    }
    (*sql)++;
  }
}

X
Xiaoyu Wang 已提交
932 933
static int32_t smlParseTelnetTags(const char *data, SArray *cols, char *childTableName, SHashObj *dumplicateKey,
                                  SSmlMsgBuf *msg) {
wmmhello's avatar
wmmhello 已提交
934
  const char *sql = data;
X
Xiaoyu Wang 已提交
935 936
  size_t      childTableNameLen = strlen(tsSmlChildTableName);
  while (*sql != '\0') {
wmmhello's avatar
wmmhello 已提交
937
    JUMP_SPACE(sql)
X
Xiaoyu Wang 已提交
938
    if (*sql == '\0') break;
wmmhello's avatar
wmmhello 已提交
939

wmmhello's avatar
wmmhello 已提交
940
    const char *key = sql;
X
Xiaoyu Wang 已提交
941
    int32_t     keyLen = 0;
wmmhello's avatar
wmmhello 已提交
942 943

    // parse key
X
Xiaoyu Wang 已提交
944 945
    while (*sql != '\0') {
      if (*sql == SPACE) {
wmmhello's avatar
wmmhello 已提交
946 947 948
        smlBuildInvalidDataMsg(msg, "invalid data", sql);
        return TSDB_CODE_SML_INVALID_DATA;
      }
X
Xiaoyu Wang 已提交
949
      if (*sql == EQUAL) {
wmmhello's avatar
wmmhello 已提交
950 951
        keyLen = sql - key;
        sql++;
952 953
        break;
      }
wmmhello's avatar
wmmhello 已提交
954
      sql++;
955
    }
wmmhello's avatar
wmmhello 已提交
956

X
Xiaoyu Wang 已提交
957
    if (IS_INVALID_COL_LEN(keyLen)) {
958
      smlBuildInvalidDataMsg(msg, "invalid key or key is too long than 64", key);
wmmhello's avatar
wmmhello 已提交
959
      return TSDB_CODE_TSC_INVALID_COLUMN_LENGTH;
960
    }
X
Xiaoyu Wang 已提交
961
    if (smlCheckDuplicateKey(key, keyLen, dumplicateKey)) {
962
      smlBuildInvalidDataMsg(msg, "dumplicate key", key);
wmmhello's avatar
wmmhello 已提交
963
      return TSDB_CODE_TSC_DUP_NAMES;
964 965 966
    }

    // parse value
wmmhello's avatar
wmmhello 已提交
967
    const char *value = sql;
X
Xiaoyu Wang 已提交
968 969
    int32_t     valueLen = 0;
    while (*sql != '\0') {
wmmhello's avatar
wmmhello 已提交
970 971
      // parse value
      if (*sql == SPACE) {
972 973
        break;
      }
wmmhello's avatar
wmmhello 已提交
974 975 976 977 978
      if (*sql == EQUAL) {
        smlBuildInvalidDataMsg(msg, "invalid data", sql);
        return TSDB_CODE_SML_INVALID_DATA;
      }
      sql++;
979
    }
wmmhello's avatar
wmmhello 已提交
980
    valueLen = sql - value;
wmmhello's avatar
wmmhello 已提交
981

X
Xiaoyu Wang 已提交
982
    if (valueLen == 0) {
983
      smlBuildInvalidDataMsg(msg, "invalid value", value);
wmmhello's avatar
wmmhello 已提交
984
      return TSDB_CODE_TSC_INVALID_VALUE;
985
    }
wmmhello's avatar
wmmhello 已提交
986

X
Xiaoyu Wang 已提交
987 988
    // handle child table name
    if (childTableNameLen != 0 && strncmp(key, tsSmlChildTableName, keyLen) == 0) {
989 990 991 992 993
      memset(childTableName, 0, TSDB_TABLE_NAME_LEN);
      strncpy(childTableName, value, (valueLen < TSDB_TABLE_NAME_LEN ? valueLen : TSDB_TABLE_NAME_LEN));
      continue;
    }

wmmhello's avatar
wmmhello 已提交
994 995 996 997
    if(valueLen > (TSDB_MAX_NCHAR_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE){
      return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
    }

998 999
    // add kv to SSmlKv
    SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
X
Xiaoyu Wang 已提交
1000
    if (!kv) return TSDB_CODE_OUT_OF_MEMORY;
1001 1002 1003
    kv->key = key;
    kv->keyLen = keyLen;
    kv->value = value;
wmmhello's avatar
wmmhello 已提交
1004
    kv->length = valueLen;
wmmhello's avatar
wmmhello 已提交
1005
    kv->type = TSDB_DATA_TYPE_NCHAR;
1006

X
Xiaoyu Wang 已提交
1007
    if (cols) taosArrayPush(cols, &kv);
1008 1009 1010 1011
  }

  return TSDB_CODE_SUCCESS;
}
wmmhello's avatar
wmmhello 已提交
1012

1013
// format: <metric> <timestamp> <value> <tagk_1>=<tagv_1>[ <tagk_n>=<tagv_n>]
X
Xiaoyu Wang 已提交
1014 1015
static int32_t smlParseTelnetString(SSmlHandle *info, const char *sql, SSmlTableInfo *tinfo, SArray *cols) {
  if (!sql) return TSDB_CODE_SML_INVALID_DATA;
1016 1017 1018

  // parse metric
  smlParseTelnetElement(&sql, &tinfo->sTableName, &tinfo->sTableNameLen);
1019
  if (!(tinfo->sTableName) || IS_INVALID_TABLE_LEN(tinfo->sTableNameLen)) {
1020
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid data", sql);
wmmhello's avatar
wmmhello 已提交
1021
    return TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
1022 1023 1024 1025
  }

  // parse timestamp
  const char *timestamp = NULL;
X
Xiaoyu Wang 已提交
1026
  int32_t     tLen = 0;
1027 1028 1029 1030 1031 1032 1033 1034 1035
  smlParseTelnetElement(&sql, &timestamp, &tLen);
  if (!timestamp || tLen == 0) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid timestamp", sql);
    return TSDB_CODE_SML_INVALID_DATA;
  }

  int32_t ret = smlParseTS(info, timestamp, tLen, cols);
  if (ret != TSDB_CODE_SUCCESS) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid timestamp", sql);
wmmhello's avatar
wmmhello 已提交
1036
    return ret;
1037 1038 1039 1040
  }

  // parse value
  const char *value = NULL;
X
Xiaoyu Wang 已提交
1041
  int32_t     valueLen = 0;
1042 1043 1044
  smlParseTelnetElement(&sql, &value, &valueLen);
  if (!value || valueLen == 0) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid value", sql);
wmmhello's avatar
wmmhello 已提交
1045
    return TSDB_CODE_TSC_INVALID_VALUE;
1046 1047 1048
  }

  SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
X
Xiaoyu Wang 已提交
1049
  if (!kv) return TSDB_CODE_OUT_OF_MEMORY;
1050 1051 1052 1053
  taosArrayPush(cols, &kv);
  kv->key = VALUE;
  kv->keyLen = VALUE_LEN;
  kv->value = value;
wmmhello's avatar
wmmhello 已提交
1054
  kv->length = valueLen;
wmmhello's avatar
wmmhello 已提交
1055 1056
  if ((ret = smlParseValue(kv, &info->msgBuf)) != TSDB_CODE_SUCCESS) {
    return ret;
1057 1058 1059
  }

  // parse tags
1060
  ret = smlParseTelnetTags(sql, tinfo->tags, tinfo->childTableName, info->dumplicateKey, &info->msgBuf);
1061 1062
  if (ret != TSDB_CODE_SUCCESS) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid data", sql);
wmmhello's avatar
wmmhello 已提交
1063
    return ret;
1064 1065 1066 1067 1068
  }

  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
1069 1070 1071
static int32_t smlParseCols(const char *data, int32_t len, SArray *cols, char *childTableName, bool isTag,
                            SHashObj *dumplicateKey, SSmlMsgBuf *msg) {
  if (len == 0) {
wmmhello's avatar
wmmhello 已提交
1072
    return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1073 1074
  }

X
Xiaoyu Wang 已提交
1075
  size_t      childTableNameLen = strlen(tsSmlChildTableName);
wmmhello's avatar
wmmhello 已提交
1076
  const char *sql = data;
X
Xiaoyu Wang 已提交
1077
  while (sql < data + len) {
wmmhello's avatar
wmmhello 已提交
1078
    const char *key = sql;
X
Xiaoyu Wang 已提交
1079
    int32_t     keyLen = 0;
wmmhello's avatar
wmmhello 已提交
1080

X
Xiaoyu Wang 已提交
1081
    while (sql < data + len) {
wmmhello's avatar
wmmhello 已提交
1082
      // parse key
X
Xiaoyu Wang 已提交
1083
      if (IS_COMMA(sql)) {
wmmhello's avatar
wmmhello 已提交
1084 1085 1086
        smlBuildInvalidDataMsg(msg, "invalid data", sql);
        return TSDB_CODE_SML_INVALID_DATA;
      }
X
Xiaoyu Wang 已提交
1087
      if (IS_EQUAL(sql)) {
wmmhello's avatar
wmmhello 已提交
1088 1089
        keyLen = sql - key;
        sql++;
wmmhello's avatar
wmmhello 已提交
1090 1091
        break;
      }
wmmhello's avatar
wmmhello 已提交
1092
      sql++;
wmmhello's avatar
wmmhello 已提交
1093
    }
wmmhello's avatar
wmmhello 已提交
1094

X
Xiaoyu Wang 已提交
1095
    if (IS_INVALID_COL_LEN(keyLen)) {
wmmhello's avatar
wmmhello 已提交
1096
      smlBuildInvalidDataMsg(msg, "invalid key or key is too long than 64", key);
wmmhello's avatar
wmmhello 已提交
1097
      return TSDB_CODE_TSC_INVALID_COLUMN_LENGTH;
wmmhello's avatar
wmmhello 已提交
1098
    }
X
Xiaoyu Wang 已提交
1099
    if (smlCheckDuplicateKey(key, keyLen, dumplicateKey)) {
1100
      smlBuildInvalidDataMsg(msg, "dumplicate key", key);
wmmhello's avatar
wmmhello 已提交
1101
      return TSDB_CODE_TSC_DUP_NAMES;
1102 1103
    }

wmmhello's avatar
wmmhello 已提交
1104
    // parse value
wmmhello's avatar
wmmhello 已提交
1105
    const char *value = sql;
X
Xiaoyu Wang 已提交
1106 1107 1108
    int32_t     valueLen = 0;
    bool        isInQuote = false;
    while (sql < data + len) {
wmmhello's avatar
wmmhello 已提交
1109
      // parse value
X
Xiaoyu Wang 已提交
1110
      if (!isTag && IS_QUOTE(sql)) {
wmmhello's avatar
wmmhello 已提交
1111
        isInQuote = !isInQuote;
wmmhello's avatar
wmmhello 已提交
1112 1113
        sql++;
        continue;
wmmhello's avatar
wmmhello 已提交
1114
      }
wmmhello's avatar
wmmhello 已提交
1115
      if (!isInQuote && IS_COMMA(sql)) {
wmmhello's avatar
wmmhello 已提交
1116 1117
        break;
      }
wmmhello's avatar
wmmhello 已提交
1118 1119 1120 1121 1122
      if (!isInQuote && IS_EQUAL(sql)) {
        smlBuildInvalidDataMsg(msg, "invalid data", sql);
        return TSDB_CODE_SML_INVALID_DATA;
      }
      sql++;
wmmhello's avatar
wmmhello 已提交
1123
    }
wmmhello's avatar
wmmhello 已提交
1124 1125 1126
    valueLen = sql - value;
    sql++;

X
Xiaoyu Wang 已提交
1127
    if (isInQuote) {
wmmhello's avatar
wmmhello 已提交
1128 1129 1130
      smlBuildInvalidDataMsg(msg, "only one quote", value);
      return TSDB_CODE_SML_INVALID_DATA;
    }
X
Xiaoyu Wang 已提交
1131
    if (valueLen == 0) {
wmmhello's avatar
wmmhello 已提交
1132
      smlBuildInvalidDataMsg(msg, "invalid value", value);
wmmhello's avatar
wmmhello 已提交
1133 1134
      return TSDB_CODE_SML_INVALID_DATA;
    }
wmmhello's avatar
wmmhello 已提交
1135 1136
    PROCESS_SLASH(key, keyLen)
    PROCESS_SLASH(value, valueLen)
wmmhello's avatar
wmmhello 已提交
1137

X
Xiaoyu Wang 已提交
1138 1139
    // handle child table name
    if (childTableName && childTableNameLen != 0 && strncmp(key, tsSmlChildTableName, keyLen) == 0) {
1140 1141 1142 1143 1144
      memset(childTableName, 0, TSDB_TABLE_NAME_LEN);
      strncpy(childTableName, value, (valueLen < TSDB_TABLE_NAME_LEN ? valueLen : TSDB_TABLE_NAME_LEN));
      continue;
    }

wmmhello's avatar
wmmhello 已提交
1145
    // add kv to SSmlKv
wmmhello's avatar
wmmhello 已提交
1146
    SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
X
Xiaoyu Wang 已提交
1147 1148
    if (!kv) return TSDB_CODE_OUT_OF_MEMORY;
    if (cols) taosArrayPush(cols, &kv);
1149

wmmhello's avatar
wmmhello 已提交
1150 1151 1152
    kv->key = key;
    kv->keyLen = keyLen;
    kv->value = value;
wmmhello's avatar
wmmhello 已提交
1153
    kv->length = valueLen;
X
Xiaoyu Wang 已提交
1154
    if (isTag) {
1155 1156 1157
      if(valueLen > (TSDB_MAX_NCHAR_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE){
        return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
      }
wmmhello's avatar
wmmhello 已提交
1158
      kv->type = TSDB_DATA_TYPE_NCHAR;
X
Xiaoyu Wang 已提交
1159
    } else {
wmmhello's avatar
wmmhello 已提交
1160 1161 1162
      int32_t ret = smlParseValue(kv, msg);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
wmmhello's avatar
wmmhello 已提交
1163
      }
wmmhello's avatar
wmmhello 已提交
1164 1165
    }
  }
wmmhello's avatar
wmmhello 已提交
1166

wmmhello's avatar
wmmhello 已提交
1167 1168 1169
  return TSDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
1170 1171
static int32_t smlUpdateMeta(SHashObj *metaHash, SArray *metaArray, SArray *cols, SSmlMsgBuf *msg) {
  for (int i = 0; i < taosArrayGetSize(cols); ++i) {
wmmhello's avatar
wmmhello 已提交
1172
    SSmlKv *kv = (SSmlKv *)taosArrayGetP(cols, i);
wmmhello's avatar
wmmhello 已提交
1173

wmmhello's avatar
wmmhello 已提交
1174
    int16_t *index = (int16_t *)taosHashGet(metaHash, kv->key, kv->keyLen);
X
Xiaoyu Wang 已提交
1175
    if (index) {
wmmhello's avatar
wmmhello 已提交
1176
      SSmlKv **value = (SSmlKv **)taosArrayGet(metaArray, *index);
X
Xiaoyu Wang 已提交
1177
      if (kv->type != (*value)->type) {
wmmhello's avatar
wmmhello 已提交
1178
        smlBuildInvalidDataMsg(msg, "the type is not the same like before", kv->key);
wmmhello's avatar
wmmhello 已提交
1179
        return TSDB_CODE_SML_NOT_SAME_TYPE;
X
Xiaoyu Wang 已提交
1180 1181 1182
      } else {
        if (IS_VAR_DATA_TYPE(kv->type)) {  // update string len, if bigger
          if (kv->length > (*value)->length) {
wmmhello's avatar
wmmhello 已提交
1183
            *value = kv;
1184 1185 1186
          }
        }
      }
X
Xiaoyu Wang 已提交
1187
    } else {
wmmhello's avatar
wmmhello 已提交
1188 1189 1190 1191 1192
      size_t tmp = taosArrayGetSize(metaArray);
      ASSERT(tmp <= INT16_MAX);
      int16_t size = tmp;
      taosArrayPush(metaArray, &kv);
      taosHashPut(metaHash, kv->key, kv->keyLen, &size, SHORT_BYTES);
1193
    }
wmmhello's avatar
wmmhello 已提交
1194
  }
wmmhello's avatar
wmmhello 已提交
1195

wmmhello's avatar
wmmhello 已提交
1196
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1197 1198
}

X
Xiaoyu Wang 已提交
1199
static void smlInsertMeta(SHashObj *metaHash, SArray *metaArray, SArray *cols) {
wmmhello's avatar
wmmhello 已提交
1200 1201 1202 1203
  for (int16_t i = 0; i < taosArrayGetSize(cols); ++i) {
    SSmlKv *kv = (SSmlKv *)taosArrayGetP(cols, i);
    taosArrayPush(metaArray, &kv);
    taosHashPut(metaHash, kv->key, kv->keyLen, &i, SHORT_BYTES);
wmmhello's avatar
wmmhello 已提交
1204 1205 1206
  }
}

X
Xiaoyu Wang 已提交
1207
static SSmlTableInfo *smlBuildTableInfo() {
1208
  SSmlTableInfo *tag = (SSmlTableInfo *)taosMemoryCalloc(sizeof(SSmlTableInfo), 1);
X
Xiaoyu Wang 已提交
1209
  if (!tag) {
1210
    return NULL;
wmmhello's avatar
wmmhello 已提交
1211
  }
1212 1213 1214 1215 1216

  tag->cols = taosArrayInit(16, POINTER_BYTES);
  if (tag->cols == NULL) {
    uError("SML:smlBuildTableInfo failed to allocate memory");
    goto cleanup;
wmmhello's avatar
wmmhello 已提交
1217
  }
1218 1219 1220 1221 1222

  tag->tags = taosArrayInit(16, POINTER_BYTES);
  if (tag->tags == NULL) {
    uError("SML:smlBuildTableInfo failed to allocate memory");
    goto cleanup;
wmmhello's avatar
wmmhello 已提交
1223
  }
1224 1225 1226 1227 1228
  return tag;

cleanup:
  taosMemoryFree(tag);
  return NULL;
wmmhello's avatar
wmmhello 已提交
1229 1230
}

X
Xiaoyu Wang 已提交
1231 1232 1233
static void smlDestroyTableInfo(SSmlHandle *info, SSmlTableInfo *tag) {
  if (info->dataFormat) {
    for (size_t i = 0; i < taosArrayGetSize(tag->cols); i++) {
1234 1235
      SArray *kvArray = (SArray *)taosArrayGetP(tag->cols, i);
      for (int j = 0; j < taosArrayGetSize(kvArray); ++j) {
wmmhello's avatar
wmmhello 已提交
1236
        SSmlKv *p = (SSmlKv *)taosArrayGetP(kvArray, j);
X
Xiaoyu Wang 已提交
1237 1238 1239
        if (info->protocol == TSDB_SML_JSON_PROTOCOL &&
            (p->type == TSDB_DATA_TYPE_NCHAR || p->type == TSDB_DATA_TYPE_BINARY)) {
          taosMemoryFree((void *)p->value);
wmmhello's avatar
wmmhello 已提交
1240
        }
1241 1242 1243 1244
        taosMemoryFree(p);
      }
      taosArrayDestroy(kvArray);
    }
X
Xiaoyu Wang 已提交
1245 1246
  } else {
    for (size_t i = 0; i < taosArrayGetSize(tag->cols); i++) {
1247
      SHashObj *kvHash = (SHashObj *)taosArrayGetP(tag->cols, i);
X
Xiaoyu Wang 已提交
1248
      void    **p1 = (void **)taosHashIterate(kvHash, NULL);
1249 1250
      while (p1) {
        taosMemoryFree(*p1);
X
Xiaoyu Wang 已提交
1251
        p1 = (void **)taosHashIterate(kvHash, p1);
1252 1253 1254 1255
      }
      taosHashCleanup(kvHash);
    }
  }
X
Xiaoyu Wang 已提交
1256
  for (size_t i = 0; i < taosArrayGetSize(tag->tags); i++) {
wmmhello's avatar
wmmhello 已提交
1257
    SSmlKv *p = (SSmlKv *)taosArrayGetP(tag->tags, i);
X
Xiaoyu Wang 已提交
1258 1259 1260 1261
    if (info->protocol == TSDB_SML_JSON_PROTOCOL) {
      taosMemoryFree((void *)p->key);
      if (p->type == TSDB_DATA_TYPE_NCHAR || p->type == TSDB_DATA_TYPE_BINARY) {
        taosMemoryFree((void *)p->value);
wmmhello's avatar
wmmhello 已提交
1262 1263 1264 1265
      }
    }
    taosMemoryFree(p);
  }
X
Xiaoyu Wang 已提交
1266 1267
  if (info->protocol == TSDB_SML_JSON_PROTOCOL && tag->sTableName) {
    taosMemoryFree((void *)tag->sTableName);
wmmhello's avatar
wmmhello 已提交
1268
  }
1269 1270 1271 1272 1273
  taosArrayDestroy(tag->cols);
  taosArrayDestroy(tag->tags);
  taosMemoryFree(tag);
}

X
Xiaoyu Wang 已提交
1274
static int32_t smlKvTimeArrayCompare(const void *key1, const void *key2) {
1275 1276
  SArray *s1 = *(SArray **)key1;
  SArray *s2 = *(SArray **)key2;
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289
  SSmlKv *kv1 = (SSmlKv *)taosArrayGetP(s1, 0);
  SSmlKv *kv2 = (SSmlKv *)taosArrayGetP(s2, 0);
  ASSERT(kv1->type == TSDB_DATA_TYPE_TIMESTAMP);
  ASSERT(kv2->type == TSDB_DATA_TYPE_TIMESTAMP);
  if (kv1->i < kv2->i) {
    return -1;
  } else if (kv1->i > kv2->i) {
    return 1;
  } else {
    return 0;
  }
}

X
Xiaoyu Wang 已提交
1290
static int32_t smlKvTimeHashCompare(const void *key1, const void *key2) {
1291 1292
  SHashObj *s1 = *(SHashObj **)key1;
  SHashObj *s2 = *(SHashObj **)key2;
1293 1294
  SSmlKv *kv1 = *(SSmlKv **)taosHashGet(s1, TS, TS_LEN);
  SSmlKv *kv2 = *(SSmlKv **)taosHashGet(s2, TS, TS_LEN);
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
  ASSERT(kv1->type == TSDB_DATA_TYPE_TIMESTAMP);
  ASSERT(kv2->type == TSDB_DATA_TYPE_TIMESTAMP);
  if (kv1->i < kv2->i) {
    return -1;
  } else if (kv1->i > kv2->i) {
    return 1;
  } else {
    return 0;
  }
}

1306 1307
static int32_t smlDealCols(SSmlTableInfo* oneTable, bool dataFormat, SArray *cols){
  if(dataFormat){
1308
    void *p = taosArraySearch(oneTable->cols, &cols, smlKvTimeArrayCompare, TD_GT);
1309 1310
    if(p == NULL){
      taosArrayPush(oneTable->cols, &cols);
1311 1312
    }else{
      taosArrayInsert(oneTable->cols, TARRAY_ELEM_IDX(oneTable->cols, p), &cols);
1313
    }
1314 1315 1316 1317
    return TSDB_CODE_SUCCESS;
  }

  SHashObj *kvHash = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
X
Xiaoyu Wang 已提交
1318
  if (!kvHash) {
1319 1320 1321
    uError("SML:smlDealCols failed to allocate memory");
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }
X
Xiaoyu Wang 已提交
1322
  for (size_t i = 0; i < taosArrayGetSize(cols); i++) {
1323
    SSmlKv *kv = (SSmlKv *)taosArrayGetP(cols, i);
wmmhello's avatar
wmmhello 已提交
1324
    taosHashPut(kvHash, kv->key, kv->keyLen, &kv, POINTER_BYTES);
1325 1326
  }

1327
  void *p = taosArraySearch(oneTable->cols, &kvHash, smlKvTimeHashCompare, TD_GT);
1328 1329
  if(p == NULL){
    taosArrayPush(oneTable->cols, &kvHash);
1330 1331
  }else{
    taosArrayInsert(oneTable->cols, TARRAY_ELEM_IDX(oneTable->cols, p), &kvHash);
1332
  }
1333 1334 1335
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
1336 1337 1338
static SSmlSTableMeta *smlBuildSTableMeta() {
  SSmlSTableMeta *meta = (SSmlSTableMeta *)taosMemoryCalloc(sizeof(SSmlSTableMeta), 1);
  if (!meta) {
1339 1340 1341 1342 1343 1344 1345 1346
    return NULL;
  }
  meta->tagHash = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  if (meta->tagHash == NULL) {
    uError("SML:smlBuildSTableMeta failed to allocate memory");
    goto cleanup;
  }

wmmhello's avatar
wmmhello 已提交
1347 1348
  meta->colHash = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  if (meta->colHash == NULL) {
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
    uError("SML:smlBuildSTableMeta failed to allocate memory");
    goto cleanup;
  }

  meta->tags = taosArrayInit(32, POINTER_BYTES);
  if (meta->tags == NULL) {
    uError("SML:smlBuildSTableMeta failed to allocate memory");
    goto cleanup;
  }

  meta->cols = taosArrayInit(32, POINTER_BYTES);
  if (meta->cols == NULL) {
    uError("SML:smlBuildSTableMeta failed to allocate memory");
    goto cleanup;
  }
  return meta;

cleanup:
  taosMemoryFree(meta);
  return NULL;
}

X
Xiaoyu Wang 已提交
1371
static void smlDestroySTableMeta(SSmlSTableMeta *meta) {
1372
  taosHashCleanup(meta->tagHash);
wmmhello's avatar
wmmhello 已提交
1373
  taosHashCleanup(meta->colHash);
1374 1375 1376
  taosArrayDestroy(meta->tags);
  taosArrayDestroy(meta->cols);
  taosMemoryFree(meta->tableMeta);
wmmhello's avatar
wmmhello 已提交
1377
  taosMemoryFree(meta);
1378 1379 1380 1381 1382
}

static void smlDestroyCols(SArray *cols) {
  if (!cols) return;
  for (int i = 0; i < taosArrayGetSize(cols); ++i) {
wmmhello's avatar
wmmhello 已提交
1383
    void *kv = taosArrayGetP(cols, i);
1384 1385 1386 1387
    taosMemoryFree(kv);
  }
}

X
Xiaoyu Wang 已提交
1388 1389
static void smlDestroyInfo(SSmlHandle *info) {
  if (!info) return;
1390 1391 1392 1393
  qDestroyQuery(info->pQuery);
  smlDestroyHandle(info->exec);

  // destroy info->childTables
X
Xiaoyu Wang 已提交
1394
  void **p1 = (void **)taosHashIterate(info->childTables, NULL);
1395
  while (p1) {
X
Xiaoyu Wang 已提交
1396 1397
    smlDestroyTableInfo(info, (SSmlTableInfo *)(*p1));
    p1 = (void **)taosHashIterate(info->childTables, p1);
1398 1399 1400 1401
  }
  taosHashCleanup(info->childTables);

  // destroy info->superTables
X
Xiaoyu Wang 已提交
1402
  p1 = (void **)taosHashIterate(info->superTables, NULL);
1403
  while (p1) {
X
Xiaoyu Wang 已提交
1404 1405
    smlDestroySTableMeta((SSmlSTableMeta *)(*p1));
    p1 = (void **)taosHashIterate(info->superTables, p1);
1406 1407 1408 1409 1410 1411
  }
  taosHashCleanup(info->superTables);

  // destroy info->pVgHash
  taosHashCleanup(info->pVgHash);
  taosHashCleanup(info->dumplicateKey);
X
Xiaoyu Wang 已提交
1412
  if (!info->dataFormat) {
wmmhello's avatar
wmmhello 已提交
1413 1414
    taosArrayDestroy(info->colsContainer);
  }
wmmhello's avatar
wmmhello 已提交
1415
  destroyRequest(info->pRequest);
1416 1417 1418
  taosMemoryFreeClear(info);
}

1419
static SSmlHandle* smlBuildSmlInfo(STscObj* pTscObj, SRequestObj* request, SMLProtocolType protocol, int8_t precision){
1420 1421 1422 1423 1424
  int32_t code = TSDB_CODE_SUCCESS;
  SSmlHandle* info = (SSmlHandle*)taosMemoryCalloc(1, sizeof(SSmlHandle));
  if (NULL == info) {
    return NULL;
  }
X
Xiaoyu Wang 已提交
1425
  info->id = smlGenId();
1426

1427
  info->pQuery = (SQuery*)nodesMakeNode(QUERY_NODE_QUERY);
1428
  if (NULL == info->pQuery) {
X
Xiaoyu Wang 已提交
1429
    uError("SML:0x%" PRIx64 " create info->pQuery error", info->id);
1430 1431
    goto cleanup;
  }
X
Xiaoyu Wang 已提交
1432
  info->pQuery->execMode = QUERY_EXEC_MODE_SCHEDULE;
1433
  info->pQuery->haveResultSet = false;
X
Xiaoyu Wang 已提交
1434 1435 1436 1437
  info->pQuery->msgType = TDMT_VND_SUBMIT;
  info->pQuery->pRoot = (SNode *)nodesMakeNode(QUERY_NODE_VNODE_MODIF_STMT);
  if (NULL == info->pQuery->pRoot) {
    uError("SML:0x%" PRIx64 " create info->pQuery->pRoot error", info->id);
1438 1439
    goto cleanup;
  }
X
Xiaoyu Wang 已提交
1440
  ((SVnodeModifOpStmt *)(info->pQuery->pRoot))->payloadType = PAYLOAD_TYPE_KV;
1441

1442 1443 1444 1445 1446 1447 1448
  if (pTscObj){
    info->taos        = pTscObj;
    code = catalogGetHandle(info->taos->pAppInfo->clusterId, &info->pCatalog);
    if (code != TSDB_CODE_SUCCESS) {
      uError("SML:0x%" PRIx64 " get catalog error %d", info->id, code);
      goto cleanup;
    }
wmmhello's avatar
wmmhello 已提交
1449
  }
1450

X
Xiaoyu Wang 已提交
1451 1452 1453
  info->precision = precision;
  info->protocol = protocol;
  if (protocol == TSDB_SML_LINE_PROTOCOL) {
1454
    info->dataFormat = tsSmlDataFormat;
X
Xiaoyu Wang 已提交
1455
  } else {
1456 1457
    info->dataFormat = true;
  }
1458 1459 1460 1461 1462 1463

  if(request){
    info->pRequest = request;
    info->msgBuf.buf = info->pRequest->msgBuf;
    info->msgBuf.len = ERROR_MSG_BUF_DEFAULT_SIZE;
  }
1464

X
Xiaoyu Wang 已提交
1465
  info->exec = smlInitHandle(info->pQuery);
1466 1467
  info->childTables = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  info->superTables = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
X
Xiaoyu Wang 已提交
1468
  info->pVgHash = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_NO_LOCK);
1469 1470

  info->dumplicateKey = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
X
Xiaoyu Wang 已提交
1471
  if (!info->dataFormat) {
1472
    info->colsContainer = taosArrayInit(32, POINTER_BYTES);
X
Xiaoyu Wang 已提交
1473 1474
    if (NULL == info->colsContainer) {
      uError("SML:0x%" PRIx64 " create info failed", info->id);
1475 1476 1477
      goto cleanup;
    }
  }
X
Xiaoyu Wang 已提交
1478 1479 1480
  if (NULL == info->exec || NULL == info->childTables || NULL == info->superTables || NULL == info->pVgHash ||
      NULL == info->dumplicateKey) {
    uError("SML:0x%" PRIx64 " create info failed", info->id);
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
    goto cleanup;
  }

  return info;
cleanup:
  smlDestroyInfo(info);
  return NULL;
}

/************* TSDB_SML_JSON_PROTOCOL function start **************/
X
Xiaoyu Wang 已提交
1491
static int32_t smlJsonCreateSring(const char **output, char *input, int32_t inputLen) {
1492
  *output = (const char *)taosMemoryMalloc(inputLen);
X
Xiaoyu Wang 已提交
1493
  if (*output == NULL) {
1494 1495 1496
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }

X
Xiaoyu Wang 已提交
1497
  memcpy((void *)(*output), input, inputLen);
1498 1499 1500 1501 1502 1503
  return TSDB_CODE_SUCCESS;
}

static int32_t smlParseMetricFromJSON(SSmlHandle *info, cJSON *root, SSmlTableInfo *tinfo) {
  cJSON *metric = cJSON_GetObjectItem(root, "metric");
  if (!cJSON_IsString(metric)) {
X
Xiaoyu Wang 已提交
1504
    return TSDB_CODE_TSC_INVALID_JSON;
1505 1506 1507
  }

  tinfo->sTableNameLen = strlen(metric->valuestring);
1508
  if (IS_INVALID_TABLE_LEN(tinfo->sTableNameLen)) {
X
Xiaoyu Wang 已提交
1509
    uError("OTD:0x%" PRIx64 " Metric lenght is 0 or large than 192", info->id);
1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
    return TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
  }

  return smlJsonCreateSring(&tinfo->sTableName, metric->valuestring, tinfo->sTableNameLen);
}

static int32_t smlParseTSFromJSONObj(SSmlHandle *info, cJSON *root, int64_t *tsVal) {
  int32_t size = cJSON_GetArraySize(root);
  if (size != OTD_JSON_SUB_FIELDS_NUM) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  cJSON *value = cJSON_GetObjectItem(root, "value");
  if (!cJSON_IsNumber(value)) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  cJSON *type = cJSON_GetObjectItem(root, "type");
  if (!cJSON_IsString(type)) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  double timeDouble = value->valuedouble;
X
Xiaoyu Wang 已提交
1533
  if (smlDoubleToInt64OverFlow(timeDouble)) {
1534
    smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
1535
    return TSDB_CODE_INVALID_TIMESTAMP;
1536
  }
wmmhello's avatar
wmmhello 已提交
1537 1538 1539 1540 1541 1542 1543 1544

  if (timeDouble == 0) {
    *tsVal = taosGetTimestampNs();
    return TSDB_CODE_SUCCESS;
  }

  if (timeDouble < 0) {
    return TSDB_CODE_INVALID_TIMESTAMP;
1545 1546
  }

1547
  *tsVal = timeDouble;
1548
  size_t typeLen = strlen(type->valuestring);
wmmhello's avatar
wmmhello 已提交
1549
  if (typeLen == 1 && (type->valuestring[0] == 's' || type->valuestring[0] == 'S')) {
X
Xiaoyu Wang 已提交
1550
    // seconds
1551 1552
    *tsVal = *tsVal * NANOSECOND_PER_SEC;
    timeDouble = timeDouble * NANOSECOND_PER_SEC;
X
Xiaoyu Wang 已提交
1553
    if (smlDoubleToInt64OverFlow(timeDouble)) {
1554
      smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
1555
      return TSDB_CODE_INVALID_TIMESTAMP;
1556
    }
wmmhello's avatar
wmmhello 已提交
1557
  } else if (typeLen == 2 && (type->valuestring[1] == 's' || type->valuestring[1] == 'S')) {
1558 1559
    switch (type->valuestring[0]) {
      case 'm':
wmmhello's avatar
wmmhello 已提交
1560
      case 'M':
X
Xiaoyu Wang 已提交
1561
        // milliseconds
1562 1563
        *tsVal = *tsVal * NANOSECOND_PER_MSEC;
        timeDouble = timeDouble * NANOSECOND_PER_MSEC;
X
Xiaoyu Wang 已提交
1564
        if (smlDoubleToInt64OverFlow(timeDouble)) {
1565
          smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
1566
          return TSDB_CODE_INVALID_TIMESTAMP;
1567 1568 1569
        }
        break;
      case 'u':
wmmhello's avatar
wmmhello 已提交
1570
      case 'U':
X
Xiaoyu Wang 已提交
1571
        // microseconds
1572 1573
        *tsVal = *tsVal * NANOSECOND_PER_USEC;
        timeDouble = timeDouble * NANOSECOND_PER_USEC;
X
Xiaoyu Wang 已提交
1574
        if (smlDoubleToInt64OverFlow(timeDouble)) {
1575
          smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
1576
          return TSDB_CODE_INVALID_TIMESTAMP;
1577 1578 1579
        }
        break;
      case 'n':
wmmhello's avatar
wmmhello 已提交
1580
      case 'N':
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601
        break;
      default:
        return TSDB_CODE_TSC_INVALID_JSON;
    }
  } else {
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  return TSDB_CODE_SUCCESS;
}

static uint8_t smlGetTimestampLen(int64_t num) {
  uint8_t len = 0;
  while ((num /= 10) != 0) {
    len++;
  }
  len++;
  return len;
}

static int32_t smlParseTSFromJSON(SSmlHandle *info, cJSON *root, SArray *cols) {
X
Xiaoyu Wang 已提交
1602
  // Timestamp must be the first KV to parse
1603 1604 1605 1606
  int64_t tsVal = 0;

  cJSON *timestamp = cJSON_GetObjectItem(root, "timestamp");
  if (cJSON_IsNumber(timestamp)) {
X
Xiaoyu Wang 已提交
1607
    // timestamp value 0 indicates current system time
1608
    double timeDouble = timestamp->valuedouble;
X
Xiaoyu Wang 已提交
1609
    if (smlDoubleToInt64OverFlow(timeDouble)) {
1610
      smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
1611
      return TSDB_CODE_INVALID_TIMESTAMP;
1612
    }
wmmhello's avatar
wmmhello 已提交
1613

X
Xiaoyu Wang 已提交
1614
    if (timeDouble < 0) {
wmmhello's avatar
wmmhello 已提交
1615
      return TSDB_CODE_INVALID_TIMESTAMP;
1616
    }
1617

1618
    uint8_t tsLen = smlGetTimestampLen((int64_t)timeDouble);
1619
    tsVal = (int64_t)timeDouble;
1620
    if (tsLen == TSDB_TIME_PRECISION_SEC_DIGITS) {
1621 1622
      tsVal = tsVal * NANOSECOND_PER_SEC;
      timeDouble = timeDouble * NANOSECOND_PER_SEC;
X
Xiaoyu Wang 已提交
1623
      if (smlDoubleToInt64OverFlow(timeDouble)) {
1624
        smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
1625
        return TSDB_CODE_INVALID_TIMESTAMP;
1626 1627
      }
    } else if (tsLen == TSDB_TIME_PRECISION_MILLI_DIGITS) {
1628 1629
      tsVal = tsVal * NANOSECOND_PER_MSEC;
      timeDouble = timeDouble * NANOSECOND_PER_MSEC;
X
Xiaoyu Wang 已提交
1630
      if (smlDoubleToInt64OverFlow(timeDouble)) {
1631
        smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
1632
        return TSDB_CODE_INVALID_TIMESTAMP;
1633
      }
X
Xiaoyu Wang 已提交
1634
    } else if (timeDouble == 0) {
wmmhello's avatar
wmmhello 已提交
1635
      tsVal = taosGetTimestampNs();
X
Xiaoyu Wang 已提交
1636
    } else {
wmmhello's avatar
wmmhello 已提交
1637
      return TSDB_CODE_INVALID_TIMESTAMP;
1638 1639 1640 1641
    }
  } else if (cJSON_IsObject(timestamp)) {
    int32_t ret = smlParseTSFromJSONObj(info, timestamp, &tsVal);
    if (ret != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
1642
      uError("SML:0x%" PRIx64 " Failed to parse timestamp from JSON Obj", info->id);
1643 1644 1645 1646
      return ret;
    }
  } else {
    return TSDB_CODE_TSC_INVALID_JSON;
wmmhello's avatar
wmmhello 已提交
1647 1648
  }

wmmhello's avatar
wmmhello 已提交
1649
  // add ts to
wmmhello's avatar
wmmhello 已提交
1650
  SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
X
Xiaoyu Wang 已提交
1651
  if (!kv) {
wmmhello's avatar
wmmhello 已提交
1652 1653 1654
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  kv->key = TS;
1655 1656
  kv->keyLen = TS_LEN;
  kv->i = tsVal;
wmmhello's avatar
wmmhello 已提交
1657
  kv->type = TSDB_DATA_TYPE_TIMESTAMP;
wmmhello's avatar
wmmhello 已提交
1658
  kv->length = (int16_t)tDataTypes[kv->type].bytes;
X
Xiaoyu Wang 已提交
1659
  if (cols) taosArrayPush(cols, &kv);
wmmhello's avatar
wmmhello 已提交
1660 1661 1662
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
1663
static int32_t smlConvertJSONBool(SSmlKv *pVal, char *typeStr, cJSON *value) {
1664 1665 1666 1667 1668 1669 1670
  if (strcasecmp(typeStr, "bool") != 0) {
    uError("OTD:invalid type(%s) for JSON Bool", typeStr);
    return TSDB_CODE_TSC_INVALID_JSON_TYPE;
  }
  pVal->type = TSDB_DATA_TYPE_BOOL;
  pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
  pVal->i = value->valueint;
wmmhello's avatar
wmmhello 已提交
1671

1672 1673
  return TSDB_CODE_SUCCESS;
}
wmmhello's avatar
wmmhello 已提交
1674

X
Xiaoyu Wang 已提交
1675 1676 1677
static int32_t smlConvertJSONNumber(SSmlKv *pVal, char *typeStr, cJSON *value) {
  // tinyint
  if (strcasecmp(typeStr, "i8") == 0 || strcasecmp(typeStr, "tinyint") == 0) {
1678 1679 1680 1681 1682 1683 1684 1685 1686
    if (!IS_VALID_TINYINT(value->valuedouble)) {
      uError("OTD:JSON value(%f) cannot fit in type(tinyint)", value->valuedouble);
      return TSDB_CODE_TSC_VALUE_OUT_OF_RANGE;
    }
    pVal->type = TSDB_DATA_TYPE_TINYINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->i = value->valuedouble;
    return TSDB_CODE_SUCCESS;
  }
X
Xiaoyu Wang 已提交
1687 1688
  // smallint
  if (strcasecmp(typeStr, "i16") == 0 || strcasecmp(typeStr, "smallint") == 0) {
1689 1690 1691 1692 1693 1694 1695 1696 1697
    if (!IS_VALID_SMALLINT(value->valuedouble)) {
      uError("OTD:JSON value(%f) cannot fit in type(smallint)", value->valuedouble);
      return TSDB_CODE_TSC_VALUE_OUT_OF_RANGE;
    }
    pVal->type = TSDB_DATA_TYPE_SMALLINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->i = value->valuedouble;
    return TSDB_CODE_SUCCESS;
  }
X
Xiaoyu Wang 已提交
1698 1699
  // int
  if (strcasecmp(typeStr, "i32") == 0 || strcasecmp(typeStr, "int") == 0) {
1700 1701 1702 1703 1704 1705 1706 1707 1708
    if (!IS_VALID_INT(value->valuedouble)) {
      uError("OTD:JSON value(%f) cannot fit in type(int)", value->valuedouble);
      return TSDB_CODE_TSC_VALUE_OUT_OF_RANGE;
    }
    pVal->type = TSDB_DATA_TYPE_INT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->i = value->valuedouble;
    return TSDB_CODE_SUCCESS;
  }
X
Xiaoyu Wang 已提交
1709 1710
  // bigint
  if (strcasecmp(typeStr, "i64") == 0 || strcasecmp(typeStr, "bigint") == 0) {
1711 1712
    pVal->type = TSDB_DATA_TYPE_BIGINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
X
Xiaoyu Wang 已提交
1713
    if (value->valuedouble >= (double)INT64_MAX) {
1714
      pVal->i = INT64_MAX;
X
Xiaoyu Wang 已提交
1715
    } else if (value->valuedouble <= (double)INT64_MIN) {
1716
      pVal->i = INT64_MIN;
X
Xiaoyu Wang 已提交
1717
    } else {
1718
      pVal->i = value->valuedouble;
1719 1720 1721
    }
    return TSDB_CODE_SUCCESS;
  }
X
Xiaoyu Wang 已提交
1722 1723
  // float
  if (strcasecmp(typeStr, "f32") == 0 || strcasecmp(typeStr, "float") == 0) {
1724 1725 1726
    if (!IS_VALID_FLOAT(value->valuedouble)) {
      uError("OTD:JSON value(%f) cannot fit in type(float)", value->valuedouble);
      return TSDB_CODE_TSC_VALUE_OUT_OF_RANGE;
wmmhello's avatar
wmmhello 已提交
1727
    }
1728 1729 1730 1731 1732
    pVal->type = TSDB_DATA_TYPE_FLOAT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->f = value->valuedouble;
    return TSDB_CODE_SUCCESS;
  }
X
Xiaoyu Wang 已提交
1733 1734
  // double
  if (strcasecmp(typeStr, "f64") == 0 || strcasecmp(typeStr, "double") == 0) {
1735 1736 1737 1738
    pVal->type = TSDB_DATA_TYPE_DOUBLE;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->d = value->valuedouble;
    return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1739 1740
  }

X
Xiaoyu Wang 已提交
1741
  // if reach here means type is unsupported
1742 1743 1744
  uError("OTD:invalid type(%s) for JSON Number", typeStr);
  return TSDB_CODE_TSC_INVALID_JSON_TYPE;
}
1745

X
Xiaoyu Wang 已提交
1746
static int32_t smlConvertJSONString(SSmlKv *pVal, char *typeStr, cJSON *value) {
1747 1748 1749 1750 1751 1752 1753 1754 1755
  if (strcasecmp(typeStr, "binary") == 0) {
    pVal->type = TSDB_DATA_TYPE_BINARY;
  } else if (strcasecmp(typeStr, "nchar") == 0) {
    pVal->type = TSDB_DATA_TYPE_NCHAR;
  } else {
    uError("OTD:invalid type(%s) for JSON String", typeStr);
    return TSDB_CODE_TSC_INVALID_JSON_TYPE;
  }
  pVal->length = (int16_t)strlen(value->valuestring);
wmmhello's avatar
wmmhello 已提交
1756 1757 1758 1759 1760 1761 1762 1763

  if (pVal->type == TSDB_DATA_TYPE_BINARY && pVal->length > TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE){
    return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
  }
  if (pVal->type == TSDB_DATA_TYPE_NCHAR  && pVal->length > (TSDB_MAX_NCHAR_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE){
    return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
  }

wmmhello's avatar
wmmhello 已提交
1764
  return smlJsonCreateSring(&pVal->value, value->valuestring, pVal->length);
1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790
}

static int32_t smlParseValueFromJSONObj(cJSON *root, SSmlKv *kv) {
  int32_t ret = TSDB_CODE_SUCCESS;
  int32_t size = cJSON_GetArraySize(root);

  if (size != OTD_JSON_SUB_FIELDS_NUM) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  cJSON *value = cJSON_GetObjectItem(root, "value");
  if (value == NULL) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  cJSON *type = cJSON_GetObjectItem(root, "type");
  if (!cJSON_IsString(type)) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  switch (value->type) {
    case cJSON_True:
    case cJSON_False: {
      ret = smlConvertJSONBool(kv, type->valuestring, value);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
wmmhello's avatar
wmmhello 已提交
1791
      }
1792
      break;
wmmhello's avatar
wmmhello 已提交
1793
    }
1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809
    case cJSON_Number: {
      ret = smlConvertJSONNumber(kv, type->valuestring, value);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }
      break;
    }
    case cJSON_String: {
      ret = smlConvertJSONString(kv, type->valuestring, value);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }
      break;
    }
    default:
      return TSDB_CODE_TSC_INVALID_JSON_TYPE;
wmmhello's avatar
wmmhello 已提交
1810
  }
1811 1812

  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1813 1814
}

1815 1816 1817 1818 1819 1820 1821 1822
static int32_t smlParseValueFromJSON(cJSON *root, SSmlKv *kv) {
  switch (root->type) {
    case cJSON_True:
    case cJSON_False: {
      kv->type = TSDB_DATA_TYPE_BOOL;
      kv->length = (int16_t)tDataTypes[kv->type].bytes;
      kv->i = root->valueint;
      break;
wmmhello's avatar
wmmhello 已提交
1823
    }
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
    case cJSON_Number: {
      kv->type = TSDB_DATA_TYPE_DOUBLE;
      kv->length = (int16_t)tDataTypes[kv->type].bytes;
      kv->d = root->valuedouble;
      break;
    }
    case cJSON_String: {
      /* set default JSON type to binary/nchar according to
       * user configured parameter tsDefaultJSONStrType
       */
wmmhello's avatar
wmmhello 已提交
1834

X
Xiaoyu Wang 已提交
1835
      char *tsDefaultJSONStrType = "nchar";  // todo
1836 1837
      smlConvertJSONString(kv, tsDefaultJSONStrType, root);
      break;
wmmhello's avatar
wmmhello 已提交
1838
    }
1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
    case cJSON_Object: {
      int32_t ret = smlParseValueFromJSONObj(root, kv);
      if (ret != TSDB_CODE_SUCCESS) {
        uError("OTD:Failed to parse value from JSON Obj");
        return ret;
      }
      break;
    }
    default:
      return TSDB_CODE_TSC_INVALID_JSON;
wmmhello's avatar
wmmhello 已提交
1849
  }
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860

  return TSDB_CODE_SUCCESS;
}

static int32_t smlParseColsFromJSON(cJSON *root, SArray *cols) {
  cJSON *metricVal = cJSON_GetObjectItem(root, "value");
  if (metricVal == NULL) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
X
Xiaoyu Wang 已提交
1861
  if (!kv) {
1862 1863
    return TSDB_CODE_OUT_OF_MEMORY;
  }
X
Xiaoyu Wang 已提交
1864
  if (cols) taosArrayPush(cols, &kv);
1865 1866 1867 1868 1869 1870 1871 1872

  kv->key = VALUE;
  kv->keyLen = VALUE_LEN;
  int32_t ret = smlParseValueFromJSON(metricVal, kv);
  if (ret != TSDB_CODE_SUCCESS) {
    return ret;
  }
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1873 1874
}

X
Xiaoyu Wang 已提交
1875 1876
static int32_t smlParseTagsFromJSON(cJSON *root, SArray *pKVs, char *childTableName, SHashObj *dumplicateKey,
                                    SSmlMsgBuf *msg) {
1877 1878 1879 1880 1881 1882
  int32_t ret = TSDB_CODE_SUCCESS;

  cJSON *tags = cJSON_GetObjectItem(root, "tags");
  if (tags == NULL || tags->type != cJSON_Object) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }
wmmhello's avatar
wmmhello 已提交
1883

X
Xiaoyu Wang 已提交
1884
  size_t  childTableNameLen = strlen(tsSmlChildTableName);
1885 1886 1887 1888 1889
  int32_t tagNum = cJSON_GetArraySize(tags);
  for (int32_t i = 0; i < tagNum; ++i) {
    cJSON *tag = cJSON_GetArrayItem(tags, i);
    if (tag == NULL) {
      return TSDB_CODE_TSC_INVALID_JSON;
wmmhello's avatar
wmmhello 已提交
1890
    }
1891 1892 1893 1894 1895
    size_t keyLen = strlen(tag->string);
    if (IS_INVALID_COL_LEN(keyLen)) {
      uError("OTD:Tag key length is 0 or too large than 64");
      return TSDB_CODE_TSC_INVALID_COLUMN_LENGTH;
    }
X
Xiaoyu Wang 已提交
1896
    // check duplicate keys
1897
    if (smlCheckDuplicateKey(tag->string, keyLen, dumplicateKey)) {
wmmhello's avatar
wmmhello 已提交
1898
      return TSDB_CODE_TSC_DUP_NAMES;
wmmhello's avatar
wmmhello 已提交
1899 1900
    }

X
Xiaoyu Wang 已提交
1901 1902
    // handle child table name
    if (childTableNameLen != 0 && strcmp(tag->string, tsSmlChildTableName) == 0) {
1903 1904 1905 1906 1907 1908 1909 1910 1911
      if (!cJSON_IsString(tag)) {
        uError("OTD:ID must be JSON string");
        return TSDB_CODE_TSC_INVALID_JSON;
      }
      memset(childTableName, 0, TSDB_TABLE_NAME_LEN);
      strncpy(childTableName, tag->valuestring, TSDB_TABLE_NAME_LEN);
      continue;
    }

1912 1913
    // add kv to SSmlKv
    SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
X
Xiaoyu Wang 已提交
1914 1915
    if (!kv) return TSDB_CODE_OUT_OF_MEMORY;
    if (pKVs) taosArrayPush(pKVs, &kv);
1916

X
Xiaoyu Wang 已提交
1917
    // key
1918
    kv->keyLen = keyLen;
1919 1920 1921 1922
    ret = smlJsonCreateSring(&kv->key, tag->string, kv->keyLen);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
X
Xiaoyu Wang 已提交
1923
    // value
1924 1925 1926 1927
    ret = smlParseValueFromJSON(tag, kv);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
wmmhello's avatar
wmmhello 已提交
1928 1929
  }

1930
  return ret;
wmmhello's avatar
wmmhello 已提交
1931 1932
}

1933 1934
static int32_t smlParseJSONString(SSmlHandle *info, cJSON *root, SSmlTableInfo *tinfo, SArray *cols) {
  int32_t ret = TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1935

1936
  if (!cJSON_IsObject(root)) {
X
Xiaoyu Wang 已提交
1937
    uError("OTD:0x%" PRIx64 " data point needs to be JSON object", info->id);
1938
    return TSDB_CODE_TSC_INVALID_JSON;
wmmhello's avatar
wmmhello 已提交
1939
  }
1940

1941
  int32_t size = cJSON_GetArraySize(root);
X
Xiaoyu Wang 已提交
1942
  // outmost json fields has to be exactly 4
1943
  if (size != OTD_JSON_FIELDS_NUM) {
X
Xiaoyu Wang 已提交
1944
    uError("OTD:0x%" PRIx64 " Invalid number of JSON fields in data point %d", info->id, size);
1945
    return TSDB_CODE_TSC_INVALID_JSON;
wmmhello's avatar
wmmhello 已提交
1946
  }
1947

X
Xiaoyu Wang 已提交
1948
  // Parse metric
1949 1950
  ret = smlParseMetricFromJSON(info, root, tinfo);
  if (ret != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
1951
    uError("OTD:0x%" PRIx64 " Unable to parse metric from JSON payload", info->id);
1952
    return ret;
wmmhello's avatar
wmmhello 已提交
1953
  }
X
Xiaoyu Wang 已提交
1954
  uDebug("OTD:0x%" PRIx64 " Parse metric from JSON payload finished", info->id);
wmmhello's avatar
wmmhello 已提交
1955

X
Xiaoyu Wang 已提交
1956
  // Parse timestamp
1957 1958
  ret = smlParseTSFromJSON(info, root, cols);
  if (ret) {
X
Xiaoyu Wang 已提交
1959
    uError("OTD:0x%" PRIx64 " Unable to parse timestamp from JSON payload", info->id);
1960
    return ret;
wmmhello's avatar
wmmhello 已提交
1961
  }
X
Xiaoyu Wang 已提交
1962
  uDebug("OTD:0x%" PRIx64 " Parse timestamp from JSON payload finished", info->id);
1963

X
Xiaoyu Wang 已提交
1964
  // Parse metric value
1965 1966
  ret = smlParseColsFromJSON(root, cols);
  if (ret) {
X
Xiaoyu Wang 已提交
1967
    uError("OTD:0x%" PRIx64 " Unable to parse metric value from JSON payload", info->id);
1968
    return ret;
1969
  }
X
Xiaoyu Wang 已提交
1970
  uDebug("OTD:0x%" PRIx64 " Parse metric value from JSON payload finished", info->id);
1971

X
Xiaoyu Wang 已提交
1972
  // Parse tags
1973
  ret = smlParseTagsFromJSON(root, tinfo->tags, tinfo->childTableName, info->dumplicateKey, &info->msgBuf);
1974
  if (ret) {
X
Xiaoyu Wang 已提交
1975
    uError("OTD:0x%" PRIx64 " Unable to parse tags from JSON payload", info->id);
1976
    return ret;
1977
  }
X
Xiaoyu Wang 已提交
1978
  uDebug("OTD:0x%" PRIx64 " Parse tags from JSON payload finished", info->id);
wmmhello's avatar
wmmhello 已提交
1979

1980
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1981
}
1982
/************* TSDB_SML_JSON_PROTOCOL function end **************/
wmmhello's avatar
wmmhello 已提交
1983

X
Xiaoyu Wang 已提交
1984
static int32_t smlParseInfluxLine(SSmlHandle *info, const char *sql) {
wmmhello's avatar
wmmhello 已提交
1985
  SSmlLineInfo elements = {0};
1986
  uDebug("SML:0x%" PRIx64 " smlParseInfluxLine sql:%s, hello", info->id, sql);
1987

X
Xiaoyu Wang 已提交
1988 1989 1990
  int          ret = smlParseInfluxString(sql, &elements, &info->msgBuf);
  if (ret != TSDB_CODE_SUCCESS) {
    uError("SML:0x%" PRIx64 " smlParseInfluxLine failed", info->id);
wmmhello's avatar
wmmhello 已提交
1991 1992 1993
    return ret;
  }

1994
  SArray *cols = NULL;
X
Xiaoyu Wang 已提交
1995
  if (info->dataFormat) {  // if dataFormat, cols need new memory to save data
1996 1997
    cols = taosArrayInit(16, POINTER_BYTES);
    if (cols == NULL) {
X
Xiaoyu Wang 已提交
1998
      uError("SML:0x%" PRIx64 " smlParseInfluxLine failed to allocate memory", info->id);
1999 2000
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
    }
X
Xiaoyu Wang 已提交
2001
  } else {  // if dataFormat is false, cols do not need to save data, there is another new memory to save data
2002
    cols = info->colsContainer;
wmmhello's avatar
wmmhello 已提交
2003
  }
wmmhello's avatar
wmmhello 已提交
2004

wmmhello's avatar
wmmhello 已提交
2005
  ret = smlParseTS(info, elements.timestamp, elements.timestampLen, cols);
X
Xiaoyu Wang 已提交
2006 2007 2008
  if (ret != TSDB_CODE_SUCCESS) {
    uError("SML:0x%" PRIx64 " smlParseTS failed", info->id);
    if (info->dataFormat) taosArrayDestroy(cols);
wmmhello's avatar
wmmhello 已提交
2009 2010
    return ret;
  }
2011
  ret = smlParseCols(elements.cols, elements.colsLen, cols, NULL, false, info->dumplicateKey, &info->msgBuf);
X
Xiaoyu Wang 已提交
2012 2013
  if (ret != TSDB_CODE_SUCCESS) {
    uError("SML:0x%" PRIx64 " smlParseCols parse cloums fields failed", info->id);
2014
    smlDestroyCols(cols);
X
Xiaoyu Wang 已提交
2015
    if (info->dataFormat) taosArrayDestroy(cols);
wmmhello's avatar
wmmhello 已提交
2016 2017
    return ret;
  }
X
Xiaoyu Wang 已提交
2018
  if (taosArrayGetSize(cols) > TSDB_MAX_COLUMNS) {
wmmhello's avatar
wmmhello 已提交
2019
    smlBuildInvalidDataMsg(&info->msgBuf, "too many columns than 4096", NULL);
wmmhello's avatar
wmmhello 已提交
2020
    return TSDB_CODE_PAR_TOO_MANY_COLUMNS;
wmmhello's avatar
wmmhello 已提交
2021
  }
wmmhello's avatar
wmmhello 已提交
2022

X
Xiaoyu Wang 已提交
2023 2024 2025 2026 2027
  bool            hasTable = true;
  SSmlTableInfo  *tinfo = NULL;
  SSmlTableInfo **oneTable =
      (SSmlTableInfo **)taosHashGet(info->childTables, elements.measure, elements.measureTagsLen);
  if (!oneTable) {
2028
    tinfo = smlBuildTableInfo();
X
Xiaoyu Wang 已提交
2029
    if (!tinfo) {
wmmhello's avatar
wmmhello 已提交
2030 2031
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
    }
2032
    taosHashPut(info->childTables, elements.measure, elements.measureTagsLen, &tinfo, POINTER_BYTES);
2033
    oneTable = &tinfo;
2034 2035 2036 2037
    hasTable = false;
  }

  ret = smlDealCols(*oneTable, info->dataFormat, cols);
X
Xiaoyu Wang 已提交
2038
  if (ret != TSDB_CODE_SUCCESS) {
2039 2040
    return ret;
  }
wmmhello's avatar
wmmhello 已提交
2041

X
Xiaoyu Wang 已提交
2042 2043 2044 2045 2046
  if (!hasTable) {
    ret = smlParseCols(elements.tags, elements.tagsLen, (*oneTable)->tags, (*oneTable)->childTableName, true,
                       info->dumplicateKey, &info->msgBuf);
    if (ret != TSDB_CODE_SUCCESS) {
      uError("SML:0x%" PRIx64 " smlParseCols parse tag fields failed", info->id);
wmmhello's avatar
wmmhello 已提交
2047 2048 2049
      return ret;
    }

X
Xiaoyu Wang 已提交
2050
    if (taosArrayGetSize((*oneTable)->tags) > TSDB_MAX_TAGS) {
wmmhello's avatar
wmmhello 已提交
2051
      smlBuildInvalidDataMsg(&info->msgBuf, "too many tags than 128", NULL);
wmmhello's avatar
wmmhello 已提交
2052
      return TSDB_CODE_PAR_INVALID_TAGS_NUM;
wmmhello's avatar
wmmhello 已提交
2053 2054
    }

2055 2056
    (*oneTable)->sTableName = elements.measure;
    (*oneTable)->sTableNameLen = elements.measureLen;
X
Xiaoyu Wang 已提交
2057 2058 2059
    if (strlen((*oneTable)->childTableName) == 0) {
      RandTableName rName = {(*oneTable)->tags, (*oneTable)->sTableName, (uint8_t)(*oneTable)->sTableNameLen,
                             (*oneTable)->childTableName, 0};
2060 2061 2062

      buildChildTableName(&rName);
      (*oneTable)->uid = rName.uid;
X
Xiaoyu Wang 已提交
2063 2064
    } else {
      (*oneTable)->uid = *(uint64_t *)((*oneTable)->childTableName);
2065
    }
2066
  }
wmmhello's avatar
wmmhello 已提交
2067

X
Xiaoyu Wang 已提交
2068 2069
  SSmlSTableMeta **tableMeta = (SSmlSTableMeta **)taosHashGet(info->superTables, elements.measure, elements.measureLen);
  if (tableMeta) {  // update meta
wmmhello's avatar
wmmhello 已提交
2070
    ret = smlUpdateMeta((*tableMeta)->colHash, (*tableMeta)->cols, cols, &info->msgBuf);
wmmhello's avatar
wmmhello 已提交
2071
    if (!hasTable && ret == TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
2072 2073
      ret = smlUpdateMeta((*tableMeta)->tagHash, (*tableMeta)->tags, (*oneTable)->tags, &info->msgBuf);
    }
wmmhello's avatar
wmmhello 已提交
2074
    if (ret != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
2075
      uError("SML:0x%" PRIx64 " smlUpdateMeta failed", info->id);
wmmhello's avatar
wmmhello 已提交
2076
      return ret;
wmmhello's avatar
wmmhello 已提交
2077
    }
X
Xiaoyu Wang 已提交
2078
  } else {
2079
    SSmlSTableMeta *meta = smlBuildSTableMeta();
wmmhello's avatar
wmmhello 已提交
2080 2081
    smlInsertMeta(meta->tagHash, meta->tags, (*oneTable)->tags);
    smlInsertMeta(meta->colHash, meta->cols, cols);
2082
    taosHashPut(info->superTables, elements.measure, elements.measureLen, &meta, POINTER_BYTES);
wmmhello's avatar
wmmhello 已提交
2083
  }
2084

X
Xiaoyu Wang 已提交
2085
  if (!info->dataFormat) {
2086 2087 2088
    taosArrayClear(info->colsContainer);
  }
  taosHashClear(info->dumplicateKey);
wmmhello's avatar
wmmhello 已提交
2089 2090 2091
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
2092 2093
static int32_t smlParseTelnetLine(SSmlHandle *info, void *data) {
  int            ret = TSDB_CODE_SUCCESS;
2094
  SSmlTableInfo *tinfo = smlBuildTableInfo();
X
Xiaoyu Wang 已提交
2095
  if (!tinfo) {
2096
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
2097 2098
  }

2099 2100
  SArray *cols = taosArrayInit(16, POINTER_BYTES);
  if (cols == NULL) {
X
Xiaoyu Wang 已提交
2101
    uError("SML:0x%" PRIx64 " smlParseTelnetLine failed to allocate memory", info->id);
2102
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
2103 2104
  }

X
Xiaoyu Wang 已提交
2105 2106 2107
  if (info->protocol == TSDB_SML_TELNET_PROTOCOL) {
    ret = smlParseTelnetString(info, (const char *)data, tinfo, cols);
  } else if (info->protocol == TSDB_SML_JSON_PROTOCOL) {
2108
    ret = smlParseJSONString(info, (cJSON *)data, tinfo, cols);
X
Xiaoyu Wang 已提交
2109
  } else {
2110 2111
    ASSERT(0);
  }
X
Xiaoyu Wang 已提交
2112 2113
  if (ret != TSDB_CODE_SUCCESS) {
    uError("SML:0x%" PRIx64 " smlParseTelnetLine failed", info->id);
wmmhello's avatar
wmmhello 已提交
2114
    smlDestroyTableInfo(info, tinfo);
wmmhello's avatar
wmmhello 已提交
2115
    smlDestroyCols(cols);
2116 2117
    taosArrayDestroy(cols);
    return ret;
wmmhello's avatar
wmmhello 已提交
2118
  }
wmmhello's avatar
wmmhello 已提交
2119

X
Xiaoyu Wang 已提交
2120
  if (taosArrayGetSize(tinfo->tags) <= 0 || taosArrayGetSize(tinfo->tags) > TSDB_MAX_TAGS) {
2121
    smlBuildInvalidDataMsg(&info->msgBuf, "invalidate tags length:[1,128]", NULL);
wmmhello's avatar
wmmhello 已提交
2122 2123 2124
    smlDestroyTableInfo(info, tinfo);
    smlDestroyCols(cols);
    taosArrayDestroy(cols);
wmmhello's avatar
wmmhello 已提交
2125
    return TSDB_CODE_PAR_INVALID_TAGS_NUM;
wmmhello's avatar
wmmhello 已提交
2126
  }
2127 2128
  taosHashClear(info->dumplicateKey);

X
Xiaoyu Wang 已提交
2129 2130
  if (strlen(tinfo->childTableName) == 0) {
    RandTableName rName = {tinfo->tags, tinfo->sTableName, (uint8_t)tinfo->sTableNameLen, tinfo->childTableName, 0};
2131 2132
    buildChildTableName(&rName);
    tinfo->uid = rName.uid;
X
Xiaoyu Wang 已提交
2133 2134
  } else {
    tinfo->uid = *(uint64_t *)(tinfo->childTableName);  // generate uid by name simple
2135 2136
  }

X
Xiaoyu Wang 已提交
2137 2138 2139 2140
  bool            hasTable = true;
  SSmlTableInfo **oneTable =
      (SSmlTableInfo **)taosHashGet(info->childTables, tinfo->childTableName, strlen(tinfo->childTableName));
  if (!oneTable) {
2141
    taosHashPut(info->childTables, tinfo->childTableName, strlen(tinfo->childTableName), &tinfo, POINTER_BYTES);
2142
    oneTable = &tinfo;
2143
    hasTable = false;
X
Xiaoyu Wang 已提交
2144
  } else {
wmmhello's avatar
wmmhello 已提交
2145
    smlDestroyTableInfo(info, tinfo);
wmmhello's avatar
wmmhello 已提交
2146
  }
wmmhello's avatar
wmmhello 已提交
2147

2148
  taosArrayPush((*oneTable)->cols, &cols);
X
Xiaoyu Wang 已提交
2149 2150 2151
  SSmlSTableMeta **tableMeta =
      (SSmlSTableMeta **)taosHashGet(info->superTables, (*oneTable)->sTableName, (*oneTable)->sTableNameLen);
  if (tableMeta) {  // update meta
wmmhello's avatar
wmmhello 已提交
2152
    ret = smlUpdateMeta((*tableMeta)->colHash, (*tableMeta)->cols, cols, &info->msgBuf);
wmmhello's avatar
wmmhello 已提交
2153
    if (!hasTable && ret == TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
2154 2155
      ret = smlUpdateMeta((*tableMeta)->tagHash, (*tableMeta)->tags, (*oneTable)->tags, &info->msgBuf);
    }
wmmhello's avatar
wmmhello 已提交
2156
    if (ret != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
2157
      uError("SML:0x%" PRIx64 " smlUpdateMeta failed", info->id);
wmmhello's avatar
wmmhello 已提交
2158
      return ret;
2159
    }
X
Xiaoyu Wang 已提交
2160
  } else {
2161
    SSmlSTableMeta *meta = smlBuildSTableMeta();
wmmhello's avatar
wmmhello 已提交
2162 2163
    smlInsertMeta(meta->tagHash, meta->tags, (*oneTable)->tags);
    smlInsertMeta(meta->colHash, meta->cols, cols);
2164
    taosHashPut(info->superTables, (*oneTable)->sTableName, (*oneTable)->sTableNameLen, &meta, POINTER_BYTES);
wmmhello's avatar
wmmhello 已提交
2165 2166
  }

2167 2168
  return TSDB_CODE_SUCCESS;
}
wmmhello's avatar
wmmhello 已提交
2169

X
Xiaoyu Wang 已提交
2170
static int32_t smlParseJSON(SSmlHandle *info, char *payload) {
2171 2172
  int32_t payloadNum = 0;
  int32_t ret = TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
2173

2174
  if (payload == NULL) {
X
Xiaoyu Wang 已提交
2175
    uError("SML:0x%" PRIx64 " empty JSON Payload", info->id);
2176
    return TSDB_CODE_TSC_INVALID_JSON;
2177
  }
2178 2179 2180

  cJSON *root = cJSON_Parse(payload);
  if (root == NULL) {
X
Xiaoyu Wang 已提交
2181
    uError("SML:0x%" PRIx64 " parse json failed:%s", info->id, payload);
2182 2183
    return TSDB_CODE_TSC_INVALID_JSON;
  }
X
Xiaoyu Wang 已提交
2184
  // multiple data points must be sent in JSON array
2185 2186 2187 2188 2189
  if (cJSON_IsObject(root)) {
    payloadNum = 1;
  } else if (cJSON_IsArray(root)) {
    payloadNum = cJSON_GetArraySize(root);
  } else {
X
Xiaoyu Wang 已提交
2190
    uError("SML:0x%" PRIx64 " Invalid JSON Payload", info->id);
2191 2192
    ret = TSDB_CODE_TSC_INVALID_JSON;
    goto end;
wmmhello's avatar
wmmhello 已提交
2193
  }
wmmhello's avatar
wmmhello 已提交
2194

2195 2196 2197
  for (int32_t i = 0; i < payloadNum; ++i) {
    cJSON *dataPoint = (payloadNum == 1 && cJSON_IsObject(root)) ? root : cJSON_GetArrayItem(root, i);
    ret = smlParseTelnetLine(info, dataPoint);
X
Xiaoyu Wang 已提交
2198 2199
    if (ret != TSDB_CODE_SUCCESS) {
      uError("SML:0x%" PRIx64 " Invalid JSON Payload", info->id);
2200 2201 2202 2203 2204 2205 2206
      goto end;
    }
  }

end:
  cJSON_Delete(root);
  return ret;
wmmhello's avatar
wmmhello 已提交
2207
}
2208

X
Xiaoyu Wang 已提交
2209
static int32_t smlInsertData(SSmlHandle *info) {
wmmhello's avatar
wmmhello 已提交
2210 2211
  int32_t code = TSDB_CODE_SUCCESS;

X
Xiaoyu Wang 已提交
2212
  SSmlTableInfo **oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, NULL);
wmmhello's avatar
wmmhello 已提交
2213
  while (oneTable) {
X
Xiaoyu Wang 已提交
2214
    SSmlTableInfo *tableData = *oneTable;
wmmhello's avatar
wmmhello 已提交
2215 2216 2217 2218

    SName pName = {TSDB_TABLE_NAME_T, info->taos->acctId, {0}, {0}};
    strcpy(pName.dbname, info->pRequest->pDb);
    memcpy(pName.tname, tableData->childTableName, strlen(tableData->childTableName));
D
dapan1121 已提交
2219 2220 2221 2222 2223 2224

    SRequestConnInfo conn = {0};
    conn.pTrans = info->taos->pAppInfo->pTransporter;
    conn.requestId = info->pRequest->requestId;
    conn.requestObjRefId = info->pRequest->self;
    conn.mgmtEps = getEpSet_s(&info->taos->pAppInfo->mgmtEp);
X
Xiaoyu Wang 已提交
2225

wmmhello's avatar
wmmhello 已提交
2226
    SVgroupInfo vg;
D
dapan1121 已提交
2227
    code = catalogGetTableHashVgroup(info->pCatalog, &conn, &pName, &vg);
2228
    if (code != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
2229
      uError("SML:0x%" PRIx64 " catalogGetTableHashVgroup failed. table name: %s", info->id, tableData->childTableName);
wmmhello's avatar
wmmhello 已提交
2230 2231
      return code;
    }
X
Xiaoyu Wang 已提交
2232
    taosHashPut(info->pVgHash, (const char *)&vg.vgId, sizeof(vg.vgId), (char *)&vg, sizeof(vg));
wmmhello's avatar
wmmhello 已提交
2233

X
Xiaoyu Wang 已提交
2234 2235 2236
    SSmlSTableMeta **pMeta =
        (SSmlSTableMeta **)taosHashGet(info->superTables, tableData->sTableName, tableData->sTableNameLen);
    ASSERT(NULL != pMeta && NULL != *pMeta);
wmmhello's avatar
wmmhello 已提交
2237

2238
    // use tablemeta of stable to save vgid and uid of child table
wmmhello's avatar
wmmhello 已提交
2239
    (*pMeta)->tableMeta->vgId = vg.vgId;
X
Xiaoyu Wang 已提交
2240
    (*pMeta)->tableMeta->uid = tableData->uid;  // one table merge data block together according uid
wmmhello's avatar
wmmhello 已提交
2241

2242
    code = smlBindData(info->exec, tableData->tags, (*pMeta)->cols, tableData->cols, info->dataFormat,
wmmhello's avatar
wmmhello 已提交
2243
                       (*pMeta)->tableMeta, tableData->childTableName, tableData->sTableName, tableData->sTableNameLen, info->msgBuf.buf, info->msgBuf.len);
X
Xiaoyu Wang 已提交
2244 2245
    if (code != TSDB_CODE_SUCCESS) {
      uError("SML:0x%" PRIx64 " smlBindData failed", info->id);
wmmhello's avatar
wmmhello 已提交
2246 2247
      return code;
    }
X
Xiaoyu Wang 已提交
2248
    oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, oneTable);
wmmhello's avatar
wmmhello 已提交
2249
  }
wmmhello's avatar
wmmhello 已提交
2250

2251 2252
  code = smlBuildOutput(info->exec, info->pVgHash);
  if (code != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
2253
    uError("SML:0x%" PRIx64 " smlBuildOutput failed", info->id);
2254 2255
    return code;
  }
2256 2257
  info->cost.insertRpcTime = taosGetTimestampUs();

X
Xiaoyu Wang 已提交
2258 2259 2260
  // launchQueryImpl(info->pRequest, info->pQuery, false, NULL);
  //  info->affectedRows = taos_affected_rows(info->pRequest);
  //  return info->pRequest->code;
wmmhello's avatar
wmmhello 已提交
2261

D
dapan1121 已提交
2262
  launchAsyncQuery(info->pRequest, info->pQuery, NULL);
wmmhello's avatar
wmmhello 已提交
2263
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
2264 2265
}

X
Xiaoyu Wang 已提交
2266 2267 2268 2269 2270 2271 2272 2273 2274
static void smlPrintStatisticInfo(SSmlHandle *info) {
  uError("SML:0x%" PRIx64
         " smlInsertLines result, code:%d,lineNum:%d,stable num:%d,ctable num:%d,create stable num:%d \
        parse cost:%" PRId64 ",schema cost:%" PRId64 ",bind cost:%" PRId64 ",rpc cost:%" PRId64 ",total cost:%" PRId64
         "",
         info->id, info->cost.code, info->cost.lineNum, info->cost.numOfSTables, info->cost.numOfCTables,
         info->cost.numOfCreateSTables, info->cost.schemaTime - info->cost.parseTime,
         info->cost.insertBindTime - info->cost.schemaTime, info->cost.insertRpcTime - info->cost.insertBindTime,
         info->cost.endTime - info->cost.insertRpcTime, info->cost.endTime - info->cost.parseTime);
2275 2276
}

X
Xiaoyu Wang 已提交
2277
static int32_t smlParseLine(SSmlHandle *info, char *lines[], int numLines) {
wmmhello's avatar
wmmhello 已提交
2278
  int32_t code = TSDB_CODE_SUCCESS;
2279 2280 2281 2282 2283 2284
  if (info->protocol == TSDB_SML_JSON_PROTOCOL) {
    code = smlParseJSON(info, *lines);
    if (code != TSDB_CODE_SUCCESS) {
      uError("SML:0x%" PRIx64 " smlParseJSON failed:%s", info->id, *lines);
      return code;
    }
wmmhello's avatar
wmmhello 已提交
2285
    return code;
wmmhello's avatar
wmmhello 已提交
2286
  }
wmmhello's avatar
wmmhello 已提交
2287

wmmhello's avatar
wmmhello 已提交
2288
  for (int32_t i = 0; i < numLines; ++i) {
X
Xiaoyu Wang 已提交
2289
    if (info->protocol == TSDB_SML_LINE_PROTOCOL) {
2290
      code = smlParseInfluxLine(info, lines[i]);
X
Xiaoyu Wang 已提交
2291
    } else if (info->protocol == TSDB_SML_TELNET_PROTOCOL) {
2292
      code = smlParseTelnetLine(info, lines[i]);
X
Xiaoyu Wang 已提交
2293
    } else {
2294 2295
      ASSERT(0);
    }
wmmhello's avatar
wmmhello 已提交
2296
    if (code != TSDB_CODE_SUCCESS) {
2297 2298
      uError("SML:0x%" PRIx64 " smlParseLine failed. line %d : %s", info->id, i, lines[i]);
      return code;
wmmhello's avatar
wmmhello 已提交
2299 2300
    }
  }
2301 2302 2303
  return code;
}

X
Xiaoyu Wang 已提交
2304
static int smlProcess(SSmlHandle *info, char *lines[], int numLines) {
2305
  int32_t code = TSDB_CODE_SUCCESS;
2306 2307
  int32_t retryNum = 0;

2308 2309 2310 2311
  info->cost.parseTime = taosGetTimestampUs();

  code = smlParseLine(info, lines, numLines);
  if (code != 0) {
X
Xiaoyu Wang 已提交
2312
    uError("SML:0x%" PRIx64 " smlParseLine error : %s", info->id, tstrerror(code));
wmmhello's avatar
wmmhello 已提交
2313
    return code;
2314
  }
wmmhello's avatar
wmmhello 已提交
2315

2316 2317 2318 2319 2320
  info->cost.lineNum = numLines;
  info->cost.numOfSTables = taosHashGetSize(info->superTables);
  info->cost.numOfCTables = taosHashGetSize(info->childTables);

  info->cost.schemaTime = taosGetTimestampUs();
2321

X
Xiaoyu Wang 已提交
2322
  do {
2323 2324
    code = smlModifyDBSchemas(info);
    if (code == 0) break;
wmmhello's avatar
wmmhello 已提交
2325
  } while (retryNum++ < taosHashGetSize(info->superTables) * MAX_RETRY_TIMES);
2326

wmmhello's avatar
wmmhello 已提交
2327
  if (code != 0) {
X
Xiaoyu Wang 已提交
2328
    uError("SML:0x%" PRIx64 " smlModifyDBSchemas error : %s", info->id, tstrerror(code));
wmmhello's avatar
wmmhello 已提交
2329
    return code;
wmmhello's avatar
wmmhello 已提交
2330
  }
wmmhello's avatar
wmmhello 已提交
2331

2332
  info->cost.insertBindTime = taosGetTimestampUs();
wmmhello's avatar
wmmhello 已提交
2333 2334
  code = smlInsertData(info);
  if (code != 0) {
X
Xiaoyu Wang 已提交
2335
    uError("SML:0x%" PRIx64 " smlInsertData error : %s", info->id, tstrerror(code));
wmmhello's avatar
wmmhello 已提交
2336
    return code;
wmmhello's avatar
wmmhello 已提交
2337 2338 2339 2340 2341
  }

  return code;
}

X
Xiaoyu Wang 已提交
2342
static int32_t isSchemalessDb(STscObj *taos, SRequestObj *request) {
wmmhello's avatar
wmmhello 已提交
2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370
//  SCatalog *catalog = NULL;
//  int32_t   code = catalogGetHandle(((STscObj *)taos)->pAppInfo->clusterId, &catalog);
//  if (code != TSDB_CODE_SUCCESS) {
//    uError("SML get catalog error %d", code);
//    return code;
//  }
//
//  SName name;
//  tNameSetDbName(&name, taos->acctId, taos->db, strlen(taos->db));
//  char dbFname[TSDB_DB_FNAME_LEN] = {0};
//  tNameGetFullDbName(&name, dbFname);
//  SDbCfgInfo pInfo = {0};
//
//  SRequestConnInfo conn = {0};
//  conn.pTrans = taos->pAppInfo->pTransporter;
//  conn.requestId = request->requestId;
//  conn.requestObjRefId = request->self;
//  conn.mgmtEps = getEpSet_s(&taos->pAppInfo->mgmtEp);
//
//  code = catalogGetDBCfg(catalog, &conn, dbFname, &pInfo);
//  if (code != TSDB_CODE_SUCCESS) {
//    return code;
//  }
//  taosArrayDestroy(pInfo.pRetensions);
//
//  if (!pInfo.schemaless) {
//    return TSDB_CODE_SML_INVALID_DB_CONF;
//  }
wmmhello's avatar
wmmhello 已提交
2371 2372 2373
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
2374
static void smlInsertCallback(void *param, void *res, int32_t code) {
wmmhello's avatar
wmmhello 已提交
2375
  SRequestObj *pRequest = (SRequestObj *)res;
X
Xiaoyu Wang 已提交
2376
  SSmlHandle  *info = (SSmlHandle *)param;
wmmhello's avatar
wmmhello 已提交
2377
  int32_t rows = taos_affected_rows(pRequest);
wmmhello's avatar
wmmhello 已提交
2378

X
Xiaoyu Wang 已提交
2379
  uDebug("SML:0x%" PRIx64 " result. code:%d, msg:%s", info->id, pRequest->code, pRequest->msgBuf);
wmmhello's avatar
wmmhello 已提交
2380
  // lock
wmmhello's avatar
wmmhello 已提交
2381 2382
  taosThreadSpinLock(&info->params->lock);
  info->params->request->body.resInfo.numOfRows += rows;
X
Xiaoyu Wang 已提交
2383
  if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
2384
    info->params->request->code = code;
wmmhello's avatar
wmmhello 已提交
2385
  }
wmmhello's avatar
wmmhello 已提交
2386
  taosThreadSpinUnlock(&info->params->lock);
wmmhello's avatar
wmmhello 已提交
2387 2388
  // unlock

wmmhello's avatar
wmmhello 已提交
2389
  uDebug("SML:0x%" PRIx64 " insert finished, code: %d, rows: %d, total: %d", info->id, code, rows, info->affectedRows);
wmmhello's avatar
wmmhello 已提交
2390
  Params *pParam = info->params;
X
Xiaoyu Wang 已提交
2391
  bool    isLast = info->isLast;
wmmhello's avatar
wmmhello 已提交
2392 2393 2394
  info->cost.endTime = taosGetTimestampUs();
  info->cost.code = code;
  smlPrintStatisticInfo(info);
wmmhello's avatar
wmmhello 已提交
2395 2396
  smlDestroyInfo(info);

X
Xiaoyu Wang 已提交
2397
  if (isLast) {
wmmhello's avatar
wmmhello 已提交
2398
    tsem_post(&pParam->sem);
wmmhello's avatar
wmmhello 已提交
2399 2400 2401
  }
}

wmmhello's avatar
wmmhello 已提交
2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
/**
 * taos_schemaless_insert() parse and insert data points into database according to
 * different protocol.
 *
 * @param $lines input array may contain multiple lines, each line indicates a data point.
 *               If protocol=2 is used input array should contain single JSON
 *               string(e.g. char *lines[] = {"$JSON_string"}). If need to insert
 *               multiple data points in JSON format, should include them in $JSON_string
 *               as a JSON array.
 * @param $numLines indicates how many data points in $lines.
 *                  If protocol = 2 is used this param will be ignored as $lines should
 *                  contain single JSON string.
 * @param $protocol indicates which protocol to use for parsing:
 *                  0 - influxDB line protocol
 *                  1 - OpenTSDB telnet line protocol
 *                  2 - OpenTSDB JSON format protocol
 * @return return zero for successful insertion. Otherwise return none-zero error code of
 *         failure reason.
 *
 */

wmmhello's avatar
wmmhello 已提交
2423
TAOS_RES* taos_schemaless_insert(TAOS* taos, char* lines[], int numLines, int protocol, int precision) {
D
dapan1121 已提交
2424
  if (NULL == taos) {
2425 2426 2427
    terrno = TSDB_CODE_TSC_DISCONNECTED;
    return NULL;
  }
D
dapan1121 已提交
2428

2429
  SRequestObj* request = (SRequestObj*)createRequest(*(int64_t*)taos, TSDB_SQL_INSERT);
wmmhello's avatar
wmmhello 已提交
2430
  if(!request){
2431
    uError("SML:taos_schemaless_insert error request is null");
2432
    return NULL;
wmmhello's avatar
wmmhello 已提交
2433 2434
  }

wmmhello's avatar
wmmhello 已提交
2435
  int    batchs = 0;
2436 2437
  STscObj* pTscObj = request->pTscObj;

2438
  pTscObj->schemalessType = 1;
wmmhello's avatar
wmmhello 已提交
2439
  SSmlMsgBuf msg = {ERROR_MSG_BUF_DEFAULT_SIZE, request->msgBuf};
wmmhello's avatar
wmmhello 已提交
2440

wmmhello's avatar
wmmhello 已提交
2441 2442
  Params params;
  params.request = request;
wmmhello's avatar
wmmhello 已提交
2443 2444 2445
  tsem_init(&params.sem, 0, 0);
  taosThreadSpinInit(&(params.lock), 0);

X
Xiaoyu Wang 已提交
2446
  if (request->pDb == NULL) {
wmmhello's avatar
wmmhello 已提交
2447
    request->code = TSDB_CODE_PAR_DB_NOT_SPECIFIED;
wmmhello's avatar
wmmhello 已提交
2448
    smlBuildInvalidDataMsg(&msg, "Database not specified", NULL);
wmmhello's avatar
wmmhello 已提交
2449 2450 2451
    goto end;
  }

2452
  if(isSchemalessDb(pTscObj, request) != TSDB_CODE_SUCCESS){
wmmhello's avatar
wmmhello 已提交
2453
    request->code = TSDB_CODE_SML_INVALID_DB_CONF;
wmmhello's avatar
wmmhello 已提交
2454
    smlBuildInvalidDataMsg(&msg, "Cannot write data to a non schemaless database", NULL);
wmmhello's avatar
wmmhello 已提交
2455 2456 2457
    goto end;
  }

2458
  if (!lines) {
2459
    request->code = TSDB_CODE_SML_INVALID_DATA;
wmmhello's avatar
wmmhello 已提交
2460
    smlBuildInvalidDataMsg(&msg, "lines is null", NULL);
2461 2462 2463
    goto end;
  }

X
Xiaoyu Wang 已提交
2464
  if (protocol < TSDB_SML_LINE_PROTOCOL || protocol > TSDB_SML_JSON_PROTOCOL) {
2465
    request->code = TSDB_CODE_SML_INVALID_PROTOCOL_TYPE;
wmmhello's avatar
wmmhello 已提交
2466
    smlBuildInvalidDataMsg(&msg, "protocol invalidate", NULL);
2467
    goto end;
wmmhello's avatar
wmmhello 已提交
2468 2469
  }

X
Xiaoyu Wang 已提交
2470 2471
  if (protocol == TSDB_SML_LINE_PROTOCOL &&
      (precision < TSDB_SML_TIMESTAMP_NOT_CONFIGURED || precision > TSDB_SML_TIMESTAMP_NANO_SECONDS)) {
2472
    request->code = TSDB_CODE_SML_INVALID_PRECISION_TYPE;
wmmhello's avatar
wmmhello 已提交
2473
    smlBuildInvalidDataMsg(&msg, "precision invalidate for line protocol", NULL);
2474 2475 2476
    goto end;
  }

wmmhello's avatar
wmmhello 已提交
2477 2478 2479 2480 2481 2482 2483 2484
  if(protocol == TSDB_SML_JSON_PROTOCOL){
    numLines = 1;
  }else if(numLines <= 0){
    request->code = TSDB_CODE_SML_INVALID_DATA;
    smlBuildInvalidDataMsg(&msg, "line num is invalid", NULL);
    goto end;
  }

wmmhello's avatar
wmmhello 已提交
2485 2486
  batchs = ceil(((double)numLines) / LINE_BATCH);
  for (int i = 0; i < batchs; ++i) {
2487
    SRequestObj* req = (SRequestObj*)createRequest(pTscObj->id, TSDB_SQL_INSERT);
wmmhello's avatar
wmmhello 已提交
2488 2489 2490 2491 2492
    if(!req){
      request->code = TSDB_CODE_OUT_OF_MEMORY;
      uError("SML:taos_schemaless_insert error request is null");
      goto end;
    }
2493
    SSmlHandle* info = smlBuildSmlInfo(pTscObj, req, (SMLProtocolType)protocol, precision);
wmmhello's avatar
wmmhello 已提交
2494 2495 2496 2497 2498 2499
    if(!info){
      request->code = TSDB_CODE_OUT_OF_MEMORY;
      uError("SML:taos_schemaless_insert error SSmlHandle is null");
      goto end;
    }

wmmhello's avatar
wmmhello 已提交
2500 2501
    int32_t perBatch = LINE_BATCH;

X
Xiaoyu Wang 已提交
2502
    if (numLines > perBatch) {
wmmhello's avatar
wmmhello 已提交
2503 2504
      numLines -= perBatch;
      info->isLast = false;
X
Xiaoyu Wang 已提交
2505
    } else {
wmmhello's avatar
wmmhello 已提交
2506 2507 2508 2509 2510
      perBatch = numLines;
      numLines = 0;
      info->isLast = true;
    }

wmmhello's avatar
wmmhello 已提交
2511
    info->params = &params;
wmmhello's avatar
wmmhello 已提交
2512 2513
    info->affectedRows = perBatch;
    info->pRequest->body.queryFp = smlInsertCallback;
X
Xiaoyu Wang 已提交
2514
    info->pRequest->body.param = info;
wmmhello's avatar
wmmhello 已提交
2515
    int32_t code = smlProcess(info, lines, perBatch);
wmmhello's avatar
wmmhello 已提交
2516
    lines += perBatch;
X
Xiaoyu Wang 已提交
2517
    if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
2518 2519 2520 2521
      info->pRequest->body.queryFp(info, req, code);
    }
  }
  tsem_wait(&params.sem);
2522 2523

end:
wmmhello's avatar
wmmhello 已提交
2524 2525
  taosThreadSpinDestroy(&params.lock);
  tsem_destroy(&params.sem);
2526
//  ((STscObj *)taos)->schemalessType = 0;
2527
  pTscObj->schemalessType = 1;
2528
  uDebug("resultend:%s", request->msgBuf);
wmmhello's avatar
wmmhello 已提交
2529
  return (TAOS_RES*)request;
wmmhello's avatar
wmmhello 已提交
2530
}