clientSmlJson.c 36.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "clientSml.h"

wmmhello's avatar
wmmhello 已提交
22 23
#define OTD_JSON_SUB_FIELDS_NUM 2

wmmhello's avatar
wmmhello 已提交
24 25
#define JUMP_JSON_SPACE(start) \
while(*(start)){\
wmmhello's avatar
wmmhello 已提交
26
  if(unlikely(*(start) > 32))\
wmmhello's avatar
wmmhello 已提交
27 28
    break;\
  else\
wmmhello's avatar
wmmhello 已提交
29
    (start)++;\
wmmhello's avatar
wmmhello 已提交
30 31
  }

wmmhello's avatar
wmmhello 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 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 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
//SArray *smlJsonParseTags(char *start, char *end){
//  SArray *tags = taosArrayInit(4, sizeof(SSmlKv));
//  while(start < end){
//    SSmlKv kv = {0};
//    kv.type = TSDB_DATA_TYPE_NCHAR;
//    bool isInQuote = false;
//    while(start < end){
//      if(unlikely(!isInQuote && *start == '"')){
//        start++;
//        kv.key = start;
//        isInQuote = true;
//        continue;
//      }
//      if(unlikely(isInQuote && *start == '"')){
//        kv.keyLen = start - kv.key;
//        start++;
//        break;
//      }
//      start++;
//    }
//    bool hasColon = false;
//    while(start < end){
//      if(unlikely(!hasColon && *start == ':')){
//        start++;
//        hasColon = true;
//        continue;
//      }
//      if(unlikely(hasColon && kv.value == NULL && (*start > 32 && *start != '"'))){
//        kv.value = start;
//        start++;
//        continue;
//      }
//
//      if(unlikely(hasColon && kv.value != NULL && (*start == '"' || *start == ',' || *start == '}'))){
//        kv.length = start - kv.value;
//        taosArrayPush(tags, &kv);
//        start++;
//        break;
//      }
//      start++;
//    }
//  }
//  return tags;
//}

//static int32_t smlParseTagsFromJSON(SSmlHandle *info, SSmlLineInfo *elements) {
//  int32_t ret = TSDB_CODE_SUCCESS;
//
//  if(is_same_child_table_telnet(elements, &info->preLine) == 0){
//    return TSDB_CODE_SUCCESS;
//  }
//
//  bool isSameMeasure = IS_SAME_SUPER_TABLE;
//
//  int     cnt = 0;
//  SArray *preLineKV = info->preLineTagKV;
//  bool    isSuperKVInit = true;
//  SArray *superKV = NULL;
//  if(info->dataFormat){
//    if(unlikely(!isSameMeasure)){
//      SSmlSTableMeta *sMeta = (SSmlSTableMeta *)nodeListGet(info->superTables, elements->measure, elements->measureLen, NULL);
//
//      if(unlikely(sMeta == NULL)){
//        sMeta = smlBuildSTableMeta(info->dataFormat);
//        STableMeta * pTableMeta = smlGetMeta(info, elements->measure, elements->measureLen);
//        sMeta->tableMeta = pTableMeta;
//        if(pTableMeta == NULL){
//          info->dataFormat = false;
//          info->reRun      = true;
//          return TSDB_CODE_SUCCESS;
//        }
//        nodeListSet(&info->superTables, elements->measure, elements->measureLen, sMeta, NULL);
//      }
//      info->currSTableMeta = sMeta->tableMeta;
//      superKV = sMeta->tags;
//
//      if(unlikely(taosArrayGetSize(superKV) == 0)){
//        isSuperKVInit = false;
//      }
//      taosArraySetSize(preLineKV, 0);
//    }
//  }else{
//    taosArraySetSize(preLineKV, 0);
//  }
//
//  SArray *tags = smlJsonParseTags(elements->tags, elements->tags + elements->tagsLen);
//  int32_t tagNum = taosArrayGetSize(tags);
//  if (tagNum == 0) {
//    uError("SML:tag is empty:%s", elements->tags)
//    taosArrayDestroy(tags);
//    return TSDB_CODE_SML_INVALID_DATA;
//  }
//  for (int32_t i = 0; i < tagNum; ++i) {
//    SSmlKv kv = *(SSmlKv*)taosArrayGet(tags, i);
//
//    if(info->dataFormat){
//      if(unlikely(cnt + 1 > info->currSTableMeta->tableInfo.numOfTags)){
//        info->dataFormat = false;
//        info->reRun      = true;
//        taosArrayDestroy(tags);
//        return TSDB_CODE_SUCCESS;
//      }
//
//      if(isSameMeasure){
//        if(unlikely(cnt >= taosArrayGetSize(preLineKV))) {
//          info->dataFormat = false;
//          info->reRun      = true;
//          taosArrayDestroy(tags);
//          return TSDB_CODE_SUCCESS;
//        }
//        SSmlKv *preKV = (SSmlKv *)taosArrayGet(preLineKV, cnt);
//        if(unlikely(kv.length > preKV->length)){
//          preKV->length = kv.length;
//          SSmlSTableMeta *tableMeta = (SSmlSTableMeta *)nodeListGet(info->superTables, elements->measure, elements->measureLen, NULL);
//          ASSERT(tableMeta != NULL);
//
//          SSmlKv *oldKV = (SSmlKv *)taosArrayGet(tableMeta->tags, cnt);
//          oldKV->length = kv.length;
//          info->needModifySchema = true;
//        }
//        if(unlikely(!IS_SAME_KEY)){
//          info->dataFormat = false;
//          info->reRun      = true;
//          taosArrayDestroy(tags);
//          return TSDB_CODE_SUCCESS;
//        }
//      }else{
//        if(isSuperKVInit){
//          if(unlikely(cnt >= taosArrayGetSize(superKV))) {
//            info->dataFormat = false;
//            info->reRun      = true;
//            taosArrayDestroy(tags);
//            return TSDB_CODE_SUCCESS;
//          }
//          SSmlKv *preKV = (SSmlKv *)taosArrayGet(superKV, cnt);
//          if(unlikely(kv.length > preKV->length)) {
//            preKV->length = kv.length;
//          }else{
//            kv.length = preKV->length;
//          }
//          info->needModifySchema = true;
//
//          if(unlikely(!IS_SAME_KEY)){
//            info->dataFormat = false;
//            info->reRun      = true;
//            taosArrayDestroy(tags);
//            return TSDB_CODE_SUCCESS;
//          }
//        }else{
//          taosArrayPush(superKV, &kv);
//        }
//        taosArrayPush(preLineKV, &kv);
//      }
//    }else{
//      taosArrayPush(preLineKV, &kv);
//    }
//    cnt++;
//  }
//  taosArrayDestroy(tags);
//
//  SSmlTableInfo *tinfo = (SSmlTableInfo *)nodeListGet(info->childTables, elements, POINTER_BYTES, is_same_child_table_telnet);
//  if (unlikely(tinfo == NULL)) {
//    tinfo = smlBuildTableInfo(1, elements->measure, elements->measureLen);
//    if (unlikely(!tinfo)) {
//      return TSDB_CODE_OUT_OF_MEMORY;
//    }
//    tinfo->tags = taosArrayDup(preLineKV, NULL);
//
//    smlSetCTableName(tinfo);
//    if (info->dataFormat) {
//      info->currSTableMeta->uid = tinfo->uid;
//      tinfo->tableDataCtx = smlInitTableDataCtx(info->pQuery, info->currSTableMeta);
//      if (tinfo->tableDataCtx == NULL) {
//        smlBuildInvalidDataMsg(&info->msgBuf, "smlInitTableDataCtx error", NULL);
//        return TSDB_CODE_SML_INVALID_DATA;
//      }
//    }
//
//    SSmlLineInfo *key = (SSmlLineInfo *)taosMemoryMalloc(sizeof(SSmlLineInfo));
//    *key = *elements;
//    tinfo->key = key;
//    nodeListSet(&info->childTables, key, POINTER_BYTES, tinfo, is_same_child_table_telnet);
//  }
//  if (info->dataFormat) info->currTableDataCtx = tinfo->tableDataCtx;
//
//  return ret;
//}
219

