clientSmlJson.c 40.7 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

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

X
Xiaoyu Wang 已提交
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
// 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;
//       }
wmmhello's avatar
wmmhello 已提交
64
//
X
Xiaoyu Wang 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78
//       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;
wmmhello's avatar
wmmhello 已提交
79
//
X
Xiaoyu Wang 已提交
80 81 82
//   if(is_same_child_table_telnet(elements, &info->preLine) == 0){
//     return TSDB_CODE_SUCCESS;
//   }
wmmhello's avatar
wmmhello 已提交
83
//
X
Xiaoyu Wang 已提交
84
//   bool isSameMeasure = IS_SAME_SUPER_TABLE;
wmmhello's avatar
wmmhello 已提交
85
//
X
Xiaoyu Wang 已提交
86 87 88 89 90 91 92 93
//   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);
wmmhello's avatar
wmmhello 已提交
94
//
X
Xiaoyu Wang 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107
//       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;
wmmhello's avatar
wmmhello 已提交
108
//
X
Xiaoyu Wang 已提交
109 110 111 112 113 114 115 116
//       if(unlikely(taosArrayGetSize(superKV) == 0)){
//         isSuperKVInit = false;
//       }
//       taosArraySetSize(preLineKV, 0);
//     }
//   }else{
//     taosArraySetSize(preLineKV, 0);
//   }
wmmhello's avatar
wmmhello 已提交
117
//
X
Xiaoyu Wang 已提交
118 119 120 121 122 123 124 125 126
//   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);
wmmhello's avatar
wmmhello 已提交
127
//
X
Xiaoyu Wang 已提交
128 129 130 131 132 133 134
//     if(info->dataFormat){
//       if(unlikely(cnt + 1 > info->currSTableMeta->tableInfo.numOfTags)){
//         info->dataFormat = false;
//         info->reRun      = true;
//         taosArrayDestroy(tags);
//         return TSDB_CODE_SUCCESS;
//       }
wmmhello's avatar
wmmhello 已提交
135
//
X
Xiaoyu Wang 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
//       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);
//            if(unlikely(NULL == tableMeta)){
//              uError("SML:0x%" PRIx64 " NULL == tableMeta", info->id);
//              return TSDB_CODE_SML_INTERNAL_ERROR;
//            }
wmmhello's avatar
wmmhello 已提交
152
//
X
Xiaoyu Wang 已提交
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
//           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;
wmmhello's avatar
wmmhello 已提交
178
//
X
Xiaoyu Wang 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
//           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);
wmmhello's avatar
wmmhello 已提交
196
//
X
Xiaoyu Wang 已提交
197 198 199 200 201 202 203
//   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);
wmmhello's avatar
wmmhello 已提交
204
//
X
Xiaoyu Wang 已提交
205 206 207 208 209 210 211 212 213
//     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 已提交
214
//
X
Xiaoyu Wang 已提交
215 216 217 218 219 220
//     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;
wmmhello's avatar
wmmhello 已提交
221
//
X
Xiaoyu Wang 已提交
222 223
//   return ret;
// }
224

X
Xiaoyu Wang 已提交
225
static char *smlJsonGetObj(char *payload) {
wmmhello's avatar
wmmhello 已提交
226 227
  int  leftBracketCnt = 0;
  bool isInQuote = false;
X
Xiaoyu Wang 已提交
228 229
  while (*payload) {
    if (*payload == '"' && *(payload - 1) != '\\') {
wmmhello's avatar
wmmhello 已提交
230
      isInQuote = !isInQuote;
X
Xiaoyu Wang 已提交
231
    } else if (!isInQuote && unlikely(*payload == '{')) {
wmmhello's avatar
wmmhello 已提交
232 233 234
      leftBracketCnt++;
      payload++;
      continue;
X
Xiaoyu Wang 已提交
235
    } else if (!isInQuote && unlikely(*payload == '}')) {
wmmhello's avatar
wmmhello 已提交
236 237 238 239 240 241
      leftBracketCnt--;
      payload++;
      if (leftBracketCnt == 0) {
        return payload;
      } else if (leftBracketCnt < 0) {
        return NULL;
242
      }
wmmhello's avatar
wmmhello 已提交
243
      continue;
244
    }
wmmhello's avatar
wmmhello 已提交
245 246 247 248 249
    payload++;
  }
  return NULL;
}

