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

#include "query.h"
#include "taos.h"
wmmhello's avatar
wmmhello 已提交
8 9 10 11
#include "taoserror.h"
#include "tdef.h"
#include "tlog.h"
#include "tmsg.h"
wmmhello's avatar
wmmhello 已提交
12
#include "tstrbuild.h"
wmmhello's avatar
wmmhello 已提交
13 14 15 16
#include "ttime.h"
#include "ttypes.h"
#include "tcommon.h"
#include "catalog.h"
17
#include "clientInt.h"
18
#include "tname.h"
19
#include "cJSON.h"
wmmhello's avatar
wmmhello 已提交
20
//=================================================================================================
wmmhello's avatar
wmmhello 已提交
21 22 23 24 25 26

#define SPACE ' '
#define COMMA ','
#define EQUAL '='
#define QUOTE '"'
#define SLASH '\\'
wmmhello's avatar
wmmhello 已提交
27
#define tsMaxSQLStringLen (1024*1024)
wmmhello's avatar
wmmhello 已提交
28

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
#define OTD_MAX_FIELDS_NUM      2
#define OTD_JSON_SUB_FIELDS_NUM 2
#define OTD_JSON_FIELDS_NUM     4

#define OTD_TIMESTAMP_COLUMN_NAME "ts"
#define OTD_METRIC_VALUE_COLUMN_NAME "value"

#define TS        "_ts"
#define TS_LEN    3
#define TAG       "_tagNone"
#define TAG_LEN   8
#define VALUE     "value"
#define VALUE_LEN 5

#define BINARY_ADD_LEN 2        // "binary"   2 means " "
#define NCHAR_ADD_LEN 3         // L"nchar"   3 means L" "
wmmhello's avatar
wmmhello 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57
//=================================================================================================
typedef TSDB_SML_PROTOCOL_TYPE SMLProtocolType;

typedef enum {
  SCHEMA_ACTION_CREATE_STABLE,
  SCHEMA_ACTION_ADD_COLUMN,
  SCHEMA_ACTION_ADD_TAG,
  SCHEMA_ACTION_CHANGE_COLUMN_SIZE,
  SCHEMA_ACTION_CHANGE_TAG_SIZE,
} ESchemaAction;

typedef struct {
  char sTableName[TSDB_TABLE_NAME_LEN];
58 59
  SArray *tags;
  SArray *fields;
wmmhello's avatar
wmmhello 已提交
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
} SCreateSTableActionInfo;

typedef struct {
  char sTableName[TSDB_TABLE_NAME_LEN];
  SSmlKv * field;
} SAlterSTableActionInfo;

typedef struct {
  ESchemaAction action;
  union {
    SCreateSTableActionInfo createSTable;
    SAlterSTableActionInfo alterSTable;
  };
} SSchemaAction;

typedef struct {
  const char* measure;
  const char* tags;
  const char* cols;
  const char* timestamp;

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

typedef struct {
  const char     *sTableName;   // super table name
90
  int32_t        sTableNameLen;
wmmhello's avatar
wmmhello 已提交
91 92 93 94 95
  char           childTableName[TSDB_TABLE_NAME_LEN];
  uint64_t       uid;

  SArray         *tags;

96 97 98
  // if info->formatData is true, elements are SArray<SSmlKv*>.
  // if info->formatData is false, elements are SHashObj<cols key string, SSmlKv*> for find by key quickly
  SArray         *cols;
wmmhello's avatar
wmmhello 已提交
99 100 101
} SSmlTableInfo;

typedef struct {
102 103 104 105
  SArray     *tags;       // save the origin order to create table
  SHashObj   *tagHash;    // elements are <key, index in tags>

  SArray     *cols;
wmmhello's avatar
wmmhello 已提交
106
  SHashObj   *fieldHash;
107

wmmhello's avatar
wmmhello 已提交
108 109 110 111 112 113 114 115
  STableMeta *tableMeta;
} SSmlSTableMeta;

typedef struct {
  int32_t   len;
  char      *buf;
} SSmlMsgBuf;

116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
typedef struct {
  int32_t code;
  int32_t lineNum;

  int32_t numOfSTables;
  int32_t numOfCTables;
  int32_t numOfCreateSTables;

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

wmmhello's avatar
wmmhello 已提交
131
typedef struct {
132
  int64_t           id;
wmmhello's avatar
wmmhello 已提交
133 134 135

  SMLProtocolType   protocol;
  int8_t            precision;
136
  bool              dataFormat;     // true means that the name, number and order of keys in each line are the same(only for influx protocol)
wmmhello's avatar
wmmhello 已提交
137 138 139 140 141 142 143 144 145 146 147

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

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

148
  SSmlCostInfo      cost;
wmmhello's avatar
wmmhello 已提交
149 150
  int32_t           affectedRows;
  SSmlMsgBuf        msgBuf;
151
  SHashObj          *dumplicateKey;  // for dumplicate key
152
  SArray            *colsContainer;  // for cols parse, if dataFormat == false
wmmhello's avatar
wmmhello 已提交
153
} SSmlHandle;
wmmhello's avatar
wmmhello 已提交
154 155
//=================================================================================================

wmmhello's avatar
wmmhello 已提交
156
//=================================================================================================
157
static volatile int64_t linesSmlHandleId = 0;
wmmhello's avatar
wmmhello 已提交
158 159
static int64_t smlGenId() {
  int64_t id;
wmmhello's avatar
wmmhello 已提交
160 161 162 163 164 165 166 167

  do {
    id = atomic_add_fetch_64(&linesSmlHandleId, 1);
  } while (id == 0);

  return id;
}

168 169 170 171 172 173 174 175 176 177 178 179 180 181
static inline bool smlDoubleToInt64OverFlow(double num) {
  if(num >= (double)INT64_MAX || num <= (double)INT64_MIN) return true;
  return false;
}

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

wmmhello's avatar
wmmhello 已提交
182
static int32_t smlBuildInvalidDataMsg(SSmlMsgBuf* pBuf, const char *msg1, const char *msg2) {
wmmhello's avatar
wmmhello 已提交
183 184 185 186 187 188
  if(msg1) strncat(pBuf->buf, msg1, pBuf->len);
  int32_t left = pBuf->len - strlen(pBuf->buf);
  if(left > 2 && msg2) {
    strncat(pBuf->buf, ":", left - 1);
    strncat(pBuf->buf, msg2, left - 2);
  }
wmmhello's avatar
wmmhello 已提交
189 190 191
  return TSDB_CODE_SML_INVALID_DATA;
}

wmmhello's avatar
wmmhello 已提交
192 193
static int32_t smlGenerateSchemaAction(SSchema* pointColField, SHashObj* dbAttrHash, SArray* dbAttrArray, bool isTag, char sTableName[],
                                       SSchemaAction* action, bool* actionNeeded, SSmlHandle* info) {
wmmhello's avatar
wmmhello 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
//  char fieldName[TSDB_COL_NAME_LEN] = {0};
//  strcpy(fieldName, pointColField->name);
//
//  size_t* pDbIndex = taosHashGet(dbAttrHash, fieldName, strlen(fieldName));
//  if (pDbIndex) {
//    SSchema* dbAttr = taosArrayGet(dbAttrArray, *pDbIndex);
//    assert(strcasecmp(dbAttr->name, pointColField->name) == 0);
//    if (pointColField->type != dbAttr->type) {
//      uError("SML:0x%"PRIx64" point type and db type mismatch. key: %s. point type: %d, db type: %d", info->id, pointColField->name,
//               pointColField->type, dbAttr->type);
//      return TSDB_CODE_TSC_INVALID_VALUE;
//    }
//
//    if (IS_VAR_DATA_TYPE(pointColField->type) && (pointColField->bytes > dbAttr->bytes)) {
//      if (isTag) {
//        action->action = SCHEMA_ACTION_CHANGE_TAG_SIZE;
//      } else {
//        action->action = SCHEMA_ACTION_CHANGE_COLUMN_SIZE;
//      }
//      memset(&action->alterSTable, 0,  sizeof(SAlterSTableActionInfo));
//      memcpy(action->alterSTable.sTableName, sTableName, TSDB_TABLE_NAME_LEN);
//      action->alterSTable.field = pointColField;
//      *actionNeeded = true;
//    }
//  } else {
//    if (isTag) {
//      action->action = SCHEMA_ACTION_ADD_TAG;
//    } else {
//      action->action = SCHEMA_ACTION_ADD_COLUMN;
//    }
//    memset(&action->alterSTable, 0, sizeof(SAlterSTableActionInfo));
//    memcpy(action->alterSTable.sTableName, sTableName, TSDB_TABLE_NAME_LEN);
//    action->alterSTable.field = pointColField;
//    *actionNeeded = true;
//  }
//  if (*actionNeeded) {
//    uDebug("SML:0x%" PRIx64 " generate schema action. column name: %s, action: %d", info->id, fieldName,
//             action->action);
//  }
wmmhello's avatar
wmmhello 已提交
233 234 235
  return 0;
}

wmmhello's avatar
wmmhello 已提交
236
static int32_t smlBuildColumnDescription(SSmlKv* field, char* buf, int32_t bufSize, int32_t* outBytes) {
wmmhello's avatar
wmmhello 已提交
237
  uint8_t type = field->type;
wmmhello's avatar
wmmhello 已提交
238 239
  char    tname[TSDB_TABLE_NAME_LEN] = {0};
  memcpy(tname, field->key, field->keyLen);
wmmhello's avatar
wmmhello 已提交
240
  if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
wmmhello's avatar
wmmhello 已提交
241
    int32_t bytes = field->valueLen;   // todo
242
    int out = snprintf(buf, bufSize,"`%s` %s(%d)",
wmmhello's avatar
wmmhello 已提交
243
                       tname,tDataTypes[field->type].name, bytes);
wmmhello's avatar
wmmhello 已提交
244 245
    *outBytes = out;
  } else {
246
    int out = snprintf(buf, bufSize, "`%s` %s", tname, tDataTypes[type].name);
wmmhello's avatar
wmmhello 已提交
247 248 249 250 251 252
    *outBytes = out;
  }

  return 0;
}

wmmhello's avatar
wmmhello 已提交
253
static int32_t smlApplySchemaAction(SSmlHandle* info, SSchemaAction* action) {
wmmhello's avatar
wmmhello 已提交
254 255
  int32_t code = 0;
  int32_t outBytes = 0;
wmmhello's avatar
wmmhello 已提交
256
  char *result = (char *)taosMemoryCalloc(1, tsMaxSQLStringLen+1);
wmmhello's avatar
wmmhello 已提交
257 258 259 260 261 262
  int32_t capacity = tsMaxSQLStringLen +  1;

  uDebug("SML:0x%"PRIx64" apply schema action. action: %d", info->id, action->action);
  switch (action->action) {
    case SCHEMA_ACTION_ADD_COLUMN: {
      int n = sprintf(result, "alter stable %s add column ", action->alterSTable.sTableName);
wmmhello's avatar
wmmhello 已提交
263 264
      smlBuildColumnDescription(action->alterSTable.field, result+n, capacity-n, &outBytes);
      TAOS_RES* res = taos_query(info->taos, result); //TODO async doAsyncQuery
wmmhello's avatar
wmmhello 已提交
265
      code = taos_errno(res);
wmmhello's avatar
wmmhello 已提交
266
      const char* errStr = taos_errstr(res);
wmmhello's avatar
wmmhello 已提交
267 268 269 270 271
      if (code != TSDB_CODE_SUCCESS) {
        uError("SML:0x%"PRIx64" apply schema action. error: %s", info->id, errStr);
      }
      taos_free_result(res);

wmmhello's avatar
wmmhello 已提交
272
//      if (code == TSDB_CODE_MND_FIELD_ALREADY_EXIST || code == TSDB_CODE_MND_TAG_ALREADY_EXIST || tscDupColNames) {
wmmhello's avatar
wmmhello 已提交
273
      if (code == TSDB_CODE_MND_TAG_ALREADY_EXIST) {
wmmhello's avatar
wmmhello 已提交
274
        TAOS_RES* res2 = taos_query(info->taos, "RESET QUERY CACHE");
wmmhello's avatar
wmmhello 已提交
275 276 277 278 279 280 281 282 283 284 285
        code = taos_errno(res2);
        if (code != TSDB_CODE_SUCCESS) {
          uError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2));
        }
        taos_free_result(res2);
        taosMsleep(500);
      }
      break;
    }
    case SCHEMA_ACTION_ADD_TAG: {
      int n = sprintf(result, "alter stable %s add tag ", action->alterSTable.sTableName);
wmmhello's avatar
wmmhello 已提交
286
      smlBuildColumnDescription(action->alterSTable.field,
wmmhello's avatar
wmmhello 已提交
287
                             result+n, capacity-n, &outBytes);
wmmhello's avatar
wmmhello 已提交
288
      TAOS_RES* res = taos_query(info->taos, result); //TODO async doAsyncQuery
wmmhello's avatar
wmmhello 已提交
289
      code = taos_errno(res);
wmmhello's avatar
wmmhello 已提交
290
      const char* errStr = taos_errstr(res);
wmmhello's avatar
wmmhello 已提交
291 292 293 294 295
      if (code != TSDB_CODE_SUCCESS) {
        uError("SML:0x%"PRIx64" apply schema action. error : %s", info->id, taos_errstr(res));
      }
      taos_free_result(res);

wmmhello's avatar
wmmhello 已提交
296
//      if (code ==TSDB_CODE_MND_TAG_ALREADY_EXIST || code == TSDB_CODE_MND_FIELD_ALREAY_EXIST || tscDupColNames) {
wmmhello's avatar
wmmhello 已提交
297
      if (code ==TSDB_CODE_MND_TAG_ALREADY_EXIST) {
wmmhello's avatar
wmmhello 已提交
298
        TAOS_RES* res2 = taos_query(info->taos, "RESET QUERY CACHE");
wmmhello's avatar
wmmhello 已提交
299 300 301 302 303 304 305 306 307 308 309
        code = taos_errno(res2);
        if (code != TSDB_CODE_SUCCESS) {
          uError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2));
        }
        taos_free_result(res2);
        taosMsleep(500);
      }
      break;
    }
    case SCHEMA_ACTION_CHANGE_COLUMN_SIZE: {
      int n = sprintf(result, "alter stable %s modify column ", action->alterSTable.sTableName);
wmmhello's avatar
wmmhello 已提交
310
      smlBuildColumnDescription(action->alterSTable.field, result+n,
wmmhello's avatar
wmmhello 已提交
311
                             capacity-n, &outBytes);
wmmhello's avatar
wmmhello 已提交
312
      TAOS_RES* res = taos_query(info->taos, result); //TODO async doAsyncQuery
wmmhello's avatar
wmmhello 已提交
313 314 315 316 317 318
      code = taos_errno(res);
      if (code != TSDB_CODE_SUCCESS) {
        uError("SML:0x%"PRIx64" apply schema action. error : %s", info->id, taos_errstr(res));
      }
      taos_free_result(res);

wmmhello's avatar
wmmhello 已提交
319 320
//      if (code == TSDB_CODE_MND_INVALID_COLUMN_LENGTH || code == TSDB_CODE_TSC_INVALID_COLUMN_LENGTH) {
      if (code == TSDB_CODE_TSC_INVALID_COLUMN_LENGTH) {
wmmhello's avatar
wmmhello 已提交
321
        TAOS_RES* res2 = taos_query(info->taos, "RESET QUERY CACHE");
wmmhello's avatar
wmmhello 已提交
322 323 324 325 326 327 328 329 330 331 332
        code = taos_errno(res2);
        if (code != TSDB_CODE_SUCCESS) {
          uError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2));
        }
        taos_free_result(res2);
        taosMsleep(500);
      }
      break;
    }
    case SCHEMA_ACTION_CHANGE_TAG_SIZE: {
      int n = sprintf(result, "alter stable %s modify tag ", action->alterSTable.sTableName);
wmmhello's avatar
wmmhello 已提交
333
      smlBuildColumnDescription(action->alterSTable.field, result+n,
wmmhello's avatar
wmmhello 已提交
334
                             capacity-n, &outBytes);
wmmhello's avatar
wmmhello 已提交
335
      TAOS_RES* res = taos_query(info->taos, result); //TODO async doAsyncQuery
wmmhello's avatar
wmmhello 已提交
336 337 338 339 340 341
      code = taos_errno(res);
      if (code != TSDB_CODE_SUCCESS) {
        uError("SML:0x%"PRIx64" apply schema action. error : %s", info->id, taos_errstr(res));
      }
      taos_free_result(res);

wmmhello's avatar
wmmhello 已提交
342 343
//      if (code == TSDB_CODE_MND_INVALID_TAG_LENGTH || code == TSDB_CODE_TSC_INVALID_TAG_LENGTH) {
      if (code == TSDB_CODE_TSC_INVALID_TAG_LENGTH) {
wmmhello's avatar
wmmhello 已提交
344
        TAOS_RES* res2 = taos_query(info->taos, "RESET QUERY CACHE");
wmmhello's avatar
wmmhello 已提交
345 346 347 348 349 350 351 352 353 354
        code = taos_errno(res2);
        if (code != TSDB_CODE_SUCCESS) {
          uError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2));
        }
        taos_free_result(res2);
        taosMsleep(500);
      }
      break;
    }
    case SCHEMA_ACTION_CREATE_STABLE: {
355
      int n = sprintf(result, "create stable `%s` (", action->createSTable.sTableName);
wmmhello's avatar
wmmhello 已提交
356
      char* pos = result + n; int freeBytes = capacity - n;
wmmhello's avatar
wmmhello 已提交
357

358
      SArray *cols = action->createSTable.fields;
wmmhello's avatar
wmmhello 已提交
359 360

      for(int i = 0; i < taosArrayGetSize(cols); i++){
wmmhello's avatar
wmmhello 已提交
361
        SSmlKv *kv = (SSmlKv *)taosArrayGetP(cols, i);
362
        smlBuildColumnDescription(kv, pos, freeBytes, &outBytes);
wmmhello's avatar
wmmhello 已提交
363 364 365
        pos += outBytes; freeBytes -= outBytes;
        *pos = ','; ++pos; --freeBytes;
      }
wmmhello's avatar
wmmhello 已提交
366

wmmhello's avatar
wmmhello 已提交
367 368 369 370 371
      --pos; ++freeBytes;

      outBytes = snprintf(pos, freeBytes, ") tags (");
      pos += outBytes; freeBytes -= outBytes;

372 373
      cols = action->createSTable.tags;
      for(int i = 0; i < taosArrayGetSize(cols); i++){
wmmhello's avatar
wmmhello 已提交
374
        SSmlKv *kv = (SSmlKv *)taosArrayGetP(cols, i);
375
        smlBuildColumnDescription(kv, pos, freeBytes, &outBytes);
wmmhello's avatar
wmmhello 已提交
376 377 378 379 380
        pos += outBytes; freeBytes -= outBytes;
        *pos = ','; ++pos; --freeBytes;
      }
      pos--; ++freeBytes;
      outBytes = snprintf(pos, freeBytes, ")");
wmmhello's avatar
wmmhello 已提交
381
      TAOS_RES* res = taos_query(info->taos, result);
wmmhello's avatar
wmmhello 已提交
382 383 384 385 386 387
      code = taos_errno(res);
      if (code != TSDB_CODE_SUCCESS) {
        uError("SML:0x%"PRIx64" apply schema action. error : %s", info->id, taos_errstr(res));
      }
      taos_free_result(res);

wmmhello's avatar
wmmhello 已提交
388
      if (code == TSDB_CODE_MND_STB_ALREADY_EXIST) {
wmmhello's avatar
wmmhello 已提交
389
        TAOS_RES* res2 = taos_query(info->taos, "RESET QUERY CACHE");
wmmhello's avatar
wmmhello 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403
        code = taos_errno(res2);
        if (code != TSDB_CODE_SUCCESS) {
          uError("SML:0x%" PRIx64 " apply schema action. reset query cache. error: %s", info->id, taos_errstr(res2));
        }
        taos_free_result(res2);
        taosMsleep(500);
      }
      break;
    }

    default:
      break;
  }