wmmhello's avatar
wmmhello 已提交
220 221 222
static char* smlJsonGetObj(char *payload){
  int   leftBracketCnt = 0;
  while(*payload) {
wmmhello's avatar
wmmhello 已提交
223
    if (unlikely(*payload == '{')) {
wmmhello's avatar
wmmhello 已提交
224 225 226 227
      leftBracketCnt++;
      payload++;
      continue;
    }
wmmhello's avatar
wmmhello 已提交
228
    if (unlikely(*payload == '}')) {
wmmhello's avatar
wmmhello 已提交
229 230 231 232 233 234
      leftBracketCnt--;
      payload++;
      if (leftBracketCnt == 0) {
        return payload;
      } else if (leftBracketCnt < 0) {
        return NULL;
235
      }
wmmhello's avatar
wmmhello 已提交
236
      continue;
237
    }
wmmhello's avatar
wmmhello 已提交
238 239 240 241 242
    payload++;
  }
  return NULL;
}

wmmhello's avatar
wmmhello 已提交
243
int smlJsonParseObjFirst(char **start, SSmlLineInfo *element, int8_t *offset){
wmmhello's avatar
wmmhello 已提交
244
  int index = 0;
wmmhello's avatar
wmmhello 已提交
245
  while(*(*start)){
wmmhello's avatar
wmmhello 已提交
246 247 248 249
    if((*start)[0] != '"'){
      (*start)++;
      continue;
    }
wmmhello's avatar
wmmhello 已提交
250

wmmhello's avatar
wmmhello 已提交
251 252 253 254 255
    if(unlikely(index >= OTD_JSON_FIELDS_NUM)) {
      uError("index >= %d, %s", OTD_JSON_FIELDS_NUM, *start)
      break;
    }

wmmhello's avatar
wmmhello 已提交
256
    char *sTmp = *start;
wmmhello's avatar
wmmhello 已提交
257
    if((*start)[1] == 'm' && (*start)[2] == 'e' && (*start)[3] == 't'
wmmhello's avatar
wmmhello 已提交
258
       && (*start)[4] == 'r' &&  (*start)[5] == 'i' && (*start)[6] == 'c' && (*start)[7] == '"'){
wmmhello's avatar
wmmhello 已提交
259

wmmhello's avatar
wmmhello 已提交
260
      (*start) += 8;
wmmhello's avatar
wmmhello 已提交
261
      bool isInQuote = false;
wmmhello's avatar
wmmhello 已提交
262 263 264
      while(*(*start)){
        if(unlikely(!isInQuote && *(*start) == '"')){
          (*start)++;
wmmhello's avatar
wmmhello 已提交
265
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
266
          element->measure = (*start);
wmmhello's avatar
wmmhello 已提交
267 268 269
          isInQuote = true;
          continue;
        }
wmmhello's avatar
wmmhello 已提交
270 271
        if(unlikely(isInQuote && *(*start) == '"')){
          element->measureLen = (*start) - element->measure;
wmmhello's avatar
wmmhello 已提交
272 273
          break;
        }
wmmhello's avatar
wmmhello 已提交
274
        (*start)++;
wmmhello's avatar
wmmhello 已提交
275
      }
wmmhello's avatar
wmmhello 已提交
276
    }else if((*start)[1] == 't' && (*start)[2] == 'i' && (*start)[3] == 'm'
wmmhello's avatar
wmmhello 已提交
277 278
             && (*start)[4] == 'e' &&  (*start)[5] == 's' && (*start)[6] == 't'
             && (*start)[7] == 'a' &&  (*start)[8] == 'm' && (*start)[9] == 'p' && (*start)[10] == '"'){
wmmhello's avatar
wmmhello 已提交
279

wmmhello's avatar
wmmhello 已提交
280
      (*start) += 11;
wmmhello's avatar
wmmhello 已提交
281
      bool hasColon = false;
wmmhello's avatar
wmmhello 已提交
282 283 284 285
      while(*(*start)){
        if(unlikely(!hasColon && *(*start) == ':')){
          (*start)++;
          JUMP_JSON_SPACE((*start))
wmmhello's avatar
wmmhello 已提交
286
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
287
          element->timestamp = (*start);
wmmhello's avatar
wmmhello 已提交
288 289 290
          hasColon = true;
          continue;
        }
wmmhello's avatar
wmmhello 已提交
291
        if(unlikely(hasColon && (*(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32))){
wmmhello's avatar
wmmhello 已提交
292
          element->timestampLen = (*start) - element->timestamp;
wmmhello's avatar
wmmhello 已提交
293 294
          break;
        }
wmmhello's avatar
wmmhello 已提交
295
        (*start)++;
wmmhello's avatar
wmmhello 已提交
296
      }
wmmhello's avatar
wmmhello 已提交
297
    }else if((*start)[1] == 'v' && (*start)[2] == 'a' && (*start)[3] == 'l'
wmmhello's avatar
wmmhello 已提交
298
             && (*start)[4] == 'u' &&  (*start)[5] == 'e' && (*start)[6] == '"'){
wmmhello's avatar
wmmhello 已提交
299

wmmhello's avatar
wmmhello 已提交
300
      (*start) += 7;
wmmhello's avatar
wmmhello 已提交
301 302

      bool hasColon = false;
wmmhello's avatar
wmmhello 已提交
303 304 305 306
      while(*(*start)){
        if(unlikely(!hasColon && *(*start) == ':')){
          (*start)++;
          JUMP_JSON_SPACE((*start))
wmmhello's avatar
wmmhello 已提交
307
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
308
          element->cols = (*start);
wmmhello's avatar
wmmhello 已提交
309 310 311
          hasColon = true;
          continue;
        }
wmmhello's avatar
wmmhello 已提交
312
        if(unlikely(hasColon && (*(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32))){
wmmhello's avatar
wmmhello 已提交
313
          element->colsLen = (*start) - element->cols;
wmmhello's avatar
wmmhello 已提交
314 315
          break;
        }
wmmhello's avatar
wmmhello 已提交
316
        (*start)++;
wmmhello's avatar
wmmhello 已提交
317
      }
wmmhello's avatar
wmmhello 已提交
318
    }else if((*start)[1] == 't' && (*start)[2] == 'a' && (*start)[3] == 'g'
wmmhello's avatar
wmmhello 已提交
319 320 321 322 323 324 325
             && (*start)[4] == 's' && (*start)[5] == '"'){
      (*start) += 6;

      while(*(*start)){
        if(unlikely(*(*start) == ':')){
          (*start)++;
          JUMP_JSON_SPACE((*start))
wmmhello's avatar
wmmhello 已提交
326
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
327 328 329 330 331 332
          element->tags = (*start);
          char* tmp = smlJsonGetObj((*start));
          if(tmp){
            element->tagsLen = tmp - (*start);
            *start = tmp;
          }
wmmhello's avatar
wmmhello 已提交
333 334
          break;
        }
wmmhello's avatar
wmmhello 已提交
335
        (*start)++;
wmmhello's avatar
wmmhello 已提交
336
      }
337
    }
wmmhello's avatar
wmmhello 已提交
338 339 340 341 342
    if(*(*start) == '}'){
      (*start)++;
      break;
    }
    (*start)++;
343
  }
wmmhello's avatar
wmmhello 已提交
344

wmmhello's avatar
wmmhello 已提交
345 346
  if(unlikely(index != OTD_JSON_FIELDS_NUM) || element->tags == NULL || element->cols == NULL || element->measure == NULL || element->timestamp == NULL) {
    uError("elements != %d or element parse null", OTD_JSON_FIELDS_NUM)
wmmhello's avatar
wmmhello 已提交
347 348 349
    return -1;
  }
  return 0;
350 351
}

wmmhello's avatar
wmmhello 已提交
352
int smlJsonParseObj(char **start, SSmlLineInfo *element, int8_t *offset){
wmmhello's avatar
wmmhello 已提交
353 354 355 356 357 358 359
  int index = 0;
  while(*(*start)){
    if((*start)[0] != '"'){
      (*start)++;
      continue;
    }

wmmhello's avatar
wmmhello 已提交
360 361 362 363 364
    if(unlikely(index >= OTD_JSON_FIELDS_NUM)) {
      uError("index >= %d, %s", OTD_JSON_FIELDS_NUM, *start)
      break;
    }

wmmhello's avatar
wmmhello 已提交
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
    if((*start)[1] == 'm'){
      (*start) += offset[index++];
      element->measure = *start;
      while(*(*start)){
        if(unlikely(*(*start) == '"')){
          element->measureLen = (*start) - element->measure;
          break;
        }
        (*start)++;
      }
    }else if((*start)[1] == 't' && (*start)[2] == 'i'){
      (*start) += offset[index++];
      element->timestamp = *start;
      while(*(*start)){
        if(unlikely(*(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32)){
          element->timestampLen = (*start) - element->timestamp;
          break;
        }
        (*start)++;
      }
    }else if((*start)[1] == 'v'){
      (*start) += offset[index++];
      element->cols = *start;
      while(*(*start)){
        if(unlikely( *(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32)){
          element->colsLen = (*start) - element->cols;
          break;
        }
        (*start)++;
      }
    }else if((*start)[1] == 't' && (*start)[2] == 'a'){
      (*start) += offset[index++];
      element->tags = (*start);
      char* tmp = smlJsonGetObj((*start));
      if(tmp){
        element->tagsLen = tmp - (*start);
        *start = tmp;
      }
      break;
    }
    if(*(*start) == '}'){
      (*start)++;
      break;
    }
    (*start)++;
  }
wmmhello's avatar
wmmhello 已提交
411 412 413 414 415 416

  if(unlikely(index != OTD_JSON_FIELDS_NUM)) {
    uError("elements != %d", OTD_JSON_FIELDS_NUM)
    return -1;
  }
  return 0;
wmmhello's avatar
wmmhello 已提交
417 418
}

wmmhello's avatar
wmmhello 已提交
419 420 421 422 423 424 425 426 427 428 429 430 431 432
static inline int32_t smlParseMetricFromJSON(SSmlHandle *info, cJSON *metric, SSmlLineInfo *elements) {
  elements->measureLen = strlen(metric->valuestring);
  if (IS_INVALID_TABLE_LEN(elements->measureLen)) {
    uError("OTD:0x%" PRIx64 " Metric lenght is 0 or large than 192", info->id);
    return TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
  }

  elements->measure = metric->valuestring;
  return TSDB_CODE_SUCCESS;
}

const char *jsonName[OTD_JSON_FIELDS_NUM] = {"metric", "timestamp", "value", "tags"};
static int32_t smlGetJsonElements(cJSON *root, cJSON ***marks){
  for (int i = 0; i < OTD_JSON_FIELDS_NUM; ++i) {
wmmhello's avatar
wmmhello 已提交
433
    cJSON *child = root->child;
wmmhello's avatar
wmmhello 已提交
434 435 436 437 438 439 440 441 442
    while(child != NULL)
    {
      if(strcasecmp(child->string, jsonName[i]) == 0){
        *marks[i] = child;
        break;
      }
      child = child->next;
    }
    if(*marks[i] == NULL){
wmmhello's avatar
wmmhello 已提交
443
      uError("smlGetJsonElements error, not find mark:%d:%s", i, jsonName[i]);
wmmhello's avatar
wmmhello 已提交
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
      return -1;
    }
  }
  return TSDB_CODE_SUCCESS;
}

static int32_t smlConvertJSONBool(SSmlKv *pVal, char *typeStr, cJSON *value) {
  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;

  return TSDB_CODE_SUCCESS;
}

static int32_t smlConvertJSONNumber(SSmlKv *pVal, char *typeStr, cJSON *value) {
  // tinyint
  if (strcasecmp(typeStr, "i8") == 0 || strcasecmp(typeStr, "tinyint") == 0) {
    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;
  }
  // smallint
  if (strcasecmp(typeStr, "i16") == 0 || strcasecmp(typeStr, "smallint") == 0) {
    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;
  }
  // int
  if (strcasecmp(typeStr, "i32") == 0 || strcasecmp(typeStr, "int") == 0) {
    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;
  }
  // bigint
  if (strcasecmp(typeStr, "i64") == 0 || strcasecmp(typeStr, "bigint") == 0) {
    pVal->type = TSDB_DATA_TYPE_BIGINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    if (value->valuedouble >= (double)INT64_MAX) {
      pVal->i = INT64_MAX;
    } else if (value->valuedouble <= (double)INT64_MIN) {
      pVal->i = INT64_MIN;
    } else {
      pVal->i = value->valuedouble;
    }
    return TSDB_CODE_SUCCESS;
  }
  // float
  if (strcasecmp(typeStr, "f32") == 0 || strcasecmp(typeStr, "float") == 0) {
    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;
    }
    pVal->type = TSDB_DATA_TYPE_FLOAT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->f = value->valuedouble;
    return TSDB_CODE_SUCCESS;
  }
  // double
  if (strcasecmp(typeStr, "f64") == 0 || strcasecmp(typeStr, "double") == 0) {
    pVal->type = TSDB_DATA_TYPE_DOUBLE;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->d = value->valuedouble;
    return TSDB_CODE_SUCCESS;
  }

  // if reach here means type is unsupported
  uError("OTD:invalid type(%s) for JSON Number", typeStr);
  return TSDB_CODE_TSC_INVALID_JSON_TYPE;
}

static int32_t smlConvertJSONString(SSmlKv *pVal, char *typeStr, cJSON *value) {
  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);

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

  pVal->value = value->valuestring;
  return TSDB_CODE_SUCCESS;
}

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;
      }
      break;
    }
    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;
  }

  return TSDB_CODE_SUCCESS;
}

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;
    }
    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
       */

      char *tsDefaultJSONStrType = "nchar";  // todo
      smlConvertJSONString(kv, tsDefaultJSONStrType, root);
      break;
    }
    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;
  }

  return TSDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