X
Xiaoyu Wang 已提交
250
int smlJsonParseObjFirst(char **start, SSmlLineInfo *element, int8_t *offset) {
wmmhello's avatar
wmmhello 已提交
251
  int index = 0;
X
Xiaoyu Wang 已提交
252 253
  while (*(*start)) {
    if ((*start)[0] != '"') {
wmmhello's avatar
wmmhello 已提交
254 255 256
      (*start)++;
      continue;
    }
wmmhello's avatar
wmmhello 已提交
257

X
Xiaoyu Wang 已提交
258 259
    if (unlikely(index >= OTD_JSON_FIELDS_NUM)) {
      uError("index >= %d, %s", OTD_JSON_FIELDS_NUM, *start) return -1;
wmmhello's avatar
wmmhello 已提交
260 261
    }

wmmhello's avatar
wmmhello 已提交
262
    char *sTmp = *start;
X
Xiaoyu Wang 已提交
263 264
    if ((*start)[1] == 'm' && (*start)[2] == 'e' && (*start)[3] == 't' && (*start)[4] == 'r' && (*start)[5] == 'i' &&
        (*start)[6] == 'c' && (*start)[7] == '"') {
wmmhello's avatar
wmmhello 已提交
265
      (*start) += 8;
wmmhello's avatar
wmmhello 已提交
266
      bool isInQuote = false;
X
Xiaoyu Wang 已提交
267 268
      while (*(*start)) {
        if (unlikely(!isInQuote && *(*start) == '"')) {
wmmhello's avatar
wmmhello 已提交
269
          (*start)++;
wmmhello's avatar
wmmhello 已提交
270
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
271
          element->measure = (*start);
wmmhello's avatar
wmmhello 已提交
272 273 274
          isInQuote = true;
          continue;
        }
X
Xiaoyu Wang 已提交
275
        if (unlikely(isInQuote && *(*start) == '"')) {
wmmhello's avatar
wmmhello 已提交
276
          element->measureLen = (*start) - element->measure;
wmmhello's avatar
wmmhello 已提交
277
          (*start)++;
wmmhello's avatar
wmmhello 已提交
278 279
          break;
        }
wmmhello's avatar
wmmhello 已提交
280
        (*start)++;
wmmhello's avatar
wmmhello 已提交
281
      }
X
Xiaoyu Wang 已提交
282 283 284
    } else if ((*start)[1] == 't' && (*start)[2] == 'i' && (*start)[3] == 'm' && (*start)[4] == 'e' &&
               (*start)[5] == 's' && (*start)[6] == 't' && (*start)[7] == 'a' && (*start)[8] == 'm' &&
               (*start)[9] == 'p' && (*start)[10] == '"') {
wmmhello's avatar
wmmhello 已提交
285
      (*start) += 11;
wmmhello's avatar
wmmhello 已提交
286
      bool hasColon = false;
X
Xiaoyu Wang 已提交
287 288
      while (*(*start)) {
        if (unlikely(!hasColon && *(*start) == ':')) {
wmmhello's avatar
wmmhello 已提交
289 290
          (*start)++;
          JUMP_JSON_SPACE((*start))
wmmhello's avatar
wmmhello 已提交
291
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
292
          element->timestamp = (*start);
X
Xiaoyu Wang 已提交
293 294 295
          if (*(*start) == '{') {
            char *tmp = smlJsonGetObj((*start));
            if (tmp) {
wmmhello's avatar
wmmhello 已提交
296 297 298 299 300
              element->timestampLen = tmp - (*start);
              *start = tmp;
            }
            break;
          }
wmmhello's avatar
wmmhello 已提交
301 302 303
          hasColon = true;
          continue;
        }
X
Xiaoyu Wang 已提交
304
        if (unlikely(hasColon && (*(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32))) {
wmmhello's avatar
wmmhello 已提交
305
          element->timestampLen = (*start) - element->timestamp;
wmmhello's avatar
wmmhello 已提交
306 307
          break;
        }
wmmhello's avatar
wmmhello 已提交
308
        (*start)++;
wmmhello's avatar
wmmhello 已提交
309
      }
X
Xiaoyu Wang 已提交
310 311
    } else if ((*start)[1] == 'v' && (*start)[2] == 'a' && (*start)[3] == 'l' && (*start)[4] == 'u' &&
               (*start)[5] == 'e' && (*start)[6] == '"') {
wmmhello's avatar
wmmhello 已提交
312
      (*start) += 7;
wmmhello's avatar
wmmhello 已提交
313 314

      bool hasColon = false;
X
Xiaoyu Wang 已提交
315 316
      while (*(*start)) {
        if (unlikely(!hasColon && *(*start) == ':')) {
wmmhello's avatar
wmmhello 已提交
317 318
          (*start)++;
          JUMP_JSON_SPACE((*start))
wmmhello's avatar
wmmhello 已提交
319
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
320
          element->cols = (*start);
X
Xiaoyu Wang 已提交
321 322 323
          if (*(*start) == '{') {
            char *tmp = smlJsonGetObj((*start));
            if (tmp) {
wmmhello's avatar
wmmhello 已提交
324 325 326 327 328
              element->colsLen = tmp - (*start);
              *start = tmp;
            }
            break;
          }
wmmhello's avatar
wmmhello 已提交
329 330 331
          hasColon = true;
          continue;
        }
X
Xiaoyu Wang 已提交
332
        if (unlikely(hasColon && (*(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32))) {
wmmhello's avatar
wmmhello 已提交
333
          element->colsLen = (*start) - element->cols;
wmmhello's avatar
wmmhello 已提交
334 335
          break;
        }
wmmhello's avatar
wmmhello 已提交
336
        (*start)++;
wmmhello's avatar
wmmhello 已提交
337
      }
X
Xiaoyu Wang 已提交
338 339
    } else if ((*start)[1] == 't' && (*start)[2] == 'a' && (*start)[3] == 'g' && (*start)[4] == 's' &&
               (*start)[5] == '"') {
wmmhello's avatar
wmmhello 已提交
340 341
      (*start) += 6;

X
Xiaoyu Wang 已提交
342 343
      while (*(*start)) {
        if (unlikely(*(*start) == ':')) {
wmmhello's avatar
wmmhello 已提交
344 345
          (*start)++;
          JUMP_JSON_SPACE((*start))
wmmhello's avatar
wmmhello 已提交
346
          offset[index++] = *start - sTmp;
wmmhello's avatar
wmmhello 已提交
347
          element->tags = (*start);
X
Xiaoyu Wang 已提交
348 349
          char *tmp = smlJsonGetObj((*start));
          if (tmp) {
wmmhello's avatar
wmmhello 已提交
350 351 352
            element->tagsLen = tmp - (*start);
            *start = tmp;
          }
wmmhello's avatar
wmmhello 已提交
353 354
          break;
        }
wmmhello's avatar
wmmhello 已提交
355
        (*start)++;
wmmhello's avatar
wmmhello 已提交
356
      }
357
    }
X
Xiaoyu Wang 已提交
358
    if (*(*start) == '\0') {
wmmhello's avatar
wmmhello 已提交
359 360
      break;
    }
X
Xiaoyu Wang 已提交
361
    if (*(*start) == '}') {
wmmhello's avatar
wmmhello 已提交
362 363 364 365
      (*start)++;
      break;
    }
    (*start)++;
366
  }
wmmhello's avatar
wmmhello 已提交
367

X
Xiaoyu Wang 已提交
368 369 370
  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) return -1;
wmmhello's avatar
wmmhello 已提交
371 372
  }
  return 0;
373 374
}

