clientSml.c 93.5 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

23 24 25 26 27 28 29 30 31 32 33 34 35
#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)
#  define expect(expr,value)    (__builtin_expect ((expr),(value)) )
#else
#  define expect(expr,value)    (expr)
#endif

#ifndef likely
#define likely(expr)     expect((expr) != 0, 1)
#endif
#ifndef unlikely
#define unlikely(expr)   expect((expr) != 0, 0)
#endif

wmmhello's avatar
wmmhello 已提交
36
//=================================================================================================
wmmhello's avatar
wmmhello 已提交
37 38 39 40 41 42 43

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

dengyihao's avatar
dengyihao 已提交
44 45 46 47 48 49
#define JUMP_SPACE(sql, sqlEnd) \
  while (sql < sqlEnd) {        \
    if (*sql == SPACE)          \
      sql++;                    \
    else                        \
      break;                    \
X
Xiaoyu Wang 已提交
50
  }
wmmhello's avatar
wmmhello 已提交
51
// comma ,
wmmhello's avatar
wmmhello 已提交
52
//#define IS_SLASH_COMMA(sql) (*(sql) == COMMA && *((sql)-1) == SLASH)
X
Xiaoyu Wang 已提交
53
#define IS_COMMA(sql)       (*(sql) == COMMA && *((sql)-1) != SLASH)
wmmhello's avatar
wmmhello 已提交
54
// space
wmmhello's avatar
wmmhello 已提交
55
//#define IS_SLASH_SPACE(sql) (*(sql) == SPACE && *((sql)-1) == SLASH)
X
Xiaoyu Wang 已提交
56
#define IS_SPACE(sql)       (*(sql) == SPACE && *((sql)-1) != SLASH)
wmmhello's avatar
wmmhello 已提交
57
// equal =
wmmhello's avatar
wmmhello 已提交
58
//#define IS_SLASH_EQUAL(sql) (*(sql) == EQUAL && *((sql)-1) == SLASH)
X
Xiaoyu Wang 已提交
59
#define IS_EQUAL(sql)       (*(sql) == EQUAL && *((sql)-1) != SLASH)
wmmhello's avatar
wmmhello 已提交
60
// quote "
wmmhello's avatar
wmmhello 已提交
61
//#define IS_SLASH_QUOTE(sql) (*(sql) == QUOTE && *((sql)-1) == SLASH)
X
Xiaoyu Wang 已提交
62
#define IS_QUOTE(sql)       (*(sql) == QUOTE && *((sql)-1) != SLASH)
wmmhello's avatar
wmmhello 已提交
63
// SLASH
wmmhello's avatar
wmmhello 已提交
64
//#define IS_SLASH_SLASH(sql) (*(sql) == SLASH && *((sql)-1) == SLASH)
wmmhello's avatar
wmmhello 已提交
65

X
Xiaoyu Wang 已提交
66
#define IS_SLASH_LETTER(sql) \
wmmhello's avatar
wmmhello 已提交
67 68
  (*((sql)-1) == SLASH && (*(sql) == COMMA || *(sql) == SPACE || *(sql) == EQUAL || *(sql) == QUOTE || *(sql) == SLASH))                          \
//  (IS_SLASH_COMMA(sql) || IS_SLASH_SPACE(sql) || IS_SLASH_EQUAL(sql) || IS_SLASH_QUOTE(sql) || IS_SLASH_SLASH(sql))
wmmhello's avatar
wmmhello 已提交
69

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

X
Xiaoyu Wang 已提交
72 73 74 75 76 77 78 79
#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 已提交
80

81 82 83
#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)

84 85 86
#define OTD_JSON_SUB_FIELDS_NUM 2
#define OTD_JSON_FIELDS_NUM     4

X
Xiaoyu Wang 已提交
87 88 89 90
#define TS        "_ts"
#define TS_LEN    3
#define VALUE     "_value"
#define VALUE_LEN 6
91

X
Xiaoyu Wang 已提交
92 93
#define BINARY_ADD_LEN 2  // "binary"   2 means " "
#define NCHAR_ADD_LEN  3  // L"nchar"   3 means L" "
wmmhello's avatar
wmmhello 已提交
94 95

#define MAX_RETRY_TIMES 5
wmmhello's avatar
wmmhello 已提交
96 97 98 99
//=================================================================================================
typedef TSDB_SML_PROTOCOL_TYPE SMLProtocolType;

typedef enum {
100
  SCHEMA_ACTION_NULL,
wmmhello's avatar
wmmhello 已提交
101 102 103 104 105
  SCHEMA_ACTION_CREATE_STABLE,
  SCHEMA_ACTION_ADD_COLUMN,
  SCHEMA_ACTION_ADD_TAG,
  SCHEMA_ACTION_CHANGE_COLUMN_SIZE,
  SCHEMA_ACTION_CHANGE_TAG_SIZE,
wmmhello's avatar
wmmhello 已提交
106 107
} ESchemaAction;

wmmhello's avatar
wmmhello 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
/*********************** list start *********************************/
typedef struct {
  const void  *key;
  int32_t      keyLen;
  void        *value;
  bool         used;
}Node;

typedef struct NodeList{
  Node             data;
  struct NodeList* next;
}NodeList;

static void* nodeListGet(NodeList* list, const void *key, int32_t len){
  NodeList *tmp = list;
  while(tmp){
    if(tmp->data.used && tmp->data.keyLen == len && memcmp(tmp->data.key, key, len) == 0) {
      return tmp->data.value;
    }
    tmp = tmp->next;
  }
  return NULL;
}

static int nodeListSet(NodeList** list, const void *key, int32_t len, void* value){
  NodeList *tmp = *list;
  while (tmp){
    if(!tmp->data.used) break;
    if(tmp->data.keyLen == len && memcmp(tmp->data.key, key, len) == 0) {
      return -1;
    }
    tmp = tmp->next;
  }
  if(tmp){
    tmp->data.key = key;
    tmp->data.keyLen = len;
    tmp->data.value = value;
    tmp->data.used = true;
  }else{
    NodeList *newNode = taosMemoryCalloc(1, sizeof(NodeList));
    if(newNode == NULL){
      return -1;
    }
    newNode->data.key = key;
    newNode->data.keyLen = len;
    newNode->data.value = value;
    newNode->data.used = true;
    newNode->next = *list;
    *list = newNode;
  }
  return 0;
}

static int nodeListSize(NodeList* list){
  int cnt = 0;
  while(list){
    if(list->data.used) cnt++;
    else break;
    list = list->next;
  }
  return cnt;
}
/*********************** list end *********************************/

wmmhello's avatar
wmmhello 已提交
172
typedef struct {
X
Xiaoyu Wang 已提交
173 174 175 176
  const char *measure;
  const char *tags;
  const char *cols;
  const char *timestamp;
wmmhello's avatar
wmmhello 已提交
177 178 179 180 181 182

  int32_t measureLen;
  int32_t measureTagsLen;
  int32_t tagsLen;
  int32_t colsLen;
  int32_t timestampLen;
183 184

  SArray *colArray;
wmmhello's avatar
wmmhello 已提交
185 186 187
} SSmlLineInfo;

typedef struct {
X
Xiaoyu Wang 已提交
188 189 190 191
  const char *sTableName;  // super table name
  int32_t     sTableNameLen;
  char        childTableName[TSDB_TABLE_NAME_LEN];
  uint64_t    uid;
wmmhello's avatar
wmmhello 已提交
192

X
Xiaoyu Wang 已提交
193
  SArray *tags;
wmmhello's avatar
wmmhello 已提交
194

195
  // elements are SHashObj<cols key string, SSmlKv*> for find by key quickly
X
Xiaoyu Wang 已提交
196
  SArray *cols;
197
  STableDataCxt *tableDataCtx;
wmmhello's avatar
wmmhello 已提交
198 199 200
} SSmlTableInfo;

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

X
Xiaoyu Wang 已提交
204 205
  SArray   *cols;
  SHashObj *colHash;
206

wmmhello's avatar
wmmhello 已提交
207 208 209 210
  STableMeta *tableMeta;
} SSmlSTableMeta;

typedef struct {
X
Xiaoyu Wang 已提交
211 212
  int32_t len;
  char   *buf;
wmmhello's avatar
wmmhello 已提交
213 214
} SSmlMsgBuf;

215 216 217 218 219 220 221
typedef struct {
  int32_t code;
  int32_t lineNum;

  int32_t numOfSTables;
  int32_t numOfCTables;
  int32_t numOfCreateSTables;
222 223
  int32_t numOfAlterColSTables;
  int32_t numOfAlterTagSTables;
224 225 226 227 228 229 230 231

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

wmmhello's avatar
wmmhello 已提交
232
typedef struct {
X
Xiaoyu Wang 已提交
233 234 235 236
  int64_t id;

  SMLProtocolType protocol;
  int8_t          precision;
237
  bool            reRun;
238 239 240
  bool            dataFormat;  // true means that the name and order of keys in each line are the same(only for influx protocol)
  bool            isRawLine;
  int32_t         ttl;
X
Xiaoyu Wang 已提交
241

wmmhello's avatar
wmmhello 已提交
242 243
  NodeList *childTables;
  NodeList *superTables;
X
Xiaoyu Wang 已提交
244 245 246 247 248 249 250 251
  SHashObj *pVgHash;

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

  SSmlCostInfo cost;
wmmhello's avatar
wmmhello 已提交
252
  int32_t      lineNum;
X
Xiaoyu Wang 已提交
253
  SSmlMsgBuf   msgBuf;
wmmhello's avatar
wmmhello 已提交
254 255

  cJSON       *root;  // for parse json
wmmhello's avatar
wmmhello 已提交
256
  SSmlLineInfo      *lines; // element is SSmlLineInfo
257 258

  //
wmmhello's avatar
wmmhello 已提交
259 260
  NodeList    *superTableTagKeyStr;
  NodeList    *superTableColKeyStr;
261 262 263 264 265 266 267 268 269 270 271
  void        *currentLineTagKeys;
  void        *preLineTagKeys;
  void        *currentLineColKeys;
  void        *preLineColKeys;

  SArray      *preLineTagKV;
  SArray      *preLineColKV;

  SSmlLineInfo preLine;
  STableMeta  *currSTableMeta;
  STableDataCxt *currTableDataCtx;
wmmhello's avatar
wmmhello 已提交
272
  bool         needModifySchema;
wmmhello's avatar
wmmhello 已提交
273
} SSmlHandle;
wmmhello's avatar
wmmhello 已提交
274 275
//=================================================================================================

wmmhello's avatar
wmmhello 已提交
276
//=================================================================================================
277
static volatile int64_t linesSmlHandleId = 0;
X
Xiaoyu Wang 已提交
278
static int64_t          smlGenId() {
279
  int64_t id;
wmmhello's avatar
wmmhello 已提交
280

281 282
  do {
    id = atomic_add_fetch_64(&linesSmlHandleId, 1);
wmmhello's avatar
wmmhello 已提交
283 284
  } while (id == 0);

285
  return id;
wmmhello's avatar
wmmhello 已提交
286 287
}

288
static inline bool smlDoubleToInt64OverFlow(double num) {
X
Xiaoyu Wang 已提交
289
  if (num >= (double)INT64_MAX || num <= (double)INT64_MIN) return true;
290 291 292 293 294 295 296 297 298 299 300 301
  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 已提交
302
static int32_t smlBuildInvalidDataMsg(SSmlMsgBuf *pBuf, const char *msg1, const char *msg2) {
303
  if (pBuf->buf) {
304 305 306 307 308 309 310
    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 已提交
311
  }
wmmhello's avatar
wmmhello 已提交
312 313 314
  return TSDB_CODE_SML_INVALID_DATA;
}

X
Xiaoyu Wang 已提交
315
static int32_t smlGenerateSchemaAction(SSchema *colField, SHashObj *colHash, SSmlKv *kv, bool isTag,
316
                                       ESchemaAction *action, SSmlHandle *info) {
wmmhello's avatar
wmmhello 已提交
317
  uint16_t *index = colHash ? (uint16_t *)taosHashGet(colHash, kv->key, kv->keyLen) : NULL;
318 319
  if (index) {
    if (colField[*index].type != kv->type) {
X
Xiaoyu Wang 已提交
320 321
      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);
322 323 324
      return TSDB_CODE_TSC_INVALID_VALUE;
    }

X
Xiaoyu Wang 已提交
325 326 327 328
    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))) {
329
      if (isTag) {
wmmhello's avatar
wmmhello 已提交
330
        *action = SCHEMA_ACTION_CHANGE_TAG_SIZE;
331
      } else {
wmmhello's avatar
wmmhello 已提交
332
        *action = SCHEMA_ACTION_CHANGE_COLUMN_SIZE;
333 334 335 336
      }
    }
  } else {
    if (isTag) {
wmmhello's avatar
wmmhello 已提交
337
      *action = SCHEMA_ACTION_ADD_TAG;
338
    } else {
wmmhello's avatar
wmmhello 已提交
339
      *action = SCHEMA_ACTION_ADD_COLUMN;
340 341
    }
  }
wmmhello's avatar
wmmhello 已提交
342 343 344
  return 0;
}