643
static int32_t smlParseTagsFromJSON(SSmlHandle *info, cJSON *tags, SSmlLineInfo *elements) {
wmmhello's avatar
wmmhello 已提交
644 645 646 647 648 649
  int32_t ret = TSDB_CODE_SUCCESS;

  bool isSameMeasure = IS_SAME_SUPER_TABLE;

  int     cnt = 0;
  SArray *preLineKV = info->preLineTagKV;
wmmhello's avatar
wmmhello 已提交
650
  SArray *maxKVs = info->maxTagKVs;
wmmhello's avatar
wmmhello 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
  bool    isSuperKVInit = true;
  SArray *superKV = NULL;
  if(info->dataFormat){
    if(unlikely(!isSameMeasure)){
      SSmlSTableMeta *sMeta = (SSmlSTableMeta *)nodeListGet(info->superTables, elements->measure, elements->measureLen, NULL);

      if(unlikely(sMeta == NULL)){
        sMeta = smlBuildSTableMeta(info->dataFormat);
        STableMeta * pTableMeta = smlGetMeta(info, elements->measure, elements->measureLen);
        sMeta->tableMeta = pTableMeta;
        if(pTableMeta == NULL){
          info->dataFormat = false;
          info->reRun      = true;
          return TSDB_CODE_SUCCESS;
        }
        nodeListSet(&info->superTables, elements->measure, elements->measureLen, sMeta, NULL);
      }
      info->currSTableMeta = sMeta->tableMeta;
      superKV = sMeta->tags;

      if(unlikely(taosArrayGetSize(superKV) == 0)){
        isSuperKVInit = false;
      }
wmmhello's avatar
wmmhello 已提交
674
      taosArraySetSize(maxKVs, 0);
wmmhello's avatar
wmmhello 已提交
675 676
    }
  }else{
wmmhello's avatar
wmmhello 已提交
677
    taosArraySetSize(maxKVs, 0);
wmmhello's avatar
wmmhello 已提交
678
  }
wmmhello's avatar
wmmhello 已提交
679
  taosArraySetSize(preLineKV, 0);
wmmhello's avatar
wmmhello 已提交
680 681

  int32_t tagNum = cJSON_GetArraySize(tags);
wmmhello's avatar
wmmhello 已提交
682 683 684 685
  if(unlikely(tagNum == 0)){
    uError("SML:Tag should not be empty");
    return TSDB_CODE_TSC_INVALID_JSON;
  }
wmmhello's avatar
wmmhello 已提交
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
  for (int32_t i = 0; i < tagNum; ++i) {
    cJSON *tag = cJSON_GetArrayItem(tags, i);
    if (unlikely(tag == NULL)) {
      return TSDB_CODE_TSC_INVALID_JSON;
    }
//    if(unlikely(tag == cMeasure)) continue;
    size_t keyLen = strlen(tag->string);
    if (unlikely(IS_INVALID_COL_LEN(keyLen))) {
      uError("OTD:Tag key length is 0 or too large than 64");
      return TSDB_CODE_TSC_INVALID_COLUMN_LENGTH;
    }

    // add kv to SSmlKv
    SSmlKv kv ={.key = tag->string, .keyLen = keyLen};
    // value
    ret = smlParseValueFromJSON(tag, &kv);
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
      return ret;
    }

    if(info->dataFormat){
      if(unlikely(cnt + 1 > info->currSTableMeta->tableInfo.numOfTags)){
        info->dataFormat = false;
        info->reRun      = true;
        return TSDB_CODE_SUCCESS;
      }

      if(isSameMeasure){
wmmhello's avatar
wmmhello 已提交
714
        if(unlikely(cnt >= taosArrayGetSize(maxKVs))) {
wmmhello's avatar
wmmhello 已提交
715 716 717 718
          info->dataFormat = false;
          info->reRun      = true;
          return TSDB_CODE_SUCCESS;
        }
wmmhello's avatar
wmmhello 已提交
719 720 721
        SSmlKv *maxKV = (SSmlKv *)taosArrayGet(maxKVs, cnt);
        if(unlikely(kv.length > maxKV->length)){
          maxKV->length = kv.length;
wmmhello's avatar
wmmhello 已提交
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740
          SSmlSTableMeta *tableMeta = (SSmlSTableMeta *)nodeListGet(info->superTables, elements->measure, elements->measureLen, NULL);
          ASSERT(tableMeta != NULL);

          SSmlKv *oldKV = (SSmlKv *)taosArrayGet(tableMeta->tags, cnt);
          oldKV->length = kv.length;
          info->needModifySchema = true;
        }
        if(unlikely(!IS_SAME_KEY)){
          info->dataFormat = false;
          info->reRun      = true;
          return TSDB_CODE_SUCCESS;
        }
      }else{
        if(isSuperKVInit){
          if(unlikely(cnt >= taosArrayGetSize(superKV))) {
            info->dataFormat = false;
            info->reRun      = true;
            return TSDB_CODE_SUCCESS;
          }
wmmhello's avatar
wmmhello 已提交
741 742 743
          SSmlKv *maxKV = (SSmlKv *)taosArrayGet(superKV, cnt);
          if(unlikely(kv.length > maxKV->length)) {
            maxKV->length = kv.length;
wmmhello's avatar
wmmhello 已提交
744
          }else{
wmmhello's avatar
wmmhello 已提交
745
            kv.length = maxKV->length;
wmmhello's avatar
wmmhello 已提交
746 747 748 749 750 751 752 753 754 755 756
          }
          info->needModifySchema = true;

          if(unlikely(!IS_SAME_KEY)){
            info->dataFormat = false;
            info->reRun      = true;
            return TSDB_CODE_SUCCESS;
          }
        }else{
          taosArrayPush(superKV, &kv);
        }
wmmhello's avatar
wmmhello 已提交
757
        taosArrayPush(maxKVs, &kv);
wmmhello's avatar
wmmhello 已提交
758 759
      }
    }else{
wmmhello's avatar
wmmhello 已提交
760
      taosArrayPush(maxKVs, &kv);
wmmhello's avatar
wmmhello 已提交
761
    }
wmmhello's avatar
wmmhello 已提交
762
    taosArrayPush(preLineKV, &kv);
wmmhello's avatar
wmmhello 已提交
763 764 765
    cnt++;
  }