wmmhello's avatar
wmmhello 已提交
404
  taosMemoryFreeClear(result);
wmmhello's avatar
wmmhello 已提交
405 406 407 408 409 410
  if (code != 0) {
    uError("SML:0x%"PRIx64 " apply schema action failure. %s", info->id, tstrerror(code));
  }
  return code;
}

wmmhello's avatar
wmmhello 已提交
411
static int32_t smlModifyDBSchemas(SSmlHandle* info) {
wmmhello's avatar
wmmhello 已提交
412 413
  int32_t code = 0;

wmmhello's avatar
wmmhello 已提交
414
  SSmlSTableMeta** tableMetaSml = (SSmlSTableMeta**)taosHashIterate(info->superTables, NULL);
wmmhello's avatar
wmmhello 已提交
415
  while (tableMetaSml) {
416
    SSmlSTableMeta* sTableData = *tableMetaSml;
wmmhello's avatar
wmmhello 已提交
417 418

    STableMeta *pTableMeta = NULL;
wmmhello's avatar
wmmhello 已提交
419
    SEpSet ep = getEpSet_s(&info->taos->pAppInfo->mgmtEp);
wmmhello's avatar
wmmhello 已提交
420

wmmhello's avatar
wmmhello 已提交
421
    size_t superTableLen = 0;
wmmhello's avatar
wmmhello 已提交
422
    void *superTable = taosHashGetKey(tableMetaSml, &superTableLen);    // todo escape
wmmhello's avatar
wmmhello 已提交
423 424 425
    SName pName = {TSDB_TABLE_NAME_T, info->taos->acctId, {0}, {0}};
    strcpy(pName.dbname, info->pRequest->pDb);
    memcpy(pName.tname, superTable, superTableLen);
wmmhello's avatar
wmmhello 已提交
426

wmmhello's avatar
wmmhello 已提交
427
    code = catalogGetSTableMeta(info->pCatalog, info->taos->pAppInfo->pTransporter, &ep, &pName, &pTableMeta);
wmmhello's avatar
wmmhello 已提交
428

D
dapan1121 已提交
429
    if (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_MND_INVALID_STB) {
wafwerar's avatar
wafwerar 已提交
430
      SSchemaAction schemaAction = { SCHEMA_ACTION_CREATE_STABLE, 0};
wmmhello's avatar
wmmhello 已提交
431
      memcpy(schemaAction.createSTable.sTableName, superTable, superTableLen);
432 433
      schemaAction.createSTable.tags = sTableData->tags;
      schemaAction.createSTable.fields = sTableData->cols;
wmmhello's avatar
wmmhello 已提交
434 435 436 437 438 439
      code = smlApplySchemaAction(info, &schemaAction);
      if (code != 0) {
        uError("SML:0x%"PRIx64" smlApplySchemaAction failed. can not create %s", info->id, schemaAction.createSTable.sTableName);
        return code;
      }

wmmhello's avatar
wmmhello 已提交
440
      code = catalogGetSTableMeta(info->pCatalog, info->taos->pAppInfo->pTransporter, &ep, &pName, &pTableMeta);
wmmhello's avatar
wmmhello 已提交
441
      if (code != 0) {
wmmhello's avatar
wmmhello 已提交
442
        uError("SML:0x%"PRIx64" catalogGetSTableMeta failed. super table name %s", info->id, schemaAction.createSTable.sTableName);
wmmhello's avatar
wmmhello 已提交
443 444
        return code;
      }
445
      info->cost.numOfCreateSTables++;
wmmhello's avatar
wmmhello 已提交
446
    }else if (code == TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
447 448 449 450
    } else {
      uError("SML:0x%"PRIx64" load table meta error: %s", info->id, tstrerror(code));
      return code;
    }
451
    sTableData->tableMeta = pTableMeta;
wmmhello's avatar
wmmhello 已提交
452

wmmhello's avatar
wmmhello 已提交
453
    tableMetaSml = (SSmlSTableMeta**)taosHashIterate(info->superTables, tableMetaSml);
wmmhello's avatar
wmmhello 已提交
454 455 456 457 458 459 460 461 462 463 464
  }
  return 0;
}

//=========================================================================

/*        Field                          Escape charaters
    1: measurement                        Comma,Space
    2: tag_key, tag_value, field_key  Comma,Equal Sign,Space
    3: field_value                    Double quote,Backslash
*/
wmmhello's avatar
wmmhello 已提交
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
//static void escapeSpecialCharacter(uint8_t field, const char **pos) {
//  const char *cur = *pos;
//  if (*cur != '\\') {
//    return;
//  }
//  switch (field) {
//    case 1:
//      switch (*(cur + 1)) {
//        case ',':
//        case ' ':
//          cur++;
//          break;
//        default:
//          break;
//      }
//      break;
//    case 2:
//      switch (*(cur + 1)) {
//        case ',':
//        case ' ':
//        case '=':
//          cur++;
//          break;
//        default:
//          break;
//      }
//      break;
//    case 3:
//      switch (*(cur + 1)) {
//        case '"':
//        case '\\':
//          cur++;
//          break;
//        default:
//          break;
//      }
//      break;
//    default:
//      break;
//  }
//  *pos = cur;
//}
wmmhello's avatar
wmmhello 已提交
507