wmmhello's avatar
wmmhello 已提交
345
static int32_t smlFindNearestPowerOf2(int32_t length, uint8_t type) {
wmmhello's avatar
wmmhello 已提交
346
  int32_t result = 1;
X
Xiaoyu Wang 已提交
347
  while (result <= length) {
wmmhello's avatar
wmmhello 已提交
348 349
    result *= 2;
  }
350
  if (type == TSDB_DATA_TYPE_BINARY && result > TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE) {
wmmhello's avatar
wmmhello 已提交
351
    result = TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE;
352
  } else if (type == TSDB_DATA_TYPE_NCHAR && result > (TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE) {
wmmhello's avatar
wmmhello 已提交
353 354
    result = (TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE;
  }
wmmhello's avatar
wmmhello 已提交
355

356
  if (type == TSDB_DATA_TYPE_NCHAR) {
357
    result = result * TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE;
358
  } else if (type == TSDB_DATA_TYPE_BINARY) {
359
    result = result + VARSTR_HEADER_SIZE;
wmmhello's avatar
wmmhello 已提交
360
  }
361
  return result;
wmmhello's avatar
wmmhello 已提交
362 363
}

X
Xiaoyu Wang 已提交
364
static int32_t smlProcessSchemaAction(SSmlHandle *info, SSchema *schemaField, SHashObj *schemaHash, SArray *cols,
365
                                      ESchemaAction *action, bool isTag) {
366 367
  int32_t code = TSDB_CODE_SUCCESS;
  for (int j = 0; j < taosArrayGetSize(cols); ++j) {
368
    if (j == 0 && !isTag) continue;
369
    SSmlKv *kv = (SSmlKv *)taosArrayGet(cols, j);
370
    code = smlGenerateSchemaAction(schemaField, schemaHash, kv, isTag, action, info);
X
Xiaoyu Wang 已提交
371
    if (code != TSDB_CODE_SUCCESS) {
372 373 374 375 376 377
      return code;
    }
  }
  return TSDB_CODE_SUCCESS;
}

378
static int32_t smlCheckMeta(SSchema *schema, int32_t length, SArray *cols, bool isTag) {
379
  SHashObj *hashTmp = taosHashInit(length, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
380 381
  int32_t   i = 0;
  for (; i < length; i++) {
382 383 384
    taosHashPut(hashTmp, schema[i].name, strlen(schema[i].name), &i, SHORT_BYTES);
  }

385
  if (isTag) {
386 387 388 389 390
    i = 0;
  } else {
    i = 1;
  }
  for (; i < taosArrayGetSize(cols); i++) {
391
    SSmlKv *kv = (SSmlKv *)taosArrayGet(cols, i);
X
Xiaoyu Wang 已提交
392
    if (taosHashGet(hashTmp, kv->key, kv->keyLen) == NULL) {
wmmhello's avatar
wmmhello 已提交
393
      taosHashCleanup(hashTmp);
394 395 396
      return -1;
    }
  }
397
  taosHashCleanup(hashTmp);
398 399 400
  return 0;
}

401
static int32_t getBytes(uint8_t type, int32_t length) {
402 403 404 405 406 407 408
  if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
    return smlFindNearestPowerOf2(length, type);
  } else {
    return tDataTypes[type].bytes;
  }
}

409 410
static int32_t smlBuildFieldsList(SSmlHandle *info, SSchema *schemaField, SHashObj *schemaHash, SArray *cols,
                                  SArray *results, int32_t numOfCols, bool isTag) {
wmmhello's avatar
wmmhello 已提交
411
  for (int j = 0; j < taosArrayGetSize(cols); ++j) {
412
    SSmlKv       *kv = (SSmlKv *)taosArrayGet(cols, j);
wmmhello's avatar
wmmhello 已提交
413 414
    ESchemaAction action = SCHEMA_ACTION_NULL;
    smlGenerateSchemaAction(schemaField, schemaHash, kv, isTag, &action, info);
415
    if (action == SCHEMA_ACTION_ADD_COLUMN || action == SCHEMA_ACTION_ADD_TAG) {
wmmhello's avatar
wmmhello 已提交
416 417 418 419 420
      SField field = {0};
      field.type = kv->type;
      field.bytes = getBytes(kv->type, kv->length);
      memcpy(field.name, kv->key, kv->keyLen);
      taosArrayPush(results, &field);
421
    } else if (action == SCHEMA_ACTION_CHANGE_COLUMN_SIZE || action == SCHEMA_ACTION_CHANGE_TAG_SIZE) {
wmmhello's avatar
wmmhello 已提交
422
      uint16_t *index = (uint16_t *)taosHashGet(schemaHash, kv->key, kv->keyLen);
423 424
      uint16_t  newIndex = *index;
      if (isTag) newIndex -= numOfCols;
wmmhello's avatar
wmmhello 已提交
425 426 427 428 429 430 431
      SField *field = (SField *)taosArrayGet(results, newIndex);
      field->bytes = getBytes(kv->type, kv->length);
    }
  }
  return TSDB_CODE_SUCCESS;
}

432 433 434 435 436
// static int32_t smlSendMetaMsg(SSmlHandle *info, SName *pName, SSmlSTableMeta *sTableData,
//                               int32_t colVer, int32_t tagVer, int8_t source, uint64_t suid){
static int32_t smlSendMetaMsg(SSmlHandle *info, SName *pName, SArray *pColumns, SArray *pTags, STableMeta *pTableMeta,
                              ESchemaAction action) {
  SRequestObj   *pRequest = NULL;
437 438 439 440
  SMCreateStbReq pReq = {0};
  int32_t        code = TSDB_CODE_SUCCESS;
  SCmdMsgInfo    pCmdMsg = {0};

wmmhello's avatar
wmmhello 已提交
441 442 443 444 445 446
  // put front for free
  pReq.numOfColumns = taosArrayGetSize(pColumns);
  pReq.pColumns = pColumns;
  pReq.numOfTags = taosArrayGetSize(pTags);
  pReq.pTags = pTags;

dengyihao's avatar
dengyihao 已提交
447
  code = buildRequest(info->taos->id, "", 0, NULL, false, &pRequest, 0);
448 449 450 451
  if (code != TSDB_CODE_SUCCESS) {
    goto end;
  }

wmmhello's avatar
wmmhello 已提交
452
  pRequest->syncQuery = true;
453 454 455 456 457
  if (!pRequest->pDb) {
    code = TSDB_CODE_PAR_DB_NOT_SPECIFIED;
    goto end;
  }

458
  if (action == SCHEMA_ACTION_CREATE_STABLE) {
wmmhello's avatar
wmmhello 已提交
459 460 461 462
    pReq.colVer = 1;
    pReq.tagVer = 1;
    pReq.suid = 0;
    pReq.source = TD_REQ_FROM_APP;
463
  } else if (action == SCHEMA_ACTION_ADD_TAG || action == SCHEMA_ACTION_CHANGE_TAG_SIZE) {
wmmhello's avatar
wmmhello 已提交
464 465 466 467
    pReq.colVer = pTableMeta->sversion;
    pReq.tagVer = pTableMeta->tversion + 1;
    pReq.suid = pTableMeta->uid;
    pReq.source = TD_REQ_FROM_TAOX;
468
  } else if (action == SCHEMA_ACTION_ADD_COLUMN || action == SCHEMA_ACTION_CHANGE_COLUMN_SIZE) {
wmmhello's avatar
wmmhello 已提交
469 470 471 472 473 474
    pReq.colVer = pTableMeta->sversion + 1;
    pReq.tagVer = pTableMeta->tversion;
    pReq.suid = pTableMeta->uid;
    pReq.source = TD_REQ_FROM_TAOX;
  }

475
  if (pReq.numOfTags == 0) {
wmmhello's avatar
wmmhello 已提交
476 477 478 479 480 481 482 483
    pReq.numOfTags = 1;
    SField field = {0};
    field.type = TSDB_DATA_TYPE_NCHAR;
    field.bytes = 1;
    strcpy(field.name, tsSmlTagName);
    taosArrayPush(pReq.pTags, &field);
  }

484 485 486 487 488 489 490 491 492 493 494 495 496 497
  pReq.commentLen = -1;
  pReq.igExists = true;
  tNameExtractFullName(pName, pReq.name);

  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) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
  tSerializeSMCreateStbReq(pCmdMsg.pMsg, pCmdMsg.msgLen, &pReq);

D
dapan1121 已提交
498 499
  SQuery pQuery;
  memset(&pQuery, 0, sizeof(pQuery));
500 501 502 503 504 505 506
  pQuery.execMode = QUERY_EXEC_MODE_RPC;
  pQuery.pCmdMsg = &pCmdMsg;
  pQuery.msgType = pQuery.pCmdMsg->msgType;
  pQuery.stableQuery = true;

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

507
  if (pRequest->code == TSDB_CODE_SUCCESS) {
508 509 510 511 512
    catalogRemoveTableMeta(info->pCatalog, pName);
  }
  code = pRequest->code;
  taosMemoryFree(pCmdMsg.pMsg);

513
  end:
514 515 516 517 518
  destroyRequest(pRequest);
  tFreeSMCreateStbReq(&pReq);
  return code;
}

X
Xiaoyu Wang 已提交
519
static int32_t smlModifyDBSchemas(SSmlHandle *info) {
wmmhello's avatar
wmmhello 已提交
520 521 522
  if(info->dataFormat && !info->needModifySchema){
    return TSDB_CODE_SUCCESS;
  }
523 524 525
  int32_t     code = 0;
  SHashObj   *hashTmp = NULL;
  STableMeta *pTableMeta = NULL;
wmmhello's avatar
wmmhello 已提交
526

527
  SName pName = {TSDB_TABLE_NAME_T, info->taos->acctId, {0}, {0}};
wmmhello's avatar
wmmhello 已提交
528
  tstrncpy(pName.dbname, info->pRequest->pDb, sizeof(pName.dbname));
wmmhello's avatar
wmmhello 已提交
529

D
dapan1121 已提交
530 531 532 533 534
  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 已提交
535

wmmhello's avatar
wmmhello 已提交
536 537 538
  NodeList *tmp = info->superTables;
  while (tmp) {
    SSmlSTableMeta *sTableData = tmp->data.value;
X
Xiaoyu Wang 已提交
539
    bool            needCheckMeta = false;  // for multi thread
wmmhello's avatar
wmmhello 已提交
540

wmmhello's avatar
wmmhello 已提交
541 542
    size_t superTableLen = (size_t)tmp->data.keyLen;
    const void  *superTable = tmp->data.key;
543
    memset(pName.tname, 0, TSDB_TABLE_NAME_LEN);
wmmhello's avatar
wmmhello 已提交
544
    memcpy(pName.tname, superTable, superTableLen);
wmmhello's avatar
wmmhello 已提交
545

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

548
    if (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_MND_STB_NOT_EXIST) {
549 550
      SArray *pColumns = taosArrayInit(taosArrayGetSize(sTableData->cols), sizeof(SField));
      SArray *pTags = taosArrayInit(taosArrayGetSize(sTableData->tags), sizeof(SField));
wmmhello's avatar
wmmhello 已提交
551 552 553 554
      smlBuildFieldsList(info, NULL, NULL, sTableData->tags, pTags, 0, true);
      smlBuildFieldsList(info, NULL, NULL, sTableData->cols, pColumns, 0, false);

      code = smlSendMetaMsg(info, &pName, pColumns, pTags, NULL, SCHEMA_ACTION_CREATE_STABLE);
555
      if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
556
        uError("SML:0x%" PRIx64 " smlSendMetaMsg failed. can not create %s", info->id, pName.tname);
557
        goto end;
wmmhello's avatar
wmmhello 已提交
558
      }
559
      info->cost.numOfCreateSTables++;
wmmhello's avatar
wmmhello 已提交
560 561 562 563 564 565 566
      taosMemoryFreeClear(pTableMeta);

      code = catalogGetSTableMeta(info->pCatalog, &conn, &pName, &pTableMeta);
      if (code != TSDB_CODE_SUCCESS) {
        uError("SML:0x%" PRIx64 " catalogGetSTableMeta failed. super table name %s", info->id, pName.tname);
        goto end;
      }
X
Xiaoyu Wang 已提交
567
    } else if (code == TSDB_CODE_SUCCESS) {
568 569
      hashTmp = taosHashInit(pTableMeta->tableInfo.numOfTags, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true,
                             HASH_NO_LOCK);
X
Xiaoyu Wang 已提交
570 571
      for (uint16_t i = pTableMeta->tableInfo.numOfColumns;
           i < pTableMeta->tableInfo.numOfColumns + pTableMeta->tableInfo.numOfTags; i++) {
572 573
        taosHashPut(hashTmp, pTableMeta->schema[i].name, strlen(pTableMeta->schema[i].name), &i, SHORT_BYTES);
      }
wmmhello's avatar
wmmhello 已提交
574

575 576
      ESchemaAction action = SCHEMA_ACTION_NULL;
      code = smlProcessSchemaAction(info, pTableMeta->schema, hashTmp, sTableData->tags, &action, true);
577
      if (code != TSDB_CODE_SUCCESS) {
578
        goto end;
579
      }
580 581 582 583 584
      if (action != SCHEMA_ACTION_NULL) {
        SArray *pColumns =
            taosArrayInit(taosArrayGetSize(sTableData->cols) + pTableMeta->tableInfo.numOfColumns, sizeof(SField));
        SArray *pTags =
            taosArrayInit(taosArrayGetSize(sTableData->tags) + pTableMeta->tableInfo.numOfTags, sizeof(SField));
wmmhello's avatar
wmmhello 已提交
585 586 587 588 589 590

        for (uint16_t i = 0; i < pTableMeta->tableInfo.numOfColumns + pTableMeta->tableInfo.numOfTags; i++) {
          SField field = {0};
          field.type = pTableMeta->schema[i].type;
          field.bytes = pTableMeta->schema[i].bytes;
          strcpy(field.name, pTableMeta->schema[i].name);
591
          if (i < pTableMeta->tableInfo.numOfColumns) {
wmmhello's avatar
wmmhello 已提交
592
            taosArrayPush(pColumns, &field);
593
          } else {
wmmhello's avatar
wmmhello 已提交
594 595 596
            taosArrayPush(pTags, &field);
          }
        }
597 598
        smlBuildFieldsList(info, pTableMeta->schema, hashTmp, sTableData->tags, pTags,
                           pTableMeta->tableInfo.numOfColumns, true);
wmmhello's avatar
wmmhello 已提交
599 600

        code = smlSendMetaMsg(info, &pName, pColumns, pTags, pTableMeta, action);
601
        if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
602
          uError("SML:0x%" PRIx64 " smlSendMetaMsg failed. can not create %s", info->id, pName.tname);
603 604 605
          goto end;
        }

606
        info->cost.numOfAlterTagSTables++;
wmmhello's avatar
wmmhello 已提交
607 608 609 610 611 612 613 614 615
        taosMemoryFreeClear(pTableMeta);
        code = catalogRefreshTableMeta(info->pCatalog, &conn, &pName, -1);
        if (code != TSDB_CODE_SUCCESS) {
          goto end;
        }
        code = catalogGetSTableMeta(info->pCatalog, &conn, &pName, &pTableMeta);
        if (code != TSDB_CODE_SUCCESS) {
          goto end;
        }
wmmhello's avatar
wmmhello 已提交
616
      }
617 618

      taosHashClear(hashTmp);
wmmhello's avatar
wmmhello 已提交
619
      for (uint16_t i = 0; i < pTableMeta->tableInfo.numOfColumns; i++) {
620 621
        taosHashPut(hashTmp, pTableMeta->schema[i].name, strlen(pTableMeta->schema[i].name), &i, SHORT_BYTES);
      }
622 623
      action = SCHEMA_ACTION_NULL;
      code = smlProcessSchemaAction(info, pTableMeta->schema, hashTmp, sTableData->cols, &action, false);
624
      if (code != TSDB_CODE_SUCCESS) {
625
        goto end;
wmmhello's avatar
wmmhello 已提交
626
      }
627 628 629 630 631
      if (action != SCHEMA_ACTION_NULL) {
        SArray *pColumns =
            taosArrayInit(taosArrayGetSize(sTableData->cols) + pTableMeta->tableInfo.numOfColumns, sizeof(SField));
        SArray *pTags =
            taosArrayInit(taosArrayGetSize(sTableData->tags) + pTableMeta->tableInfo.numOfTags, sizeof(SField));
wmmhello's avatar
wmmhello 已提交
632 633 634 635 636 637

        for (uint16_t i = 0; i < pTableMeta->tableInfo.numOfColumns + pTableMeta->tableInfo.numOfTags; i++) {
          SField field = {0};
          field.type = pTableMeta->schema[i].type;
          field.bytes = pTableMeta->schema[i].bytes;
          strcpy(field.name, pTableMeta->schema[i].name);
638
          if (i < pTableMeta->tableInfo.numOfColumns) {
wmmhello's avatar
wmmhello 已提交
639
            taosArrayPush(pColumns, &field);
640
          } else {
wmmhello's avatar
wmmhello 已提交
641 642 643 644
            taosArrayPush(pTags, &field);
          }
        }

645 646
        smlBuildFieldsList(info, pTableMeta->schema, hashTmp, sTableData->cols, pColumns,
                           pTableMeta->tableInfo.numOfColumns, false);
wmmhello's avatar
wmmhello 已提交
647 648

        code = smlSendMetaMsg(info, &pName, pColumns, pTags, pTableMeta, action);
649
        if (code != TSDB_CODE_SUCCESS) {
650
          uError("SML:0x%" PRIx64 " smlSendMetaMsg failed. can not create %s", info->id, pName.tname);
651 652
          goto end;
        }
wmmhello's avatar
wmmhello 已提交
653

654
        info->cost.numOfAlterColSTables++;
wmmhello's avatar
wmmhello 已提交
655
        taosMemoryFreeClear(pTableMeta);
wmmhello's avatar
wmmhello 已提交
656 657 658 659
        code = catalogRefreshTableMeta(info->pCatalog, &conn, &pName, -1);
        if (code != TSDB_CODE_SUCCESS) {
          goto end;
        }
660 661 662 663 664
        code = catalogGetSTableMeta(info->pCatalog, &conn, &pName, &pTableMeta);
        if (code != TSDB_CODE_SUCCESS) {
          uError("SML:0x%" PRIx64 " catalogGetSTableMeta failed. super table name %s", info->id, pName.tname);
          goto end;
        }
wmmhello's avatar
wmmhello 已提交
665
      }
wmmhello's avatar
wmmhello 已提交
666

667
      needCheckMeta = true;
wmmhello's avatar
wmmhello 已提交
668 669
      taosHashCleanup(hashTmp);
      hashTmp = NULL;
wmmhello's avatar
wmmhello 已提交
670
    } else {
X
Xiaoyu Wang 已提交
671
      uError("SML:0x%" PRIx64 " load table meta error: %s", info->id, tstrerror(code));
672
      goto end;
wmmhello's avatar
wmmhello 已提交
673
    }
674

X
Xiaoyu Wang 已提交
675 676
    if (needCheckMeta) {
      code = smlCheckMeta(&(pTableMeta->schema[pTableMeta->tableInfo.numOfColumns]), pTableMeta->tableInfo.numOfTags,
677
                          sTableData->tags, true);
678
      if (code != TSDB_CODE_SUCCESS) {
679
        uError("SML:0x%" PRIx64 " check tag failed. super table name %s", info->id, pName.tname);
680 681
        goto end;
      }
682
      code = smlCheckMeta(&(pTableMeta->schema[0]), pTableMeta->tableInfo.numOfColumns, sTableData->cols, false);
683
      if (code != TSDB_CODE_SUCCESS) {
684
        uError("SML:0x%" PRIx64 " check cols failed. super table name %s", info->id, pName.tname);
685 686 687 688
        goto end;
      }
    }

689
    sTableData->tableMeta = pTableMeta;
wmmhello's avatar
wmmhello 已提交
690

wmmhello's avatar
wmmhello 已提交
691
    tmp = tmp->next;
wmmhello's avatar
wmmhello 已提交
692 693
  }
  return 0;
694

695
  end:
wmmhello's avatar
wmmhello 已提交
696 697
  taosHashCleanup(hashTmp);
  taosMemoryFreeClear(pTableMeta);
wmmhello's avatar
wmmhello 已提交
698
//  catalogRefreshTableMeta(info->pCatalog, &conn, &pName, 1);
699
  return code;
wmmhello's avatar
wmmhello 已提交
700 701
}