wmmhello's avatar
wmmhello 已提交
766
  SSmlTableInfo *tinfo = (SSmlTableInfo *)nodeListGet(info->childTables, elements, POINTER_BYTES, is_same_child_table_telnet);
wmmhello's avatar
wmmhello 已提交
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783
  if (unlikely(tinfo == NULL)) {
    tinfo = smlBuildTableInfo(1, elements->measure, elements->measureLen);
    if (unlikely(!tinfo)) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
    tinfo->tags = taosArrayDup(preLineKV, NULL);

    smlSetCTableName(tinfo);
    if (info->dataFormat) {
      info->currSTableMeta->uid = tinfo->uid;
      tinfo->tableDataCtx = smlInitTableDataCtx(info->pQuery, info->currSTableMeta);
      if (tinfo->tableDataCtx == NULL) {
        smlBuildInvalidDataMsg(&info->msgBuf, "smlInitTableDataCtx error", NULL);
        return TSDB_CODE_SML_INVALID_DATA;
      }
    }

wmmhello's avatar
wmmhello 已提交
784 785
    SSmlLineInfo *key = (SSmlLineInfo *)taosMemoryMalloc(sizeof(SSmlLineInfo));
    *key = *elements;
wmmhello's avatar
wmmhello 已提交
786 787 788 789 790
    if(info->parseJsonByLib){
      key->tags = taosMemoryMalloc(elements->tagsLen + 1);
      memcpy(key->tags, elements->tags, elements->tagsLen);
      key->tags[elements->tagsLen] = 0;
    }
wmmhello's avatar
wmmhello 已提交
791 792
    tinfo->key = key;
    nodeListSet(&info->childTables, key, POINTER_BYTES, tinfo, is_same_child_table_telnet);
wmmhello's avatar
wmmhello 已提交
793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
  }
  if (info->dataFormat) info->currTableDataCtx = tinfo->tableDataCtx;

  return ret;
}