508
static bool smlParseNumber(SSmlKv *kvVal, SSmlMsgBuf *msg){
wmmhello's avatar
wmmhello 已提交
509 510
  const char *pVal = kvVal->value;
  int32_t len = kvVal->valueLen;
511 512 513 514
  char *endptr = NULL;
  double result = strtod(pVal, &endptr);
  if(pVal == endptr){
    smlBuildInvalidDataMsg(msg, "invalid data", pVal);
wmmhello's avatar
wmmhello 已提交
515 516 517
    return false;
  }

518 519 520 521 522 523 524 525
  int32_t left = len - (endptr - pVal);
  if(left == 0 || (left == 3 && strncasecmp(endptr, "f64", left) == 0)){
    kvVal->type = TSDB_DATA_TYPE_DOUBLE;
    kvVal->d = result;
  }else if ((left == 3 && strncasecmp(endptr, "f32", left) == 0)){
    if(!IS_VALID_FLOAT(result)){
      smlBuildInvalidDataMsg(msg, "float out of range[-3.402823466e+38,3.402823466e+38]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
526
    }
527 528 529 530 531 532
    kvVal->type = TSDB_DATA_TYPE_FLOAT;
    kvVal->f = (float)result;
  }else if ((left == 1 && *endptr == 'i') || (left == 3 && strncasecmp(endptr, "i64", left) == 0)){
    if(smlDoubleToInt64OverFlow(result)){
      smlBuildInvalidDataMsg(msg, "big int is too large, out of precision", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
533
    }
534 535 536 537 538 539
    kvVal->type = TSDB_DATA_TYPE_BIGINT;
    kvVal->i = (int64_t)result;
  }else if ((left == 3 && strncasecmp(endptr, "u64", left) == 0)){
    if(result >= (double)UINT64_MAX || result < 0){
      smlBuildInvalidDataMsg(msg, "unsigned big int is too large, out of precision", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
540
    }
541 542 543 544 545 546
    kvVal->type = TSDB_DATA_TYPE_UBIGINT;
    kvVal->u = result;
  }else if (left == 3 && strncasecmp(endptr, "i32", left) == 0){
    if(!IS_VALID_INT(result)){
      smlBuildInvalidDataMsg(msg, "int out of range[-2147483648,2147483647]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
547
    }
548 549 550 551 552 553
    kvVal->type = TSDB_DATA_TYPE_INT;
    kvVal->i = result;
  }else if (left == 3 && strncasecmp(endptr, "u32", left) == 0){
    if(!IS_VALID_UINT(result)){
      smlBuildInvalidDataMsg(msg, "unsigned int out of range[0,4294967295]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
554
    }
555 556 557 558 559 560
    kvVal->type = TSDB_DATA_TYPE_UINT;
    kvVal->u = result;
  }else if (left == 3 && strncasecmp(endptr, "i16", left) == 0){
    if(!IS_VALID_SMALLINT(result)){
      smlBuildInvalidDataMsg(msg, "small int our of range[-32768,32767]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
561
    }
562 563 564 565 566 567
    kvVal->type = TSDB_DATA_TYPE_SMALLINT;
    kvVal->i = result;
  }else if (left == 3 && strncasecmp(endptr, "u16", left) == 0){
    if(!IS_VALID_USMALLINT(result)){
      smlBuildInvalidDataMsg(msg, "unsigned small int out of rang[0,65535]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
568
    }
569 570 571 572 573 574
    kvVal->type = TSDB_DATA_TYPE_USMALLINT;
    kvVal->u = result;
  }else if (left == 2 && strncasecmp(endptr, "i8", left) == 0){
    if(!IS_VALID_TINYINT(result)){
      smlBuildInvalidDataMsg(msg, "tiny int out of range[-128,127]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
575
    }
576 577 578 579 580 581
    kvVal->type = TSDB_DATA_TYPE_TINYINT;
    kvVal->i = result;
  }else if (left == 2 && strncasecmp(endptr, "u8", left) == 0){
    if(!IS_VALID_UTINYINT(result)){
      smlBuildInvalidDataMsg(msg, "unsigned tiny int out of range[0,255]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
582
    }
583 584 585 586
    kvVal->type = TSDB_DATA_TYPE_UTINYINT;
    kvVal->u = result;
  }else{
    smlBuildInvalidDataMsg(msg, "invalid data", pVal);
wmmhello's avatar
wmmhello 已提交
587 588
    return false;
  }
589
  return true;
wmmhello's avatar
wmmhello 已提交
590 591
}

wmmhello's avatar
wmmhello 已提交
592
static bool smlParseBool(SSmlKv *kvVal) {
wmmhello's avatar
wmmhello 已提交
593 594
  const char *pVal = kvVal->value;
  int32_t len = kvVal->valueLen;
595
  if ((len == 1) && pVal[0] == 't') {
wmmhello's avatar
wmmhello 已提交
596
    kvVal->i = true;
wmmhello's avatar
wmmhello 已提交
597 598 599
    return true;
  }

600
  if ((len == 1) && pVal[0] == 'f') {
wmmhello's avatar
wmmhello 已提交
601
    kvVal->i = false;
wmmhello's avatar
wmmhello 已提交
602 603 604
    return true;
  }

wmmhello's avatar
wmmhello 已提交
605
  if((len == 4) && !strncasecmp(pVal, "true", len)) {
wmmhello's avatar
wmmhello 已提交
606
    kvVal->i = true;
wmmhello's avatar
wmmhello 已提交
607 608
    return true;
  }
wmmhello's avatar
wmmhello 已提交
609
  if((len == 5) && !strncasecmp(pVal, "false", len)) {
wmmhello's avatar
wmmhello 已提交
610
    kvVal->i = false;
wmmhello's avatar
wmmhello 已提交
611 612 613 614 615
    return true;
  }
  return false;
}

wmmhello's avatar
wmmhello 已提交
616
static bool smlIsBinary(const char *pVal, uint16_t len) {
wmmhello's avatar
wmmhello 已提交
617 618 619 620 621 622 623 624 625 626
  //binary: "abc"
  if (len < 2) {
    return false;
  }
  if (pVal[0] == '"' && pVal[len - 1] == '"') {
    return true;
  }
  return false;
}

wmmhello's avatar
wmmhello 已提交
627
static bool smlIsNchar(const char *pVal, uint16_t len) {
wmmhello's avatar
wmmhello 已提交
628 629 630 631 632 633 634 635 636 637
  //nchar: L"abc"
  if (len < 3) {
    return false;
  }
  if ((pVal[0] == 'l' || pVal[0] == 'L')&& pVal[1] == '"' && pVal[len - 1] == '"') {
    return true;
  }
  return false;
}

638 639 640 641 642
static int64_t smlGetTimeValue(const char *value, int32_t len, int8_t type) {
  char *endPtr = NULL;
  double ts = (double)strtoll(value, &endPtr, 10);
  if(value + len != endPtr){
    return -1;
wmmhello's avatar
wmmhello 已提交
643
  }
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
  switch (type) {
    case TSDB_TIME_PRECISION_HOURS:
      ts *= (3600 * 1e9);
      break;
    case TSDB_TIME_PRECISION_MINUTES:
      ts *= (60 * 1e9);
      break;
    case TSDB_TIME_PRECISION_SECONDS:
      ts *= (1e9);
      break;
    case TSDB_TIME_PRECISION_MILLI:
      ts *= (1e6);
      break;
    case TSDB_TIME_PRECISION_MICRO:
      ts *= (1e3);
      break;
    case TSDB_TIME_PRECISION_NANO:
      break;
    default:
      ASSERT(0);
wmmhello's avatar
wmmhello 已提交
664
  }
665 666
  if(ts >= (double)INT64_MAX || ts <= 0){
    return -1;
wmmhello's avatar
wmmhello 已提交
667 668
  }

669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
  return (int64_t)ts;
}

static int64_t smlGetTimeNow(int8_t precision) {
  switch (precision) {
    case TSDB_TIME_PRECISION_HOURS:
      return taosGetTimestampMs()/1000/3600;
    case TSDB_TIME_PRECISION_MINUTES:
      return taosGetTimestampMs()/1000/60;
    case TSDB_TIME_PRECISION_SECONDS:
      return taosGetTimestampMs()/1000;
    case TSDB_TIME_PRECISION_MILLI:
    case TSDB_TIME_PRECISION_MICRO:
    case TSDB_TIME_PRECISION_NANO:
      return taosGetTimestamp(precision);
    default:
      ASSERT(0);
wmmhello's avatar
wmmhello 已提交
686
  }
687
}
wmmhello's avatar
wmmhello 已提交
688

689 690 691 692 693 694 695
static int8_t smlGetTsTypeByLen(int32_t len) {
  if (len == TSDB_TIME_PRECISION_SEC_DIGITS) {
    return TSDB_TIME_PRECISION_SECONDS;
  } else if (len == TSDB_TIME_PRECISION_MILLI_DIGITS) {
    return TSDB_TIME_PRECISION_MILLI_DIGITS;
  } else {
    return -1;
wmmhello's avatar
wmmhello 已提交
696
  }
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
}

static int8_t smlGetTsTypeByPrecision(int8_t precision) {
  switch (precision) {
    case TSDB_SML_TIMESTAMP_HOURS:
      return TSDB_TIME_PRECISION_HOURS;
    case TSDB_SML_TIMESTAMP_MILLI_SECONDS:
      return TSDB_TIME_PRECISION_MILLI;
    case TSDB_SML_TIMESTAMP_NANO_SECONDS:
    case TSDB_SML_TIMESTAMP_NOT_CONFIGURED:
      return TSDB_TIME_PRECISION_NANO;
    case TSDB_SML_TIMESTAMP_MICRO_SECONDS:
      return TSDB_TIME_PRECISION_MICRO;
    case TSDB_SML_TIMESTAMP_SECONDS:
      return TSDB_TIME_PRECISION_SECONDS;
    case TSDB_SML_TIMESTAMP_MINUTES:
      return TSDB_TIME_PRECISION_MINUTES;
    default:
      return -1;
wmmhello's avatar
wmmhello 已提交
716
  }
717 718 719 720 721 722 723
}

static int64_t smlParseInfluxTime(SSmlHandle* info, const char* data, int32_t len){
  int8_t tsType = smlGetTsTypeByPrecision(info->precision);
  if (tsType == -1) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid timestamp precision", NULL);
    return -1;
wmmhello's avatar
wmmhello 已提交
724
  }
725 726
  if(!data){
    return smlGetTimeNow(tsType);
wmmhello's avatar
wmmhello 已提交
727
  }
728 729 730 731 732

  int64_t ts = smlGetTimeValue(data, len, tsType);
  if(ts == -1){
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid timestamp", data);
    return -1;
wmmhello's avatar
wmmhello 已提交
733
  }
734 735 736 737 738 739 740
  return ts;
}

static int64_t smlParseOpenTsdbTime(SSmlHandle* info, const char* data, int32_t len){
  if(!data){
    smlBuildInvalidDataMsg(&info->msgBuf, "timestamp can not be null", NULL);
    return -1;
wmmhello's avatar
wmmhello 已提交
741
  }
742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800
  int8_t tsType = smlGetTsTypeByLen(len);
  if (tsType == -1) {
    smlBuildInvalidDataMsg(&info->msgBuf, "timestamp precision can only be seconds(10 digits) or milli seconds(13 digits)", data);
    return -1;
  }
  int64_t ts = smlGetTimeValue(data, len, tsType);
  if(ts == -1){
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid timestamp", data);
    return -1;
  }
  return ts;
}

static int32_t smlParseTS(SSmlHandle* info, const char* data, int32_t len, SArray *cols){
  int64_t ts = 0;
  if(info->protocol == TSDB_SML_LINE_PROTOCOL){
    ts = smlParseInfluxTime(info, data, len);
  }else{
    ts = smlParseOpenTsdbTime(info, data, len);
  }
  if(ts == -1)  return TSDB_CODE_TSC_INVALID_TIME_STAMP;

  // add ts to
  SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
  if(!kv){
    return TSDB_CODE_OUT_OF_MEMORY;
  }

  kv->key = TS;
  kv->keyLen = TS_LEN;
  kv->i = ts;
  kv->type = TSDB_DATA_TYPE_TIMESTAMP;
  kv->length = (int16_t)tDataTypes[kv->type].bytes;
  if(cols) taosArrayPush(cols, &kv);
  return TSDB_CODE_SUCCESS;
}

static bool smlParseValue(SSmlKv *pVal, SSmlMsgBuf *msg) {
  //binary
  if (smlIsBinary(pVal->value, pVal->valueLen)) {
    pVal->type = TSDB_DATA_TYPE_BINARY;
    pVal->valueLen -= BINARY_ADD_LEN;
    pVal->length = pVal->valueLen;
    pVal->value += (BINARY_ADD_LEN - 1);
    return true;
  }
  //nchar
  if (smlIsNchar(pVal->value, pVal->valueLen)) {
    pVal->type = TSDB_DATA_TYPE_NCHAR;
    pVal->valueLen -= NCHAR_ADD_LEN;
    pVal->length = pVal->valueLen;
    pVal->value += (NCHAR_ADD_LEN - 1);
    return true;
  }

  //bool
  if (smlParseBool(pVal)) {
    pVal->type = TSDB_DATA_TYPE_BOOL;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
wmmhello's avatar
wmmhello 已提交
801 802
    return true;
  }
803 804
  //number
  if (smlParseNumber(pVal, msg)) {
wmmhello's avatar
wmmhello 已提交
805 806 807 808 809 810 811
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    return true;
  }

  return false;
}

812
static int32_t smlParseInfluxString(const char* sql, SSmlLineInfo *elements, SSmlMsgBuf *msg){
wmmhello's avatar
wmmhello 已提交
813 814 815 816 817 818 819 820
  if(!sql) return TSDB_CODE_SML_INVALID_DATA;
  while (*sql != '\0') {           // jump the space at the begining
    if(*sql != SPACE) {
      elements->measure = sql;
      break;
    }
    sql++;
  }
wmmhello's avatar
wmmhello 已提交
821 822 823 824
  if (!elements->measure || *sql == COMMA) {
    smlBuildInvalidDataMsg(msg, "invalid data", sql);
    return TSDB_CODE_SML_INVALID_DATA;
  }
wmmhello's avatar
wmmhello 已提交
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846

  // parse measure and tag
  while (*sql != '\0') {
    if (elements->measureLen == 0 && *sql == COMMA && *(sql - 1) != SLASH) {  // find the first comma
      elements->measureLen = sql - elements->measure;
      sql++;
      elements->tags = sql;
      continue;
    }

    if (*sql == SPACE && *(sql - 1) != SLASH) {   // find the first space
      if (elements->measureLen == 0) {
        elements->measureLen = sql - elements->measure;
        elements->tags = sql;
      }
      elements->tagsLen = sql - elements->tags;
      elements->measureTagsLen = sql - elements->measure;
      break;
    }

    sql++;
  }
wmmhello's avatar
wmmhello 已提交
847 848 849 850 851 852 853
  if(elements->tagsLen == 0){     // measure, cols1=a         measure cols1=a
    elements->measureTagsLen = elements->measureLen;
  }
  if(elements->measureLen == 0) {
    smlBuildInvalidDataMsg(msg, "invalid measure", elements->measure);
    return TSDB_CODE_SML_INVALID_DATA;
  }
wmmhello's avatar
wmmhello 已提交
854 855 856 857 858 859 860 861 862

  // parse cols
  while (*sql != '\0') {
    if(*sql != SPACE) {
      elements->cols = sql;
      break;
    }
    sql++;
  }
wmmhello's avatar
wmmhello 已提交
863 864 865
  if(!elements->cols) {
    smlBuildInvalidDataMsg(msg, "invalid columns", elements->cols);
    return TSDB_CODE_SML_INVALID_DATA;
866
  }
wmmhello's avatar
wmmhello 已提交
867

wmmhello's avatar
wmmhello 已提交
868
  bool isInQuote = false;
wmmhello's avatar
wmmhello 已提交
869
  while (*sql != '\0') {
wmmhello's avatar
wmmhello 已提交
870 871 872 873
    if(*sql == QUOTE && *(sql - 1) != SLASH){
      isInQuote = !isInQuote;
    }
    if(!isInQuote && *sql == SPACE && *(sql - 1) != SLASH) {
wmmhello's avatar
wmmhello 已提交
874 875 876 877
      break;
    }
    sql++;
  }
878 879 880 881
  if(isInQuote){
    smlBuildInvalidDataMsg(msg, "only one quote", elements->cols);
    return TSDB_CODE_SML_INVALID_DATA;
  }
wmmhello's avatar
wmmhello 已提交
882
  elements->colsLen = sql - elements->cols;
wmmhello's avatar
wmmhello 已提交
883

wmmhello's avatar
wmmhello 已提交
884
  // parse ts,ts can be empty
wmmhello's avatar
wmmhello 已提交
885
  while (*sql != '\0') {
886
    if(*sql != SPACE && elements->timestamp == NULL) {
wmmhello's avatar
wmmhello 已提交
887
      elements->timestamp = sql;
888 889
    }
    if(*sql == SPACE && elements->timestamp != NULL){
wmmhello's avatar
wmmhello 已提交
890 891 892 893
      break;
    }
    sql++;
  }
wmmhello's avatar
wmmhello 已提交
894 895 896
  if(elements->timestamp){
    elements->timestampLen = sql - elements->timestamp;
  }
wmmhello's avatar
wmmhello 已提交
897 898 899 900

  return TSDB_CODE_SUCCESS;
}

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 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
static void smlParseTelnetElement(const char **sql, const char **data, int32_t *len){
  while (**sql != '\0') {
    if(**sql != SPACE && !(*data)) {
      *data = *sql;
    }else if (**sql == SPACE && *data) {
      *len = *sql - *data;
      break;
    }
    (*sql)++;
  }
}

static int32_t smlParseTelnetTags(const char* data, int32_t len, SArray *cols, SHashObj *dumplicateKey, SSmlMsgBuf *msg){
  for(int i = 0; i < len; i++){
    // parse key
    const char *key = data + i;
    int32_t keyLen = 0;
    while(i < len){
      if(data[i] == EQUAL){
        keyLen = data + i - key;
        break;
      }
      i++;
    }
    if(keyLen == 0 || keyLen >= TSDB_COL_NAME_LEN){
      smlBuildInvalidDataMsg(msg, "invalid key or key is too long than 64", key);
      return TSDB_CODE_SML_INVALID_DATA;
    }

    if(smlCheckDuplicateKey(key, keyLen, dumplicateKey)){
      smlBuildInvalidDataMsg(msg, "dumplicate key", key);
      return TSDB_CODE_TSC_DUP_TAG_NAMES;
    }

    // parse value
    i++;
    const char *value = data + i;
    while(i < len){
      if(data[i] == SPACE){
        break;
      }
      i++;
    }
    int32_t valueLen = data + i - value;
    if(valueLen == 0){
      smlBuildInvalidDataMsg(msg, "invalid value", value);
      return TSDB_CODE_SML_INVALID_DATA;
    }

    // add kv to SSmlKv
    SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
    if(!kv) return TSDB_CODE_OUT_OF_MEMORY;
    kv->key = key;
    kv->keyLen = keyLen;
    kv->value = value;
    kv->valueLen = valueLen;
    kv->type = TSDB_DATA_TYPE_NCHAR;

    if(cols) taosArrayPush(cols, &kv);
  }

  return TSDB_CODE_SUCCESS;
}
// format: <metric> <timestamp> <value> <tagk_1>=<tagv_1>[ <tagk_n>=<tagv_n>]
static int32_t smlParseTelnetString(SSmlHandle *info, const char* sql, SSmlTableInfo *tinfo, SArray *cols){
  if(!sql) return TSDB_CODE_SML_INVALID_DATA;

  // parse metric
  smlParseTelnetElement(&sql, &tinfo->sTableName, &tinfo->sTableNameLen);
  if (!(tinfo->sTableName) || tinfo->sTableNameLen == 0) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid data", sql);
    return TSDB_CODE_SML_INVALID_DATA;
  }

  // parse timestamp
  const char *timestamp = NULL;
  int32_t tLen = 0;
  smlParseTelnetElement(&sql, &timestamp, &tLen);
  if (!timestamp || tLen == 0) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid timestamp", sql);
    return TSDB_CODE_SML_INVALID_DATA;
  }

  int32_t ret = smlParseTS(info, timestamp, tLen, cols);
  if (ret != TSDB_CODE_SUCCESS) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid timestamp", sql);
    return TSDB_CODE_SML_INVALID_DATA;
  }

  // parse value
  const char *value = NULL;
  int32_t valueLen = 0;
  smlParseTelnetElement(&sql, &value, &valueLen);
  if (!value || valueLen == 0) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid value", sql);
    return TSDB_CODE_SML_INVALID_DATA;
  }

  SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
  if(!kv) return TSDB_CODE_OUT_OF_MEMORY;
  taosArrayPush(cols, &kv);
  kv->key = VALUE;
  kv->keyLen = VALUE_LEN;
  kv->value = value;
  kv->valueLen = valueLen;
  if(!smlParseValue(kv, &info->msgBuf) || kv->type == TSDB_DATA_TYPE_BINARY
      || kv->type == TSDB_DATA_TYPE_NCHAR || kv->type == TSDB_DATA_TYPE_BOOL){
    return TSDB_CODE_SML_INVALID_DATA;
  }

  // parse tags
  while(*sql == SPACE){
    sql++;
  }
  ret = smlParseTelnetTags(sql, strlen(sql), tinfo->tags, info->dumplicateKey, &info->msgBuf);
  if (ret != TSDB_CODE_SUCCESS) {
    smlBuildInvalidDataMsg(&info->msgBuf, "invalid data", sql);
    return TSDB_CODE_SML_INVALID_DATA;
  }

  return TSDB_CODE_SUCCESS;
}

1024
static int32_t smlParseCols(const char* data, int32_t len, SArray *cols, bool isTag, SHashObj *dumplicateKey, SSmlMsgBuf *msg){
wmmhello's avatar
wmmhello 已提交
1025
  if(isTag && len == 0){
wmmhello's avatar
wmmhello 已提交
1026
    SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
1027
    if(!kv) return TSDB_CODE_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
1028
    kv->key = TAG;
1029
    kv->keyLen = TAG_LEN;
wmmhello's avatar
wmmhello 已提交
1030
    kv->value = TAG;
1031
    kv->valueLen = TAG_LEN;
wmmhello's avatar
wmmhello 已提交
1032 1033
    kv->type = TSDB_DATA_TYPE_NCHAR;
    if(cols) taosArrayPush(cols, &kv);
wmmhello's avatar
wmmhello 已提交
1034
    return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1035 1036
  }

wmmhello's avatar
wmmhello 已提交
1037
  for(int i = 0; i < len; i++){
wmmhello's avatar
wmmhello 已提交
1038
    // parse key
wmmhello's avatar
wmmhello 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047
    const char *key = data + i;
    int32_t keyLen = 0;
    while(i < len){
      if(data[i] == EQUAL && i > 0 && data[i-1] != SLASH){
        keyLen = data + i - key;
        break;
      }
      i++;
    }
wmmhello's avatar
wmmhello 已提交
1048
    if(keyLen == 0 || keyLen >= TSDB_COL_NAME_LEN){
wmmhello's avatar
wmmhello 已提交
1049
      smlBuildInvalidDataMsg(msg, "invalid key or key is too long than 64", key);
wmmhello's avatar
wmmhello 已提交
1050 1051 1052
      return TSDB_CODE_SML_INVALID_DATA;
    }

1053
    if(smlCheckDuplicateKey(key, keyLen, dumplicateKey)){
1054
      smlBuildInvalidDataMsg(msg, "dumplicate key", key);
1055
      return TSDB_CODE_TSC_DUP_TAG_NAMES;
1056 1057
    }

wmmhello's avatar
wmmhello 已提交
1058
    // parse value
wmmhello's avatar
wmmhello 已提交
1059 1060
    i++;
    const char *value = data + i;
wmmhello's avatar
wmmhello 已提交
1061
    bool isInQuote = false;
wmmhello's avatar
wmmhello 已提交
1062
    while(i < len){
1063
      if(!isTag && data[i] == QUOTE && data[i-1] != SLASH){
wmmhello's avatar
wmmhello 已提交
1064 1065 1066
        isInQuote = !isInQuote;
      }
      if(!isInQuote && data[i] == COMMA && i > 0 && data[i-1] != SLASH){
wmmhello's avatar
wmmhello 已提交
1067 1068 1069 1070
        break;
      }
      i++;
    }
1071
    if(!isTag && isInQuote){
wmmhello's avatar
wmmhello 已提交
1072 1073 1074
      smlBuildInvalidDataMsg(msg, "only one quote", value);
      return TSDB_CODE_SML_INVALID_DATA;
    }
wmmhello's avatar
wmmhello 已提交
1075
    int32_t valueLen = data + i - value;
wmmhello's avatar
wmmhello 已提交
1076
    if(valueLen == 0){
wmmhello's avatar
wmmhello 已提交
1077
      smlBuildInvalidDataMsg(msg, "invalid value", value);
wmmhello's avatar
wmmhello 已提交
1078 1079
      return TSDB_CODE_SML_INVALID_DATA;
    }
wmmhello's avatar
wmmhello 已提交
1080 1081

    // add kv to SSmlKv
wmmhello's avatar
wmmhello 已提交
1082
    SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
1083 1084 1085
    if(!kv) return TSDB_CODE_OUT_OF_MEMORY;
    if(cols) taosArrayPush(cols, &kv);

wmmhello's avatar
wmmhello 已提交
1086 1087 1088 1089
    kv->key = key;
    kv->keyLen = keyLen;
    kv->value = value;
    kv->valueLen = valueLen;
wmmhello's avatar
wmmhello 已提交
1090 1091
    if(isTag){
      kv->type = TSDB_DATA_TYPE_NCHAR;
wmmhello's avatar
wmmhello 已提交
1092
    }else{
wmmhello's avatar
wmmhello 已提交
1093
      if(!smlParseValue(kv, msg)){
wmmhello's avatar
wmmhello 已提交
1094 1095
        return TSDB_CODE_SML_INVALID_DATA;
      }
wmmhello's avatar
wmmhello 已提交
1096 1097
    }
  }
wmmhello's avatar
wmmhello 已提交
1098

wmmhello's avatar
wmmhello 已提交
1099 1100 1101
  return TSDB_CODE_SUCCESS;
}

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
//static int32_t parseSmlCols(const char* data, SArray *cols){
//  while(*data != '\0'){
//    if(*data == EQUAL) return TSDB_CODE_SML_INVALID_DATA;
//    const char *key = data;
//    int32_t keyLen = 0;
//    while(*data != '\0'){
//      if(*data == EQUAL && *(data-1) != SLASH){
//        keyLen = data - key;
//        data ++;
//        break;
//      }
//      data++;
//    }
//    if(keyLen == 0){
//      return TSDB_CODE_SML_INVALID_DATA;
//    }
//
//    if(*data == COMMA) return TSDB_CODE_SML_INVALID_DATA;
//    const char *value = data;
//    int32_t valueLen = 0;
//    while(*data != '\0'){
//      if(*data == COMMA && *(data-1) != SLASH){
//        valueLen = data - value;
//        data ++;
//        break;
//      }
//      data++;
//    }
//    if(valueLen == 0){
//      return TSDB_CODE_SML_INVALID_DATA;
//    }
//
//    TAOS_SML_KV *kv = taosMemoryCalloc(sizeof(TAOS_SML_KV), 1);
//    kv->key = key;
//    kv->keyLen = keyLen;
//    kv->value = value;
//    kv->valueLen = valueLen;
//    kv->type = TSDB_DATA_TYPE_NCHAR;
//    if(cols) taosArrayPush(cols, &kv);
//  }
//  return TSDB_CODE_SUCCESS;
//}
wmmhello's avatar
wmmhello 已提交
1144

1145 1146 1147 1148 1149
static bool smlUpdateMeta(SSmlSTableMeta* tableMeta, SArray *tags, SArray *cols, SSmlMsgBuf *msg){
  if(tags){
    for (int i = 0; i < taosArrayGetSize(tags); ++i) {
      SSmlKv *kv = (SSmlKv *)taosArrayGetP(tags, i);
      ASSERT(kv->type == TSDB_DATA_TYPE_NCHAR);
wmmhello's avatar
wmmhello 已提交
1150

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
      uint8_t *index = (uint8_t *)taosHashGet(tableMeta->tagHash, kv->key, kv->keyLen);
      if(index){
        SSmlKv **value = (SSmlKv **)taosArrayGet(tableMeta->tags, *index);
        ASSERT((*value)->type == TSDB_DATA_TYPE_NCHAR);
        if(kv->valueLen > (*value)->valueLen){    // tags type is nchar
          *value = kv;
        }
      }else{
        size_t tmp = taosArrayGetSize(tableMeta->tags);
        ASSERT(tmp <= UINT8_MAX);
        uint8_t size = tmp;
        taosArrayPush(tableMeta->tags, &kv);
        taosHashPut(tableMeta->tagHash, kv->key, kv->keyLen, &size, CHAR_BYTES);
      }
    }
wmmhello's avatar
wmmhello 已提交
1166 1167
  }

1168 1169 1170
  if(cols){
    for (int i = 1; i < taosArrayGetSize(cols); ++i) {  //jump timestamp
      SSmlKv *kv = (SSmlKv *)taosArrayGetP(cols, i);
wmmhello's avatar
wmmhello 已提交
1171

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

1197 1198 1199 1200 1201 1202 1203
static void smlInsertMeta(SSmlSTableMeta* tableMeta, SArray *tags, SArray *cols){
  if(tags){
    for (uint8_t i = 0; i < taosArrayGetSize(tags); ++i) {
      SSmlKv *kv = (SSmlKv *)taosArrayGetP(tags, i);
      taosArrayPush(tableMeta->tags, &kv);
      taosHashPut(tableMeta->tagHash, kv->key, kv->keyLen, &i, CHAR_BYTES);
    }
wmmhello's avatar
wmmhello 已提交
1204 1205
  }

1206 1207 1208 1209 1210 1211
  if(cols){
    for (int16_t i = 0; i < taosArrayGetSize(cols); ++i) {
      SSmlKv *kv = (SSmlKv *)taosArrayGetP(cols, i);
      taosArrayPush(tableMeta->cols, &kv);
      taosHashPut(tableMeta->fieldHash, kv->key, kv->keyLen, &i, SHORT_BYTES);
    }
wmmhello's avatar
wmmhello 已提交
1212 1213 1214
  }
}

1215 1216 1217 1218
static SSmlTableInfo* smlBuildTableInfo(){
  SSmlTableInfo *tag = (SSmlTableInfo *)taosMemoryCalloc(sizeof(SSmlTableInfo), 1);
  if(!tag){
    return NULL;
wmmhello's avatar
wmmhello 已提交
1219
  }
1220 1221 1222 1223 1224

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

  tag->tags = taosArrayInit(16, POINTER_BYTES);
  if (tag->tags == NULL) {
    uError("SML:smlBuildTableInfo failed to allocate memory");
    goto cleanup;
wmmhello's avatar
wmmhello 已提交
1231
  }
1232 1233 1234 1235 1236
  return tag;

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

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
static void smlDestroyTableInfo(SSmlTableInfo *tag, bool format){
  if(format){
    for(size_t i = 0; i < taosArrayGetSize(tag->cols); i++){
      SArray *kvArray = (SArray *)taosArrayGetP(tag->cols, i);
      for (int j = 0; j < taosArrayGetSize(kvArray); ++j) {
        void *p = taosArrayGetP(kvArray, j);
        taosMemoryFree(p);
      }
      taosArrayDestroy(kvArray);
    }
wmmhello's avatar
wmmhello 已提交
1249
  }else{
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428
    for(size_t i = 0; i < taosArrayGetSize(tag->cols); i++){
      SHashObj *kvHash = (SHashObj *)taosArrayGetP(tag->cols, i);
      void** p1 = (void**)taosHashIterate(kvHash, NULL);
      while (p1) {
        taosMemoryFree(*p1);
        p1 = (void**)taosHashIterate(kvHash, p1);
      }
      taosHashCleanup(kvHash);
    }
  }
  taosArrayDestroy(tag->cols);
  taosArrayDestroy(tag->tags);
  taosMemoryFree(tag);
}

static int32_t smlDealCols(SSmlTableInfo* oneTable, bool dataFormat, SArray *cols){
  if(dataFormat){
    taosArrayPush(oneTable->cols, &cols);
    return TSDB_CODE_SUCCESS;
  }

  SHashObj *kvHash = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  if(!kvHash){
    uError("SML:smlDealCols failed to allocate memory");
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }
  for(size_t i = 0; i < taosArrayGetSize(cols); i++){
    SSmlKv *kv = (SSmlKv *)taosArrayGetP(cols, i);
    taosHashPut(kvHash, kv->key, kv->keyLen, &kv, POINTER_BYTES);   // todo key need escape, like \=, because find by schema name later
  }
  taosArrayPush(oneTable->cols, &kvHash);

  return TSDB_CODE_SUCCESS;
}

static SSmlSTableMeta* smlBuildSTableMeta(){
  SSmlSTableMeta* meta = (SSmlSTableMeta*)taosMemoryCalloc(sizeof(SSmlSTableMeta), 1);
  if(!meta){
    return NULL;
  }
  meta->tagHash = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  if (meta->tagHash == NULL) {
    uError("SML:smlBuildSTableMeta failed to allocate memory");
    goto cleanup;
  }

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

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

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

cleanup:
  taosMemoryFree(meta);
  return NULL;
}

static void smlDestroySTableMeta(SSmlSTableMeta *meta){
  taosHashCleanup(meta->tagHash);
  taosHashCleanup(meta->fieldHash);
  taosArrayDestroy(meta->tags);
  taosArrayDestroy(meta->cols);
  taosMemoryFree(meta->tableMeta);
}

static void smlDestroyCols(SArray *cols) {
  if (!cols) return;
  for (int i = 0; i < taosArrayGetSize(cols); ++i) {
    void *kv = taosArrayGet(cols, i);
    taosMemoryFree(kv);
  }
}

static void smlDestroyInfo(SSmlHandle* info){
  if(!info) return;
  qDestroyQuery(info->pQuery);
  smlDestroyHandle(info->exec);

  // destroy info->childTables
  void** p1 = (void**)taosHashIterate(info->childTables, NULL);
  while (p1) {
    smlDestroyTableInfo((SSmlTableInfo*)(*p1), info->dataFormat);
    p1 = (void**)taosHashIterate(info->childTables, p1);
  }
  taosHashCleanup(info->childTables);

  // destroy info->superTables
  p1 = (void**)taosHashIterate(info->superTables, NULL);
  while (p1) {
    smlDestroySTableMeta((SSmlSTableMeta*)(*p1));
    p1 = (void**)taosHashIterate(info->superTables, p1);
  }
  taosHashCleanup(info->superTables);

  // destroy info->pVgHash
  taosHashCleanup(info->pVgHash);
  taosHashCleanup(info->dumplicateKey);

  taosMemoryFreeClear(info);
}

static SSmlHandle* smlBuildSmlInfo(TAOS* taos, SRequestObj* request, SMLProtocolType protocol, int8_t precision, bool dataFormat){
  int32_t code = TSDB_CODE_SUCCESS;
  SSmlHandle* info = (SSmlHandle*)taosMemoryCalloc(1, sizeof(SSmlHandle));
  if (NULL == info) {
    return NULL;
  }
  info->id          = smlGenId();

  info->pQuery      = (SQuery *)taosMemoryCalloc(1, sizeof(SQuery));
  if (NULL == info->pQuery) {
    uError("SML:0x%"PRIx64" create info->pQuery error", info->id);
    goto cleanup;
  }
  info->pQuery->execMode      = QUERY_EXEC_MODE_SCHEDULE;
  info->pQuery->haveResultSet = false;
  info->pQuery->msgType       = TDMT_VND_SUBMIT;
  info->pQuery->pRoot         = (SNode*)nodesMakeNode(QUERY_NODE_VNODE_MODIF_STMT);
  if(NULL == info->pQuery->pRoot){
    uError("SML:0x%"PRIx64" create info->pQuery->pRoot error", info->id);
    goto cleanup;
  }
  ((SVnodeModifOpStmt*)(info->pQuery->pRoot))->payloadType = PAYLOAD_TYPE_KV;

  info->taos        = (STscObj *)taos;
  code = catalogGetHandle(info->taos->pAppInfo->clusterId, &info->pCatalog);
  if(code != TSDB_CODE_SUCCESS){
    uError("SML:0x%"PRIx64" get catalog error %d", info->id, code);
    goto cleanup;
  }

  info->precision   = precision;
  info->protocol    = protocol;
  info->dataFormat  = dataFormat;
  info->pRequest    = request;
  info->msgBuf.buf  = info->pRequest->msgBuf;
  info->msgBuf.len  = ERROR_MSG_BUF_DEFAULT_SIZE;

  info->exec        = smlInitHandle(info->pQuery);
  info->childTables = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  info->superTables = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  info->pVgHash     = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_NO_LOCK);

  info->dumplicateKey = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  if(!dataFormat){
    info->colsContainer = taosArrayInit(32, POINTER_BYTES);
    if(NULL == info->colsContainer){
      uError("SML:0x%"PRIx64" create info failed", info->id);
      goto cleanup;
    }
  }
  if(NULL == info->exec || NULL == info->childTables
      || NULL == info->superTables || NULL == info->pVgHash
      || NULL == info->dumplicateKey){
    uError("SML:0x%"PRIx64" create info failed", info->id);
    goto cleanup;
  }

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

/************* TSDB_SML_JSON_PROTOCOL function start **************/
static int32_t smlJsonCreateSring(const char **output, char *input, int32_t inputLen){
1429
  *output = (const char *)taosMemoryMalloc(inputLen);
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
  if (*output == NULL){
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }

  memcpy((void*)(*output), input, inputLen);
  return TSDB_CODE_SUCCESS;
}

static int32_t smlParseMetricFromJSON(SSmlHandle *info, cJSON *root, SSmlTableInfo *tinfo) {
  cJSON *metric = cJSON_GetObjectItem(root, "metric");
  if (!cJSON_IsString(metric)) {
    return  TSDB_CODE_TSC_INVALID_JSON;
  }

  tinfo->sTableNameLen = strlen(metric->valuestring);
  if (tinfo->sTableNameLen >= TSDB_TABLE_NAME_LEN) {
    uError("OTD:0x%"PRIx64" Metric cannot exceeds %d characters in JSON", info->id, TSDB_TABLE_NAME_LEN - 1);
    return TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
  }

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

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

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

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

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

  size_t typeLen = strlen(type->valuestring);
  if (typeLen == 1 && type->valuestring[0] == 's') {
    //seconds
    timeDouble = timeDouble * 1e9;
    if(smlDoubleToInt64OverFlow(timeDouble)){
      smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
      return TSDB_CODE_TSC_INVALID_TIME_STAMP;
    }
    *tsVal = timeDouble;
  } else if (typeLen == 2 && type->valuestring[1] == 's') {
    switch (type->valuestring[0]) {
      case 'm':
        //milliseconds
        timeDouble = timeDouble * 1e6;
        if(smlDoubleToInt64OverFlow(timeDouble)){
          smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
          return TSDB_CODE_TSC_INVALID_TIME_STAMP;
        }
        *tsVal = timeDouble;
        break;
      case 'u':
        //microseconds
        timeDouble = timeDouble * 1e3;
        if(smlDoubleToInt64OverFlow(timeDouble)){
          smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
          return TSDB_CODE_TSC_INVALID_TIME_STAMP;
        }
        *tsVal = timeDouble;
        break;
      case 'n':
        //nanoseconds
        *tsVal = timeDouble;
        break;
      default:
        return TSDB_CODE_TSC_INVALID_JSON;
    }
  } else {
    return TSDB_CODE_TSC_INVALID_JSON;
  }

  return TSDB_CODE_SUCCESS;
}

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

static int32_t smlParseTSFromJSON(SSmlHandle *info, cJSON *root, SArray *cols) {
  //Timestamp must be the first KV to parse
  int64_t tsVal = 0;

  cJSON *timestamp = cJSON_GetObjectItem(root, "timestamp");
  if (cJSON_IsNumber(timestamp)) {
    //timestamp value 0 indicates current system time
    double timeDouble = timestamp->valuedouble;
    if(smlDoubleToInt64OverFlow(timeDouble)){
      smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
      return TSDB_CODE_TSC_INVALID_TIME_STAMP;
    }
    if(timeDouble <= 0){
      return TSDB_CODE_TSC_INVALID_TIME_STAMP;
    }
    uint8_t tsLen = smlGetTimestampLen((int64_t)timeDouble);
    if (tsLen == TSDB_TIME_PRECISION_SEC_DIGITS) {
      timeDouble = timeDouble * 1e9;
      if(smlDoubleToInt64OverFlow(timeDouble)){
        smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
        return TSDB_CODE_TSC_INVALID_TIME_STAMP;
      }
      tsVal = timeDouble;
    } else if (tsLen == TSDB_TIME_PRECISION_MILLI_DIGITS) {
      timeDouble = timeDouble * 1e6;
      if(smlDoubleToInt64OverFlow(timeDouble)){
        smlBuildInvalidDataMsg(&info->msgBuf, "timestamp is too large", NULL);
        return TSDB_CODE_TSC_INVALID_TIME_STAMP;
      }
      tsVal = timeDouble;
    } else {
      return TSDB_CODE_TSC_INVALID_TIME_STAMP;
    }
  } else if (cJSON_IsObject(timestamp)) {
    int32_t ret = smlParseTSFromJSONObj(info, timestamp, &tsVal);
    if (ret != TSDB_CODE_SUCCESS) {
      uError("SML:0x%"PRIx64" Failed to parse timestamp from JSON Obj", info->id);
      return ret;
    }
  } else {
    return TSDB_CODE_TSC_INVALID_JSON;
wmmhello's avatar
wmmhello 已提交
1571 1572
  }

wmmhello's avatar
wmmhello 已提交
1573
  // add ts to
wmmhello's avatar
wmmhello 已提交
1574
  SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
wmmhello's avatar
wmmhello 已提交
1575 1576 1577 1578
  if(!kv){
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  kv->key = TS;
1579 1580
  kv->keyLen = TS_LEN;
  kv->i = tsVal;
wmmhello's avatar
wmmhello 已提交
1581
  kv->type = TSDB_DATA_TYPE_TIMESTAMP;
wmmhello's avatar
wmmhello 已提交
1582
  kv->length = (int16_t)tDataTypes[kv->type].bytes;
wmmhello's avatar
wmmhello 已提交
1583
  if(cols) taosArrayPush(cols, &kv);
wmmhello's avatar
wmmhello 已提交
1584
  return TSDB_CODE_SUCCESS;
1585

wmmhello's avatar
wmmhello 已提交
1586 1587
}

1588 1589 1590 1591 1592 1593 1594 1595
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;
wmmhello's avatar
wmmhello 已提交
1596

1597 1598
  return TSDB_CODE_SUCCESS;
}
wmmhello's avatar
wmmhello 已提交
1599

1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
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(smlDoubleToInt64OverFlow(value->valuedouble)){
      uError("OTD:JSON value(%f) cannot fit in type(big int)", value->valuedouble);
      return TSDB_CODE_TSC_VALUE_OUT_OF_RANGE;
    }
    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;
wmmhello's avatar
wmmhello 已提交
1655
    }
1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667
    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;
wmmhello's avatar
wmmhello 已提交
1668 1669
  }

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

1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712
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);
  pVal->valueLen = pVal->length;
  return smlJsonCreateSring(&pVal->value, value->valuestring, pVal->valueLen);
}

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

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

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

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

  switch (value->type) {
    case cJSON_True:
    case cJSON_False: {
      ret = smlConvertJSONBool(kv, type->valuestring, value);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
wmmhello's avatar
wmmhello 已提交
1713
      }
1714
      break;
wmmhello's avatar
wmmhello 已提交
1715
    }
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731
    case cJSON_Number: {
      ret = smlConvertJSONNumber(kv, type->valuestring, value);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }
      break;
    }
    case cJSON_String: {
      ret = smlConvertJSONString(kv, type->valuestring, value);
      if (ret != TSDB_CODE_SUCCESS) {
        return ret;
      }
      break;
    }
    default:
      return TSDB_CODE_TSC_INVALID_JSON_TYPE;
wmmhello's avatar
wmmhello 已提交
1732
  }
1733 1734

  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1735 1736
}

1737 1738 1739 1740 1741 1742 1743 1744
static int32_t smlParseValueFromJSON(cJSON *root, SSmlKv *kv) {
  switch (root->type) {
    case cJSON_True:
    case cJSON_False: {
      kv->type = TSDB_DATA_TYPE_BOOL;
      kv->length = (int16_t)tDataTypes[kv->type].bytes;
      kv->i = root->valueint;
      break;
wmmhello's avatar
wmmhello 已提交
1745
    }
1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
    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 已提交
1756

1757
      char *tsDefaultJSONStrType = "binary";   //todo
1758 1759
      smlConvertJSONString(kv, tsDefaultJSONStrType, root);
      break;
wmmhello's avatar
wmmhello 已提交
1760
    }
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
    case cJSON_Object: {
      int32_t ret = smlParseValueFromJSONObj(root, kv);
      if (ret != TSDB_CODE_SUCCESS) {
        uError("OTD:Failed to parse value from JSON Obj");
        return ret;
      }
      break;
    }
    default:
      return TSDB_CODE_TSC_INVALID_JSON;
wmmhello's avatar
wmmhello 已提交
1771
  }
1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794

  return TSDB_CODE_SUCCESS;
}

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

  SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
  if(!kv){
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  if(cols) taosArrayPush(cols, &kv);

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

1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
static int32_t smlParseTagsFromJSON(cJSON *root, SArray *pKVs, SHashObj *dumplicateKey, SSmlMsgBuf *msg) {
  int32_t ret = TSDB_CODE_SUCCESS;

  cJSON *tags = cJSON_GetObjectItem(root, "tags");
  if (tags == NULL || tags->type != cJSON_Object) {
    return TSDB_CODE_TSC_INVALID_JSON;
  }
  //handle child table name  todo
//  size_t childTableNameLen = strlen(tsSmlChildTableName);
//  char childTbName[TSDB_TABLE_NAME_LEN] = {0};
//  if (childTableNameLen != 0) {
//    memcpy(childTbName, tsSmlChildTableName, childTableNameLen);
//    cJSON *id = cJSON_GetObjectItem(tags, childTbName);
//    if (id != NULL) {
//      if (!cJSON_IsString(id)) {
//        tscError("OTD:0x%"PRIx64" ID must be JSON string", info->id);
//        return TSDB_CODE_TSC_INVALID_JSON;
//      }
//      size_t idLen = strlen(id->valuestring);
//      *childTableName = tcalloc(idLen + TS_BACKQUOTE_CHAR_SIZE + 1, sizeof(char));
//      memcpy(*childTableName, id->valuestring, idLen);
//      addEscapeCharToString(*childTableName, (int32_t)idLen);
//
//      //check duplicate IDs
//      cJSON_DeleteItemFromObject(tags, childTbName);
//      id = cJSON_GetObjectItem(tags, childTbName);
//      if (id != NULL) {
//        return TSDB_CODE_TSC_DUP_TAG_NAMES;
//      }
//    }
//  }
wmmhello's avatar
wmmhello 已提交
1828

1829 1830 1831 1832 1833
  int32_t tagNum = cJSON_GetArraySize(tags);
  for (int32_t i = 0; i < tagNum; ++i) {
    cJSON *tag = cJSON_GetArrayItem(tags, i);
    if (tag == NULL) {
      return TSDB_CODE_TSC_INVALID_JSON;
wmmhello's avatar
wmmhello 已提交
1834
    }
1835 1836 1837
    //check duplicate keys
    if (smlCheckDuplicateKey(tag->string, strlen(tag->string), dumplicateKey)) {
      return TSDB_CODE_TSC_DUP_TAG_NAMES;
wmmhello's avatar
wmmhello 已提交
1838 1839
    }

1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859
    // add kv to SSmlKv
    SSmlKv *kv = (SSmlKv *)taosMemoryCalloc(sizeof(SSmlKv), 1);
    if(!kv) return TSDB_CODE_OUT_OF_MEMORY;
    if(pKVs) taosArrayPush(pKVs, &kv);

    //key
    kv->keyLen = strlen(tag->string);
    if (kv->keyLen >= TSDB_COL_NAME_LEN) {
      uError("OTD:Tag key cannot exceeds %d characters in JSON", TSDB_COL_NAME_LEN - 1);
      return TSDB_CODE_TSC_INVALID_COLUMN_LENGTH;
    }
    ret = smlJsonCreateSring(&kv->key, tag->string, kv->keyLen);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
    //value
    ret = smlParseValueFromJSON(tag, kv);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }
wmmhello's avatar
wmmhello 已提交
1860 1861
  }

1862
  return ret;
wmmhello's avatar
wmmhello 已提交
1863 1864 1865

}

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