702
/******************************* parse basic type function **********************/
X
Xiaoyu Wang 已提交
703
static bool smlParseNumber(SSmlKv *kvVal, SSmlMsgBuf *msg) {
wmmhello's avatar
wmmhello 已提交
704
  const char *pVal = kvVal->value;
X
Xiaoyu Wang 已提交
705 706 707 708
  int32_t     len = kvVal->length;
  char       *endptr = NULL;
  double      result = taosStr2Double(pVal, &endptr);
  if (pVal == endptr) {
709
    smlBuildInvalidDataMsg(msg, "invalid data", pVal);
wmmhello's avatar
wmmhello 已提交
710 711 712
    return false;
  }

713
  int32_t left = len - (endptr - pVal);
X
Xiaoyu Wang 已提交
714
  if (left == 0 || (left == 3 && strncasecmp(endptr, "f64", left) == 0)) {
715 716
    kvVal->type = TSDB_DATA_TYPE_DOUBLE;
    kvVal->d = result;
X
Xiaoyu Wang 已提交
717 718
  } else if ((left == 3 && strncasecmp(endptr, "f32", left) == 0)) {
    if (!IS_VALID_FLOAT(result)) {
719 720
      smlBuildInvalidDataMsg(msg, "float out of range[-3.402823466e+38,3.402823466e+38]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
721
    }
722 723
    kvVal->type = TSDB_DATA_TYPE_FLOAT;
    kvVal->f = (float)result;
X
Xiaoyu Wang 已提交
724 725
  } else if ((left == 1 && *endptr == 'i') || (left == 3 && strncasecmp(endptr, "i64", left) == 0)) {
    if (smlDoubleToInt64OverFlow(result)) {
wmmhello's avatar
wmmhello 已提交
726 727
      errno = 0;
      int64_t tmp = taosStr2Int64(pVal, &endptr, 10);
X
Xiaoyu Wang 已提交
728
      if (errno == ERANGE) {
wmmhello's avatar
wmmhello 已提交
729 730 731 732 733 734
        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 已提交
735
    }
736
    kvVal->type = TSDB_DATA_TYPE_BIGINT;
wmmhello's avatar
wmmhello 已提交
737
    kvVal->i = (int64_t)result;
wmmhello's avatar
wmmhello 已提交
738
  } else if ((left == 1 && *endptr == 'u') || (left == 3 && strncasecmp(endptr, "u64", left) == 0)) {
X
Xiaoyu Wang 已提交
739
    if (result >= (double)UINT64_MAX || result < 0) {
wmmhello's avatar
wmmhello 已提交
740 741
      errno = 0;
      uint64_t tmp = taosStr2UInt64(pVal, &endptr, 10);
X
Xiaoyu Wang 已提交
742
      if (errno == ERANGE || result < 0) {
wmmhello's avatar
wmmhello 已提交
743 744 745 746 747 748
        smlBuildInvalidDataMsg(msg, "unsigned big int out of range[0,18446744073709551615]", pVal);
        return false;
      }
      kvVal->type = TSDB_DATA_TYPE_UBIGINT;
      kvVal->u = tmp;
      return true;
749
    }
750
    kvVal->type = TSDB_DATA_TYPE_UBIGINT;
wmmhello's avatar
wmmhello 已提交
751
    kvVal->u = result;
X
Xiaoyu Wang 已提交
752 753
  } else if (left == 3 && strncasecmp(endptr, "i32", left) == 0) {
    if (!IS_VALID_INT(result)) {
754 755
      smlBuildInvalidDataMsg(msg, "int out of range[-2147483648,2147483647]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
756
    }
757 758
    kvVal->type = TSDB_DATA_TYPE_INT;
    kvVal->i = result;
X
Xiaoyu Wang 已提交
759 760
  } else if (left == 3 && strncasecmp(endptr, "u32", left) == 0) {
    if (!IS_VALID_UINT(result)) {
761 762
      smlBuildInvalidDataMsg(msg, "unsigned int out of range[0,4294967295]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
763
    }
764 765
    kvVal->type = TSDB_DATA_TYPE_UINT;
    kvVal->u = result;
X
Xiaoyu Wang 已提交
766 767
  } else if (left == 3 && strncasecmp(endptr, "i16", left) == 0) {
    if (!IS_VALID_SMALLINT(result)) {
768 769
      smlBuildInvalidDataMsg(msg, "small int our of range[-32768,32767]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
770
    }
771 772
    kvVal->type = TSDB_DATA_TYPE_SMALLINT;
    kvVal->i = result;
X
Xiaoyu Wang 已提交
773 774
  } else if (left == 3 && strncasecmp(endptr, "u16", left) == 0) {
    if (!IS_VALID_USMALLINT(result)) {
775 776
      smlBuildInvalidDataMsg(msg, "unsigned small int out of rang[0,65535]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
777
    }
778 779
    kvVal->type = TSDB_DATA_TYPE_USMALLINT;
    kvVal->u = result;
X
Xiaoyu Wang 已提交
780 781
  } else if (left == 2 && strncasecmp(endptr, "i8", left) == 0) {
    if (!IS_VALID_TINYINT(result)) {
782 783
      smlBuildInvalidDataMsg(msg, "tiny int out of range[-128,127]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
784
    }
785 786
    kvVal->type = TSDB_DATA_TYPE_TINYINT;
    kvVal->i = result;
X
Xiaoyu Wang 已提交
787 788
  } else if (left == 2 && strncasecmp(endptr, "u8", left) == 0) {
    if (!IS_VALID_UTINYINT(result)) {
789 790
      smlBuildInvalidDataMsg(msg, "unsigned tiny int out of range[0,255]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
791
    }
792 793
    kvVal->type = TSDB_DATA_TYPE_UTINYINT;
    kvVal->u = result;
X
Xiaoyu Wang 已提交
794
  } else {
795
    smlBuildInvalidDataMsg(msg, "invalid data", pVal);
wmmhello's avatar
wmmhello 已提交
796 797
    return false;
  }
798
  return true;
wmmhello's avatar
wmmhello 已提交
799 800
}

wmmhello's avatar
wmmhello 已提交
801
static bool smlParseBool(SSmlKv *kvVal) {
wmmhello's avatar
wmmhello 已提交
802
  const char *pVal = kvVal->value;
X
Xiaoyu Wang 已提交
803
  int32_t     len = kvVal->length;
804
  if ((len == 1) && (pVal[0] == 't' || pVal[0] == 'T')) {
805
    kvVal->i = TSDB_TRUE;
wmmhello's avatar
wmmhello 已提交
806 807 808
    return true;
  }

809
  if ((len == 1) && (pVal[0] == 'f' || pVal[0] == 'F')) {
810
    kvVal->i = TSDB_FALSE;
wmmhello's avatar
wmmhello 已提交
811 812 813
    return true;
  }

X
Xiaoyu Wang 已提交
814
  if ((len == 4) && !strncasecmp(pVal, "true", len)) {
815
    kvVal->i = TSDB_TRUE;
wmmhello's avatar
wmmhello 已提交
816 817
    return true;
  }
X
Xiaoyu Wang 已提交
818
  if ((len == 5) && !strncasecmp(pVal, "false", len)) {
819
    kvVal->i = TSDB_FALSE;
wmmhello's avatar
wmmhello 已提交
820 821 822 823 824
    return true;
  }
  return false;
}

wmmhello's avatar
wmmhello 已提交
825
static bool smlIsBinary(const char *pVal, uint16_t len) {
X
Xiaoyu Wang 已提交
826
  // binary: "abc"
wmmhello's avatar
wmmhello 已提交
827 828 829 830 831 832 833 834 835
  if (len < 2) {
    return false;
  }
  if (pVal[0] == '"' && pVal[len - 1] == '"') {
    return true;
  }
  return false;
}

wmmhello's avatar
wmmhello 已提交
836
static bool smlIsNchar(const char *pVal, uint16_t len) {
X
Xiaoyu Wang 已提交
837
  // nchar: L"abc"
wmmhello's avatar
wmmhello 已提交
838 839 840
  if (len < 3) {
    return false;
  }
wmmhello's avatar
wmmhello 已提交
841
  if (pVal[1] == '"' && pVal[len - 1] == '"' && (pVal[0] == 'l' || pVal[0] == 'L')) {
wmmhello's avatar
wmmhello 已提交
842 843 844 845
    return true;
  }
  return false;
}
846
/******************************* parse basic type function end **********************/
wmmhello's avatar
wmmhello 已提交
847

848
/******************************* time function **********************/
wmmhello's avatar
wmmhello 已提交
849 850 851 852
static int8_t precisionConvert[7] = {TSDB_TIME_PRECISION_NANO, TSDB_TIME_PRECISION_HOURS, TSDB_TIME_PRECISION_MINUTES,
                                     TSDB_TIME_PRECISION_SECONDS, TSDB_TIME_PRECISION_MILLI, TSDB_TIME_PRECISION_MICRO,
                                     TSDB_TIME_PRECISION_NANO};

853
static int64_t smlGetTimeValue(const char *value, int32_t len, int8_t type) {
X
Xiaoyu Wang 已提交
854
  char   *endPtr = NULL;
wafwerar's avatar
wafwerar 已提交
855
  int64_t tsInt64 = taosStr2Int64(value, &endPtr, 10);
X
Xiaoyu Wang 已提交
856
  if (value + len != endPtr) {
857
    return -1;
wmmhello's avatar
wmmhello 已提交
858
  }
859
  double ts = tsInt64;
860 861
  switch (type) {
    case TSDB_TIME_PRECISION_HOURS:
wmmhello's avatar
wmmhello 已提交
862 863
      ts *= NANOSECOND_PER_HOUR;
      tsInt64 *= NANOSECOND_PER_HOUR;
864 865
      break;
    case TSDB_TIME_PRECISION_MINUTES:
wmmhello's avatar
wmmhello 已提交
866 867
      ts *= NANOSECOND_PER_MINUTE;
      tsInt64 *= NANOSECOND_PER_MINUTE;
868 869
      break;
    case TSDB_TIME_PRECISION_SECONDS:
wmmhello's avatar
wmmhello 已提交
870 871
      ts *= NANOSECOND_PER_SEC;
      tsInt64 *= NANOSECOND_PER_SEC;
872 873
      break;
    case TSDB_TIME_PRECISION_MILLI:
wmmhello's avatar
wmmhello 已提交
874 875
      ts *= NANOSECOND_PER_MSEC;
      tsInt64 *= NANOSECOND_PER_MSEC;
876 877
      break;
    case TSDB_TIME_PRECISION_MICRO:
wmmhello's avatar
wmmhello 已提交
878 879
      ts *= NANOSECOND_PER_USEC;
      tsInt64 *= NANOSECOND_PER_USEC;
880 881 882 883 884
      break;
    case TSDB_TIME_PRECISION_NANO:
      break;
    default:
      ASSERT(0);
wmmhello's avatar
wmmhello 已提交
885
  }
X
Xiaoyu Wang 已提交
886
  if (ts >= (double)INT64_MAX || ts < 0) {
887
    return -1;
wmmhello's avatar
wmmhello 已提交
888 889
  }

890
  return tsInt64;
891 892 893 894 895 896
}

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) {
897
    return TSDB_TIME_PRECISION_MILLI;
898 899
  } else {
    return -1;
wmmhello's avatar
wmmhello 已提交
900
  }
901 902
}

X
Xiaoyu Wang 已提交
903 904
static int64_t smlParseInfluxTime(SSmlHandle *info, const char *data, int32_t len) {
  if (len == 0 || (len == 1 && data[0] == '0')) {
905
    return taosGetTimestampNs();
wmmhello's avatar
wmmhello 已提交
906 907
  }

wmmhello's avatar
wmmhello 已提交
908
  int8_t tsType = precisionConvert[info->precision];
909 910 911
  if (tsType == -1) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid timestamp precision", NULL);
    return -1;
wmmhello's avatar
wmmhello 已提交
912
  }
913 914

  int64_t ts = smlGetTimeValue(data, len, tsType);
X
Xiaoyu Wang 已提交
915
  if (ts == -1) {
916 917
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid timestamp", data);
    return -1;
wmmhello's avatar
wmmhello 已提交
918
  }
919 920 921
  return ts;
}

X
Xiaoyu Wang 已提交
922 923
static int64_t smlParseOpenTsdbTime(SSmlHandle *info, const char *data, int32_t len) {
  if (!data) {
924 925
    smlBuildInvalidDataMsg(&info->msgBuf, "timestamp can not be null", NULL);
    return -1;
wmmhello's avatar
wmmhello 已提交
926
  }
X
Xiaoyu Wang 已提交
927
  if (len == 1 && data[0] == '0') {
928 929
    return taosGetTimestampNs();
  }
930 931
  int8_t tsType = smlGetTsTypeByLen(len);
  if (tsType == -1) {
X
Xiaoyu Wang 已提交
932 933
    smlBuildInvalidDataMsg(&info->msgBuf,
                           "timestamp precision can only be seconds(10 digits) or milli seconds(13 digits)", data);
934 935 936
    return -1;
  }
  int64_t ts = smlGetTimeValue(data, len, tsType);
X
Xiaoyu Wang 已提交
937
  if (ts == -1) {
938 939 940 941 942 943
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid timestamp", data);
    return -1;
  }
  return ts;
}

X
Xiaoyu Wang 已提交
944
static int32_t smlParseTS(SSmlHandle *info, const char *data, int32_t len, SArray *cols) {
945
  int64_t ts = 0;
X
Xiaoyu Wang 已提交
946
  if (info->protocol == TSDB_SML_LINE_PROTOCOL) {
947
    //    uError("SML:data:%s,len:%d", data, len);
948
    ts = smlParseInfluxTime(info, data, len);
X
Xiaoyu Wang 已提交
949
  } else if (info->protocol == TSDB_SML_TELNET_PROTOCOL) {
950
    ts = smlParseOpenTsdbTime(info, data, len);
X
Xiaoyu Wang 已提交
951
  } else {
952
    ASSERT(0);
953
  }
wmmhello's avatar
wmmhello 已提交
954
  uDebug("SML:0x%" PRIx64 " smlParseTS:%" PRId64, info->id, ts);
955

956 957 958 959
  if (ts <= 0) {
    uError("SML:0x%" PRIx64 " smlParseTS error:%" PRId64, info->id, ts);
    return TSDB_CODE_INVALID_TIMESTAMP;
  }
960 961

  // add ts to
962 963 964 965 966 967
  SSmlKv kv = { .key = TS, .keyLen = TS_LEN, .i = ts, .type = TSDB_DATA_TYPE_TIMESTAMP, .length = (int16_t)tDataTypes[TSDB_DATA_TYPE_TIMESTAMP].bytes};
  if(info->dataFormat){
    kv.i = convertTimePrecision(kv.i, TSDB_TIME_PRECISION_NANO, info->currSTableMeta->tableInfo.precision);
    smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kv, 0);
  }else{
    taosArraySet(cols, 0, &kv);
968 969
  }

970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
  return TSDB_CODE_SUCCESS;
}
/******************************* time function end **********************/

/******************************* Sml struct related function **********************/
static SSmlTableInfo *smlBuildTableInfo(int numRows, const char* measure, int32_t measureLen) {
  SSmlTableInfo *tag = (SSmlTableInfo *)taosMemoryCalloc(sizeof(SSmlTableInfo), 1);
  if (!tag) {
    return NULL;
  }

  tag->sTableName = measure;
  tag->sTableNameLen = measureLen;

  tag->cols = taosArrayInit(numRows, POINTER_BYTES);
  if (tag->cols == NULL) {
    uError("SML:smlBuildTableInfo failed to allocate memory");
    goto cleanup;
  }

  tag->tags = taosArrayInit(16, sizeof(SSmlKv));
  if (tag->tags == NULL) {
    uError("SML:smlBuildTableInfo failed to allocate memory");
    goto cleanup;
  }
  return tag;

  cleanup:
  taosMemoryFree(tag);
  return NULL;
}

static int32_t smlCheckDupUnit(SHashObj *dumplicateKey, SArray *tags, SSmlMsgBuf *msg){
  for(int i = 0; i < taosArrayGetSize(tags); i++) {
    SSmlKv *tag = taosArrayGet(tags, i);
    if (smlCheckDuplicateKey(tag->key, tag->keyLen, dumplicateKey)) {
      smlBuildInvalidDataMsg(msg, "dumplicate key", tag->key);
      return TSDB_CODE_TSC_DUP_NAMES;
    }
  }
  return TSDB_CODE_SUCCESS;
}

static int32_t smlJudgeDupColName(SArray *cols, SArray *tags, SSmlMsgBuf *msg) {
  SHashObj *dumplicateKey = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  int ret = smlCheckDupUnit(dumplicateKey, cols, msg);
  if(ret != TSDB_CODE_SUCCESS){
    goto end;
  }
  ret = smlCheckDupUnit(dumplicateKey, tags, msg);
  if(ret != TSDB_CODE_SUCCESS){
    goto end;
  }

  end:
  taosHashCleanup(dumplicateKey);
  return ret;
}

static int32_t smlParseTableName(SArray *tags, char *childTableName) {
  size_t      childTableNameLen = strlen(tsSmlChildTableName);
  if (childTableNameLen <= 0) return TSDB_CODE_SUCCESS;

  for(int i = 0; i < taosArrayGetSize(tags); i++){
    SSmlKv *tag = taosArrayGet(tags, i);
    // handle child table name
    if (childTableNameLen == tag->keyLen && strncmp(tag->key, tsSmlChildTableName, tag->keyLen) == 0) {
      memset(childTableName, 0, TSDB_TABLE_NAME_LEN);
      strncpy(childTableName, tag->value, (tag->length < TSDB_TABLE_NAME_LEN ? tag->length : TSDB_TABLE_NAME_LEN));
      break;
    }
  }
wmmhello's avatar
wmmhello 已提交
1042

1043 1044 1045
  return TSDB_CODE_SUCCESS;
}

1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
static int32_t smlSetCTableName(SSmlTableInfo *oneTable){
  smlParseTableName(oneTable->tags, oneTable->childTableName);

  if (strlen(oneTable->childTableName) == 0) {
    RandTableName rName = {oneTable->tags, oneTable->sTableName, (uint8_t)oneTable->sTableNameLen,
                           oneTable->childTableName, 0};

    buildChildTableName(&rName);
    oneTable->uid = rName.uid;
  } else {
    oneTable->uid = *(uint64_t *)(oneTable->childTableName);
  }
  return TSDB_CODE_SUCCESS;
}

static SSmlSTableMeta *smlBuildSTableMeta(bool isDataFormat) {
  SSmlSTableMeta *meta = (SSmlSTableMeta *)taosMemoryCalloc(sizeof(SSmlSTableMeta), 1);
  if (!meta) {
    return NULL;
  }

  if(unlikely(!isDataFormat)){
    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;
    }

    meta->colHash = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
    if (meta->colHash == NULL) {
      uError("SML:smlBuildSTableMeta failed to allocate memory");
      goto cleanup;
    }
  }

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

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

  cleanup:
  taosMemoryFree(meta);
  return NULL;
}

static void smlInsertMeta(SHashObj *metaHash, SArray *metaArray, SArray *cols){
  for (int16_t i = 0; i < taosArrayGetSize(cols); ++i) {
    SSmlKv *kv = (SSmlKv *)taosArrayGet(cols, i);
1102
    taosArrayPush(metaArray, kv);
1103 1104 1105 1106 1107 1108
    if(unlikely(metaHash != NULL)) {
      taosHashPut(metaHash, kv->key, kv->keyLen, &i, SHORT_BYTES);
    }
  }
}

wmmhello's avatar
wmmhello 已提交
1109 1110
bool smlFormatJudge(NodeList **superTableKeyStr, void* preLineKeys, void* currentLineKeys,
                    SSmlLineInfo *currElements, bool isSameMeasure, int32_t len){
1111
  // same measure
wmmhello's avatar
wmmhello 已提交
1112
  if(isSameMeasure){
1113 1114 1115 1116 1117
    if(varDataTLen(preLineKeys) != varDataTLen(currentLineKeys)
       || memcmp(preLineKeys, currentLineKeys, varDataTLen(preLineKeys)) != 0){
      return false;
    }
  }else{  // diff measure
wmmhello's avatar
wmmhello 已提交
1118
    void *keyStr = nodeListGet(*superTableKeyStr, currElements->measure, currElements->measureLen);
1119 1120 1121
    if(unlikely(keyStr == NULL)){
      keyStr = taosMemoryMalloc(len);
      varDataCopy(keyStr, currentLineKeys);
wmmhello's avatar
wmmhello 已提交
1122
      nodeListSet(superTableKeyStr, currElements->measure, currElements->measureLen, keyStr);
1123 1124 1125 1126 1127 1128 1129
    }else{
      if(varDataTLen(keyStr) != varDataTLen(currentLineKeys)
         && memcmp(keyStr, currentLineKeys, varDataTLen(currentLineKeys)) != 0){
        return false;
      }
    }
  }
1130
  varDataCopy(preLineKeys, currentLineKeys);
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162

  return true;
}

static STableMeta* smlGetMeta(SSmlHandle *info, const void* measure, int32_t measureLen){
  STableMeta *pTableMeta = NULL;

  SName pName = {TSDB_TABLE_NAME_T, info->taos->acctId, {0}, {0}};
  tstrncpy(pName.dbname, info->pRequest->pDb, sizeof(pName.dbname));

  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);
  memset(pName.tname, 0, TSDB_TABLE_NAME_LEN);
  memcpy(pName.tname, measure, measureLen);

  catalogGetSTableMeta(info->pCatalog, &conn, &pName, &pTableMeta);
  return pTableMeta;
}

static void smlDestroySTableMeta(SSmlSTableMeta *meta) {
  taosHashCleanup(meta->tagHash);
  taosHashCleanup(meta->colHash);
  taosArrayDestroy(meta->tags);
  taosArrayDestroy(meta->cols);
  taosMemoryFree(meta->tableMeta);
  taosMemoryFree(meta);
}
/******************************* Sml struct related function end **********************/

wmmhello's avatar
wmmhello 已提交
1163
static int32_t smlParseValue(SSmlKv *pVal, SSmlMsgBuf *msg) {
X
Xiaoyu Wang 已提交
1164
  // binary
wmmhello's avatar
wmmhello 已提交
1165
  if (smlIsBinary(pVal->value, pVal->length)) {
1166
    pVal->type = TSDB_DATA_TYPE_BINARY;
wmmhello's avatar
wmmhello 已提交
1167
    pVal->length -= BINARY_ADD_LEN;
1168
    if (pVal->length > TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE) {
wmmhello's avatar
wmmhello 已提交
1169 1170
      return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
    }
1171
    pVal->value += (BINARY_ADD_LEN - 1);
wmmhello's avatar
wmmhello 已提交
1172
    return TSDB_CODE_SUCCESS;
1173
  }
X
Xiaoyu Wang 已提交
1174
  // nchar
wmmhello's avatar
wmmhello 已提交
1175
  if (smlIsNchar(pVal->value, pVal->length)) {
1176
    pVal->type = TSDB_DATA_TYPE_NCHAR;
wmmhello's avatar
wmmhello 已提交
1177
    pVal->length -= NCHAR_ADD_LEN;
1178
    if (pVal->length > (TSDB_MAX_NCHAR_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE) {
wmmhello's avatar
wmmhello 已提交
1179 1180
      return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
    }
1181
    pVal->value += (NCHAR_ADD_LEN - 1);
wmmhello's avatar
wmmhello 已提交
1182
    return TSDB_CODE_SUCCESS;
1183 1184
  }

X
Xiaoyu Wang 已提交
1185
  // bool
1186 1187 1188
  if (smlParseBool(pVal)) {
    pVal->type = TSDB_DATA_TYPE_BOOL;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
wmmhello's avatar
wmmhello 已提交
1189
    return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1190
  }
X
Xiaoyu Wang 已提交
1191
  // number
1192
  if (smlParseNumber(pVal, msg)) {
wmmhello's avatar
wmmhello 已提交
1193
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
wmmhello's avatar
wmmhello 已提交
1194
    return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1195 1196
  }

wmmhello's avatar
wmmhello 已提交
1197
  return TSDB_CODE_TSC_INVALID_VALUE;
wmmhello's avatar
wmmhello 已提交
1198 1199
}

1200 1201 1202 1203 1204 1205
static int32_t smlParseKv(SSmlHandle *info, const char **sql, const char *sqlEnd,
                          SSmlLineInfo* currElement, bool isTag){
  bool isSameMeasure = false;
  bool isSameCTable = false;
  int   cnt = 0;
  void *keyStr = NULL;
1206
//  bool isPreLineKVNULL = false;
1207 1208 1209 1210
  SArray *preLineKV = NULL;
  bool    isSuperKVInit = false;
  SArray *superKV = NULL;
  if(info->dataFormat){
wmmhello's avatar
wmmhello 已提交
1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
    if(currElement->measureTagsLen == info->preLine.measureTagsLen
       && memcmp(currElement->measure, info->preLine.measure, currElement->measureTagsLen) == 0){
      isSameCTable = true;
      if(isTag) return TSDB_CODE_SUCCESS;
    }else if(!isTag){
      SSmlTableInfo *oneTable = (SSmlTableInfo *)nodeListGet(info->childTables, currElement->measure, currElement->measureTagsLen);
      if (unlikely(oneTable == NULL)) {
        smlBuildInvalidDataMsg(&info->msgBuf, "child table should inside", currElement->measure);
        return TSDB_CODE_SML_INVALID_DATA;
      }
      info->currTableDataCtx = oneTable->tableDataCtx;
    }

    if(isSameCTable){
      isSameMeasure = true;
    }else if(currElement->measureLen == info->preLine.measureLen
         && memcmp(currElement->measure, info->preLine.measure, currElement->measureLen) == 0){
1228 1229 1230
      isSameMeasure = true;
    }

wmmhello's avatar
wmmhello 已提交
1231

1232
    if(!isSameMeasure){
wmmhello's avatar
wmmhello 已提交
1233 1234 1235 1236
      SSmlSTableMeta *sMeta = (SSmlSTableMeta *)nodeListGet(info->superTables, currElement->measure, currElement->measureLen);

      if(sMeta == NULL){
        sMeta = smlBuildSTableMeta(info->dataFormat);
1237
        STableMeta * pTableMeta = smlGetMeta(info, currElement->measure, currElement->measureLen);
wmmhello's avatar
wmmhello 已提交
1238
        sMeta->tableMeta = pTableMeta;
1239 1240 1241 1242 1243
        if(pTableMeta == NULL){
          info->dataFormat = false;
          info->reRun      = true;
          return TSDB_CODE_SUCCESS;
        }
wmmhello's avatar
wmmhello 已提交
1244
        nodeListSet(&info->superTables, currElement->measure, currElement->measureLen, sMeta);
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
      }
      info->currSTableMeta = sMeta->tableMeta;

      if(isTag){
        superKV = sMeta->tags;
      }else{
        superKV = sMeta->cols;
      }
      if(unlikely(taosArrayGetSize(superKV) == 0)){
        isSuperKVInit = true;
      }
    }

    if(isTag){
      // prepare for judging if tag or col is the same for each line
      if(unlikely(info->currentLineTagKeys == NULL)){   // sml todo size need remalloc
        info->currentLineTagKeys = taosMemoryMalloc(sqlEnd - *sql);
      }
1263 1264 1265 1266
      if(info->preLineTagKeys == NULL){
        info->preLineTagKeys = taosMemoryMalloc(sqlEnd - *sql);
      }
      keyStr = info->currentLineTagKeys;
1267 1268 1269

      if(info->preLineTagKV == NULL){
        info->preLineTagKV = taosArrayInit(8, sizeof(SSmlKv));
1270
//        isPreLineKVNULL = true;
1271 1272 1273 1274 1275 1276
      }
      preLineKV = info->preLineTagKV;
    }else{
      if(unlikely(info->currentLineColKeys == NULL)){   // sml todo size need remalloc
        info->currentLineColKeys = taosMemoryMalloc(sqlEnd - *sql);
      }
1277 1278 1279 1280 1281

      if(info->preLineColKeys == NULL){
        info->preLineColKeys = taosMemoryMalloc(sqlEnd - *sql);
      }
      keyStr = info->currentLineColKeys;
1282 1283 1284

      if(info->preLineColKV == NULL){
        info->preLineColKV = taosArrayInit(8, sizeof(SSmlKv));
1285
//        isPreLineKVNULL = true;
1286 1287 1288 1289 1290 1291 1292 1293
      }
      preLineKV = info->preLineColKV;
    }

    if(!isSameMeasure){
      taosArraySetSize(preLineKV, 0);
    }
    varDataLen(keyStr) = 0; // clear keys
1294 1295
  }else{
    preLineKV = taosArrayInit(8, sizeof(SSmlKv));
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324
  }

  while (*sql < sqlEnd) {
    if (IS_SPACE(*sql)) {
      break;
    }

    // parse key
    const char *key = *sql;
    int32_t     keyLen = 0;
    while (*sql < sqlEnd) {

      if (IS_COMMA(*sql)) {
        smlBuildInvalidDataMsg(&info->msgBuf, "invalid data", *sql);
        return TSDB_CODE_SML_INVALID_DATA;
      }
      if (IS_EQUAL(*sql)) {
        keyLen = *sql - key;
        (*sql)++;
        break;
      }
      (*sql)++;
    }

    if (IS_INVALID_COL_LEN(keyLen)) {
      smlBuildInvalidDataMsg(&info->msgBuf, "invalid key or key is too long than 64", key);
      return TSDB_CODE_TSC_INVALID_COLUMN_LENGTH;
    }

1325 1326 1327 1328
    if(info->dataFormat){
      memcpy(keyStr + varDataTLen(keyStr), key, keyLen + 1); // use = symbol
      varDataLen(keyStr) += keyLen + 1;
    }
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340

    // parse value
    const char *value = *sql;
    int32_t     valueLen = 0;
    bool        isInQuote = false;
    while (*sql < sqlEnd) {
      // parse value
      if (!isTag && IS_QUOTE(*sql)) {
        isInQuote = !isInQuote;
        (*sql)++;
        continue;
      }
wmmhello's avatar
wmmhello 已提交
1341 1342 1343 1344 1345 1346 1347 1348 1349
      if (!isInQuote){
        if (IS_SPACE(*sql)) {
          break;
        }else if (IS_COMMA(*sql)) {
          break;
        }else if (IS_EQUAL(*sql)) {
          smlBuildInvalidDataMsg(&info->msgBuf, "invalid data", *sql);
          return TSDB_CODE_SML_INVALID_DATA;
        }
1350
      }
wmmhello's avatar
wmmhello 已提交
1351

1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389
      (*sql)++;
    }
    valueLen = *sql - value;

    if (isInQuote) {
      smlBuildInvalidDataMsg(&info->msgBuf, "only one quote", value);
      return TSDB_CODE_SML_INVALID_DATA;
    }
    if (valueLen == 0) {
      smlBuildInvalidDataMsg(&info->msgBuf, "invalid value", value);
      return TSDB_CODE_SML_INVALID_DATA;
    }
    PROCESS_SLASH(key, keyLen)
    PROCESS_SLASH(value, valueLen)

    SSmlKv kv = {.key = key, .keyLen = keyLen, .value = value, .length = valueLen};
    if (!isTag) {
      int32_t ret = smlParseValue(&kv, &info->msgBuf);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }
    } else {
      if (valueLen > (TSDB_MAX_NCHAR_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE) {
        return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
      }
      kv.type = TSDB_DATA_TYPE_NCHAR;
    }

    if(info->dataFormat){
      if(!isTag && cnt + 1 > info->currSTableMeta->tableInfo.numOfColumns){
        smlBuildInvalidDataMsg(&info->msgBuf, "col more than meta", NULL);
        return TSDB_CODE_PAR_TOO_MANY_COLUMNS;
      }
      if(isTag && cnt + 1 > info->currSTableMeta->tableInfo.numOfTags){
        smlBuildInvalidDataMsg(&info->msgBuf, "tag more than meta", NULL);
        return TSDB_CODE_PAR_TOO_MANY_COLUMNS;
      }
      // bind data
1390 1391 1392 1393 1394 1395
      if(!isTag){
        int ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kv, cnt + 1);
        if (ret != TSDB_CODE_SUCCESS) {
          smlBuildInvalidDataMsg(&info->msgBuf, "smlBuildCol error", NULL);
          return ret;
        }
1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413
      }

      do {
        if(isSameMeasure){
          if(cnt >= taosArrayGetSize(preLineKV)) {
            info->dataFormat = false;
            info->reRun      = true;
            return TSDB_CODE_SUCCESS;
          }
          SSmlKv *preKV = taosArrayGet(preLineKV, cnt);
          if(!isTag && kv.type != preKV->type){
            info->dataFormat = false;
            info->reRun      = true;
            return TSDB_CODE_SUCCESS;
          }

          if(IS_VAR_DATA_TYPE(kv.type) && kv.length > preKV->length){
            preKV->length = kv.length;
wmmhello's avatar
wmmhello 已提交
1414
            SSmlSTableMeta *tableMeta = (SSmlSTableMeta *)nodeListGet(info->superTables, currElement->measure, currElement->measureLen);
1415 1416 1417 1418 1419 1420
            if(tableMeta == NULL){
              smlBuildInvalidDataMsg(&info->msgBuf, "measure should has inside", value);
              return TSDB_CODE_SML_INVALID_DATA;
            }

            if(isTag){
wmmhello's avatar
wmmhello 已提交
1421
              superKV = tableMeta->tags;
1422
            }else{
wmmhello's avatar
wmmhello 已提交
1423
              superKV = tableMeta->cols;
1424 1425 1426
            }
            SSmlKv *oldKV = taosArrayGet(superKV, cnt);
            oldKV->length = kv.length;
wmmhello's avatar
wmmhello 已提交
1427
            info->needModifySchema = true;
1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
          }
        }else{
          if(isSuperKVInit){
            taosArrayPush(superKV, &kv);
          }else{
            if(cnt >= taosArrayGetSize(superKV)) {
              info->dataFormat = false;
              info->reRun      = true;
              return TSDB_CODE_SUCCESS;
            }
            SSmlKv *preKV = taosArrayGet(superKV, cnt);
            if(!isTag && kv.type != preKV->type){
              info->dataFormat = false;
              info->reRun      = true;
              return TSDB_CODE_SUCCESS;
            }

            if(IS_VAR_DATA_TYPE(kv.type)){
              if(kv.length > preKV->length) {
                preKV->length = kv.length;
              }else{
                kv.length = preKV->length;
              }
wmmhello's avatar
wmmhello 已提交
1451
              info->needModifySchema = true;
1452 1453 1454 1455 1456 1457
            }
          }
          taosArrayPush(preLineKV, &kv);
        }
        break;
      }while(0);
1458 1459
    }else{
      taosArrayPush(preLineKV, &kv);
1460 1461 1462 1463 1464 1465 1466 1467 1468
    }

    if(!info->dataFormat && !isTag){
      if(currElement->colArray == NULL){
        currElement->colArray = taosArrayInit(16, sizeof(SSmlKv));
        taosArraySetSize(currElement->colArray, 1);
      }
      taosArrayPush(currElement->colArray, &kv);   //reserve for timestamp
    }
1469 1470 1471 1472 1473
    cnt++;
    if(IS_SPACE(*sql)){
      break;
    }
    (*sql)++;
1474 1475
  }

1476
  if(isTag && cnt > TSDB_MAX_TAGS){
1477 1478 1479 1480 1481 1482
    smlBuildInvalidDataMsg(&info->msgBuf, "too many tags than 128", NULL);
    return TSDB_CODE_PAR_INVALID_TAGS_NUM;
  }

  if(info->dataFormat){
    if(isTag){
wmmhello's avatar
wmmhello 已提交
1483 1484
      info->dataFormat = smlFormatJudge(&info->superTableTagKeyStr, info->preLineTagKeys,
                                        info->currentLineTagKeys, currElement, isSameMeasure, sqlEnd - currElement->tags);
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
      if(!info->dataFormat) {
        info->reRun = true;
        return TSDB_CODE_SUCCESS;
      }
      if(!isSameCTable){
        if(taosArrayGetSize(preLineKV) > TSDB_MAX_TAGS){
          smlBuildInvalidDataMsg(&info->msgBuf, "too many tags than 128", NULL);
          return TSDB_CODE_PAR_INVALID_TAGS_NUM;
        }

wmmhello's avatar
wmmhello 已提交
1495
        void* oneTable = nodeListGet(info->childTables, currElement->measure, currElement->measureTagsLen);
1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
        if (unlikely(oneTable == NULL)) {
          SSmlTableInfo *tinfo = smlBuildTableInfo(1, currElement->measure, currElement->measureLen);
          if (!tinfo) {
            return TSDB_CODE_OUT_OF_MEMORY;
          }
          for(int i = 0; i < taosArrayGetSize(preLineKV); i++){
            taosArrayPush(tinfo->tags, taosArrayGet(preLineKV, i));
          }
          smlSetCTableName(tinfo);
          info->currSTableMeta->uid = tinfo->uid;
          tinfo->tableDataCtx = smlInitTableDataCtx(info->pQuery, info->currSTableMeta);
1507 1508 1509 1510
          if(tinfo->tableDataCtx == NULL){
            smlBuildInvalidDataMsg(&info->msgBuf, "smlInitTableDataCtx error", NULL);
            return TSDB_CODE_SML_INVALID_DATA;
          }
wmmhello's avatar
wmmhello 已提交
1511
          nodeListSet(&info->childTables, currElement->measure, currElement->measureTagsLen, tinfo);
1512 1513 1514
        }
      }
    }else{
wmmhello's avatar
wmmhello 已提交
1515 1516
      info->dataFormat = smlFormatJudge(&info->superTableColKeyStr, info->preLineColKeys,
                                        info->currentLineColKeys, currElement, isSameMeasure, sqlEnd - currElement->cols);
1517 1518 1519 1520 1521 1522
      if(!info->dataFormat) {
        info->reRun = true;
        return TSDB_CODE_SUCCESS;
      }
    }
  }else{
wmmhello's avatar
wmmhello 已提交
1523
    void* oneTable = nodeListGet(info->childTables, currElement->measure, currElement->measureTagsLen);
1524
    if (unlikely(oneTable == NULL)) {
wmmhello's avatar
wmmhello 已提交
1525
      SSmlTableInfo *tinfo = smlBuildTableInfo(info->lineNum / 2, currElement->measure, currElement->measureLen);
1526 1527 1528 1529 1530 1531 1532
      if (!tinfo) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      for(int i = 0; i < taosArrayGetSize(preLineKV); i++){
        taosArrayPush(tinfo->tags, taosArrayGet(preLineKV, i));
      }
      smlSetCTableName(tinfo);
wmmhello's avatar
wmmhello 已提交
1533
      nodeListSet(&info->childTables, currElement->measure, currElement->measureTagsLen, tinfo);
1534
    }
1535
    taosArrayDestroy(preLineKV);      // smltodo
1536 1537 1538 1539 1540 1541
  }

  return TSDB_CODE_SUCCESS;
}

static int32_t smlParseInfluxString(SSmlHandle *info, const char *sql, const char *sqlEnd, SSmlLineInfo *elements) {
X
Xiaoyu Wang 已提交
1542
  if (!sql) return TSDB_CODE_SML_INVALID_DATA;
wmmhello's avatar
wmmhello 已提交
1543
  JUMP_SPACE(sql, sqlEnd)
X
Xiaoyu Wang 已提交
1544
  if (*sql == COMMA) return TSDB_CODE_SML_INVALID_DATA;
wmmhello's avatar
wmmhello 已提交
1545
  elements->measure = sql;
wmmhello's avatar
wmmhello 已提交
1546

wmmhello's avatar
wmmhello 已提交
1547
  // parse measure
wmmhello's avatar
wmmhello 已提交
1548
  while (sql < sqlEnd) {
X
Xiaoyu Wang 已提交
1549
    if ((sql != elements->measure) && IS_SLASH_LETTER(sql)) {
wmmhello's avatar
wmmhello 已提交
1550 1551
      MOVE_FORWARD_ONE(sql, sqlEnd - sql);
      sqlEnd--;
wmmhello's avatar
wmmhello 已提交
1552 1553
      continue;
    }
X
Xiaoyu Wang 已提交
1554
    if (IS_COMMA(sql)) {
wmmhello's avatar
wmmhello 已提交
1555 1556 1557
      break;
    }

X
Xiaoyu Wang 已提交
1558
    if (IS_SPACE(sql)) {
wmmhello's avatar
wmmhello 已提交
1559 1560
      break;
    }
wmmhello's avatar
wmmhello 已提交
1561 1562
    sql++;
  }
wmmhello's avatar
wmmhello 已提交
1563
  elements->measureLen = sql - elements->measure;
X
Xiaoyu Wang 已提交
1564
  if (IS_INVALID_TABLE_LEN(elements->measureLen)) {
1565
    smlBuildInvalidDataMsg(&info->msgBuf, "measure is empty or too large than 192", NULL);
wmmhello's avatar
wmmhello 已提交
1566
    return TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
wmmhello's avatar
wmmhello 已提交
1567
  }
wmmhello's avatar
wmmhello 已提交
1568

1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
  // to get measureTagsLen before
  const char* tmp = sql;
  while (tmp < sqlEnd){
    if (IS_SPACE(tmp)) {
      break;
    }
    tmp++;
  }
  elements->measureTagsLen = tmp - elements->measure;

wmmhello's avatar
wmmhello 已提交
1579
  // parse tag
X
Xiaoyu Wang 已提交
1580
  if (*sql == SPACE) {
wmmhello's avatar
wmmhello 已提交
1581
    elements->tagsLen = 0;
X
Xiaoyu Wang 已提交
1582 1583
  } else {
    if (*sql == COMMA) sql++;
wmmhello's avatar
wmmhello 已提交
1584
    elements->tags = sql;
1585 1586 1587 1588 1589

    // tinfo != NULL means child table has never occur before
    int ret = smlParseKv(info, &sql, sqlEnd, elements, true);
    if(ret != TSDB_CODE_SUCCESS){
      return ret;
wmmhello's avatar
wmmhello 已提交
1590
    }
1591 1592 1593 1594 1595 1596
    sql = elements->measure + elements->measureTagsLen;

    if(info->reRun){
      return TSDB_CODE_SUCCESS;
    }

wmmhello's avatar
wmmhello 已提交
1597
    elements->tagsLen = sql - elements->tags;
1598
  }
wmmhello's avatar
wmmhello 已提交
1599

wmmhello's avatar
wmmhello 已提交
1600
  // parse cols
wmmhello's avatar
wmmhello 已提交
1601
  JUMP_SPACE(sql, sqlEnd)
wmmhello's avatar
wmmhello 已提交
1602
  elements->cols = sql;
1603 1604 1605 1606

  int ret = smlParseKv(info, &sql, sqlEnd, elements, false);
  if(ret != TSDB_CODE_SUCCESS){
    return ret;
wmmhello's avatar
wmmhello 已提交
1607
  }
1608 1609 1610

  if(info->reRun){
    return TSDB_CODE_SUCCESS;
1611
  }
1612

wmmhello's avatar
wmmhello 已提交
1613
  elements->colsLen = sql - elements->cols;
X
Xiaoyu Wang 已提交
1614
  if (elements->colsLen == 0) {
1615
    smlBuildInvalidDataMsg(&info->msgBuf, "cols is empty", NULL);
wmmhello's avatar
wmmhello 已提交
1616 1617
    return TSDB_CODE_SML_INVALID_DATA;
  }
wmmhello's avatar
wmmhello 已提交
1618

wmmhello's avatar
wmmhello 已提交
1619
  // parse timestamp
wmmhello's avatar
wmmhello 已提交
1620
  JUMP_SPACE(sql, sqlEnd)
wmmhello's avatar
wmmhello 已提交
1621
  elements->timestamp = sql;
wmmhello's avatar
wmmhello 已提交
1622 1623
  while (sql < sqlEnd) {
    if (isspace(*sql)) {
wmmhello's avatar
wmmhello 已提交
1624 1625 1626 1627
      break;
    }
    sql++;
  }
wmmhello's avatar
wmmhello 已提交
1628
  elements->timestampLen = sql - elements->timestamp;
wmmhello's avatar
wmmhello 已提交
1629

1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
  ret = smlParseTS(info, elements->timestamp, elements->timestampLen, elements->colArray);
  if (ret != TSDB_CODE_SUCCESS) {
    uError("SML:0x%" PRIx64 " smlParseTS failed", info->id);
    return ret;
  }

  if(info->dataFormat){
    smlBuildRow(info->currTableDataCtx);
    info->preLine = *elements;
  }

wmmhello's avatar
wmmhello 已提交
1641 1642 1643
  return TSDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
1644 1645
static void smlParseTelnetElement(const char **sql, const char *sqlEnd, const char **data, int32_t *len) {
  while (*sql < sqlEnd) {
X
Xiaoyu Wang 已提交
1646
    if (**sql != SPACE && !(*data)) {
1647
      *data = *sql;
X
Xiaoyu Wang 已提交
1648
    } else if (**sql == SPACE && *data) {
1649 1650 1651 1652 1653 1654 1655
      *len = *sql - *data;
      break;
    }
    (*sql)++;
  }
}

dengyihao's avatar
dengyihao 已提交
1656 1657 1658
static int32_t smlParseTelnetTags(const char *data, const char *sqlEnd, SArray *cols, char *childTableName,
                                  SHashObj *dumplicateKey, SSmlMsgBuf *msg) {
  if (!cols) return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
1659
  const char *sql = data;
X
Xiaoyu Wang 已提交
1660
  size_t      childTableNameLen = strlen(tsSmlChildTableName);
wmmhello's avatar
wmmhello 已提交
1661 1662
  while (sql < sqlEnd) {
    JUMP_SPACE(sql, sqlEnd)
X
Xiaoyu Wang 已提交
1663
    if (*sql == '\0') break;
wmmhello's avatar
wmmhello 已提交
1664

wmmhello's avatar
wmmhello 已提交
1665
    const char *key = sql;
X
Xiaoyu Wang 已提交
1666
    int32_t     keyLen = 0;
wmmhello's avatar
wmmhello 已提交
1667 1668

    // parse key
wmmhello's avatar
wmmhello 已提交
1669
    while (sql < sqlEnd) {
X
Xiaoyu Wang 已提交
1670
      if (*sql == SPACE) {
wmmhello's avatar
wmmhello 已提交
1671 1672 1673
        smlBuildInvalidDataMsg(msg, "invalid data", sql);
        return TSDB_CODE_SML_INVALID_DATA;
      }
X
Xiaoyu Wang 已提交
1674
      if (*sql == EQUAL) {
wmmhello's avatar
wmmhello 已提交
1675 1676
        keyLen = sql - key;
        sql++;
1677 1678
        break;
      }
wmmhello's avatar
wmmhello 已提交
1679
      sql++;
1680
    }
wmmhello's avatar
wmmhello 已提交
1681

X
Xiaoyu Wang 已提交
1682
    if (IS_INVALID_COL_LEN(keyLen)) {
1683
      smlBuildInvalidDataMsg(msg, "invalid key or key is too long than 64", key);
wmmhello's avatar
wmmhello 已提交
1684
      return TSDB_CODE_TSC_INVALID_COLUMN_LENGTH;
1685
    }
X
Xiaoyu Wang 已提交
1686
    if (smlCheckDuplicateKey(key, keyLen, dumplicateKey)) {
1687
      smlBuildInvalidDataMsg(msg, "dumplicate key", key);
wmmhello's avatar
wmmhello 已提交
1688
      return TSDB_CODE_TSC_DUP_NAMES;
1689 1690 1691
    }

    // parse value
wmmhello's avatar
wmmhello 已提交
1692
    const char *value = sql;
X
Xiaoyu Wang 已提交
1693
    int32_t     valueLen = 0;
wmmhello's avatar
wmmhello 已提交
1694
    while (sql < sqlEnd) {
wmmhello's avatar
wmmhello 已提交
1695 1696
      // parse value
      if (*sql == SPACE) {
1697 1698
        break;
      }
wmmhello's avatar
wmmhello 已提交
1699 1700 1701 1702 1703
      if (*sql == EQUAL) {
        smlBuildInvalidDataMsg(msg, "invalid data", sql);
        return TSDB_CODE_SML_INVALID_DATA;
      }
      sql++;
1704
    }
wmmhello's avatar
wmmhello 已提交
1705
    valueLen = sql - value;
wmmhello's avatar
wmmhello 已提交
1706

X
Xiaoyu Wang 已提交
1707
    if (valueLen == 0) {
1708
      smlBuildInvalidDataMsg(msg, "invalid value", value);
wmmhello's avatar
wmmhello 已提交
1709
      return TSDB_CODE_TSC_INVALID_VALUE;
1710
    }
wmmhello's avatar
wmmhello 已提交
1711

X
Xiaoyu Wang 已提交
1712 1713
    // handle child table name
    if (childTableNameLen != 0 && strncmp(key, tsSmlChildTableName, keyLen) == 0) {
1714 1715 1716 1717 1718
      memset(childTableName, 0, TSDB_TABLE_NAME_LEN);
      strncpy(childTableName, value, (valueLen < TSDB_TABLE_NAME_LEN ? valueLen : TSDB_TABLE_NAME_LEN));
      continue;
    }

1719
    if (valueLen > (TSDB_MAX_NCHAR_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE) {
wmmhello's avatar
wmmhello 已提交
1720 1721 1722
      return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
    }

1723 1724
    // add kv to SSmlKv
    SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
X
Xiaoyu Wang 已提交
1725
    if (!kv) return TSDB_CODE_OUT_OF_MEMORY;
1726 1727 1728
    kv->key = key;
    kv->keyLen = keyLen;
    kv->value = value;
wmmhello's avatar
wmmhello 已提交
1729
    kv->length = valueLen;
wmmhello's avatar
wmmhello 已提交
1730
    kv->type = TSDB_DATA_TYPE_NCHAR;
1731

wmmhello's avatar
wmmhello 已提交
1732
    taosArrayPush(cols, &kv);
1733 1734 1735 1736
  }

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

1738
// format: <metric> <timestamp> <value> <tagk_1>=<tagv_1>[ <tagk_n>=<tagv_n>]
dengyihao's avatar
dengyihao 已提交
1739 1740
static int32_t smlParseTelnetString(SSmlHandle *info, const char *sql, const char *sqlEnd, SSmlTableInfo *tinfo,
                                    SArray *cols) {
X
Xiaoyu Wang 已提交
1741
  if (!sql) return TSDB_CODE_SML_INVALID_DATA;
1742 1743

  // parse metric
wmmhello's avatar
wmmhello 已提交
1744
  smlParseTelnetElement(&sql, sqlEnd, &tinfo->sTableName, &tinfo->sTableNameLen);
1745
  if (!(tinfo->sTableName) || IS_INVALID_TABLE_LEN(tinfo->sTableNameLen)) {
1746
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid data", sql);
wmmhello's avatar
wmmhello 已提交
1747
    return TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
1748 1749 1750 1751
  }

  // parse timestamp
  const char *timestamp = NULL;
X
Xiaoyu Wang 已提交
1752
  int32_t     tLen = 0;
wmmhello's avatar
wmmhello 已提交
1753
  smlParseTelnetElement(&sql, sqlEnd, &timestamp, &tLen);
1754 1755 1756 1757 1758 1759 1760 1761
  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 已提交
1762
    return ret;
1763 1764 1765 1766
  }

  // parse value
  const char *value = NULL;
1767 1768 1769 1770 1771 1772
  int32_t     valueLen = 0;
  smlParseTelnetElement(&sql, sqlEnd, &value, &valueLen);
  if (!value || valueLen == 0) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid value", sql);
    return TSDB_CODE_TSC_INVALID_VALUE;
  }
1773

1774 1775 1776 1777 1778 1779 1780 1781 1782 1783
  SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
  if (!kv) return TSDB_CODE_OUT_OF_MEMORY;
  taosArrayPush(cols, &kv);
  kv->key = VALUE;
  kv->keyLen = VALUE_LEN;
  kv->value = value;
  kv->length = valueLen;
  if ((ret = smlParseValue(kv, &info->msgBuf)) != TSDB_CODE_SUCCESS) {
    return ret;
  }
1784

wmmhello's avatar
wmmhello 已提交
1785 1786 1787
  // parse tags  sml todo
  ret = smlParseTelnetTags(sql, sqlEnd, tinfo->tags, tinfo->childTableName, NULL, &info->msgBuf);
//  ret = smlParseTelnetTags(sql, sqlEnd, tinfo->tags, tinfo->childTableName, info->dumplicateKey, &info->msgBuf);
1788 1789 1790
  if (ret != TSDB_CODE_SUCCESS) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid data", sql);
    return ret;
wmmhello's avatar
wmmhello 已提交
1791
  }
wmmhello's avatar
wmmhello 已提交
1792

wmmhello's avatar
wmmhello 已提交
1793 1794 1795
  return TSDB_CODE_SUCCESS;
}

1796
static int32_t smlUpdateMeta(SHashObj *metaHash, SArray *metaArray, SArray *cols, bool isTag, SSmlMsgBuf *msg) {
wmmhello's avatar
wmmhello 已提交
1797
  for (int i = 0; i < taosArrayGetSize(cols); ++i) {
1798
    SSmlKv *kv = (SSmlKv *)taosArrayGet(cols, i);
wmmhello's avatar
wmmhello 已提交
1799

wmmhello's avatar
wmmhello 已提交
1800
    int16_t *index = (int16_t *)taosHashGet(metaHash, kv->key, kv->keyLen);
X
Xiaoyu Wang 已提交
1801
    if (index) {
1802 1803 1804 1805 1806 1807 1808 1809
      SSmlKv *value = (SSmlKv *)taosArrayGet(metaArray, *index);
      if (isTag){
        if (kv->length > value->length) {
          value->length = kv->length;
        }
        continue;
      }
      if (kv->type != value->type) {
wmmhello's avatar
wmmhello 已提交
1810
        smlBuildInvalidDataMsg(msg, "the type is not the same like before", kv->key);
wmmhello's avatar
wmmhello 已提交
1811
        return TSDB_CODE_SML_NOT_SAME_TYPE;
1812 1813 1814 1815
      }

      if (IS_VAR_DATA_TYPE(kv->type) && (kv->length > value->length)) {  // update string len, if bigger
        value->length = kv->length;
1816
      }
X
Xiaoyu Wang 已提交
1817
    } else {
wmmhello's avatar
wmmhello 已提交
1818 1819 1820 1821 1822
      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);
1823
    }
wmmhello's avatar
wmmhello 已提交
1824
  }
wmmhello's avatar
wmmhello 已提交
1825

wmmhello's avatar
wmmhello 已提交
1826
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1827 1828
}

wmmhello's avatar
wmmhello 已提交
1829
static void smlDestroyTableInfo(SSmlTableInfo *tag) {
1830 1831 1832
  for (size_t i = 0; i < taosArrayGetSize(tag->cols); i++) {
    SHashObj *kvHash = (SHashObj *)taosArrayGetP(tag->cols, i);
    taosHashCleanup(kvHash);
wmmhello's avatar
wmmhello 已提交
1833
  }
1834

1835 1836 1837 1838 1839
  taosArrayDestroy(tag->cols);
  taosArrayDestroy(tag->tags);
  taosMemoryFree(tag);
}

1840
static int32_t smlPushCols(SArray *colsArray, SArray *cols) {
1841
  SHashObj *kvHash = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
X
Xiaoyu Wang 已提交
1842
  if (!kvHash) {
1843
    uError("SML:smlDealCols failed to allocate memory");
1844
    return TSDB_CODE_OUT_OF_MEMORY;
1845
  }
X
Xiaoyu Wang 已提交
1846
  for (size_t i = 0; i < taosArrayGetSize(cols); i++) {
1847
    SSmlKv *kv = (SSmlKv *)taosArrayGet(cols, i);
wmmhello's avatar
wmmhello 已提交
1848
    taosHashPut(kvHash, kv->key, kv->keyLen, &kv, POINTER_BYTES);
1849 1850
  }

1851
  taosArrayPush(colsArray, &kvHash);
1852 1853 1854
  return TSDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
1855 1856
void smlDestroyInfo(SSmlHandle *info) {
  if (!info) return;
1857 1858 1859
  qDestroyQuery(info->pQuery);

  // destroy info->childTables
wmmhello's avatar
wmmhello 已提交
1860 1861 1862 1863 1864 1865 1866 1867
  NodeList* tmp = info->childTables;
  while (tmp) {
    if(tmp->data.used) {
      smlDestroyTableInfo(tmp->data.value);
    }
    NodeList* t = tmp->next;
    taosMemoryFree(tmp);
    tmp = t;
1868 1869 1870
  }

  // destroy info->superTables
wmmhello's avatar
wmmhello 已提交
1871 1872 1873 1874 1875 1876 1877 1878
  tmp = info->superTables;
  while (tmp) {
    if(tmp->data.used) {
      smlDestroySTableMeta(tmp->data.value);
    }
    NodeList* t = tmp->next;
    taosMemoryFree(tmp);
    tmp = t;
1879 1880 1881 1882
  }

  // destroy info->pVgHash
  taosHashCleanup(info->pVgHash);
wmmhello's avatar
wmmhello 已提交
1883

wmmhello's avatar
wmmhello 已提交
1884 1885 1886 1887 1888 1889 1890 1891
  tmp = info->superTableTagKeyStr;
  while (tmp) {
    if(tmp->data.used) {
      taosMemoryFree(tmp->data.value);
    }
    NodeList* t = tmp->next;
    taosMemoryFree(tmp);
    tmp = tmp->next;
1892 1893
  }

wmmhello's avatar
wmmhello 已提交
1894 1895 1896 1897 1898 1899 1900 1901
  tmp = info->superTableColKeyStr;
  while (tmp) {
    if(tmp->data.used) {
      taosMemoryFree(tmp->data.value);
    }
    NodeList* t = tmp->next;
    taosMemoryFree(tmp);
    tmp = tmp->next;
1902 1903
  }

1904 1905 1906 1907 1908 1909 1910
  taosMemoryFree(info->currentLineTagKeys);
  taosMemoryFree(info->preLineTagKeys);
  taosMemoryFree(info->currentLineColKeys);
  taosMemoryFree(info->preLineColKeys);
  taosArrayDestroy(info->preLineTagKV);
  taosArrayDestroy(info->preLineColKV);

wmmhello's avatar
wmmhello 已提交
1911 1912 1913 1914
  if(!info->dataFormat){
    for(int i = 0; i < info->lineNum; i++){
      taosArrayDestroy(info->lines[i].colArray);
    }
wmmhello's avatar
wmmhello 已提交
1915
    taosMemoryFree(info->lines);
wmmhello's avatar
wmmhello 已提交
1916
  }
wmmhello's avatar
wmmhello 已提交
1917

wmmhello's avatar
wmmhello 已提交
1918
  cJSON_Delete(info->root);
wmmhello's avatar
wmmhello 已提交
1919
  taosMemoryFreeClear(info);
wmmhello's avatar
wmmhello 已提交
1920
}
1921

wmmhello's avatar
wmmhello 已提交
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933
static SSmlHandle *smlBuildSmlInfo(TAOS *taos) {
  int32_t     code = TSDB_CODE_SUCCESS;
  SSmlHandle *info = (SSmlHandle *)taosMemoryCalloc(1, sizeof(SSmlHandle));
  if (NULL == info) {
    return NULL;
  }
  info->taos = acquireTscObj(*(int64_t *)taos);
  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;
  }
X
Xiaoyu Wang 已提交
1934
  info->pVgHash = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_NO_LOCK);
wmmhello's avatar
wmmhello 已提交
1935 1936 1937
  info->id = smlGenId();
  info->pQuery = smlInitHandle();
  info->dataFormat = true;
1938

wmmhello's avatar
wmmhello 已提交
1939 1940
  if (NULL == info->pVgHash) {
    uError("create SSmlHandle failed");
1941 1942 1943 1944
    goto cleanup;
  }

  return info;
wmmhello's avatar
wmmhello 已提交
1945 1946

cleanup:
1947 1948 1949 1950 1951 1952 1953 1954
  smlDestroyInfo(info);
  return NULL;
}