static int64_t smlParseTSFromJSONObj(SSmlHandle *info, cJSON *root, int32_t toPrecision) {
  int32_t size = cJSON_GetArraySize(root);
  if (unlikely(size != OTD_JSON_SUB_FIELDS_NUM)) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalidate json", NULL);
    return -1;
  }

  cJSON *value = cJSON_GetObjectItem(root, "value");
  if (unlikely(!cJSON_IsNumber(value))) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalidate json", NULL);
    return -1;
  }

  cJSON *type = cJSON_GetObjectItem(root, "type");
  if (unlikely(!cJSON_IsString(type))) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalidate json", NULL);
    return -1;
  }

  double timeDouble = value->valuedouble;
  if (unlikely(smlDoubleToInt64OverFlow(timeDouble))) {
    smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
    return -1;
  }

  if (timeDouble == 0) {
    return taosGetTimestampNs()/smlFactorNS[toPrecision];
  }

  if (timeDouble < 0) {
    return timeDouble;
  }

  int64_t tsInt64 = timeDouble;
  size_t typeLen = strlen(type->valuestring);
  if (typeLen == 1 && (type->valuestring[0] == 's' || type->valuestring[0] == 'S')) {
    // seconds
    int8_t fromPrecision = TSDB_TIME_PRECISION_SECONDS;
    if(smlFactorS[toPrecision] < INT64_MAX / tsInt64){
      return tsInt64 * smlFactorS[toPrecision];
    }
    return -1;
  } else if (typeLen == 2 && (type->valuestring[1] == 's' || type->valuestring[1] == 'S')) {
    switch (type->valuestring[0]) {
      case 'm':
      case 'M':
        // milliseconds
        return convertTimePrecision(tsInt64, TSDB_TIME_PRECISION_MILLI, toPrecision);
        break;
      case 'u':
      case 'U':
        // microseconds
        return convertTimePrecision(tsInt64, TSDB_TIME_PRECISION_MICRO, toPrecision);
        break;
      case 'n':
      case 'N':
        return convertTimePrecision(tsInt64, TSDB_TIME_PRECISION_NANO, toPrecision);
        break;
      default:
        return -1;
    }
  } else {
    return -1;
  }
}

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