X
Xiaoyu Wang 已提交
375
int smlJsonParseObj(char **start, SSmlLineInfo *element, int8_t *offset) {
wmmhello's avatar
wmmhello 已提交
376
  int index = 0;
X
Xiaoyu Wang 已提交
377 378
  while (*(*start)) {
    if ((*start)[0] != '"') {
wmmhello's avatar
wmmhello 已提交
379 380 381 382
      (*start)++;
      continue;
    }

X
Xiaoyu Wang 已提交
383 384
    if (unlikely(index >= OTD_JSON_FIELDS_NUM)) {
      uError("index >= %d, %s", OTD_JSON_FIELDS_NUM, *start) return -1;
wmmhello's avatar
wmmhello 已提交
385 386
    }

X
Xiaoyu Wang 已提交
387
    if ((*start)[1] == 'm') {
wmmhello's avatar
wmmhello 已提交
388 389
      (*start) += offset[index++];
      element->measure = *start;
X
Xiaoyu Wang 已提交
390 391
      while (*(*start)) {
        if (unlikely(*(*start) == '"')) {
wmmhello's avatar
wmmhello 已提交
392
          element->measureLen = (*start) - element->measure;
wmmhello's avatar
wmmhello 已提交
393
          (*start)++;
wmmhello's avatar
wmmhello 已提交
394 395 396 397
          break;
        }
        (*start)++;
      }
X
Xiaoyu Wang 已提交
398
    } else if ((*start)[1] == 't' && (*start)[2] == 'i') {
wmmhello's avatar
wmmhello 已提交
399 400
      (*start) += offset[index++];
      element->timestamp = *start;
X
Xiaoyu Wang 已提交
401 402 403
      if (*(*start) == '{') {
        char *tmp = smlJsonGetObj((*start));
        if (tmp) {
wmmhello's avatar
wmmhello 已提交
404 405 406
          element->timestampLen = tmp - (*start);
          *start = tmp;
        }
X
Xiaoyu Wang 已提交
407 408 409
      } else {
        while (*(*start)) {
          if (unlikely(*(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32)) {
wmmhello's avatar
wmmhello 已提交
410 411 412 413
            element->timestampLen = (*start) - element->timestamp;
            break;
          }
          (*start)++;
wmmhello's avatar
wmmhello 已提交
414 415
        }
      }
X
Xiaoyu Wang 已提交
416
    } else if ((*start)[1] == 'v') {
wmmhello's avatar
wmmhello 已提交
417 418
      (*start) += offset[index++];
      element->cols = *start;
X
Xiaoyu Wang 已提交
419 420 421
      if (*(*start) == '{') {
        char *tmp = smlJsonGetObj((*start));
        if (tmp) {
wmmhello's avatar
wmmhello 已提交
422 423 424
          element->colsLen = tmp - (*start);
          *start = tmp;
        }
X
Xiaoyu Wang 已提交
425 426 427
      } else {
        while (*(*start)) {
          if (unlikely(*(*start) == ',' || *(*start) == '}' || (*(*start)) <= 32)) {
wmmhello's avatar
wmmhello 已提交
428 429 430 431
            element->colsLen = (*start) - element->cols;
            break;
          }
          (*start)++;
wmmhello's avatar
wmmhello 已提交
432 433
        }
      }
X
Xiaoyu Wang 已提交
434
    } else if ((*start)[1] == 't' && (*start)[2] == 'a') {
wmmhello's avatar
wmmhello 已提交
435 436
      (*start) += offset[index++];
      element->tags = (*start);
X
Xiaoyu Wang 已提交
437 438
      char *tmp = smlJsonGetObj((*start));
      if (tmp) {
wmmhello's avatar
wmmhello 已提交
439 440 441 442
        element->tagsLen = tmp - (*start);
        *start = tmp;
      }
    }
X
Xiaoyu Wang 已提交
443
    if (*(*start) == '}') {
wmmhello's avatar
wmmhello 已提交
444 445 446 447 448
      (*start)++;
      break;
    }
    (*start)++;
  }
wmmhello's avatar
wmmhello 已提交
449

X
Xiaoyu Wang 已提交
450 451
  if (unlikely(index != 0 && index != OTD_JSON_FIELDS_NUM)) {
    uError("elements != %d", OTD_JSON_FIELDS_NUM) return -1;
wmmhello's avatar
wmmhello 已提交
452 453
  }
  return 0;
wmmhello's avatar
wmmhello 已提交
454 455
}

wmmhello's avatar
wmmhello 已提交
456 457 458 459 460 461 462 463 464 465 466
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;
}