/************* TSDB_SML_JSON_PROTOCOL function start **************/
static int32_t smlParseMetricFromJSON(SSmlHandle *info, cJSON *root, SSmlTableInfo *tinfo) {
  cJSON *metric = cJSON_GetObjectItem(root, "metric");
  if (!cJSON_IsString(metric)) {
X
Xiaoyu Wang 已提交
1955
    return TSDB_CODE_TSC_INVALID_JSON;
1956 1957 1958
  }

  tinfo->sTableNameLen = strlen(metric->valuestring);
1959
  if (IS_INVALID_TABLE_LEN(tinfo->sTableNameLen)) {
X
Xiaoyu Wang 已提交
1960
    uError("OTD:0x%" PRIx64 " Metric lenght is 0 or large than 192", info->id);
1961 1962 1963
    return TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
  }

wmmhello's avatar
wmmhello 已提交
1964 1965
  tinfo->sTableName = metric->valuestring;
  return TSDB_CODE_SUCCESS;
1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984
}

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 已提交
1985
  if (smlDoubleToInt64OverFlow(timeDouble)) {
1986
    smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
1987
    return TSDB_CODE_INVALID_TIMESTAMP;
1988
  }
wmmhello's avatar
wmmhello 已提交
1989 1990 1991 1992 1993 1994 1995 1996

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

  if (timeDouble < 0) {
    return TSDB_CODE_INVALID_TIMESTAMP;
1997 1998
  }