static int64_t smlParseTSFromJSON(SSmlHandle *info, cJSON *timestamp) {
  // Timestamp must be the first KV to parse
  int32_t toPrecision = info->currSTableMeta ? info->currSTableMeta->tableInfo.precision : TSDB_TIME_PRECISION_NANO;
  if (cJSON_IsNumber(timestamp)) {
    // timestamp value 0 indicates current system time
    double timeDouble = timestamp->valuedouble;
    if (unlikely(smlDoubleToInt64OverFlow(timeDouble))) {
      smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
      return -1;
    }

    if (unlikely(timeDouble < 0)) {
      smlBuildInvalidDataMsg(&info->msgBuf,
                             "timestamp is negative", NULL);
      return timeDouble;
    }else if (unlikely(timeDouble == 0)) {
      return taosGetTimestampNs()/smlFactorNS[toPrecision];
    }

    uint8_t tsLen = smlGetTimestampLen((int64_t)timeDouble);

    int8_t fromPrecision = smlGetTsTypeByLen(tsLen);
    if (unlikely(fromPrecision == -1)) {
      smlBuildInvalidDataMsg(&info->msgBuf,
                             "timestamp precision can only be seconds(10 digits) or milli seconds(13 digits)", NULL);
      return -1;
    }
    int64_t tsInt64 = timeDouble;
    if(fromPrecision == TSDB_TIME_PRECISION_SECONDS){
      if(smlFactorS[toPrecision] < INT64_MAX / tsInt64){
        return tsInt64 * smlFactorS[toPrecision];
      }
      return -1;
    }else{
      return convertTimePrecision(timeDouble, fromPrecision, toPrecision);
    }
  } else if (cJSON_IsObject(timestamp)) {
    return smlParseTSFromJSONObj(info, timestamp, toPrecision);
  } else {
    smlBuildInvalidDataMsg(&info->msgBuf,
                           "invalidate json", NULL);
    return -1;
  }
}