1869 1870 1871
  if (!cJSON_IsObject(root)) {
    uError("OTD:0x%"PRIx64" data point needs to be JSON object", info->id);
    return TSDB_CODE_TSC_INVALID_JSON;
wmmhello's avatar
wmmhello 已提交
1872
  }
1873

1874 1875 1876 1877 1878
  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 已提交
1879
  }
1880 1881 1882 1883 1884 1885

  //Parse metric
  ret = smlParseMetricFromJSON(info, root, tinfo);
  if (ret != TSDB_CODE_SUCCESS) {
    uError("OTD:0x%"PRIx64" Unable to parse metric from JSON payload", info->id);
    return ret;
wmmhello's avatar
wmmhello 已提交
1886
  }
1887
  uDebug("OTD:0x%"PRIx64" Parse metric from JSON payload finished", info->id);
wmmhello's avatar
wmmhello 已提交
1888

1889 1890 1891 1892 1893
  //Parse timestamp
  ret = smlParseTSFromJSON(info, root, cols);
  if (ret) {
    uError("OTD:0x%"PRIx64" Unable to parse timestamp from JSON payload", info->id);
    return ret;
wmmhello's avatar
wmmhello 已提交
1894
  }
1895
  uDebug("OTD:0x%"PRIx64" Parse timestamp from JSON payload finished", info->id);