X
Xiaoyu Wang 已提交
467 468
const char    *jsonName[OTD_JSON_FIELDS_NUM] = {"metric", "timestamp", "value", "tags"};
static int32_t smlGetJsonElements(cJSON *root, cJSON ***marks) {
wmmhello's avatar
wmmhello 已提交
469
  for (int i = 0; i < OTD_JSON_FIELDS_NUM; ++i) {
wmmhello's avatar
wmmhello 已提交
470
    cJSON *child = root->child;
X
Xiaoyu Wang 已提交
471 472
    while (child != NULL) {
      if (strcasecmp(child->string, jsonName[i]) == 0) {
wmmhello's avatar
wmmhello 已提交
473 474 475 476 477
        *marks[i] = child;
        break;
      }
      child = child->next;
    }
X
Xiaoyu Wang 已提交
478
    if (*marks[i] == NULL) {
wmmhello's avatar
wmmhello 已提交
479
      uError("smlGetJsonElements error, not find mark:%d:%s", i, jsonName[i]);
wmmhello's avatar
wmmhello 已提交
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
      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;
  }
578
  pVal->length = strlen(value->valuestring);
wmmhello's avatar
wmmhello 已提交
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 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659

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

wmmhello's avatar
wmmhello 已提交
660
      char *tsDefaultJSONStrType = "binary";  // todo
wmmhello's avatar
wmmhello 已提交
661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678
      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 已提交
679
static int32_t smlParseTagsFromJSON(SSmlHandle *info, cJSON *tags, SSmlLineInfo *elements) {
wmmhello's avatar
wmmhello 已提交
680 681 682 683 684 685
  int32_t ret = TSDB_CODE_SUCCESS;

  bool isSameMeasure = IS_SAME_SUPER_TABLE;

  int     cnt = 0;
  SArray *preLineKV = info->preLineTagKV;
X
Xiaoyu Wang 已提交
686 687
  if (info->dataFormat) {
    if (unlikely(!isSameMeasure)) {
688
      SSmlSTableMeta **tmp = (SSmlSTableMeta **)taosHashGet(info->superTables, elements->measure, elements->measureLen);
689
      SSmlSTableMeta *sMeta = NULL;
X
Xiaoyu Wang 已提交
690 691 692
      if (unlikely(tmp == NULL)) {
        STableMeta *pTableMeta = smlGetMeta(info, elements->measure, elements->measureLen);
        if (pTableMeta == NULL) {
wmmhello's avatar
wmmhello 已提交
693
          info->dataFormat = false;
X
Xiaoyu Wang 已提交
694
          info->reRun = true;
wmmhello's avatar
wmmhello 已提交
695 696
          return TSDB_CODE_SUCCESS;
        }
wmmhello's avatar
wmmhello 已提交
697
        sMeta = smlBuildSTableMeta(info->dataFormat);
wmmhello's avatar
wmmhello 已提交
698
        if(sMeta == NULL){
wmmhello's avatar
wmmhello 已提交
699
          taosMemoryFreeClear(pTableMeta);
wmmhello's avatar
wmmhello 已提交
700 701
          return TSDB_CODE_OUT_OF_MEMORY;
        }
wmmhello's avatar
wmmhello 已提交
702
        sMeta->tableMeta = pTableMeta;
703
        taosHashPut(info->superTables, elements->measure, elements->measureLen, &sMeta, POINTER_BYTES);
704 705 706 707 708
        for(int i = pTableMeta->tableInfo.numOfColumns; i < pTableMeta->tableInfo.numOfTags + pTableMeta->tableInfo.numOfColumns; i++){
          SSchema *tag = pTableMeta->schema + i;
          SSmlKv kv = {.key = tag->name, .keyLen = strlen(tag->name), .type = tag->type, .length = (tag->bytes - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE };
          taosArrayPush(sMeta->tags, &kv);
        }
709
        tmp = &sMeta;
wmmhello's avatar
wmmhello 已提交
710
      }
711
      info->currSTableMeta = (*tmp)->tableMeta;
712
      info->maxTagKVs = (*tmp)->tags;
wmmhello's avatar
wmmhello 已提交
713 714
    }
  }
X
Xiaoyu Wang 已提交
715
  taosArrayClear(preLineKV);
wmmhello's avatar
wmmhello 已提交
716 717

  int32_t tagNum = cJSON_GetArraySize(tags);
X
Xiaoyu Wang 已提交
718
  if (unlikely(tagNum == 0)) {
wmmhello's avatar
wmmhello 已提交
719 720 721
    uError("SML:Tag should not be empty");
    return TSDB_CODE_TSC_INVALID_JSON;
  }
wmmhello's avatar
wmmhello 已提交
722 723 724 725 726
  for (int32_t i = 0; i < tagNum; ++i) {
    cJSON *tag = cJSON_GetArrayItem(tags, i);
    if (unlikely(tag == NULL)) {
      return TSDB_CODE_TSC_INVALID_JSON;
    }
X
Xiaoyu Wang 已提交
727
    //    if(unlikely(tag == cMeasure)) continue;
wmmhello's avatar
wmmhello 已提交
728 729 730 731 732 733 734
    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
X
Xiaoyu Wang 已提交
735
    SSmlKv kv = {.key = tag->string, .keyLen = keyLen};
wmmhello's avatar
wmmhello 已提交
736 737 738 739 740 741
    // value
    ret = smlParseValueFromJSON(tag, &kv);
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
      return ret;
    }

X
Xiaoyu Wang 已提交
742 743
    if (info->dataFormat) {
      if (unlikely(cnt + 1 > info->currSTableMeta->tableInfo.numOfTags)) {
wmmhello's avatar
wmmhello 已提交
744
        info->dataFormat = false;
X
Xiaoyu Wang 已提交
745
        info->reRun = true;
wmmhello's avatar
wmmhello 已提交
746 747 748
        return TSDB_CODE_SUCCESS;
      }

749 750 751 752 753 754 755 756 757 758 759 760 761 762
      if (unlikely(cnt >= taosArrayGetSize(info->maxTagKVs))) {
        info->dataFormat = false;
        info->reRun = true;
        return TSDB_CODE_SUCCESS;
      }
      SSmlKv *maxKV = (SSmlKv *)taosArrayGet(info->maxTagKVs, cnt);
      if (unlikely(!IS_SAME_KEY)) {
        info->dataFormat = false;
        info->reRun = true;
        return TSDB_CODE_SUCCESS;
      }
      if (unlikely(kv.length > maxKV->length)) {
        maxKV->length = kv.length;
        info->needModifySchema = true;
wmmhello's avatar
wmmhello 已提交
763 764
      }
    }
wmmhello's avatar
wmmhello 已提交
765
    taosArrayPush(preLineKV, &kv);
wmmhello's avatar
wmmhello 已提交
766 767 768
    cnt++;
  }

X
Xiaoyu Wang 已提交
769
  elements->measureTag = (char *)taosMemoryMalloc(elements->measureLen + elements->tagsLen);
770 771
  memcpy(elements->measureTag, elements->measure, elements->measureLen);
  memcpy(elements->measureTag + elements->measureLen, elements->tags, elements->tagsLen);
772
  elements->measureTagsLen = elements->measureLen + elements->tagsLen;
773

X
Xiaoyu Wang 已提交
774 775
  SSmlTableInfo **tmp =
      (SSmlTableInfo **)taosHashGet(info->childTables, elements->measureTag, elements->measureLen + elements->tagsLen);
776 777
  SSmlTableInfo *tinfo = NULL;
  if (unlikely(tmp == NULL)) {
wmmhello's avatar
wmmhello 已提交
778 779 780 781 782 783 784
    tinfo = smlBuildTableInfo(1, elements->measure, elements->measureLen);
    if (unlikely(!tinfo)) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
    tinfo->tags = taosArrayDup(preLineKV, NULL);

    smlSetCTableName(tinfo);
785
    getTableUid(info, elements, tinfo);
wmmhello's avatar
wmmhello 已提交
786 787 788 789 790
    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);
wmmhello's avatar
wmmhello 已提交
791
        smlDestroyTableInfo(&tinfo);
wmmhello's avatar
wmmhello 已提交
792 793 794 795
        return TSDB_CODE_SML_INVALID_DATA;
      }
    }

X
Xiaoyu Wang 已提交
796 797 798 799 800 801 802 803 804 805
    //    SSmlLineInfo *key = (SSmlLineInfo *)taosMemoryMalloc(sizeof(SSmlLineInfo));
    //    *key = *elements;
    //    if(info->parseJsonByLib){
    //      key->tags = taosMemoryMalloc(elements->tagsLen + 1);
    //      memcpy(key->tags, elements->tags, elements->tagsLen);
    //      key->tags[elements->tagsLen] = 0;
    //    }
    //    tinfo->key = key;
    taosHashPut(info->childTables, elements->measureTag, elements->measureLen + elements->tagsLen, &tinfo,
                POINTER_BYTES);
806
    tmp = &tinfo;
wmmhello's avatar
wmmhello 已提交
807
  }