static int32_t smlParseJSONStringExt(SSmlHandle *info, cJSON *root, SSmlLineInfo *elements) {
  int32_t ret = TSDB_CODE_SUCCESS;

  cJSON *metricJson = NULL;
  cJSON *tsJson = NULL;
  cJSON *valueJson = NULL;
  cJSON *tagsJson = NULL;
wmmhello's avatar
wmmhello 已提交
926 927 928
  char* rootStr = cJSON_PrintUnformatted(root);
  uError("rootStr:%s", rootStr);
  taosMemoryFree(rootStr);
wmmhello's avatar
wmmhello 已提交
929

wmmhello's avatar
wmmhello 已提交
930 931 932 933 934 935 936
  int32_t size = cJSON_GetArraySize(root);
  // outmost json fields has to be exactly 4
  if (size != OTD_JSON_FIELDS_NUM) {
    uError("OTD:0x%" PRIx64 " Invalid number of JSON fields in data point %d", info->id, size);
    return TSDB_CODE_TSC_INVALID_JSON;
  }

wmmhello's avatar
wmmhello 已提交
937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
  cJSON **marks[OTD_JSON_FIELDS_NUM] = {&metricJson, &tsJson, &valueJson, &tagsJson};
  ret = smlGetJsonElements(root, marks);
  if (unlikely(ret != TSDB_CODE_SUCCESS)) {
    return ret;
  }

  // Parse metric
  ret = smlParseMetricFromJSON(info, metricJson, elements);
  if (unlikely(ret != TSDB_CODE_SUCCESS)) {
    uError("OTD:0x%" PRIx64 " Unable to parse metric from JSON payload", info->id);
    return ret;
  }

  // Parse metric value
  SSmlKv kv = {.key = VALUE, .keyLen = VALUE_LEN};
  ret = smlParseValueFromJSON(valueJson, &kv);
  if (unlikely(ret)) {
    uError("OTD:0x%" PRIx64 " Unable to parse metric value from JSON payload", info->id);
    return ret;
  }

  // Parse tags
wmmhello's avatar
wmmhello 已提交
959 960 961 962 963 964 965
  elements->tags = cJSON_PrintUnformatted(tagsJson);
  elements->tagsLen = strlen(elements->tags);
  if(is_same_child_table_telnet(elements, &info->preLine) != 0) {
    ret = smlParseTagsFromJSON(info, tagsJson, elements);
    if (unlikely(ret)) {
      uError("OTD:0x%" PRIx64 " Unable to parse tags from JSON payload", info->id);
      taosMemoryFree(elements->tags);
wmmhello's avatar
wmmhello 已提交
966
      elements->tags = NULL;
wmmhello's avatar
wmmhello 已提交
967 968 969 970 971 972
      return ret;
    }
  }

  if(info->dataFormat){
    taosMemoryFree(elements->tags);
wmmhello's avatar
wmmhello 已提交
973
    elements->tags = NULL;
wmmhello's avatar
wmmhello 已提交
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
  }

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

  // Parse timestamp
  // notice!!! put ts back to tag to ensure get meta->precision
  int64_t ts = smlParseTSFromJSON(info, tsJson);
  if (unlikely(ts < 0)) {
    uError("OTD:0x%" PRIx64 " Unable to parse timestamp from JSON payload", info->id);
    return TSDB_CODE_INVALID_TIMESTAMP;
  }
  SSmlKv kvTs = { .key = TS, .keyLen = TS_LEN, .type = TSDB_DATA_TYPE_TIMESTAMP, .i = ts, .length = (size_t)tDataTypes[TSDB_DATA_TYPE_TIMESTAMP].bytes};

  if(info->dataFormat){
    ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kvTs, 0);
    if(ret == TSDB_CODE_SUCCESS){
      ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kv, 1);
    }
    if(ret == TSDB_CODE_SUCCESS){
      ret = smlBuildRow(info->currTableDataCtx);
    }
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
      smlBuildInvalidDataMsg(&info->msgBuf, "smlBuildCol error", NULL);
      return ret;
    }
  }else{
    if(elements->colArray == NULL){
      elements->colArray = taosArrayInit(16, sizeof(SSmlKv));
    }
    taosArrayPush(elements->colArray, &kvTs);
    taosArrayPush(elements->colArray, &kv);
  }
  info->preLine = *elements;

  return TSDB_CODE_SUCCESS;
}