1896

1897 1898 1899 1900 1901
  //Parse metric value
  ret = smlParseColsFromJSON(root, cols);
  if (ret) {
    uError("OTD:0x%"PRIx64" Unable to parse metric value from JSON payload", info->id);
    return ret;
1902
  }
1903
  uDebug("OTD:0x%"PRIx64" Parse metric value from JSON payload finished", info->id);
1904

1905 1906 1907 1908 1909
  //Parse tags
  ret = smlParseTagsFromJSON(root, tinfo->tags, info->dumplicateKey, &info->msgBuf);
  if (ret) {
    uError("OTD:0x%"PRIx64" Unable to parse tags from JSON payload", info->id);
    return ret;
1910
  }
1911
  uDebug("OTD:0x%"PRIx64" Parse tags from JSON payload finished", info->id);
wmmhello's avatar
wmmhello 已提交
1912

1913
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1914
}
1915
/************* TSDB_SML_JSON_PROTOCOL function end **************/
wmmhello's avatar
wmmhello 已提交
1916 1917


1918 1919

static int32_t smlParseInfluxLine(SSmlHandle* info, const char* sql) {
wmmhello's avatar
wmmhello 已提交
1920
  SSmlLineInfo elements = {0};
1921
  int ret = smlParseInfluxString(sql, &elements, &info->msgBuf);
wmmhello's avatar
wmmhello 已提交
1922
  if(ret != TSDB_CODE_SUCCESS){
1923
    uError("SML:0x%"PRIx64" smlParseInfluxLine failed", info->id);
wmmhello's avatar
wmmhello 已提交
1924 1925 1926
    return ret;
  }

1927 1928 1929 1930
  SArray *cols = NULL;
  if(info->dataFormat){   // if dataFormat, cols need new memory to save data
    cols = taosArrayInit(16, POINTER_BYTES);
    if (cols == NULL) {
1931
      uError("SML:0x%"PRIx64" smlParseInfluxLine failed to allocate memory", info->id);
1932 1933 1934 1935
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
    }
  }else{      // if dataFormat is false, cols do not need to save data, there is another new memory to save data
    cols = info->colsContainer;
wmmhello's avatar
wmmhello 已提交
1936
  }
wmmhello's avatar
wmmhello 已提交
1937

wmmhello's avatar
wmmhello 已提交
1938
  ret = smlParseTS(info, elements.timestamp, elements.timestampLen, cols);
wmmhello's avatar
wmmhello 已提交
1939
  if(ret != TSDB_CODE_SUCCESS){
wmmhello's avatar
wmmhello 已提交
1940
    uError("SML:0x%"PRIx64" smlParseTS failed", info->id);
1941
    if(info->dataFormat) taosArrayDestroy(cols);
wmmhello's avatar
wmmhello 已提交
1942 1943
    return ret;
  }
1944
  ret = smlParseCols(elements.cols, elements.colsLen, cols, false, info->dumplicateKey, &info->msgBuf);
wmmhello's avatar
wmmhello 已提交
1945
  if(ret != TSDB_CODE_SUCCESS){
wmmhello's avatar
wmmhello 已提交
1946
    uError("SML:0x%"PRIx64" smlParseCols parse cloums fields failed", info->id);
1947 1948
    smlDestroyCols(cols);
    if(info->dataFormat) taosArrayDestroy(cols);
wmmhello's avatar
wmmhello 已提交
1949 1950
    return ret;
  }
wmmhello's avatar
wmmhello 已提交
1951
  if(taosArrayGetSize(cols) > TSDB_MAX_COLUMNS){
wmmhello's avatar
wmmhello 已提交
1952
    smlBuildInvalidDataMsg(&info->msgBuf, "too many columns than 4096", NULL);
wmmhello's avatar
wmmhello 已提交
1953 1954
    return TSDB_CODE_SML_INVALID_DATA;
  }
wmmhello's avatar
wmmhello 已提交
1955

1956
  bool hasTable = true;
1957
  SSmlTableInfo *tinfo = NULL;
wmmhello's avatar
wmmhello 已提交
1958
  SSmlTableInfo **oneTable = (SSmlTableInfo **)taosHashGet(info->childTables, elements.measure, elements.measureTagsLen);
1959
  if(!oneTable){
1960
    tinfo = smlBuildTableInfo();
1961
    if(!tinfo){
wmmhello's avatar
wmmhello 已提交
1962 1963
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
    }
1964
    taosHashPut(info->childTables, elements.measure, elements.measureTagsLen, &tinfo, POINTER_BYTES);
1965
    oneTable = &tinfo;
1966 1967 1968 1969 1970 1971 1972
    hasTable = false;
  }

  ret = smlDealCols(*oneTable, info->dataFormat, cols);
  if(ret != TSDB_CODE_SUCCESS){
    return ret;
  }
wmmhello's avatar
wmmhello 已提交
1973

1974 1975
  if(!hasTable){
    ret = smlParseCols(elements.tags, elements.tagsLen, (*oneTable)->tags, true, info->dumplicateKey, &info->msgBuf);
wmmhello's avatar
wmmhello 已提交
1976
    if(ret != TSDB_CODE_SUCCESS){
wmmhello's avatar
wmmhello 已提交
1977
      uError("SML:0x%"PRIx64" smlParseCols parse tag fields failed", info->id);
wmmhello's avatar
wmmhello 已提交
1978 1979 1980
      return ret;
    }

1981
    if(taosArrayGetSize((*oneTable)->tags) > TSDB_MAX_TAGS){
wmmhello's avatar
wmmhello 已提交
1982
      smlBuildInvalidDataMsg(&info->msgBuf, "too many tags than 128", NULL);
wmmhello's avatar
wmmhello 已提交
1983 1984 1985
      return TSDB_CODE_SML_INVALID_DATA;
    }

1986 1987
    (*oneTable)->sTableName = elements.measure;
    (*oneTable)->sTableNameLen = elements.measureLen;
1988
    RandTableName rName = {.tags=(*oneTable)->tags, .sTableName=(*oneTable)->sTableName, .sTableNameLen=(uint8_t)(*oneTable)->sTableNameLen,
1989
                           .childTableName=(*oneTable)->childTableName};
wmmhello's avatar
wmmhello 已提交
1990

1991
    buildChildTableName(&rName);
1992 1993
    (*oneTable)->uid = rName.uid;
  }
wmmhello's avatar
wmmhello 已提交
1994

1995 1996 1997 1998 1999 2000
  SSmlSTableMeta** tableMeta = (SSmlSTableMeta**)taosHashGet(info->superTables, elements.measure, elements.measureLen);
  if(tableMeta){  // update meta
    ret = smlUpdateMeta(*tableMeta, hasTable ? NULL : (*oneTable)->tags, cols, &info->msgBuf);
    if(!ret){
      uError("SML:0x%"PRIx64" smlUpdateMeta failed", info->id);
      return TSDB_CODE_SML_INVALID_DATA;
wmmhello's avatar
wmmhello 已提交
2001
    }
2002 2003 2004 2005
  }else{
    SSmlSTableMeta *meta = smlBuildSTableMeta();
    smlInsertMeta(meta, (*oneTable)->tags, cols);
    taosHashPut(info->superTables, elements.measure, elements.measureLen, &meta, POINTER_BYTES);
wmmhello's avatar
wmmhello 已提交
2006
  }
2007 2008 2009 2010 2011

  if(!info->dataFormat){
    taosArrayClear(info->colsContainer);
  }
  taosHashClear(info->dumplicateKey);
wmmhello's avatar
wmmhello 已提交
2012 2013 2014
  return TSDB_CODE_SUCCESS;
}