808
  if (info->dataFormat) info->currTableDataCtx = (*tmp)->tableDataCtx;
wmmhello's avatar
wmmhello 已提交
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

  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) {
X
Xiaoyu Wang 已提交
839
    return taosGetTimestampNs() / smlFactorNS[toPrecision];
wmmhello's avatar
wmmhello 已提交
840 841 842 843 844 845 846
  }

  if (timeDouble < 0) {
    return timeDouble;
  }

  int64_t tsInt64 = timeDouble;
X
Xiaoyu Wang 已提交
847
  size_t  typeLen = strlen(type->valuestring);
wmmhello's avatar
wmmhello 已提交
848 849 850
  if (typeLen == 1 && (type->valuestring[0] == 's' || type->valuestring[0] == 'S')) {
    // seconds
    int8_t fromPrecision = TSDB_TIME_PRECISION_SECONDS;
X
Xiaoyu Wang 已提交
851
    if (smlFactorS[toPrecision] < INT64_MAX / tsInt64) {
wmmhello's avatar
wmmhello 已提交
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
      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)) {
X
Xiaoyu Wang 已提交
900
      smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is negative", NULL);
wmmhello's avatar
wmmhello 已提交
901
      return timeDouble;
X
Xiaoyu Wang 已提交
902 903
    } else if (unlikely(timeDouble == 0)) {
      return taosGetTimestampNs() / smlFactorNS[toPrecision];
wmmhello's avatar
wmmhello 已提交
904 905 906 907 908 909 910 911 912 913 914
    }

    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;
X
Xiaoyu Wang 已提交
915 916
    if (fromPrecision == TSDB_TIME_PRECISION_SECONDS) {
      if (smlFactorS[toPrecision] < INT64_MAX / tsInt64) {
wmmhello's avatar
wmmhello 已提交
917 918 919
        return tsInt64 * smlFactorS[toPrecision];
      }
      return -1;
X
Xiaoyu Wang 已提交
920
    } else {
wmmhello's avatar
wmmhello 已提交
921 922 923 924 925
      return convertTimePrecision(timeDouble, fromPrecision, toPrecision);
    }
  } else if (cJSON_IsObject(timestamp)) {
    return smlParseTSFromJSONObj(info, timestamp, toPrecision);
  } else {
X
Xiaoyu Wang 已提交
926
    smlBuildInvalidDataMsg(&info->msgBuf, "invalidate json", NULL);
wmmhello's avatar
wmmhello 已提交
927 928 929 930 931 932 933 934 935 936 937 938
    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 已提交
939 940 941 942 943 944 945
  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 已提交
946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
  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 已提交
968
  bool needFree = info->dataFormat;
wmmhello's avatar
wmmhello 已提交
969 970
  elements->tags = cJSON_PrintUnformatted(tagsJson);
  elements->tagsLen = strlen(elements->tags);
X
Xiaoyu Wang 已提交
971
  if (is_same_child_table_telnet(elements, &info->preLine) != 0) {
wmmhello's avatar
wmmhello 已提交
972 973 974 975
    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 已提交
976
      elements->tags = NULL;
wmmhello's avatar
wmmhello 已提交
977 978
      return ret;
    }
X
Xiaoyu Wang 已提交
979
  } else {
980
    elements->measureTag = info->preLine.measureTag;
wmmhello's avatar
wmmhello 已提交
981 982
  }