1999
  *tsVal = timeDouble;
2000
  size_t typeLen = strlen(type->valuestring);
wmmhello's avatar
wmmhello 已提交
2001
  if (typeLen == 1 && (type->valuestring[0] == 's' || type->valuestring[0] == 'S')) {
X
Xiaoyu Wang 已提交
2002
    // seconds
2003 2004
    *tsVal = *tsVal * NANOSECOND_PER_SEC;
    timeDouble = timeDouble * NANOSECOND_PER_SEC;
X
Xiaoyu Wang 已提交
2005
    if (smlDoubleToInt64OverFlow(timeDouble)) {
2006
      smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
2007
      return TSDB_CODE_INVALID_TIMESTAMP;
2008
    }
wmmhello's avatar
wmmhello 已提交
2009
  } else if (typeLen == 2 && (type->valuestring[1] == 's' || type->valuestring[1] == 'S')) {
2010 2011
    switch (type->valuestring[0]) {
      case 'm':
wmmhello's avatar
wmmhello 已提交
2012
      case 'M':
X
Xiaoyu Wang 已提交
2013
        // milliseconds
2014 2015
        *tsVal = *tsVal * NANOSECOND_PER_MSEC;
        timeDouble = timeDouble * NANOSECOND_PER_MSEC;
X
Xiaoyu Wang 已提交
2016
        if (smlDoubleToInt64OverFlow(timeDouble)) {
2017
          smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
2018
          return TSDB_CODE_INVALID_TIMESTAMP;
2019 2020 2021
        }
        break;
      case 'u':
wmmhello's avatar
wmmhello 已提交
2022
      case 'U':
X
Xiaoyu Wang 已提交
2023
        // microseconds
2024 2025
        *tsVal = *tsVal * NANOSECOND_PER_USEC;
        timeDouble = timeDouble * NANOSECOND_PER_USEC;
X
Xiaoyu Wang 已提交
2026
        if (smlDoubleToInt64OverFlow(timeDouble)) {
2027
          smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
2028
          return TSDB_CODE_INVALID_TIMESTAMP;
2029 2030 2031
        }
        break;
      case 'n':
wmmhello's avatar
wmmhello 已提交
2032
      case 'N':
2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
        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 已提交
2054
  // Timestamp must be the first KV to parse
2055 2056 2057 2058
  int64_t tsVal = 0;

  cJSON *timestamp = cJSON_GetObjectItem(root, "timestamp");
  if (cJSON_IsNumber(timestamp)) {
X
Xiaoyu Wang 已提交
2059
    // timestamp value 0 indicates current system time
2060
    double timeDouble = timestamp->valuedouble;
X
Xiaoyu Wang 已提交
2061
    if (smlDoubleToInt64OverFlow(timeDouble)) {
2062
      smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
2063
      return TSDB_CODE_INVALID_TIMESTAMP;
2064
    }
wmmhello's avatar
wmmhello 已提交
2065

X
Xiaoyu Wang 已提交
2066
    if (timeDouble < 0) {
wmmhello's avatar
wmmhello 已提交
2067
      return TSDB_CODE_INVALID_TIMESTAMP;
2068
    }
2069

2070
    uint8_t tsLen = smlGetTimestampLen((int64_t)timeDouble);
2071
    tsVal = (int64_t)timeDouble;
2072
    if (tsLen == TSDB_TIME_PRECISION_SEC_DIGITS) {
2073 2074
      tsVal = tsVal * NANOSECOND_PER_SEC;
      timeDouble = timeDouble * NANOSECOND_PER_SEC;
X
Xiaoyu Wang 已提交
2075
      if (smlDoubleToInt64OverFlow(timeDouble)) {
2076
        smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
2077
        return TSDB_CODE_INVALID_TIMESTAMP;
2078 2079
      }
    } else if (tsLen == TSDB_TIME_PRECISION_MILLI_DIGITS) {
2080 2081
      tsVal = tsVal * NANOSECOND_PER_MSEC;
      timeDouble = timeDouble * NANOSECOND_PER_MSEC;
X
Xiaoyu Wang 已提交
2082
      if (smlDoubleToInt64OverFlow(timeDouble)) {
2083
        smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
wmmhello's avatar
wmmhello 已提交
2084
        return TSDB_CODE_INVALID_TIMESTAMP;
2085
      }
X
Xiaoyu Wang 已提交
2086
    } else if (timeDouble == 0) {
wmmhello's avatar
wmmhello 已提交
2087
      tsVal = taosGetTimestampNs();
X
Xiaoyu Wang 已提交
2088
    } else {
wmmhello's avatar
wmmhello 已提交
2089
      return TSDB_CODE_INVALID_TIMESTAMP;
2090 2091 2092 2093
    }
  } else if (cJSON_IsObject(timestamp)) {
    int32_t ret = smlParseTSFromJSONObj(info, timestamp, &tsVal);
    if (ret != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
2094
      uError("SML:0x%" PRIx64 " Failed to parse timestamp from JSON Obj", info->id);
2095 2096 2097 2098
      return ret;
    }
  } else {
    return TSDB_CODE_TSC_INVALID_JSON;
wmmhello's avatar
wmmhello 已提交
2099 2100
  }

wmmhello's avatar
wmmhello 已提交
2101
  // add ts to
2102 2103 2104
  SSmlKv kv = {.key = TS, .keyLen = TS_LEN, .i = tsVal,
               .type = TSDB_DATA_TYPE_TIMESTAMP, .length = (int16_t)tDataTypes[TSDB_DATA_TYPE_TIMESTAMP].bytes};

wmmhello's avatar
wmmhello 已提交
2105
  taosArrayPush(cols, &kv);
wmmhello's avatar
wmmhello 已提交
2106 2107 2108
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
2109
static int32_t smlConvertJSONBool(SSmlKv *pVal, char *typeStr, cJSON *value) {
2110 2111 2112 2113 2114 2115 2116
  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 已提交
2117

2118 2119
  return TSDB_CODE_SUCCESS;
}
wmmhello's avatar
wmmhello 已提交
2120

X
Xiaoyu Wang 已提交
2121 2122 2123
static int32_t smlConvertJSONNumber(SSmlKv *pVal, char *typeStr, cJSON *value) {
  // tinyint
  if (strcasecmp(typeStr, "i8") == 0 || strcasecmp(typeStr, "tinyint") == 0) {
2124 2125 2126 2127 2128 2129 2130 2131 2132
    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 已提交
2133 2134
  // smallint
  if (strcasecmp(typeStr, "i16") == 0 || strcasecmp(typeStr, "smallint") == 0) {
2135 2136 2137 2138 2139 2140 2141 2142 2143
    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 已提交
2144 2145
  // int
  if (strcasecmp(typeStr, "i32") == 0 || strcasecmp(typeStr, "int") == 0) {
2146 2147 2148 2149 2150 2151 2152 2153 2154
    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 已提交
2155 2156
  // bigint
  if (strcasecmp(typeStr, "i64") == 0 || strcasecmp(typeStr, "bigint") == 0) {
2157 2158
    pVal->type = TSDB_DATA_TYPE_BIGINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
X
Xiaoyu Wang 已提交
2159
    if (value->valuedouble >= (double)INT64_MAX) {
2160
      pVal->i = INT64_MAX;
X
Xiaoyu Wang 已提交
2161
    } else if (value->valuedouble <= (double)INT64_MIN) {
2162
      pVal->i = INT64_MIN;
X
Xiaoyu Wang 已提交
2163
    } else {
2164
      pVal->i = value->valuedouble;
2165 2166 2167
    }
    return TSDB_CODE_SUCCESS;
  }
X
Xiaoyu Wang 已提交
2168 2169
  // float
  if (strcasecmp(typeStr, "f32") == 0 || strcasecmp(typeStr, "float") == 0) {
2170 2171 2172
    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 已提交
2173
    }
2174 2175 2176 2177 2178
    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 已提交
2179 2180
  // double
  if (strcasecmp(typeStr, "f64") == 0 || strcasecmp(typeStr, "double") == 0) {
2181 2182 2183 2184
    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 已提交
2185 2186
  }

X
Xiaoyu Wang 已提交
2187
  // if reach here means type is unsupported
2188 2189 2190
  uError("OTD:invalid type(%s) for JSON Number", typeStr);
  return TSDB_CODE_TSC_INVALID_JSON_TYPE;
}
2191

X
Xiaoyu Wang 已提交
2192
static int32_t smlConvertJSONString(SSmlKv *pVal, char *typeStr, cJSON *value) {
2193 2194 2195 2196 2197 2198 2199 2200 2201
  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 已提交
2202

2203
  if (pVal->type == TSDB_DATA_TYPE_BINARY && pVal->length > TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE) {
wmmhello's avatar
wmmhello 已提交
2204 2205
    return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
  }
2206 2207
  if (pVal->type == TSDB_DATA_TYPE_NCHAR &&
      pVal->length > (TSDB_MAX_NCHAR_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE) {
wmmhello's avatar
wmmhello 已提交
2208 2209 2210
    return TSDB_CODE_PAR_INVALID_VAR_COLUMN_LEN;
  }

wmmhello's avatar
wmmhello 已提交
2211 2212
  pVal->value = value->valuestring;
  return TSDB_CODE_SUCCESS;
2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238
}

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 已提交
2239
      }
2240
      break;
wmmhello's avatar
wmmhello 已提交
2241
    }
2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257
    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 已提交
2258
  }
2259 2260

  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
2261 2262
}

2263 2264 2265 2266 2267 2268 2269 2270
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 已提交
2271
    }
2272 2273 2274 2275 2276 2277 2278 2279 2280 2281
    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 已提交
2282

X
Xiaoyu Wang 已提交
2283
      char *tsDefaultJSONStrType = "nchar";  // todo
2284 2285
      smlConvertJSONString(kv, tsDefaultJSONStrType, root);
      break;
wmmhello's avatar
wmmhello 已提交
2286
    }
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296
    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 已提交