static int32_t smlParseJSONExt(SSmlHandle *info, char *payload) {
  int32_t payloadNum = 0;
  int32_t ret = TSDB_CODE_SUCCESS;

  if (unlikely(payload == NULL)) {
    uError("SML:0x%" PRIx64 " empty JSON Payload", info->id);
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  info->root = cJSON_Parse(payload);
  if (unlikely(info->root == NULL)) {
    uError("SML:0x%" PRIx64 " parse json failed:%s", info->id, payload);
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  // multiple data points must be sent in JSON array
  if (cJSON_IsArray(info->root)) {
    payloadNum = cJSON_GetArraySize(info->root);
  } else if (cJSON_IsObject(info->root)) {
    payloadNum = 1;
  } else {
wmmhello's avatar
wmmhello 已提交
1034
    uError("SML:0x%" PRIx64 " Invalid JSON Payload 3:%s", info->id, payload);
wmmhello's avatar
wmmhello 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  info->lineNum = payloadNum;
  info->dataFormat = true;
  if (unlikely(info->lines != NULL)) {
    taosMemoryFree(info->lines);
    info->lines = NULL;
  }
  ret = smlClearForRerun(info);
wmmhello's avatar
wmmhello 已提交
1045 1046 1047
  if(ret != TSDB_CODE_SUCCESS){
    return ret;
  }
wmmhello's avatar
wmmhello 已提交
1048 1049

  info->parseJsonByLib = true;
wmmhello's avatar
wmmhello 已提交
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
  cJSON *head = (payloadNum == 1 && cJSON_IsObject(info->root)) ? info->root : info->root->child;

  int cnt = 0;
  cJSON *dataPoint = head;
  while (dataPoint) {
    if(info->dataFormat) {
      SSmlLineInfo element = {0};
      ret = smlParseJSONStringExt(info, dataPoint, &element);
    }else{
      ret = smlParseJSONStringExt(info, dataPoint, info->lines + cnt);
    }
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
wmmhello's avatar
wmmhello 已提交
1062
      uError("SML:0x%" PRIx64 " Invalid JSON Payload 2:%s", info->id, payload);
wmmhello's avatar
wmmhello 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
      return ret;
    }

    if(unlikely(info->reRun)){
      cnt = 0;
      dataPoint = head;
      info->lineNum = payloadNum;
      ret = smlClearForRerun(info);
      if(ret != TSDB_CODE_SUCCESS){
        return ret;
      }
      continue;
    }
    cnt++;
    dataPoint = dataPoint->next;
  }

  return TSDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
static int32_t smlParseJSONString(SSmlHandle *info, char **start, SSmlLineInfo *elements) {
  int32_t ret = TSDB_CODE_SUCCESS;

  if(info->offset[0] == 0){
    ret = smlJsonParseObjFirst(start, elements, info->offset);
  }else{
    ret = smlJsonParseObj(start, elements, info->offset);
  }

  if (ret != TSDB_CODE_SUCCESS) {
    return TSDB_CODE_TSC_INVALID_VALUE;
  }

  if(unlikely(**start == '\0' && elements->measure == NULL)) return TSDB_CODE_SUCCESS;

  SSmlKv kv = {.key = VALUE, .keyLen = VALUE_LEN, .value = elements->cols, .length = (size_t)elements->colsLen};
  if (elements->colsLen == 0 || smlParseValue(&kv, &info->msgBuf) != TSDB_CODE_SUCCESS) {
    uError("SML:cols invalidate:%s", elements->cols);
    return TSDB_CODE_TSC_INVALID_VALUE;
  }

  // Parse tags
  if(is_same_child_table_telnet(elements, &info->preLine) != 0){
    char tmp = *(elements->tags + elements->tagsLen);
    *(elements->tags + elements->tagsLen) = 0;
    cJSON* tagsJson = cJSON_Parse(elements->tags);
    *(elements->tags + elements->tagsLen) = tmp;
    if (unlikely(tagsJson == NULL)) {
      uError("SML:0x%" PRIx64 " parse json failed:%s", info->id, elements->tags);
      return TSDB_CODE_TSC_INVALID_JSON;
    }

    ret = smlParseTagsFromJSON(info, tagsJson, elements);
    cJSON_free(tagsJson);
    if (unlikely(ret)) {
      uError("OTD:0x%" PRIx64 " Unable to parse tags from JSON payload", info->id);
      return ret;
    }
  }

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

  // Parse timestamp
  // notice!!! put ts back to tag to ensure get meta->precision
  int64_t ts = smlParseOpenTsdbTime(info, elements->timestamp, elements->timestampLen);
  if (unlikely(ts < 0)) {
    uError("OTD:0x%" PRIx64 " Unable to parse timestamp from JSON payload", info->id);
    return TSDB_CODE_INVALID_TIMESTAMP;
  }
  SSmlKv kvTs = { .key = TS, .keyLen = TS_LEN, .type = TSDB_DATA_TYPE_TIMESTAMP, .i = ts, .length = (size_t)tDataTypes[TSDB_DATA_TYPE_TIMESTAMP].bytes};

  if(info->dataFormat){
    ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kvTs, 0);
    if(ret == TSDB_CODE_SUCCESS){
      ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kv, 1);
    }
    if(ret == TSDB_CODE_SUCCESS){
      ret = smlBuildRow(info->currTableDataCtx);
    }
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
      smlBuildInvalidDataMsg(&info->msgBuf, "smlBuildCol error", NULL);
      return ret;
    }
  }else{
    if(elements->colArray == NULL){
      elements->colArray = taosArrayInit(16, sizeof(SSmlKv));
    }
    taosArrayPush(elements->colArray, &kvTs);
    taosArrayPush(elements->colArray, &kv);
  }
  info->preLine = *elements;

  return TSDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
1160 1161
int32_t smlParseJSON(SSmlHandle *info, char *payload) {
  int32_t payloadNum = 1 << 15;
1162 1163 1164
  int32_t ret = TSDB_CODE_SUCCESS;

  int cnt = 0;
wmmhello's avatar
wmmhello 已提交
1165 1166
  char *dataPointStart = payload;
  while (1) {
1167 1168
    if(info->dataFormat) {
      SSmlLineInfo element = {0};
wmmhello's avatar
wmmhello 已提交
1169
      ret = smlParseJSONString(info, &dataPointStart, &element);
1170
    }else{
wmmhello's avatar
wmmhello 已提交
1171 1172 1173 1174 1175
      if(cnt >= payloadNum){
        payloadNum = payloadNum << 1;
        void* tmp = taosMemoryRealloc(info->lines, payloadNum * sizeof(SSmlLineInfo));
        if(tmp != NULL){
          info->lines = (SSmlLineInfo*)tmp;
wmmhello's avatar
wmmhello 已提交
1176
          memset(info->lines + cnt, 0, (payloadNum - cnt) * sizeof(SSmlLineInfo));
wmmhello's avatar
wmmhello 已提交
1177 1178
        }
      }
wmmhello's avatar
wmmhello 已提交
1179
      ret = smlParseJSONString(info, &dataPointStart, info->lines + cnt);
1180 1181
    }
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
wmmhello's avatar
wmmhello 已提交
1182
      uError("SML:0x%" PRIx64 " Invalid JSON Payload 1:%s", info->id, payload);
wmmhello's avatar
wmmhello 已提交
1183
      return smlParseJSONExt(info, payload);
1184 1185 1186
    }

    if(unlikely(info->reRun)){
1187
      cnt = 0;
wmmhello's avatar
wmmhello 已提交
1188
      dataPointStart = payload;
1189 1190 1191 1192 1193 1194 1195
      info->lineNum = payloadNum;
      ret = smlClearForRerun(info);
      if(ret != TSDB_CODE_SUCCESS){
        return ret;
      }
      continue;
    }
wmmhello's avatar
wmmhello 已提交
1196 1197

    if(*dataPointStart == '\0') break;
1198
    cnt++;
1199
  }
wmmhello's avatar
wmmhello 已提交
1200
  info->lineNum = cnt;
1201 1202

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