X
Xiaoyu Wang 已提交
983
  if (needFree) {
wmmhello's avatar
wmmhello 已提交
984
    taosMemoryFree(elements->tags);
wmmhello's avatar
wmmhello 已提交
985
    elements->tags = NULL;
wmmhello's avatar
wmmhello 已提交
986 987
  }

X
Xiaoyu Wang 已提交
988
  if (unlikely(info->reRun)) {
wmmhello's avatar
wmmhello 已提交
989 990 991 992 993 994 995 996 997 998
    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;
  }
X
Xiaoyu Wang 已提交
999 1000 1001 1002 1003
  SSmlKv kvTs = {.key = TS,
                 .keyLen = TS_LEN,
                 .type = TSDB_DATA_TYPE_TIMESTAMP,
                 .i = ts,
                 .length = (size_t)tDataTypes[TSDB_DATA_TYPE_TIMESTAMP].bytes};
wmmhello's avatar
wmmhello 已提交
1004

X
Xiaoyu Wang 已提交
1005
  if (info->dataFormat) {
wmmhello's avatar
wmmhello 已提交
1006
    ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kvTs, 0);
X
Xiaoyu Wang 已提交
1007
    if (ret == TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
1008 1009
      ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kv, 1);
    }
X
Xiaoyu Wang 已提交
1010
    if (ret == TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
1011 1012
      ret = smlBuildRow(info->currTableDataCtx);
    }
wmmhello's avatar
wmmhello 已提交
1013
    clearColValArray(info->currTableDataCtx->pValues);
wmmhello's avatar
wmmhello 已提交
1014 1015 1016 1017
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
      smlBuildInvalidDataMsg(&info->msgBuf, "smlBuildCol error", NULL);
      return ret;
    }
X
Xiaoyu Wang 已提交
1018 1019
  } else {
    if (elements->colArray == NULL) {
wmmhello's avatar
wmmhello 已提交
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
      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 已提交
1051
    uError("SML:0x%" PRIx64 " Invalid JSON Payload 3:%s", info->id, payload);
wmmhello's avatar
wmmhello 已提交
1052 1053 1054
    return TSDB_CODE_TSC_INVALID_JSON;
  }

wmmhello's avatar
wmmhello 已提交
1055

wmmhello's avatar
wmmhello 已提交
1056
  if (unlikely(info->lines != NULL)) {
wmmhello's avatar
wmmhello 已提交
1057 1058 1059 1060
    for (int i = 0; i < info->lineNum; i++) {
      taosArrayDestroyEx(info->lines[i].colArray, freeSSmlKv);
      if (info->lines[i].measureTagsLen != 0) taosMemoryFree(info->lines[i].measureTag);
    }
wmmhello's avatar
wmmhello 已提交
1061 1062 1063
    taosMemoryFree(info->lines);
    info->lines = NULL;
  }
wmmhello's avatar
wmmhello 已提交
1064 1065 1066
  info->lineNum = payloadNum;
  info->dataFormat = true;

wmmhello's avatar
wmmhello 已提交
1067
  ret = smlClearForRerun(info);
X
Xiaoyu Wang 已提交
1068
  if (ret != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
1069 1070
    return ret;
  }
wmmhello's avatar
wmmhello 已提交
1071 1072

  info->parseJsonByLib = true;
wmmhello's avatar
wmmhello 已提交
1073 1074
  cJSON *head = (payloadNum == 1 && cJSON_IsObject(info->root)) ? info->root : info->root->child;

X
Xiaoyu Wang 已提交
1075
  int    cnt = 0;
wmmhello's avatar
wmmhello 已提交
1076 1077
  cJSON *dataPoint = head;
  while (dataPoint) {
X
Xiaoyu Wang 已提交
1078
    if (info->dataFormat) {
wmmhello's avatar
wmmhello 已提交
1079 1080
      SSmlLineInfo element = {0};
      ret = smlParseJSONStringExt(info, dataPoint, &element);
X
Xiaoyu Wang 已提交
1081
    } else {
wmmhello's avatar
wmmhello 已提交
1082 1083 1084
      ret = smlParseJSONStringExt(info, dataPoint, info->lines + cnt);
    }
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
wmmhello's avatar
wmmhello 已提交
1085
      uError("SML:0x%" PRIx64 " Invalid JSON Payload 2:%s", info->id, payload);
wmmhello's avatar
wmmhello 已提交
1086 1087 1088
      return ret;
    }

X
Xiaoyu Wang 已提交
1089
    if (unlikely(info->reRun)) {
wmmhello's avatar
wmmhello 已提交
1090 1091 1092 1093
      cnt = 0;
      dataPoint = head;
      info->lineNum = payloadNum;
      ret = smlClearForRerun(info);
X
Xiaoyu Wang 已提交
1094
      if (ret != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
        return ret;
      }
      continue;
    }
    cnt++;
    dataPoint = dataPoint->next;
  }

  return TSDB_CODE_SUCCESS;
}