2297
  }
2298 2299 2300 2301 2302

  return TSDB_CODE_SUCCESS;
}

static int32_t smlParseColsFromJSON(cJSON *root, SArray *cols) {
dengyihao's avatar
dengyihao 已提交
2303
  if (!cols) return TSDB_CODE_OUT_OF_MEMORY;
2304 2305 2306 2307 2308
  cJSON *metricVal = cJSON_GetObjectItem(root, "value");
  if (metricVal == NULL) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }

2309 2310
  SSmlKv kv = {.key = VALUE, .keyLen = VALUE_LEN};
  int32_t ret = smlParseValueFromJSON(metricVal, &kv);
2311 2312 2313
  if (ret != TSDB_CODE_SUCCESS) {
    return ret;
  }
2314 2315
  taosArrayPush(cols, &kv);

2316
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
2317 2318
}

X
Xiaoyu Wang 已提交
2319 2320
static int32_t smlParseTagsFromJSON(cJSON *root, SArray *pKVs, char *childTableName, SHashObj *dumplicateKey,
                                    SSmlMsgBuf *msg) {
2321
  int32_t ret = TSDB_CODE_SUCCESS;
dengyihao's avatar
dengyihao 已提交
2322
  if (!pKVs) {
wmmhello's avatar
wmmhello 已提交
2323 2324
    return TSDB_CODE_OUT_OF_MEMORY;
  }
2325 2326 2327 2328
  cJSON *tags = cJSON_GetObjectItem(root, "tags");
  if (tags == NULL || tags->type != cJSON_Object) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }
wmmhello's avatar
wmmhello 已提交
2329

X
Xiaoyu Wang 已提交
2330
  size_t  childTableNameLen = strlen(tsSmlChildTableName);
2331 2332 2333 2334 2335
  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 已提交
2336
    }
2337 2338 2339 2340 2341
    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 已提交
2342
    // check duplicate keys
2343
    if (smlCheckDuplicateKey(tag->string, keyLen, dumplicateKey)) {
wmmhello's avatar
wmmhello 已提交
2344
      return TSDB_CODE_TSC_DUP_NAMES;
wmmhello's avatar
wmmhello 已提交
2345 2346
    }

X
Xiaoyu Wang 已提交
2347 2348
    // handle child table name
    if (childTableNameLen != 0 && strcmp(tag->string, tsSmlChildTableName) == 0) {
2349 2350 2351 2352 2353
      if (!cJSON_IsString(tag)) {
        uError("OTD:ID must be JSON string");
        return TSDB_CODE_TSC_INVALID_JSON;
      }
      memset(childTableName, 0, TSDB_TABLE_NAME_LEN);
wmmhello's avatar
wmmhello 已提交
2354
      tstrncpy(childTableName, tag->valuestring, TSDB_TABLE_NAME_LEN);
2355 2356 2357
      continue;
    }