2015 2016 2017 2018 2019
static int32_t smlParseTelnetLine(SSmlHandle* info, void *data) {
  int ret = TSDB_CODE_SUCCESS;
  SSmlTableInfo *tinfo = smlBuildTableInfo();
  if(!tinfo){
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
2020 2021
  }

2022 2023 2024 2025
  SArray *cols = taosArrayInit(16, POINTER_BYTES);
  if (cols == NULL) {
    uError("SML:0x%"PRIx64" smlParseTelnetLine failed to allocate memory", info->id);
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
wmmhello's avatar
wmmhello 已提交
2026 2027
  }

2028 2029 2030 2031 2032 2033 2034 2035
  if(info->protocol == TSDB_SML_TELNET_PROTOCOL){
    smlParseTelnetString(info, (const char*)data, tinfo, cols);
  }else if(info->protocol == TSDB_SML_JSON_PROTOCOL){
    smlParseJSONString(info, (cJSON *)data, tinfo, cols);
  }else{
    ASSERT(0);
  }
  if(ret != TSDB_CODE_SUCCESS){
2036
    uError("SML:0x%"PRIx64" smlParseTelnetLine failed", info->id);
2037 2038 2039
    smlDestroyTableInfo(tinfo, true);
    taosArrayDestroy(cols);
    return ret;
wmmhello's avatar
wmmhello 已提交
2040
  }
wmmhello's avatar
wmmhello 已提交
2041

2042 2043 2044
  if(taosArrayGetSize(tinfo->tags) <= 0 || taosArrayGetSize(tinfo->tags) > TSDB_MAX_TAGS){
    smlBuildInvalidDataMsg(&info->msgBuf, "invalidate tags length:[1,128]", NULL);
    return TSDB_CODE_SML_INVALID_DATA;
wmmhello's avatar
wmmhello 已提交
2045
  }
2046 2047
  taosHashClear(info->dumplicateKey);

2048
  RandTableName rName = {.tags=tinfo->tags, .sTableName=tinfo->sTableName, .sTableNameLen=(uint8_t)tinfo->sTableNameLen,
2049 2050 2051 2052 2053
                         .childTableName=tinfo->childTableName};
  buildChildTableName(&rName);
  tinfo->uid = rName.uid;

  bool hasTable = true;
2054
  SSmlTableInfo **oneTable = (SSmlTableInfo **)taosHashGet(info->childTables, tinfo->childTableName, strlen(tinfo->childTableName));
2055 2056
  if(!oneTable) {
    taosHashPut(info->childTables, tinfo->childTableName, strlen(tinfo->childTableName), &tinfo, POINTER_BYTES);
2057
    oneTable = &tinfo;
2058 2059 2060
    hasTable = false;
  }else{
    smlDestroyTableInfo(tinfo, true);
wmmhello's avatar
wmmhello 已提交
2061
  }
wmmhello's avatar
wmmhello 已提交
2062

2063
  taosArrayPush((*oneTable)->cols, &cols);
2064
  SSmlSTableMeta** tableMeta = (SSmlSTableMeta** )taosHashGet(info->superTables, (*oneTable)->sTableName, (*oneTable)->sTableNameLen);
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
  if(tableMeta){  // update meta
    ret = smlUpdateMeta(*tableMeta, hasTable ? NULL : (*oneTable)->tags, cols, &info->msgBuf);
    if(!ret){
      uError("SML:0x%"PRIx64" smlUpdateMeta failed", info->id);
      return TSDB_CODE_SML_INVALID_DATA;
    }
  }else{
    SSmlSTableMeta *meta = smlBuildSTableMeta();
    smlInsertMeta(meta, (*oneTable)->tags, cols);
    taosHashPut(info->superTables, (*oneTable)->sTableName, (*oneTable)->sTableNameLen, &meta, POINTER_BYTES);
wmmhello's avatar
wmmhello 已提交
2075 2076
  }

2077 2078
  return TSDB_CODE_SUCCESS;
}
wmmhello's avatar
wmmhello 已提交
2079