wmmhello's avatar
wmmhello 已提交
1106 1107 1108
static int32_t smlParseJSONString(SSmlHandle *info, char **start, SSmlLineInfo *elements) {
  int32_t ret = TSDB_CODE_SUCCESS;

X
Xiaoyu Wang 已提交
1109
  if (info->offset[0] == 0) {
wmmhello's avatar
wmmhello 已提交
1110
    ret = smlJsonParseObjFirst(start, elements, info->offset);
X
Xiaoyu Wang 已提交
1111
  } else {
wmmhello's avatar
wmmhello 已提交
1112 1113 1114 1115 1116 1117 1118
    ret = smlJsonParseObj(start, elements, info->offset);
  }

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

X
Xiaoyu Wang 已提交
1119
  if (unlikely(**start == '\0' && elements->measure == NULL)) return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1120

1121 1122 1123 1124 1125
  if (unlikely(IS_INVALID_TABLE_LEN(elements->measureLen))) {
    smlBuildInvalidDataMsg(&info->msgBuf, "measure is empty or too large than 192", NULL);
    return TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
  }

wmmhello's avatar
wmmhello 已提交
1126
  SSmlKv kv = {.key = VALUE, .keyLen = VALUE_LEN, .value = elements->cols, .length = (size_t)elements->colsLen};
wmmhello's avatar
wmmhello 已提交
1127 1128 1129 1130

  if (unlikely(elements->colsLen == 0)) {
    uError("SML:colsLen == 0");
    return TSDB_CODE_TSC_INVALID_VALUE;
X
Xiaoyu Wang 已提交
1131
  } else if (unlikely(elements->cols[0] == '{')) {
wmmhello's avatar
wmmhello 已提交
1132 1133
    char tmp = elements->cols[elements->colsLen];
    elements->cols[elements->colsLen] = '\0';
X
Xiaoyu Wang 已提交
1134
    cJSON *valueJson = cJSON_Parse(elements->cols);
1135 1136 1137 1138 1139
    if (unlikely(valueJson == NULL)) {
      uError("SML:0x%" PRIx64 " parse json cols failed:%s", info->id, elements->cols);
      return TSDB_CODE_TSC_INVALID_JSON;
    }
    taosArrayPush(info->tagJsonArray, &valueJson);
wmmhello's avatar
wmmhello 已提交
1140 1141 1142 1143 1144 1145 1146
    ret = smlParseValueFromJSONObj(valueJson, &kv);
    if (ret != TSDB_CODE_SUCCESS) {
      uError("SML:Failed to parse value from JSON Obj:%s", elements->cols);
      elements->cols[elements->colsLen] = tmp;
      return TSDB_CODE_TSC_INVALID_VALUE;
    }
    elements->cols[elements->colsLen] = tmp;
X
Xiaoyu Wang 已提交
1147
  } else if (smlParseValue(&kv, &info->msgBuf) != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
1148 1149 1150 1151 1152
    uError("SML:cols invalidate:%s", elements->cols);
    return TSDB_CODE_TSC_INVALID_VALUE;
  }

  // Parse tags
X
Xiaoyu Wang 已提交
1153
  if (is_same_child_table_telnet(elements, &info->preLine) != 0) {
wmmhello's avatar
wmmhello 已提交
1154 1155
    char tmp = *(elements->tags + elements->tagsLen);
    *(elements->tags + elements->tagsLen) = 0;
X
Xiaoyu Wang 已提交
1156
    cJSON *tagsJson = cJSON_Parse(elements->tags);
wmmhello's avatar
wmmhello 已提交
1157 1158
    *(elements->tags + elements->tagsLen) = tmp;
    if (unlikely(tagsJson == NULL)) {
1159
      uError("SML:0x%" PRIx64 " parse json tag failed:%s", info->id, elements->tags);
wmmhello's avatar
wmmhello 已提交
1160 1161 1162
      return TSDB_CODE_TSC_INVALID_JSON;
    }

wmmhello's avatar
wmmhello 已提交
1163
    taosArrayPush(info->tagJsonArray, &tagsJson);
wmmhello's avatar
wmmhello 已提交
1164 1165 1166 1167 1168
    ret = smlParseTagsFromJSON(info, tagsJson, elements);
    if (unlikely(ret)) {
      uError("OTD:0x%" PRIx64 " Unable to parse tags from JSON payload", info->id);
      return ret;
    }
X
Xiaoyu Wang 已提交
1169
  } else {
1170
    elements->measureTag = info->preLine.measureTag;
wmmhello's avatar
wmmhello 已提交
1171 1172
  }

X
Xiaoyu Wang 已提交
1173
  if (unlikely(info->reRun)) {
wmmhello's avatar
wmmhello 已提交
1174 1175 1176 1177 1178
    return TSDB_CODE_SUCCESS;
  }

  // Parse timestamp
  // notice!!! put ts back to tag to ensure get meta->precision
wmmhello's avatar
wmmhello 已提交
1179
  int64_t ts = 0;
X
Xiaoyu Wang 已提交
1180
  if (unlikely(elements->timestampLen == 0)) {
wmmhello's avatar
wmmhello 已提交
1181
    uError("OTD:0x%" PRIx64 " elements->timestampLen == 0", info->id);
wmmhello's avatar
wmmhello 已提交
1182
    return TSDB_CODE_INVALID_TIMESTAMP;
X
Xiaoyu Wang 已提交
1183
  } else if (elements->timestamp[0] == '{') {
wmmhello's avatar
wmmhello 已提交
1184
    char tmp = elements->timestamp[elements->timestampLen];
1185
    elements->timestamp[elements->timestampLen] = '\0';
X
Xiaoyu Wang 已提交
1186
    cJSON *tsJson = cJSON_Parse(elements->timestamp);
wmmhello's avatar
wmmhello 已提交
1187 1188 1189 1190 1191 1192 1193 1194 1195
    ts = smlParseTSFromJSON(info, tsJson);
    if (unlikely(ts < 0)) {
      uError("SML:0x%" PRIx64 " Unable to parse timestamp from JSON payload:%s", info->id, elements->timestamp);
      elements->timestamp[elements->timestampLen] = tmp;
      cJSON_Delete(tsJson);
      return TSDB_CODE_INVALID_TIMESTAMP;
    }
    elements->timestamp[elements->timestampLen] = tmp;
    cJSON_Delete(tsJson);
X
Xiaoyu Wang 已提交
1196
  } else {
wmmhello's avatar
wmmhello 已提交
1197 1198 1199 1200 1201
    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;
    }
wmmhello's avatar
wmmhello 已提交
1202
  }