2358
    // add kv to SSmlKv
2359
    SSmlKv kv ={.key = tag->string, .keyLen = keyLen};
X
Xiaoyu Wang 已提交
2360
    // value
2361
    ret = smlParseValueFromJSON(tag, &kv);
2362 2363 2364
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
2365
    taosArrayPush(pKVs, &kv);
wmmhello's avatar
wmmhello 已提交
2366 2367
  }

2368
  return ret;
wmmhello's avatar
wmmhello 已提交
2369 2370
}

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

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

2379
  int32_t size = cJSON_GetArraySize(root);
X
Xiaoyu Wang 已提交
2380
  // outmost json fields has to be exactly 4
2381
  if (size != OTD_JSON_FIELDS_NUM) {
X
Xiaoyu Wang 已提交
2382
    uError("OTD:0x%" PRIx64 " Invalid number of JSON fields in data point %d", info->id, size);
2383
    return TSDB_CODE_TSC_INVALID_JSON;
wmmhello's avatar
wmmhello 已提交
2384
  }
2385

X
Xiaoyu Wang 已提交
2386
  // Parse metric
2387 2388
  ret = smlParseMetricFromJSON(info, root, tinfo);
  if (ret != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
2389
    uError("OTD:0x%" PRIx64 " Unable to parse metric from JSON payload", info->id);
2390
    return ret;
wmmhello's avatar
wmmhello 已提交
2391
  }
X
Xiaoyu Wang 已提交
2392
  uDebug("OTD:0x%" PRIx64 " Parse metric from JSON payload finished", info->id);
wmmhello's avatar
wmmhello 已提交
2393

X
Xiaoyu Wang 已提交
2394
  // Parse timestamp
2395 2396
  ret = smlParseTSFromJSON(info, root, cols);
  if (ret) {
X
Xiaoyu Wang 已提交
2397
    uError("OTD:0x%" PRIx64 " Unable to parse timestamp from JSON payload", info->id);
2398
    return ret;
wmmhello's avatar
wmmhello 已提交
2399
  }
X
Xiaoyu Wang 已提交
2400
  uDebug("OTD:0x%" PRIx64 " Parse timestamp from JSON payload finished", info->id);
2401

X
Xiaoyu Wang 已提交
2402
  // Parse metric value
2403 2404
  ret = smlParseColsFromJSON(root, cols);
  if (ret) {
X
Xiaoyu Wang 已提交
2405
    uError("OTD:0x%" PRIx64 " Unable to parse metric value from JSON payload", info->id);
2406
    return ret;
2407
  }
X
Xiaoyu Wang 已提交
2408
  uDebug("OTD:0x%" PRIx64 " Parse metric value from JSON payload finished", info->id);
2409

wmmhello's avatar
wmmhello 已提交
2410 2411 2412
  // Parse tags sml todo
  ret = smlParseTagsFromJSON(root, tinfo->tags, tinfo->childTableName, NULL, &info->msgBuf);
//  ret = smlParseTagsFromJSON(root, tinfo->tags, tinfo->childTableName, info->dumplicateKey, &info->msgBuf);
2413
  if (ret) {
X
Xiaoyu Wang 已提交
2414
    uError("OTD:0x%" PRIx64 " Unable to parse tags from JSON payload", info->id);
2415
    return ret;
2416
  }
X
Xiaoyu Wang 已提交
2417
  uDebug("OTD:0x%" PRIx64 " Parse tags from JSON payload finished", info->id);
wmmhello's avatar
wmmhello 已提交
2418

2419
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
2420
}
2421
/************* TSDB_SML_JSON_PROTOCOL function end **************/
2422 2423 2424
static int32_t smlParseLineBottom(SSmlHandle *info) {
  if(info->dataFormat) return TSDB_CODE_SUCCESS;

wmmhello's avatar
wmmhello 已提交
2425 2426 2427 2428 2429
  for(int32_t i = 0; i < info->lineNum; i ++){
    SSmlLineInfo* elements = info->lines + i;
    SSmlTableInfo *tinfo =
        (SSmlTableInfo *)nodeListGet(info->childTables, elements->measure, elements->measureTagsLen);
    if(tinfo == NULL){
2430 2431 2432
      uError("SML:0x%" PRIx64 "get oneTable failed, line num:%d", info->id, i);
      smlBuildInvalidDataMsg(&info->msgBuf, "get oneTable failed", elements->measure);
      return TSDB_CODE_SML_INVALID_DATA;
2433
    }
wmmhello's avatar
wmmhello 已提交
2434

2435 2436 2437
    if (taosArrayGetSize(elements->colArray) + taosArrayGetSize(tinfo->tags) > TSDB_MAX_COLUMNS) {
      smlBuildInvalidDataMsg(&info->msgBuf, "too many columns than 4096", NULL);
      return TSDB_CODE_PAR_TOO_MANY_COLUMNS;
wmmhello's avatar
wmmhello 已提交
2438
    }
wmmhello's avatar
wmmhello 已提交
2439

2440
    int ret = smlPushCols(tinfo->cols, elements->colArray);
X
Xiaoyu Wang 已提交
2441
    if (ret != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
2442 2443 2444
      return ret;
    }

wmmhello's avatar
wmmhello 已提交
2445
    SSmlSTableMeta *tableMeta = (SSmlSTableMeta *)nodeListGet(info->superTables, elements->measure, elements->measureLen);
2446
    if (tableMeta) {  // update meta
wmmhello's avatar
wmmhello 已提交
2447
      ret = smlUpdateMeta(tableMeta->colHash, tableMeta->cols, elements->colArray, false, &info->msgBuf);
2448
      if (ret == TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
2449
        ret = smlUpdateMeta(tableMeta->tagHash, tableMeta->tags, tinfo->tags, true, &info->msgBuf);
2450 2451 2452 2453 2454
      }
      if (ret != TSDB_CODE_SUCCESS) {
        uError("SML:0x%" PRIx64 " smlUpdateMeta failed", info->id);
        return ret;
      }
X
Xiaoyu Wang 已提交
2455
    } else {
2456 2457 2458 2459 2460
      ret = smlJudgeDupColName(elements->colArray, tinfo->tags, &info->msgBuf);
      if (ret != TSDB_CODE_SUCCESS) {
        uError("SML:0x%" PRIx64 " smlUpdateMeta failed", info->id);
        return ret;
      }
wmmhello's avatar
wmmhello 已提交
2461

2462 2463 2464
      SSmlSTableMeta *meta = smlBuildSTableMeta(info->dataFormat);
      smlInsertMeta(meta->tagHash, meta->tags, tinfo->tags);
      smlInsertMeta(meta->colHash, meta->cols, elements->colArray);
wmmhello's avatar
wmmhello 已提交
2465
      nodeListSet(&info->superTables, elements->measure, elements->measureLen, meta);
wmmhello's avatar
wmmhello 已提交
2466
    }
wmmhello's avatar
wmmhello 已提交
2467
  }
2468

wmmhello's avatar
wmmhello 已提交
2469 2470 2471
  return TSDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
2472
static int32_t smlParseTelnetLine(SSmlHandle *info, void *data, const int len) {
X
Xiaoyu Wang 已提交
2473
  int            ret = TSDB_CODE_SUCCESS;
2474
  SSmlTableInfo *tinfo = smlBuildTableInfo(1, "", 0);
X
Xiaoyu Wang 已提交
2475
  if (!tinfo) {
2476
    return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
2477 2478
  }

2479 2480
  SArray *cols = taosArrayInit(16, POINTER_BYTES);
  if (cols == NULL) {
X
Xiaoyu Wang 已提交
2481
    uError("SML:0x%" PRIx64 " smlParseTelnetLine failed to allocate memory", info->id);
2482
    return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
2483 2484
  }

X
Xiaoyu Wang 已提交
2485
  if (info->protocol == TSDB_SML_TELNET_PROTOCOL) {
dengyihao's avatar
dengyihao 已提交
2486
    ret = smlParseTelnetString(info, (const char *)data, (char *)data + len, tinfo, cols);
X
Xiaoyu Wang 已提交
2487
  } else if (info->protocol == TSDB_SML_JSON_PROTOCOL) {
2488
    ret = smlParseJSONString(info, (cJSON *)data, tinfo, cols);
X
Xiaoyu Wang 已提交
2489
  } else {
2490 2491
    ASSERT(0);
  }
X
Xiaoyu Wang 已提交
2492 2493
  if (ret != TSDB_CODE_SUCCESS) {
    uError("SML:0x%" PRIx64 " smlParseTelnetLine failed", info->id);
wmmhello's avatar
wmmhello 已提交
2494
    smlDestroyTableInfo(tinfo);
2495 2496
    taosArrayDestroy(cols);
    return ret;
wmmhello's avatar
wmmhello 已提交
2497
  }
wmmhello's avatar
wmmhello 已提交
2498

X
Xiaoyu Wang 已提交
2499
  if (taosArrayGetSize(tinfo->tags) <= 0 || taosArrayGetSize(tinfo->tags) > TSDB_MAX_TAGS) {
2500
    smlBuildInvalidDataMsg(&info->msgBuf, "invalidate tags length:[1,128]", NULL);
wmmhello's avatar
wmmhello 已提交
2501
    smlDestroyTableInfo(tinfo);
wmmhello's avatar
wmmhello 已提交
2502
    taosArrayDestroy(cols);
wmmhello's avatar
wmmhello 已提交
2503
    return TSDB_CODE_PAR_INVALID_TAGS_NUM;
wmmhello's avatar
wmmhello 已提交
2504
  }
2505

X
Xiaoyu Wang 已提交
2506 2507
  if (strlen(tinfo->childTableName) == 0) {
    RandTableName rName = {tinfo->tags, tinfo->sTableName, (uint8_t)tinfo->sTableNameLen, tinfo->childTableName, 0};
2508 2509
    buildChildTableName(&rName);
    tinfo->uid = rName.uid;
X
Xiaoyu Wang 已提交
2510 2511
  } else {
    tinfo->uid = *(uint64_t *)(tinfo->childTableName);  // generate uid by name simple
2512 2513
  }

X
Xiaoyu Wang 已提交
2514
  bool            hasTable = true;
wmmhello's avatar
wmmhello 已提交
2515 2516
  SSmlTableInfo *oneTable =
      (SSmlTableInfo *)nodeListGet(info->childTables, tinfo->childTableName, strlen(tinfo->childTableName));
X
Xiaoyu Wang 已提交
2517
  if (!oneTable) {
wmmhello's avatar
wmmhello 已提交
2518 2519
    nodeListSet(&info->childTables, tinfo->childTableName, strlen(tinfo->childTableName), tinfo);
    oneTable = tinfo;
2520
    hasTable = false;
X
Xiaoyu Wang 已提交
2521
  } else {
wmmhello's avatar
wmmhello 已提交
2522
    smlDestroyTableInfo(tinfo);
wmmhello's avatar
wmmhello 已提交
2523
  }
wmmhello's avatar
wmmhello 已提交
2524

wmmhello's avatar
wmmhello 已提交
2525 2526 2527
  taosArrayPush(oneTable->cols, &cols);
  SSmlSTableMeta *tableMeta =
      (SSmlSTableMeta *)nodeListGet(info->superTables, oneTable->sTableName, oneTable->sTableNameLen);
X
Xiaoyu Wang 已提交
2528
  if (tableMeta) {  // update meta
wmmhello's avatar
wmmhello 已提交
2529
    ret = smlUpdateMeta(tableMeta->colHash, tableMeta->cols, cols, false, &info->msgBuf);
wmmhello's avatar
wmmhello 已提交
2530
    if (!hasTable && ret == TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
2531
      ret = smlUpdateMeta(tableMeta->tagHash, tableMeta->tags, oneTable->tags, true, &info->msgBuf);
wmmhello's avatar
wmmhello 已提交
2532
    }
wmmhello's avatar
wmmhello 已提交
2533
    if (ret != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
2534
      uError("SML:0x%" PRIx64 " smlUpdateMeta failed", info->id);
wmmhello's avatar
wmmhello 已提交
2535
      return ret;
2536
    }
X
Xiaoyu Wang 已提交
2537
  } else {
2538
    SSmlSTableMeta *meta = smlBuildSTableMeta(false);
wmmhello's avatar
wmmhello 已提交
2539
    smlInsertMeta(meta->tagHash, meta->tags, oneTable->tags);
wmmhello's avatar
wmmhello 已提交
2540
    smlInsertMeta(meta->colHash, meta->cols, cols);
wmmhello's avatar
wmmhello 已提交
2541
    nodeListSet(&info->superTables, oneTable->sTableName, oneTable->sTableNameLen, meta);
wmmhello's avatar
wmmhello 已提交
2542 2543
  }

2544 2545
  return TSDB_CODE_SUCCESS;
}
wmmhello's avatar
wmmhello 已提交
2546

X
Xiaoyu Wang 已提交
2547
static int32_t smlParseJSON(SSmlHandle *info, char *payload) {
2548 2549
  int32_t payloadNum = 0;
  int32_t ret = TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
2550

2551
  if (payload == NULL) {
X
Xiaoyu Wang 已提交
2552
    uError("SML:0x%" PRIx64 " empty JSON Payload", info->id);
2553
    return TSDB_CODE_TSC_INVALID_JSON;
2554
  }
2555

wmmhello's avatar
wmmhello 已提交
2556 2557
  info->root = cJSON_Parse(payload);
  if (info->root == NULL) {
X
Xiaoyu Wang 已提交
2558
    uError("SML:0x%" PRIx64 " parse json failed:%s", info->id, payload);
2559 2560
    return TSDB_CODE_TSC_INVALID_JSON;
  }
X
Xiaoyu Wang 已提交
2561
  // multiple data points must be sent in JSON array
wmmhello's avatar
wmmhello 已提交
2562
  if (cJSON_IsObject(info->root)) {
2563
    payloadNum = 1;
wmmhello's avatar
wmmhello 已提交
2564 2565
  } else if (cJSON_IsArray(info->root)) {
    payloadNum = cJSON_GetArraySize(info->root);
2566
  } else {
X
Xiaoyu Wang 已提交
2567
    uError("SML:0x%" PRIx64 " Invalid JSON Payload", info->id);
2568 2569
    ret = TSDB_CODE_TSC_INVALID_JSON;
    goto end;
wmmhello's avatar
wmmhello 已提交
2570
  }
wmmhello's avatar
wmmhello 已提交
2571

2572
  for (int32_t i = 0; i < payloadNum; ++i) {
wmmhello's avatar
wmmhello 已提交
2573
    cJSON *dataPoint = (payloadNum == 1 && cJSON_IsObject(info->root)) ? info->root : cJSON_GetArrayItem(info->root, i);
wmmhello's avatar
wmmhello 已提交
2574
    ret = smlParseTelnetLine(info, dataPoint, -1);
X
Xiaoyu Wang 已提交
2575 2576
    if (ret != TSDB_CODE_SUCCESS) {
      uError("SML:0x%" PRIx64 " Invalid JSON Payload", info->id);
2577 2578 2579 2580
      goto end;
    }
  }

2581
  end:
2582
  return ret;
wmmhello's avatar
wmmhello 已提交
2583
}
2584

X
Xiaoyu Wang 已提交
2585
static int32_t smlInsertData(SSmlHandle *info) {
wmmhello's avatar
wmmhello 已提交
2586 2587
  int32_t code = TSDB_CODE_SUCCESS;

wmmhello's avatar
wmmhello 已提交
2588 2589 2590
  NodeList* tmp = info->childTables;
  while (tmp) {
    SSmlTableInfo *tableData = (SSmlTableInfo *)tmp->data.value;
wmmhello's avatar
wmmhello 已提交
2591 2592

    SName pName = {TSDB_TABLE_NAME_T, info->taos->acctId, {0}, {0}};
wmmhello's avatar
wmmhello 已提交
2593
    tstrncpy(pName.dbname, info->pRequest->pDb, sizeof(pName.dbname));
wmmhello's avatar
wmmhello 已提交
2594
    memcpy(pName.tname, tableData->childTableName, strlen(tableData->childTableName));
D
dapan1121 已提交
2595 2596 2597 2598 2599 2600

    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 已提交
2601

wmmhello's avatar
wmmhello 已提交
2602
    SVgroupInfo vg;
D
dapan1121 已提交
2603
    code = catalogGetTableHashVgroup(info->pCatalog, &conn, &pName, &vg);
2604
    if (code != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
2605
      uError("SML:0x%" PRIx64 " catalogGetTableHashVgroup failed. table name: %s", info->id, tableData->childTableName);
wmmhello's avatar
wmmhello 已提交
2606 2607
      return code;
    }
X
Xiaoyu Wang 已提交
2608
    taosHashPut(info->pVgHash, (const char *)&vg.vgId, sizeof(vg.vgId), (char *)&vg, sizeof(vg));
wmmhello's avatar
wmmhello 已提交
2609

wmmhello's avatar
wmmhello 已提交
2610 2611 2612
    SSmlSTableMeta *pMeta =
        (SSmlSTableMeta *)nodeListGet(info->superTables, tableData->sTableName, tableData->sTableNameLen);
    ASSERT(NULL != pMeta);
wmmhello's avatar
wmmhello 已提交
2613

2614
    // use tablemeta of stable to save vgid and uid of child table
wmmhello's avatar
wmmhello 已提交
2615 2616
    pMeta->tableMeta->vgId = vg.vgId;
    pMeta->tableMeta->uid = tableData->uid;  // one table merge data block together according uid
wmmhello's avatar
wmmhello 已提交
2617

wmmhello's avatar
wmmhello 已提交
2618 2619
    code = smlBindData(info->pQuery, info->dataFormat, tableData->tags, pMeta->cols, tableData->cols,
                       pMeta->tableMeta, tableData->childTableName, tableData->sTableName, tableData->sTableNameLen,
2620
                       info->ttl, info->msgBuf.buf, info->msgBuf.len);
X
Xiaoyu Wang 已提交
2621 2622
    if (code != TSDB_CODE_SUCCESS) {
      uError("SML:0x%" PRIx64 " smlBindData failed", info->id);
wmmhello's avatar
wmmhello 已提交
2623 2624
      return code;
    }
wmmhello's avatar
wmmhello 已提交
2625
    tmp = tmp->next;
wmmhello's avatar
wmmhello 已提交
2626
  }
wmmhello's avatar
wmmhello 已提交
2627

wmmhello's avatar
wmmhello 已提交
2628
  code = smlBuildOutput(info->pQuery, info->pVgHash);
2629
  if (code != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
2630
    uError("SML:0x%" PRIx64 " smlBuildOutput failed", info->id);
2631 2632
    return code;
  }
2633 2634
  info->cost.insertRpcTime = taosGetTimestampUs();

2635 2636 2637
  SAppClusterSummary *pActivity = &info->taos->pAppInfo->summary;
  atomic_add_fetch_64((int64_t *)&pActivity->numOfInsertsReq, 1);

wmmhello's avatar
wmmhello 已提交
2638 2639
  launchQueryImpl(info->pRequest, info->pQuery, true, NULL);
  return info->pRequest->code;
wmmhello's avatar
wmmhello 已提交
2640 2641
}

X
Xiaoyu Wang 已提交
2642 2643
static void smlPrintStatisticInfo(SSmlHandle *info) {
  uError("SML:0x%" PRIx64
2644
             " smlInsertLines result, code:%d,lineNum:%d,stable num:%d,ctable num:%d,create stable num:%d,alter stable tag num:%d,alter stable col num:%d \
X
Xiaoyu Wang 已提交
2645
        parse cost:%" PRId64 ",schema cost:%" PRId64 ",bind cost:%" PRId64 ",rpc cost:%" PRId64 ",total cost:%" PRId64
2646
             "",
X
Xiaoyu Wang 已提交
2647
         info->id, info->cost.code, info->cost.lineNum, info->cost.numOfSTables, info->cost.numOfCTables,
2648 2649
         info->cost.numOfCreateSTables, info->cost.numOfAlterTagSTables, info->cost.numOfAlterColSTables,
         info->cost.schemaTime - info->cost.parseTime,
X
Xiaoyu Wang 已提交
2650 2651
         info->cost.insertBindTime - info->cost.schemaTime, info->cost.insertRpcTime - info->cost.insertBindTime,
         info->cost.endTime - info->cost.insertRpcTime, info->cost.endTime - info->cost.parseTime);
2652 2653
}

dengyihao's avatar
dengyihao 已提交
2654
static int32_t smlParseLine(SSmlHandle *info, char *lines[], char *rawLine, char *rawLineEnd, int numLines) {
wmmhello's avatar
wmmhello 已提交
2655
  int32_t code = TSDB_CODE_SUCCESS;
2656
  if (info->protocol == TSDB_SML_JSON_PROTOCOL) {
dengyihao's avatar
dengyihao 已提交
2657
    if (lines) {
wmmhello's avatar
wmmhello 已提交
2658
      code = smlParseJSON(info, *lines);
dengyihao's avatar
dengyihao 已提交
2659
    } else if (rawLine) {
wmmhello's avatar
wmmhello 已提交
2660 2661
      code = smlParseJSON(info, rawLine);
    }
2662
    if (code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
2663
      uError("SML:0x%" PRIx64 " smlParseJSON failed:%s", info->id, lines ? *lines : rawLine);
2664 2665
      return code;
    }
wmmhello's avatar
wmmhello 已提交
2666
    return code;
wmmhello's avatar
wmmhello 已提交
2667
  }
wmmhello's avatar
wmmhello 已提交
2668

2669 2670
  int32_t i = 0;
  while (i < numLines) {
wmmhello's avatar
wmmhello 已提交
2671
    char *tmp = NULL;
dengyihao's avatar
dengyihao 已提交
2672 2673
    int   len = 0;
    if (lines) {
wmmhello's avatar
wmmhello 已提交
2674 2675
      tmp = lines[i];
      len = strlen(tmp);
dengyihao's avatar
dengyihao 已提交
2676
    } else if (rawLine) {
wmmhello's avatar
wmmhello 已提交
2677
      tmp = rawLine;
dengyihao's avatar
dengyihao 已提交
2678 2679
      while (rawLine < rawLineEnd) {
        if (*(rawLine++) == '\n') {
wmmhello's avatar
wmmhello 已提交
2680 2681 2682 2683
          break;
        }
        len++;
      }
dengyihao's avatar
dengyihao 已提交
2684
      if (info->protocol == TSDB_SML_LINE_PROTOCOL && tmp[0] == '#') {  // this line is comment
2685
        i++;
wmmhello's avatar
wmmhello 已提交
2686 2687
        continue;
      }
wmmhello's avatar
wmmhello 已提交
2688 2689
    }

2690 2691
    uDebug("SML:0x%" PRIx64 " smlParseLine israw:%d, len:%d, sql:%s", info->id, info->isRawLine, len, (info->isRawLine ? "rawdata" : tmp));

X
Xiaoyu Wang 已提交
2692
    if (info->protocol == TSDB_SML_LINE_PROTOCOL) {
wmmhello's avatar
wmmhello 已提交
2693 2694 2695 2696 2697 2698
      if(info->dataFormat){
        SSmlLineInfo element = {0};
        code = smlParseInfluxString(info, tmp, tmp + len, &element);
      }else{
        code = smlParseInfluxString(info, tmp, tmp + len, info->lines + i);
      }
X
Xiaoyu Wang 已提交
2699
    } else if (info->protocol == TSDB_SML_TELNET_PROTOCOL) {
wmmhello's avatar
wmmhello 已提交
2700
      code = smlParseTelnetLine(info, tmp, len);
X
Xiaoyu Wang 已提交
2701
    } else {
2702 2703
      ASSERT(0);
    }
wmmhello's avatar
wmmhello 已提交
2704
    if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
2705
      uError("SML:0x%" PRIx64 " smlParseLine failed. line %d : %s", info->id, i, tmp);
2706
      return code;
wmmhello's avatar
wmmhello 已提交
2707
    }
2708 2709 2710 2711
    if(info->reRun){
      i = 0;
      info->reRun = false;
      // clear info->childTables
wmmhello's avatar
wmmhello 已提交
2712 2713 2714 2715 2716 2717 2718
      NodeList* pList = info->childTables;
      while (pList) {
        if(pList->data.used) {
          smlDestroyTableInfo(pList->data.value);
          pList->data.used = false;
        }
        pList = pList->next;
2719 2720 2721
      }

      // clear info->superTables
wmmhello's avatar
wmmhello 已提交
2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733
      pList = info->superTables;
      while (pList) {
        if(pList->data.used) {
          smlDestroySTableMeta(pList->data.value);
          pList->data.used = false;
        }
        pList = pList->next;
      }

      if(info->lines != NULL){
        uError("SML:0x%" PRIx64 " info->lines != NULL", info->id);
        return TSDB_CODE_SML_INVALID_DATA;
2734
      }
wmmhello's avatar
wmmhello 已提交
2735 2736
      info->lines = taosMemoryCalloc(info->lineNum, sizeof(SSmlLineInfo));

2737
      continue;
2738
    }
2739
    i++;
wmmhello's avatar
wmmhello 已提交
2740
  }
2741

2742 2743 2744
  return code;
}