2080 2081 2082
static int32_t smlParseJSON(SSmlHandle *info, char* payload) {
  int32_t payloadNum = 0;
  int32_t ret = TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
2083

2084 2085 2086
  if (payload == NULL) {
    uError("SML:0x%"PRIx64" empty JSON Payload", info->id);
    return TSDB_CODE_TSC_INVALID_JSON;
2087
  }
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102

  cJSON *root = cJSON_Parse(payload);
  if (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_IsObject(root)) {
    payloadNum = 1;
  } else if (cJSON_IsArray(root)) {
    payloadNum = cJSON_GetArraySize(root);
  } else {
    uError("SML:0x%"PRIx64" Invalid JSON Payload", info->id);
    ret = TSDB_CODE_TSC_INVALID_JSON;
    goto end;
wmmhello's avatar
wmmhello 已提交
2103
  }
wmmhello's avatar
wmmhello 已提交
2104

2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
  for (int32_t i = 0; i < payloadNum; ++i) {
    cJSON *dataPoint = (payloadNum == 1 && cJSON_IsObject(root)) ? root : cJSON_GetArrayItem(root, i);
    ret = smlParseTelnetLine(info, dataPoint);
    if(ret != TSDB_CODE_SUCCESS){
      uError("SML:0x%"PRIx64" Invalid JSON Payload", info->id);
      goto end;
    }
  }

end:
  cJSON_Delete(root);
  return ret;
wmmhello's avatar
wmmhello 已提交
2117
}
2118 2119