X
Xiaoyu Wang 已提交
1203 1204 1205 1206 1207
  SSmlKv kvTs = {.key = TS,
                 .keyLen = TS_LEN,
                 .type = TSDB_DATA_TYPE_TIMESTAMP,
                 .i = ts,
                 .length = (size_t)tDataTypes[TSDB_DATA_TYPE_TIMESTAMP].bytes};
wmmhello's avatar
wmmhello 已提交
1208

X
Xiaoyu Wang 已提交
1209
  if (info->dataFormat) {
wmmhello's avatar
wmmhello 已提交
1210
    ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kvTs, 0);
X
Xiaoyu Wang 已提交
1211
    if (ret == TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
1212 1213
      ret = smlBuildCol(info->currTableDataCtx, info->currSTableMeta->schema, &kv, 1);
    }
X
Xiaoyu Wang 已提交
1214
    if (ret == TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
1215 1216
      ret = smlBuildRow(info->currTableDataCtx);
    }
wmmhello's avatar
wmmhello 已提交
1217
    clearColValArray(info->currTableDataCtx->pValues);
wmmhello's avatar
wmmhello 已提交
1218 1219 1220 1221
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
      smlBuildInvalidDataMsg(&info->msgBuf, "smlBuildCol error", NULL);
      return ret;
    }
X
Xiaoyu Wang 已提交
1222 1223
  } else {
    if (elements->colArray == NULL) {
wmmhello's avatar
wmmhello 已提交
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
      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 已提交
1234 1235
int32_t smlParseJSON(SSmlHandle *info, char *payload) {
  int32_t payloadNum = 1 << 15;
1236 1237
  int32_t ret = TSDB_CODE_SUCCESS;

wmmhello's avatar
wmmhello 已提交
1238
  uDebug("SML:0x%" PRIx64 "json:%s", info->id, payload);
X
Xiaoyu Wang 已提交
1239
  int   cnt = 0;
wmmhello's avatar
wmmhello 已提交
1240 1241
  char *dataPointStart = payload;
  while (1) {
X
Xiaoyu Wang 已提交
1242
    if (info->dataFormat) {
1243
      SSmlLineInfo element = {0};
wmmhello's avatar
wmmhello 已提交
1244
      ret = smlParseJSONString(info, &dataPointStart, &element);
X
Xiaoyu Wang 已提交
1245 1246 1247
      if (element.measureTagsLen != 0) taosMemoryFree(element.measureTag);
    } else {
      if (cnt >= payloadNum) {
wmmhello's avatar
wmmhello 已提交
1248
        payloadNum = payloadNum << 1;
X
Xiaoyu Wang 已提交
1249
        void *tmp = taosMemoryRealloc(info->lines, payloadNum * sizeof(SSmlLineInfo));
wmmhello's avatar
wmmhello 已提交
1250 1251 1252
        if (tmp == NULL) {
          ret = TSDB_CODE_OUT_OF_MEMORY;
          return ret;
wmmhello's avatar
wmmhello 已提交
1253
        }
wmmhello's avatar
wmmhello 已提交
1254 1255
        info->lines = (SSmlLineInfo *)tmp;
        memset(info->lines + cnt, 0, (payloadNum - cnt) * sizeof(SSmlLineInfo));
wmmhello's avatar
wmmhello 已提交
1256
      }
wmmhello's avatar
wmmhello 已提交
1257
      ret = smlParseJSONString(info, &dataPointStart, info->lines + cnt);
X
Xiaoyu Wang 已提交
1258
      if ((info->lines + cnt)->measure == NULL) break;
1259 1260
    }
    if (unlikely(ret != TSDB_CODE_SUCCESS)) {
wmmhello's avatar
wmmhello 已提交
1261
      uError("SML:0x%" PRIx64 " Invalid JSON Payload 1:%s", info->id, payload);
wmmhello's avatar
wmmhello 已提交
1262
      return smlParseJSONExt(info, payload);
1263 1264
    }

X
Xiaoyu Wang 已提交
1265
    if (unlikely(info->reRun)) {
1266
      cnt = 0;
wmmhello's avatar
wmmhello 已提交
1267
      dataPointStart = payload;
1268 1269
      info->lineNum = payloadNum;
      ret = smlClearForRerun(info);
X
Xiaoyu Wang 已提交
1270
      if (ret != TSDB_CODE_SUCCESS) {
1271 1272 1273 1274
        return ret;
      }
      continue;
    }
wmmhello's avatar
wmmhello 已提交
1275

1276
    cnt++;
X
Xiaoyu Wang 已提交
1277
    if (*dataPointStart == '\0') break;
1278
  }
wmmhello's avatar
wmmhello 已提交
1279
  info->lineNum = cnt;
1280 1281

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