dengyihao's avatar
dengyihao 已提交
2745
static int smlProcess(SSmlHandle *info, char *lines[], char *rawLine, char *rawLineEnd, int numLines) {
2746
  int32_t code = TSDB_CODE_SUCCESS;
2747 2748
  int32_t retryNum = 0;

2749 2750
  info->cost.parseTime = taosGetTimestampUs();

wmmhello's avatar
wmmhello 已提交
2751
  code = smlParseLine(info, lines, rawLine, rawLineEnd, numLines);
2752
  if (code != 0) {
X
Xiaoyu Wang 已提交
2753
    uError("SML:0x%" PRIx64 " smlParseLine error : %s", info->id, tstrerror(code));
wmmhello's avatar
wmmhello 已提交
2754
    return code;
2755
  }
wmmhello's avatar
wmmhello 已提交
2756

2757 2758 2759 2760 2761 2762
  code = smlParseLineBottom(info);
  if (code != 0) {
    uError("SML:0x%" PRIx64 " smlParseLineBottom error : %s", info->id, tstrerror(code));
    return code;
  }

2763
  info->cost.lineNum = numLines;
wmmhello's avatar
wmmhello 已提交
2764 2765
  info->cost.numOfSTables = nodeListSize(info->superTables);
  info->cost.numOfCTables = nodeListSize(info->childTables);
2766 2767

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

X
Xiaoyu Wang 已提交
2769
  do {
2770 2771
    code = smlModifyDBSchemas(info);
    if (code == 0) break;
wmmhello's avatar
wmmhello 已提交
2772
  } while (retryNum++ < nodeListSize(info->superTables) * MAX_RETRY_TIMES);
2773

wmmhello's avatar
wmmhello 已提交
2774
  if (code != 0) {
X
Xiaoyu Wang 已提交
2775
    uError("SML:0x%" PRIx64 " smlModifyDBSchemas error : %s", info->id, tstrerror(code));
wmmhello's avatar
wmmhello 已提交
2776
    return code;
wmmhello's avatar
wmmhello 已提交
2777
  }
wmmhello's avatar
wmmhello 已提交
2778

2779
  info->cost.insertBindTime = taosGetTimestampUs();
wmmhello's avatar
wmmhello 已提交
2780 2781
  code = smlInsertData(info);
  if (code != 0) {
X
Xiaoyu Wang 已提交
2782
    uError("SML:0x%" PRIx64 " smlInsertData error : %s", info->id, tstrerror(code));
wmmhello's avatar
wmmhello 已提交
2783
    return code;
wmmhello's avatar
wmmhello 已提交
2784 2785 2786 2787 2788
  }

  return code;
}

wmmhello's avatar
wmmhello 已提交
2789 2790 2791 2792 2793
TAOS_RES *taos_schemaless_insert_inner(TAOS *taos, char *lines[], char *rawLine, char *rawLineEnd,
                                       int numLines, int protocol, int precision, int32_t ttl, int64_t reqid) {
  if (NULL == taos) {
    terrno = TSDB_CODE_TSC_DISCONNECTED;
    return NULL;
2794
  }
2795

wmmhello's avatar
wmmhello 已提交
2796 2797 2798 2799
  SRequestObj *request = (SRequestObj *)createRequest(*(int64_t *)taos, TSDB_SQL_INSERT, reqid);
  if (request == NULL) {
    uError("SML:taos_schemaless_insert error request is null");
    return NULL;
wmmhello's avatar
wmmhello 已提交
2800
  }
2801

wmmhello's avatar
wmmhello 已提交
2802 2803 2804 2805
  SSmlHandle *info = smlBuildSmlInfo(taos);
  if (info == NULL) {
    request->code = TSDB_CODE_OUT_OF_MEMORY;
    uError("SML:taos_schemaless_insert error SSmlHandle is null");
wmmhello's avatar
wmmhello 已提交
2806 2807
    goto end;
  }
wmmhello's avatar
wmmhello 已提交
2808 2809 2810 2811 2812 2813 2814 2815
  info->pRequest = request;
  info->isRawLine = rawLine != NULL;
  info->ttl       = ttl;
  info->precision = precision;
  info->protocol = protocol;
  info->msgBuf.buf = info->pRequest->msgBuf;
  info->msgBuf.len = ERROR_MSG_BUF_DEFAULT_SIZE;
  info->lineNum = numLines;
wmmhello's avatar
wmmhello 已提交
2816

wmmhello's avatar
wmmhello 已提交
2817
  SSmlMsgBuf msg = {ERROR_MSG_BUF_DEFAULT_SIZE, request->msgBuf};
wmmhello's avatar
wmmhello 已提交
2818 2819 2820
  if (request->pDb == NULL) {
    request->code = TSDB_CODE_PAR_DB_NOT_SPECIFIED;
    smlBuildInvalidDataMsg(&msg, "Database not specified", NULL);
wmmhello's avatar
wmmhello 已提交
2821 2822 2823
    goto end;
  }

X
Xiaoyu Wang 已提交
2824
  if (protocol < TSDB_SML_LINE_PROTOCOL || protocol > TSDB_SML_JSON_PROTOCOL) {
2825
    request->code = TSDB_CODE_SML_INVALID_PROTOCOL_TYPE;
wmmhello's avatar
wmmhello 已提交
2826
    smlBuildInvalidDataMsg(&msg, "protocol invalidate", NULL);
2827
    goto end;
wmmhello's avatar
wmmhello 已提交
2828 2829
  }

X
Xiaoyu Wang 已提交
2830 2831
  if (protocol == TSDB_SML_LINE_PROTOCOL &&
      (precision < TSDB_SML_TIMESTAMP_NOT_CONFIGURED || precision > TSDB_SML_TIMESTAMP_NANO_SECONDS)) {
2832
    request->code = TSDB_CODE_SML_INVALID_PRECISION_TYPE;
wmmhello's avatar
wmmhello 已提交
2833
    smlBuildInvalidDataMsg(&msg, "precision invalidate for line protocol", NULL);
2834 2835 2836
    goto end;
  }

2837
  if (protocol == TSDB_SML_JSON_PROTOCOL) {
wmmhello's avatar
wmmhello 已提交
2838
    numLines = 1;
2839
  } else if (numLines <= 0) {
wmmhello's avatar
wmmhello 已提交
2840 2841 2842 2843 2844
    request->code = TSDB_CODE_SML_INVALID_DATA;
    smlBuildInvalidDataMsg(&msg, "line num is invalid", NULL);
    goto end;
  }

wmmhello's avatar
wmmhello 已提交
2845 2846 2847 2848 2849
  int32_t code = smlProcess(info, lines, rawLine, rawLineEnd, numLines);
  request->code = code;
  info->cost.endTime = taosGetTimestampUs();
  info->cost.code = code;
  smlPrintStatisticInfo(info);
2850

wmmhello's avatar
wmmhello 已提交
2851
end:
2852
  uDebug("resultend:%s", request->msgBuf);
wmmhello's avatar
wmmhello 已提交
2853
  smlDestroyInfo(info);
2854
  return (TAOS_RES *)request;
wmmhello's avatar
wmmhello 已提交
2855
}
wmmhello's avatar
wmmhello 已提交
2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872

/**
 * 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
dengyihao's avatar
dengyihao 已提交
2873
 * @return TAOS_RES
wmmhello's avatar
wmmhello 已提交
2874 2875
 */

2876 2877
TAOS_RES *taos_schemaless_insert_ttl_with_reqid(TAOS *taos, char *lines[], int numLines, int protocol, int precision,
                                                int32_t ttl, int64_t reqid) {
wmmhello's avatar
wmmhello 已提交
2878
  return taos_schemaless_insert_inner(taos, lines, NULL, NULL, numLines, protocol, precision, ttl, reqid);
dengyihao's avatar
dengyihao 已提交
2879 2880
}

2881 2882 2883
TAOS_RES *taos_schemaless_insert(TAOS *taos, char *lines[], int numLines, int protocol, int precision) {
  return taos_schemaless_insert_ttl_with_reqid(taos, lines, numLines, protocol, precision, TSDB_DEFAULT_TABLE_TTL, 0);
}
wmmhello's avatar
wmmhello 已提交
2884

2885 2886 2887
TAOS_RES *taos_schemaless_insert_ttl(TAOS *taos, char *lines[], int numLines, int protocol, int precision, int32_t ttl) {
  return taos_schemaless_insert_ttl_with_reqid(taos, lines, numLines, protocol, precision, ttl, 0);
}
wmmhello's avatar
wmmhello 已提交
2888

2889 2890
TAOS_RES *taos_schemaless_insert_with_reqid(TAOS *taos, char *lines[], int numLines, int protocol, int precision, int64_t reqid) {
  return taos_schemaless_insert_ttl_with_reqid(taos, lines, numLines, protocol, precision, TSDB_DEFAULT_TABLE_TTL, reqid);
wmmhello's avatar
wmmhello 已提交
2891 2892
}

2893
TAOS_RES *taos_schemaless_insert_raw_ttl_with_reqid(TAOS *taos, char *lines, int len, int32_t *totalRows, int protocol,
2894
                                                    int precision, int32_t ttl, int64_t reqid) {
dengyihao's avatar
dengyihao 已提交
2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906
  int numLines = 0;
  *totalRows = 0;
  char *tmp = lines;
  for (int i = 0; i < len; i++) {
    if (lines[i] == '\n' || i == len - 1) {
      numLines++;
      if (tmp[0] != '#' || protocol != TSDB_SML_LINE_PROTOCOL) {  // ignore comment
        (*totalRows)++;
      }
      tmp = lines + i + 1;
    }
  }
wmmhello's avatar
wmmhello 已提交
2907
  return taos_schemaless_insert_inner(taos, NULL, lines, lines + len, *totalRows, protocol, precision, ttl, reqid);
dengyihao's avatar
dengyihao 已提交
2908 2909
}

2910 2911 2912 2913 2914 2915
TAOS_RES *taos_schemaless_insert_raw_with_reqid(TAOS *taos, char *lines, int len, int32_t *totalRows, int protocol, int precision, int64_t reqid) {
  return taos_schemaless_insert_raw_ttl_with_reqid(taos, lines, len, totalRows, protocol, precision, TSDB_DEFAULT_TABLE_TTL, reqid);
}
TAOS_RES *taos_schemaless_insert_raw_ttl(TAOS *taos, char *lines, int len, int32_t *totalRows, int protocol, int precision, int32_t ttl) {
  return taos_schemaless_insert_raw_ttl_with_reqid(taos, lines, len, totalRows, protocol, precision, ttl, 0);
}
wmmhello's avatar
wmmhello 已提交
2916

2917 2918
TAOS_RES *taos_schemaless_insert_raw(TAOS *taos, char *lines, int len, int32_t *totalRows, int protocol, int precision) {
  return taos_schemaless_insert_raw_ttl_with_reqid(taos, lines, len, totalRows, protocol, precision, TSDB_DEFAULT_TABLE_TTL, 0);
wmmhello's avatar
wmmhello 已提交
2919
}