wmmhello's avatar
wmmhello 已提交
2120
static int32_t smlInsertData(SSmlHandle* info) {
wmmhello's avatar
wmmhello 已提交
2121 2122
  int32_t code = TSDB_CODE_SUCCESS;

wmmhello's avatar
wmmhello 已提交
2123
  SSmlTableInfo** oneTable = (SSmlTableInfo**)taosHashIterate(info->childTables, NULL);
wmmhello's avatar
wmmhello 已提交
2124 2125 2126 2127 2128 2129 2130 2131 2132
  while (oneTable) {
    SSmlTableInfo* tableData = *oneTable;

    SName pName = {TSDB_TABLE_NAME_T, info->taos->acctId, {0}, {0}};
    strcpy(pName.dbname, info->pRequest->pDb);
    memcpy(pName.tname, tableData->childTableName, strlen(tableData->childTableName));
    SEpSet ep = getEpSet_s(&info->taos->pAppInfo->mgmtEp);
    SVgroupInfo vg;
    code = catalogGetTableHashVgroup(info->pCatalog, info->taos->pAppInfo->pTransporter, &ep, &pName, &vg);
2133
    if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
2134 2135 2136 2137 2138
      uError("SML:0x%"PRIx64" catalogGetTableHashVgroup failed. table name: %s", info->id, tableData->childTableName);
      return code;
    }
    taosHashPut(info->pVgHash, (const char*)&vg.vgId, sizeof(vg.vgId), (char*)&vg, sizeof(vg));

wmmhello's avatar
wmmhello 已提交
2139
    SSmlSTableMeta** pMeta = (SSmlSTableMeta** )taosHashGet(info->superTables, tableData->sTableName, tableData->sTableNameLen);
wmmhello's avatar
wmmhello 已提交
2140 2141
    ASSERT (NULL != pMeta && NULL != *pMeta);

2142
    // use tablemeta of stable to save vgid and uid of child table
wmmhello's avatar
wmmhello 已提交
2143 2144 2145
    (*pMeta)->tableMeta->vgId = vg.vgId;
    (*pMeta)->tableMeta->uid = tableData->uid; // one table merge data block together according uid

2146 2147
    code = smlBindData(info->exec, tableData->tags, (*pMeta)->cols, tableData->cols, info->dataFormat,
                       (*pMeta)->tableMeta, tableData->childTableName, info->msgBuf.buf, info->msgBuf.len);
wmmhello's avatar
wmmhello 已提交
2148 2149 2150
    if(code != TSDB_CODE_SUCCESS){
      return code;
    }
wmmhello's avatar
wmmhello 已提交
2151
    oneTable = (SSmlTableInfo**)taosHashIterate(info->childTables, oneTable);
wmmhello's avatar
wmmhello 已提交
2152
  }
wmmhello's avatar
wmmhello 已提交
2153

2154 2155 2156 2157 2158
  code = smlBuildOutput(info->exec, info->pVgHash);
  if (code != TSDB_CODE_SUCCESS) {
    uError("SML:0x%"PRIx64" smlBuildOutput failed", info->id);
    return code;
  }
2159 2160
  info->cost.insertRpcTime = taosGetTimestampUs();

D
dapan 已提交
2161
  launchQueryImpl(info->pRequest, info->pQuery, TSDB_CODE_SUCCESS, true, NULL);
wmmhello's avatar
wmmhello 已提交
2162 2163 2164 2165 2166

  info->affectedRows = taos_affected_rows(info->pRequest);
  return info->pRequest->code;
}

2167
static void smlPrintStatisticInfo(SSmlHandle *info){
2168
  uError("SML:0x%"PRIx64" smlInsertLines result, code:%d,lineNum:%d,stable num:%d,ctable num:%d,create stable num:%d \
wmmhello's avatar
wmmhello 已提交
2169
        parse cost:%"PRId64",schema cost:%"PRId64",bind cost:%"PRId64",rpc cost:%"PRId64",total cost:%"PRId64"", info->id, info->cost.code,
2170 2171 2172 2173 2174 2175
         info->cost.lineNum, info->cost.numOfSTables, info->cost.numOfCTables, info->cost.numOfCreateSTables,
         info->cost.schemaTime-info->cost.parseTime, info->cost.insertBindTime-info->cost.schemaTime,
         info->cost.insertRpcTime-info->cost.insertBindTime, info->cost.endTime-info->cost.insertRpcTime,
         info->cost.endTime-info->cost.parseTime);
}

2176
static int32_t smlParseLine(SSmlHandle *info, char* lines[], int numLines){
wmmhello's avatar
wmmhello 已提交
2177
  int32_t code = TSDB_CODE_SUCCESS;
2178 2179 2180 2181 2182 2183
  if (info->protocol == TSDB_SML_JSON_PROTOCOL) {
    code = smlParseJSON(info, *lines);
    if (code != TSDB_CODE_SUCCESS) {
      uError("SML:0x%" PRIx64 " smlParseJSON failed:%s", info->id, *lines);
      return code;
    }
wmmhello's avatar
wmmhello 已提交
2184
  }
wmmhello's avatar
wmmhello 已提交
2185

wmmhello's avatar
wmmhello 已提交
2186
  for (int32_t i = 0; i < numLines; ++i) {
2187 2188 2189 2190 2191 2192 2193
    if(info->protocol == TSDB_SML_LINE_PROTOCOL){
      code = smlParseInfluxLine(info, lines[i]);
    }else if(info->protocol == TSDB_SML_TELNET_PROTOCOL){
      code = smlParseTelnetLine(info, lines[i]);
    }else{
      ASSERT(0);
    }
wmmhello's avatar
wmmhello 已提交
2194
    if (code != TSDB_CODE_SUCCESS) {
2195 2196
      uError("SML:0x%" PRIx64 " smlParseLine failed. line %d : %s", info->id, i, lines[i]);
      return code;
wmmhello's avatar
wmmhello 已提交
2197 2198
    }
  }
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
  return code;
}

static int smlProcess(SSmlHandle *info, char* lines[], int numLines) {
  int32_t code = TSDB_CODE_SUCCESS;
  info->cost.parseTime = taosGetTimestampUs();

  code = smlParseLine(info, lines, numLines);
  if (code != 0) {
    uError("SML:0x%"PRIx64" smlParseLine error : %s", info->id, tstrerror(code));
    goto cleanup;
  }
wmmhello's avatar
wmmhello 已提交
2211

2212 2213 2214 2215 2216
  info->cost.lineNum = numLines;
  info->cost.numOfSTables = taosHashGetSize(info->superTables);
  info->cost.numOfCTables = taosHashGetSize(info->childTables);

  info->cost.schemaTime = taosGetTimestampUs();
wmmhello's avatar
wmmhello 已提交
2217 2218 2219 2220 2221
  code = smlModifyDBSchemas(info);
  if (code != 0) {
    uError("SML:0x%"PRIx64" smlModifyDBSchemas error : %s", info->id, tstrerror(code));
    goto cleanup;
  }
wmmhello's avatar
wmmhello 已提交
2222

2223
  info->cost.insertBindTime = taosGetTimestampUs();
wmmhello's avatar
wmmhello 已提交
2224 2225 2226
  code = smlInsertData(info);
  if (code != 0) {
    uError("SML:0x%"PRIx64" smlInsertData error : %s", info->id, tstrerror(code));
wmmhello's avatar
wmmhello 已提交
2227 2228
    goto cleanup;
  }
2229
  info->cost.endTime = taosGetTimestampUs();
wmmhello's avatar
wmmhello 已提交
2230 2231

cleanup:
2232
  info->cost.code = code;
2233
  smlPrintStatisticInfo(info);
wmmhello's avatar
wmmhello 已提交
2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257
  return code;
}

/**
 * taos_schemaless_insert() parse and insert data points into database according to
 * different protocol.
 *
 * @param $lines input array may contain multiple lines, each line indicates a data point.
 *               If protocol=2 is used input array should contain single JSON
 *               string(e.g. char *lines[] = {"$JSON_string"}). If need to insert
 *               multiple data points in JSON format, should include them in $JSON_string
 *               as a JSON array.
 * @param $numLines indicates how many data points in $lines.
 *                  If protocol = 2 is used this param will be ignored as $lines should
 *                  contain single JSON string.
 * @param $protocol indicates which protocol to use for parsing:
 *                  0 - influxDB line protocol
 *                  1 - OpenTSDB telnet line protocol
 *                  2 - OpenTSDB JSON format protocol
 * @return return zero for successful insertion. Otherwise return none-zero error code of
 *         failure reason.
 *
 */

wmmhello's avatar
wmmhello 已提交
2258
TAOS_RES* taos_schemaless_insert(TAOS* taos, char* lines[], int numLines, int protocol, int precision) {
wmmhello's avatar
wmmhello 已提交
2259
  SRequestObj* request = (SRequestObj*)createRequest((STscObj *)taos, NULL, NULL, TSDB_SQL_INSERT);
wmmhello's avatar
wmmhello 已提交
2260
  if(!request){
2261
    uError("SML:taos_schemaless_insert error request is null");
2262
    return NULL;
wmmhello's avatar
wmmhello 已提交
2263 2264
  }

wmmhello's avatar
wmmhello 已提交
2265
  SSmlHandle* info = smlBuildSmlInfo(taos, request, (SMLProtocolType)protocol, precision, true);
wmmhello's avatar
wmmhello 已提交
2266
  if(!info){
2267
    return (TAOS_RES*)request;
wmmhello's avatar
wmmhello 已提交
2268 2269
  }

2270 2271 2272 2273 2274 2275 2276 2277 2278 2279
  if (numLines <= 0 || numLines > 65536) {
    request->code = TSDB_CODE_SML_INVALID_DATA;
    smlBuildInvalidDataMsg(&info->msgBuf, "numLines should be between 1 and 65536", NULL);
    goto end;
  }

  if(protocol < TSDB_SML_LINE_PROTOCOL || protocol > TSDB_SML_JSON_PROTOCOL){
    request->code = TSDB_CODE_SML_INVALID_PROTOCOL_TYPE;
    smlBuildInvalidDataMsg(&info->msgBuf, "protocol invalidate", NULL);
    goto end;
wmmhello's avatar
wmmhello 已提交
2280 2281
  }

2282 2283 2284 2285 2286 2287 2288 2289 2290 2291
  if(protocol == TSDB_SML_LINE_PROTOCOL && (precision < TSDB_SML_TIMESTAMP_HOURS || precision > TSDB_SML_TIMESTAMP_NANO_SECONDS)){
    request->code = TSDB_CODE_SML_INVALID_PRECISION_TYPE;
    smlBuildInvalidDataMsg(&info->msgBuf, "precision invalidate for line protocol", NULL);
    goto end;
  }

  info->pRequest->code = smlProcess(info, lines, numLines);

end:
  smlDestroyInfo(info);
wmmhello's avatar
wmmhello 已提交
2292
  return (TAOS_RES*)request;
wmmhello's avatar
wmmhello 已提交
2293
}
2294