tscParseLineProtocol.c 53.1 KB
Newer Older
S
shenglian zhou 已提交
1 2 3 4
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
5

S
shenglian zhou 已提交
6 7 8 9 10 11 12 13
#include "os.h"
#include "osString.h"
#include "ttype.h"
#include "tmd5.h"
#include "tstrbuild.h"
#include "tname.h"
#include "hash.h"
#include "tskiplist.h"
14

S
shenglian zhou 已提交
15
#include "tscUtil.h"
16 17
#include "tsclient.h"
#include "tscLog.h"
S
shenglian zhou 已提交
18

19
#include "taos.h"
20

S
shenglian zhou 已提交
21 22 23 24 25 26
typedef struct  {
  char sTableName[TSDB_TABLE_NAME_LEN];
  SHashObj* tagHash;
  SHashObj* fieldHash;
  SArray* tags; //SArray<SSchema>
  SArray* fields; //SArray<SSchema>
S
shenglian zhou 已提交
27
  uint8_t precision;
S
shenglian zhou 已提交
28 29
} SSmlSTableSchema;

S
shenglian zhou 已提交
30 31 32 33 34
typedef struct {
  char* key;
  uint8_t type;
  int16_t length;
  char* value;
35 36

  //===================================
37
  size_t fieldSchemaIdx;
S
shenglian zhou 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50
} TAOS_SML_KV;

typedef struct {
  char* stableName;

  char* childTableName;
  TAOS_SML_KV* tags;
  int tagNum;

  // first kv must be timestamp
  TAOS_SML_KV* fields;
  int fieldNum;

S
shenglian zhou 已提交
51
  //================================
52
  size_t schemaIdx;
S
shenglian zhou 已提交
53 54
} TAOS_SML_DATA_POINT;

55 56 57 58 59 60 61 62
typedef enum {
  SML_TIME_STAMP_NOW,
  SML_TIME_STAMP_SECONDS,
  SML_TIME_STAMP_MILLI_SECONDS,
  SML_TIME_STAMP_MICRO_SECONDS,
  SML_TIME_STAMP_NANO_SECONDS
} SMLTimeStampType;

63 64
//=================================================================================================

S
shenglian zhou 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
int compareSmlColKv(const void* p1, const void* p2) {
  TAOS_SML_KV* kv1 = (TAOS_SML_KV*)p1;
  TAOS_SML_KV* kv2 = (TAOS_SML_KV*)p2;
  int kvLen1 = (int)strlen(kv1->key);
  int kvLen2 = (int)strlen(kv2->key);
  int res = strncasecmp(kv1->key, kv2->key, MIN(kvLen1, kvLen2));
  if (res != 0) {
    return res;
  } else {
    return kvLen1-kvLen2;
  }
}

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];
  SArray* tags; //SArray<SSchema>
  SArray* fields; //SArray<SSchema>
} SCreateSTableActionInfo;

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

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

S
shenglian zhou 已提交
105
static int32_t getFieldBytesFromSmlKv(TAOS_SML_KV* kv, int32_t* bytes) {
S
shenglian zhou 已提交
106 107 108 109 110 111
  if (!IS_VAR_DATA_TYPE(kv->type)) {
    *bytes = tDataTypes[kv->type].bytes;
  } else {
    if (kv->type == TSDB_DATA_TYPE_NCHAR) {
      char* ucs = malloc(kv->length * TSDB_NCHAR_SIZE + 1);
      int32_t bytesNeeded = 0;
S
Shenglian Zhou 已提交
112 113 114 115 116 117
      bool succ = taosMbsToUcs4(kv->value, kv->length, ucs, kv->length * TSDB_NCHAR_SIZE, &bytesNeeded);
      if (!succ) {
        free(ucs);
        tscError("convert nchar string to UCS4_LE failed:%s", kv->value);
        return TSDB_CODE_TSC_INVALID_VALUE;
      }
S
shenglian zhou 已提交
118 119 120 121 122 123 124 125 126
      free(ucs);
      *bytes =  bytesNeeded + VARSTR_HEADER_SIZE;
    } else if (kv->type == TSDB_DATA_TYPE_BINARY) {
      *bytes = kv->length + VARSTR_HEADER_SIZE;
    }
  }
  return 0;
}

S
shenglian zhou 已提交
127
static int32_t buildSmlKvSchema(TAOS_SML_KV* smlKv, SHashObj* hash, SArray* array) {
S
shenglian zhou 已提交
128
  SSchema* pField = NULL;
129 130
  size_t* pFieldIdx = taosHashGet(hash, smlKv->key, strlen(smlKv->key));
  size_t fieldIdx = -1;
S
Shenglian Zhou 已提交
131
  int32_t code = 0;
132 133 134
  if (pFieldIdx) {
    fieldIdx = *pFieldIdx;
    pField = taosArrayGet(array, fieldIdx);
S
shenglian zhou 已提交
135 136

    if (pField->type != smlKv->type) {
S
Shenglian Zhou 已提交
137 138
      tscError("type mismatch. key %s, type %d. type before %d", smlKv->key, smlKv->type, pField->type);
      return TSDB_CODE_TSC_INVALID_VALUE;
S
shenglian zhou 已提交
139 140 141
    }

    int32_t bytes = 0;
S
Shenglian Zhou 已提交
142 143 144 145
    code = getFieldBytesFromSmlKv(smlKv, &bytes);
    if (code != 0) {
      return code;
    }
S
shenglian zhou 已提交
146 147 148
    pField->bytes = MAX(pField->bytes, bytes);

  } else {
S
shenglian zhou 已提交
149
    SSchema field = {0};
S
shenglian zhou 已提交
150 151 152 153 154 155
    size_t tagKeyLen = strlen(smlKv->key);
    strncpy(field.name, smlKv->key, tagKeyLen);
    field.name[tagKeyLen] = '\0';
    field.type = smlKv->type;

    int32_t bytes = 0;
S
Shenglian Zhou 已提交
156 157 158 159
    code = getFieldBytesFromSmlKv(smlKv, &bytes);
    if (code != 0) {
      return code;
    }
S
shenglian zhou 已提交
160 161 162
    field.bytes = bytes;

    pField = taosArrayPush(array, &field);
163 164
    fieldIdx = taosArrayGetSize(array) - 1;
    taosHashPut(hash, field.name, tagKeyLen, &fieldIdx, sizeof(fieldIdx));
S
shenglian zhou 已提交
165
  }
166

167
  smlKv->fieldSchemaIdx = fieldIdx;
168

S
shenglian zhou 已提交
169 170 171
  return 0;
}

S
shenglian zhou 已提交
172
static int32_t buildDataPointSchemas(TAOS_SML_DATA_POINT* points, int numPoint, SArray* stableSchemas) {
S
Shenglian Zhou 已提交
173
  int32_t code = 0;
S
shenglian zhou 已提交
174 175 176 177 178 179
  SHashObj* sname2shema = taosHashInit(32,
                                       taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, false);

  for (int i = 0; i < numPoint; ++i) {
    TAOS_SML_DATA_POINT* point = &points[i];
    size_t stableNameLen = strlen(point->stableName);
180
    size_t* pStableIdx = taosHashGet(sname2shema, point->stableName, stableNameLen);
S
shenglian zhou 已提交
181
    SSmlSTableSchema* pStableSchema = NULL;
182 183 184 185
    size_t stableIdx = -1;
    if (pStableIdx) {
      pStableSchema= taosArrayGet(stableSchemas, *pStableIdx);
      stableIdx = *pStableIdx;
S
shenglian zhou 已提交
186 187 188 189 190 191 192 193 194 195
    } else {
      SSmlSTableSchema schema;
      strncpy(schema.sTableName, point->stableName, stableNameLen);
      schema.sTableName[stableNameLen] = '\0';
      schema.fields = taosArrayInit(64, sizeof(SSchema));
      schema.tags = taosArrayInit(8, sizeof(SSchema));
      schema.tagHash = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, false);
      schema.fieldHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, false);

      pStableSchema = taosArrayPush(stableSchemas, &schema);
196 197
      stableIdx = taosArrayGetSize(stableSchemas) - 1;
      taosHashPut(sname2shema, schema.sTableName, stableNameLen, &stableIdx, sizeof(size_t));
S
shenglian zhou 已提交
198 199 200 201
    }

    for (int j = 0; j < point->tagNum; ++j) {
      TAOS_SML_KV* tagKv = point->tags + j;
S
Shenglian Zhou 已提交
202 203 204 205 206
      code = buildSmlKvSchema(tagKv, pStableSchema->tagHash, pStableSchema->tags);
      if (code != 0) {
        tscError("build data point schema failed. point no.: %d, tag key: %s", i, tagKv->key);
        return code;
      }
S
shenglian zhou 已提交
207 208 209 210
    }

    for (int j = 0; j < point->fieldNum; ++j) {
      TAOS_SML_KV* fieldKv = point->fields + j;
S
Shenglian Zhou 已提交
211 212 213 214 215
      code = buildSmlKvSchema(fieldKv, pStableSchema->fieldHash, pStableSchema->fields);
      if (code != 0) {
        tscError("build data point schema failed. point no.: %d, tag key: %s", i, fieldKv->key);
        return code;
      }
S
shenglian zhou 已提交
216 217
    }

218
    point->schemaIdx = stableIdx;
S
shenglian zhou 已提交
219 220 221 222 223 224 225 226 227 228
  }

  size_t numStables = taosArrayGetSize(stableSchemas);
  for (int32_t i = 0; i < numStables; ++i) {
    SSmlSTableSchema* schema = taosArrayGet(stableSchemas, i);
    taosHashCleanup(schema->tagHash);
    taosHashCleanup(schema->fieldHash);
  }
  taosHashCleanup(sname2shema);

S
Shenglian Zhou 已提交
229 230 231 232 233 234 235
  tscDebug("build point schema succeed. num of super table: %zu", numStables);
  for (int32_t i = 0; i < numStables; ++i) {
    SSmlSTableSchema* schema = taosArrayGet(stableSchemas, i);
    tscDebug("\ttable name: %s, tags number: %zu, fields number: %zu", schema->sTableName,
             taosArrayGetSize(schema->tags), taosArrayGetSize(schema->fields));
  }

S
shenglian zhou 已提交
236 237 238
  return 0;
}

239
static int32_t generateSchemaAction(SSchema* pointColField, SHashObj* dbAttrHash, SArray* dbAttrArray, bool isTag, char sTableName[],
S
shenglian zhou 已提交
240
                                       SSchemaAction* action, bool* actionNeeded) {
241 242 243 244
  size_t* pDbIndex = taosHashGet(dbAttrHash, pointColField->name, strlen(pointColField->name));
  if (pDbIndex) {
    SSchema* dbAttr = taosArrayGet(dbAttrArray, *pDbIndex);
    assert(strcasecmp(dbAttr->name, pointColField->name) == 0);
S
shenglian zhou 已提交
245
    if (pointColField->type != dbAttr->type) {
S
Shenglian Zhou 已提交
246 247 248
      tscError("point type and db type mismatch. key: %s. point type: %d, db type: %d", pointColField->name,
               pointColField->type, dbAttr->type);
      return TSDB_CODE_TSC_INVALID_VALUE;
S
shenglian zhou 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
    }

    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;
  }
S
Shenglian Zhou 已提交
273
  tscDebug("generate schema action. action needed: %d, action: %d", *actionNeeded, action->action);
S
shenglian zhou 已提交
274 275 276
  return 0;
}

S
shenglian zhou 已提交
277
static int32_t buildColumnDescription(SSchema* field,
S
shenglian zhou 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
                               char* buf, int32_t bufSize, int32_t* outBytes) {
  uint8_t type = field->type;

  if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
    int32_t bytes = field->bytes - VARSTR_HEADER_SIZE;
    if (type == TSDB_DATA_TYPE_NCHAR) {
      bytes =  bytes/TSDB_NCHAR_SIZE;
    }
    int out = snprintf(buf, bufSize,"%s %s(%d)",
                       field->name,tDataTypes[field->type].name, bytes);
    *outBytes = out;
  } else {
    int out = snprintf(buf, bufSize, "%s %s",
                       field->name, tDataTypes[type].name);
    *outBytes = out;
  }

  return 0;
}

S
shenglian zhou 已提交
298 299

static int32_t applySchemaAction(TAOS* taos, SSchemaAction* action) {
S
shenglian zhou 已提交
300 301
  int32_t code = 0;
  int32_t outBytes = 0;
302 303
  char *result = (char *)calloc(1, tsMaxSQLStringLen+1);
  int32_t capacity = tsMaxSQLStringLen +  1;
S
shenglian zhou 已提交
304

S
Shenglian Zhou 已提交
305
  tscDebug("apply schema action: %d", action->action);
S
shenglian zhou 已提交
306 307 308 309 310 311
  switch (action->action) {
    case SCHEMA_ACTION_ADD_COLUMN: {
      int n = sprintf(result, "alter stable %s add column ", action->alterSTable.sTableName);
      buildColumnDescription(action->alterSTable.field, result+n, capacity-n, &outBytes);
      TAOS_RES* res = taos_query(taos, result); //TODO async doAsyncQuery
      code = taos_errno(res);
S
Shenglian Zhou 已提交
312
      taos_free_result(res);
S
shenglian zhou 已提交
313 314 315 316 317 318 319 320
      break;
    }
    case SCHEMA_ACTION_ADD_TAG: {
      int n = sprintf(result, "alter stable %s add tag ", action->alterSTable.sTableName);
      buildColumnDescription(action->alterSTable.field,
                             result+n, capacity-n, &outBytes);
      TAOS_RES* res = taos_query(taos, result); //TODO async doAsyncQuery
      code = taos_errno(res);
S
Shenglian Zhou 已提交
321
      taos_free_result(res);
S
shenglian zhou 已提交
322 323 324 325 326 327 328 329
      break;
    }
    case SCHEMA_ACTION_CHANGE_COLUMN_SIZE: {
      int n = sprintf(result, "alter stable %s modify column ", action->alterSTable.sTableName);
      buildColumnDescription(action->alterSTable.field, result+n,
                             capacity-n, &outBytes);
      TAOS_RES* res = taos_query(taos, result); //TODO async doAsyncQuery
      code = taos_errno(res);
S
Shenglian Zhou 已提交
330
      taos_free_result(res);
331
      break;
S
shenglian zhou 已提交
332 333 334 335 336 337 338
    }
    case SCHEMA_ACTION_CHANGE_TAG_SIZE: {
      int n = sprintf(result, "alter stable %s modify tag ", action->alterSTable.sTableName);
      buildColumnDescription(action->alterSTable.field, result+n,
                             capacity-n, &outBytes);
      TAOS_RES* res = taos_query(taos, result); //TODO async doAsyncQuery
      code = taos_errno(res);
S
Shenglian Zhou 已提交
339
      taos_free_result(res);
S
shenglian zhou 已提交
340 341 342 343 344
      break;
    }
    case SCHEMA_ACTION_CREATE_STABLE: {
      int n = sprintf(result, "create stable %s (", action->createSTable.sTableName);
      char* pos = result + n; int freeBytes = capacity - n;
S
shenglian zhou 已提交
345
      size_t numCols = taosArrayGetSize(action->createSTable.fields);
S
shenglian zhou 已提交
346 347 348 349 350 351 352
      for (int32_t i = 0; i < numCols; ++i) {
        SSchema* field = taosArrayGet(action->createSTable.fields, i);
        buildColumnDescription(field, pos, freeBytes, &outBytes);
        pos += outBytes; freeBytes -= outBytes;
        *pos = ','; ++pos; --freeBytes;
      }
      --pos; ++freeBytes;
353

S
shenglian zhou 已提交
354 355
      outBytes = snprintf(pos, freeBytes, ") tags (");
      pos += outBytes; freeBytes -= outBytes;
356

S
shenglian zhou 已提交
357
      size_t numTags = taosArrayGetSize(action->createSTable.tags);
S
shenglian zhou 已提交
358 359 360 361 362 363 364 365 366 367
      for (int32_t i = 0; i < numTags; ++i) {
        SSchema* field = taosArrayGet(action->createSTable.tags, i);
        buildColumnDescription(field, pos, freeBytes, &outBytes);
        pos += outBytes; freeBytes -= outBytes;
        *pos = ','; ++pos; --freeBytes;
      }
      pos--; ++freeBytes;
      outBytes = snprintf(pos, freeBytes, ")");
      TAOS_RES* res = taos_query(taos, result);
      code = taos_errno(res);
S
Shenglian Zhou 已提交
368
      taos_free_result(res);
S
shenglian zhou 已提交
369 370
      break;
    }
S
shenglian zhou 已提交
371

S
shenglian zhou 已提交
372 373 374
    default:
      break;
  }
S
Shenglian Zhou 已提交
375

S
shenglian zhou 已提交
376
  free(result);
S
Shenglian Zhou 已提交
377 378 379
  if (code != 0) {
    tscError("apply schema action failure. %s", tstrerror(code));
  }
S
shenglian zhou 已提交
380 381 382
  return code;
}

383
static int32_t destroySmlSTableSchema(SSmlSTableSchema* schema) {
S
shenglian zhou 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
  taosHashCleanup(schema->tagHash);
  taosHashCleanup(schema->fieldHash);
  taosArrayDestroy(schema->tags);
  taosArrayDestroy(schema->fields);
  return 0;
}

int32_t loadTableMeta(TAOS* taos, char* tableName, SSmlSTableSchema* schema) {
  int32_t code = 0;

  STscObj *pObj = (STscObj *)taos;
  if (pObj == NULL || pObj->signature != pObj) {
    terrno = TSDB_CODE_TSC_DISCONNECTED;
    return TSDB_CODE_TSC_DISCONNECTED;
  }

S
Shenglian Zhou 已提交
400 401
  tscDebug("load table schema. super table name: %s", tableName);

S
shenglian zhou 已提交
402 403 404 405 406
  char sql[256];
  snprintf(sql, 256, "describe %s", tableName);
  TAOS_RES* res = taos_query(taos, sql);
  code = taos_errno(res);
  if (code != 0) {
S
Shenglian Zhou 已提交
407
    tscError("describe table failure. %s", taos_errstr(res));
S
shenglian zhou 已提交
408 409 410 411 412 413 414 415 416 417
    taos_free_result(res);
    return code;
  }
  taos_free_result(res);

  SSqlObj* pSql = calloc(1, sizeof(SSqlObj));
  pSql->pTscObj = taos;
  pSql->signature = pSql;
  pSql->fp = NULL;

S
shenglian zhou 已提交
418
  SStrToken tableToken = {.z=tableName, .n=(uint32_t)strlen(tableName), .type=TK_ID};
S
shenglian zhou 已提交
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
  tGetToken(tableName, &tableToken.type);
  // Check if the table name available or not
  if (tscValidateName(&tableToken) != TSDB_CODE_SUCCESS) {
    code = TSDB_CODE_TSC_INVALID_TABLE_ID_LENGTH;
    sprintf(pSql->cmd.payload, "table name is invalid");
    return code;
  }

  SName sname = {0};
  if ((code = tscSetTableFullName(&sname, &tableToken, pSql)) != TSDB_CODE_SUCCESS) {
    return code;
  }
  char  fullTableName[TSDB_TABLE_FNAME_LEN] = {0};
  memset(fullTableName, 0, tListLen(fullTableName));
  tNameExtractFullName(&sname, fullTableName);
  if (code != TSDB_CODE_SUCCESS) {
    tscFreeSqlObj(pSql);
    return code;
  }
  tscFreeSqlObj(pSql);

  schema->tags = taosArrayInit(8, sizeof(SSchema));
  schema->fields = taosArrayInit(64, sizeof(SSchema));
  schema->tagHash = taosHashInit(8, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, false);
  schema->fieldHash = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, false);

  uint32_t size = tscGetTableMetaMaxSize();
  STableMeta* tableMeta = calloc(1, size);
  taosHashGetClone(tscTableMetaInfo, fullTableName, strlen(fullTableName), NULL, tableMeta, -1);

  tstrncpy(schema->sTableName, tableName, strlen(tableName)+1);
  schema->precision = tableMeta->tableInfo.precision;
  for (int i=0; i<tableMeta->tableInfo.numOfColumns; ++i) {
    SSchema field;
    tstrncpy(field.name, tableMeta->schema[i].name, strlen(tableMeta->schema[i].name)+1);
    field.type = tableMeta->schema[i].type;
    field.bytes = tableMeta->schema[i].bytes;
456 457 458
    taosArrayPush(schema->fields, &field);
    size_t fieldIndex = taosArrayGetSize(schema->fields) - 1;
    taosHashPut(schema->fieldHash, field.name, strlen(field.name), &fieldIndex, sizeof(fieldIndex));
S
shenglian zhou 已提交
459 460 461 462 463 464 465 466
  }

  for (int i=0; i<tableMeta->tableInfo.numOfTags; ++i) {
    int j = i + tableMeta->tableInfo.numOfColumns;
    SSchema field;
    tstrncpy(field.name, tableMeta->schema[j].name, strlen(tableMeta->schema[j].name)+1);
    field.type = tableMeta->schema[j].type;
    field.bytes = tableMeta->schema[j].bytes;
467 468 469
    taosArrayPush(schema->tags, &field);
    size_t tagIndex = taosArrayGetSize(schema->tags) - 1;
    taosHashPut(schema->tagHash, field.name, strlen(field.name), &tagIndex, sizeof(tagIndex));
S
shenglian zhou 已提交
470
  }
S
Shenglian Zhou 已提交
471 472
  tscDebug("load table meta succeed. %s, columns number: %d, tag number: %d, precision: %d",
           tableName, tableMeta->tableInfo.numOfColumns, tableMeta->tableInfo.numOfTags, schema->precision);
S
shenglian zhou 已提交
473 474 475 476 477 478 479 480 481
  free(tableMeta); tableMeta = NULL;
  return code;
}

static int32_t reconcileDBSchemas(TAOS* taos, SArray* stableSchemas) {
  int32_t code = 0;
  size_t numStable = taosArrayGetSize(stableSchemas);
  for (int i = 0; i < numStable; ++i) {
    SSmlSTableSchema* pointSchema = taosArrayGet(stableSchemas, i);
S
shenglian zhou 已提交
482 483
    SSmlSTableSchema  dbSchema;
    memset(&dbSchema, 0, sizeof(SSmlSTableSchema));
S
shenglian zhou 已提交
484 485 486 487 488 489 490 491 492 493 494

    code = loadTableMeta(taos, pointSchema->sTableName, &dbSchema);
    if (code == TSDB_CODE_MND_INVALID_TABLE_NAME) {
      SSchemaAction schemaAction = {0};
      schemaAction.action = SCHEMA_ACTION_CREATE_STABLE;
      memset(&schemaAction.createSTable, 0, sizeof(SCreateSTableActionInfo));
      memcpy(schemaAction.createSTable.sTableName, pointSchema->sTableName, TSDB_TABLE_NAME_LEN);
      schemaAction.createSTable.tags = pointSchema->tags;
      schemaAction.createSTable.fields = pointSchema->fields;
      applySchemaAction(taos, &schemaAction);
      code = loadTableMeta(taos, pointSchema->sTableName, &dbSchema);
S
Shenglian Zhou 已提交
495 496
      if (code != 0) {
        tscError("reconcile point schema failed. can not create %s", pointSchema->sTableName);
497
        return code;
S
Shenglian Zhou 已提交
498 499 500 501
      } else {
        pointSchema->precision = dbSchema.precision;
        destroySmlSTableSchema(&dbSchema);
      }
S
shenglian zhou 已提交
502 503 504 505 506 507 508 509 510 511 512
    } else if (code == TSDB_CODE_SUCCESS) {
      size_t pointTagSize = taosArrayGetSize(pointSchema->tags);
      size_t pointFieldSize = taosArrayGetSize(pointSchema->fields);

      SHashObj* dbTagHash = dbSchema.tagHash;
      SHashObj* dbFieldHash = dbSchema.fieldHash;

      for (int j = 0; j < pointTagSize; ++j) {
        SSchema* pointTag = taosArrayGet(pointSchema->tags, j);
        SSchemaAction schemaAction = {0};
        bool actionNeeded = false;
513
        generateSchemaAction(pointTag, dbTagHash, dbSchema.tags, true, pointSchema->sTableName, &schemaAction, &actionNeeded);
S
shenglian zhou 已提交
514 515 516 517 518 519 520 521 522 523 524 525 526
        if (actionNeeded) {
          applySchemaAction(taos, &schemaAction);
        }
      }

      SSchema* pointColTs = taosArrayGet(pointSchema->fields, 0);
      SSchema* dbColTs = taosArrayGet(dbSchema.fields, 0);
      memcpy(pointColTs->name, dbColTs->name, TSDB_COL_NAME_LEN);

      for (int j = 1; j < pointFieldSize; ++j) {
        SSchema* pointCol = taosArrayGet(pointSchema->fields, j);
        SSchemaAction schemaAction = {0};
        bool actionNeeded = false;
527
        generateSchemaAction(pointCol, dbFieldHash, dbSchema.fields,false, pointSchema->sTableName, &schemaAction, &actionNeeded);
S
shenglian zhou 已提交
528 529 530 531 532 533 534
        if (actionNeeded) {
          applySchemaAction(taos, &schemaAction);
        }
      }

      pointSchema->precision = dbSchema.precision;

535
      destroySmlSTableSchema(&dbSchema);
S
shenglian zhou 已提交
536
    } else {
S
Shenglian Zhou 已提交
537
      tscError("load table meta error: %s", tstrerror(code));
S
shenglian zhou 已提交
538 539 540 541 542 543
      return code;
    }
  }
  return 0;
}

544 545
static int32_t getSmlMd5ChildTableName(TAOS_SML_DATA_POINT* point, char* tableName, int* tableNameLen) {
  tscDebug("taos_sml_insert get child table name through md5");
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
  qsort(point->tags, point->tagNum, sizeof(TAOS_SML_KV), compareSmlColKv);

  SStringBuilder sb; memset(&sb, 0, sizeof(sb));
  taosStringBuilderAppendString(&sb, point->stableName);
  for (int j = 0; j < point->tagNum; ++j) {
    taosStringBuilderAppendChar(&sb, ',');
    TAOS_SML_KV* tagKv = point->tags + j;
    taosStringBuilderAppendString(&sb, tagKv->key);
    taosStringBuilderAppendChar(&sb, '=');
    taosStringBuilderAppend(&sb, tagKv->value, tagKv->length);
  }
  size_t len = 0;
  char* keyJoined = taosStringBuilderGetResult(&sb, &len);
  MD5_CTX context;
  MD5Init(&context);
  MD5Update(&context, (uint8_t *)keyJoined, (uint32_t)len);
  MD5Final(&context);
  *tableNameLen = snprintf(tableName, *tableNameLen,
S
Shenglian Zhou 已提交
564
                           "t_%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", context.digest[0],
565 566 567 568
                           context.digest[1], context.digest[2], context.digest[3], context.digest[4], context.digest[5], context.digest[6],
                           context.digest[7], context.digest[8], context.digest[9], context.digest[10], context.digest[11],
                           context.digest[12], context.digest[13], context.digest[14], context.digest[15]);
  taosStringBuilderDestroy(&sb);
S
Shenglian Zhou 已提交
569
  tscDebug("child table name: %s", tableName);
570 571 572
  return 0;
}

S
shenglian zhou 已提交
573
static int32_t creatChildTableIfNotExists(TAOS* taos, const char* cTableName, const char* sTableName, SArray* tagsSchema, SArray* tagsBind) {
S
shenglian zhou 已提交
574
  size_t numTags = taosArrayGetSize(tagsSchema);
575 576
  char* sql = malloc(tsMaxSQLStringLen+1);
  int freeBytes = tsMaxSQLStringLen + 1;
S
shenglian zhou 已提交
577
  sprintf(sql, "create table if not exists %s using %s", cTableName, sTableName);
578

S
shenglian zhou 已提交
579 580 581 582 583 584
  snprintf(sql+strlen(sql), freeBytes-strlen(sql), "(");
  for (int i = 0; i < numTags; ++i) {
    SSchema* tagSchema = taosArrayGet(tagsSchema, i);
    snprintf(sql+strlen(sql), freeBytes-strlen(sql), "%s,", tagSchema->name);
  }
  snprintf(sql + strlen(sql) - 1, freeBytes-strlen(sql)+1, ")");
585

S
shenglian zhou 已提交
586
  snprintf(sql + strlen(sql), freeBytes-strlen(sql), " tags (");
587

S
shenglian zhou 已提交
588
  for (int i = 0; i < numTags; ++i) {
S
shenglian zhou 已提交
589
    snprintf(sql+strlen(sql), freeBytes-strlen(sql), "?,");
S
shenglian zhou 已提交
590
  }
S
shenglian zhou 已提交
591
  snprintf(sql + strlen(sql) - 1, freeBytes-strlen(sql)+1, ")");
592
  sql[strlen(sql)] = '\0';
S
shenglian zhou 已提交
593

S
Shenglian Zhou 已提交
594 595
  tscDebug("create table : %s", sql);

S
shenglian zhou 已提交
596 597
  TAOS_STMT* stmt = taos_stmt_init(taos);
  int32_t code;
S
shenglian zhou 已提交
598
  code = taos_stmt_prepare(stmt, sql, (unsigned long)strlen(sql));
599 600
  free(sql);

S
shenglian zhou 已提交
601
  if (code != 0) {
S
Shenglian Zhou 已提交
602
    tscError("%s", taos_stmt_errstr(stmt));
S
shenglian zhou 已提交
603 604 605 606 607
    return code;
  }

  code = taos_stmt_bind_param(stmt, TARRAY_GET_START(tagsBind));
  if (code != 0) {
S
Shenglian Zhou 已提交
608
    tscError("%s", taos_stmt_errstr(stmt));
S
shenglian zhou 已提交
609 610 611 612 613
    return code;
  }

  code = taos_stmt_execute(stmt);
  if (code != 0) {
S
Shenglian Zhou 已提交
614
    tscError("%s", taos_stmt_errstr(stmt));
S
shenglian zhou 已提交
615 616
    return code;
  }
S
shenglian zhou 已提交
617

618 619 620 621 622 623
  code = taos_stmt_close(stmt);
  if (code != 0) {
    tscError("%s", taos_stmt_errstr(stmt));
    return code;
  }
  return code;
S
shenglian zhou 已提交
624 625
}

S
shenglian zhou 已提交
626
static int32_t insertChildTableBatch(TAOS* taos,  char* cTableName, SArray* colsSchema, SArray* rowsBind) {
S
shenglian zhou 已提交
627
  size_t numCols = taosArrayGetSize(colsSchema);
628 629
  char* sql = malloc(tsMaxSQLStringLen+1);
  int32_t freeBytes = tsMaxSQLStringLen + 1 ;
S
shenglian zhou 已提交
630
  sprintf(sql, "insert into ? (");
631

S
shenglian zhou 已提交
632 633
  for (int i = 0; i < numCols; ++i) {
    SSchema* colSchema = taosArrayGet(colsSchema, i);
S
shenglian zhou 已提交
634
    snprintf(sql+strlen(sql), freeBytes-strlen(sql), "%s,", colSchema->name);
S
shenglian zhou 已提交
635
  }
S
shenglian zhou 已提交
636
  snprintf(sql + strlen(sql)-1, freeBytes-strlen(sql)+1, ") values (");
637

S
shenglian zhou 已提交
638
  for (int i = 0; i < numCols; ++i) {
S
shenglian zhou 已提交
639
    snprintf(sql+strlen(sql), freeBytes-strlen(sql), "?,");
640
  }
S
shenglian zhou 已提交
641
  snprintf(sql + strlen(sql)-1, freeBytes-strlen(sql)+1, ")");
642
  sql[strlen(sql)] = '\0';
643

S
Shenglian Zhou 已提交
644
  tscDebug("insert rows %zu into child table %s. ", taosArrayGetSize(rowsBind), cTableName);
W
wpan 已提交
645

646 647
  int32_t code = 0;
  int32_t try = 0;
S
shenglian zhou 已提交
648

W
wpan 已提交
649
  TAOS_STMT* stmt = taos_stmt_init(taos);
650

S
shenglian zhou 已提交
651
  code = taos_stmt_prepare(stmt, sql, (unsigned long)strlen(sql));
652 653
  free(sql);

W
wpan 已提交
654
  if (code != 0) {
S
Shenglian Zhou 已提交
655
    tscError("%s", taos_stmt_errstr(stmt));
W
wpan 已提交
656 657 658 659
    return code;
  }

  do {
660 661

    code = taos_stmt_set_tbname(stmt, cTableName);
662
    if (code != 0) {
S
Shenglian Zhou 已提交
663
      tscError("%s", taos_stmt_errstr(stmt));
664 665
      return code;
    }
666

667 668 669 670 671
    size_t rows = taosArrayGetSize(rowsBind);
    for (int32_t i = 0; i < rows; ++i) {
      TAOS_BIND* colsBinds = taosArrayGetP(rowsBind, i);
      code = taos_stmt_bind_param(stmt, colsBinds);
      if (code != 0) {
S
Shenglian Zhou 已提交
672
        tscError("%s", taos_stmt_errstr(stmt));
673 674 675 676
        return code;
      }
      code = taos_stmt_add_batch(stmt);
      if (code != 0) {
S
Shenglian Zhou 已提交
677
        tscError("%s", taos_stmt_errstr(stmt));
678 679 680 681 682 683
        return code;
      }
    }

    code = taos_stmt_execute(stmt);
    if (code != 0) {
S
Shenglian Zhou 已提交
684
      tscError("%s", taos_stmt_errstr(stmt));
685 686
    }
  } while (code == TSDB_CODE_TDB_TABLE_RECONFIGURE && try++ < TSDB_MAX_REPLICA);
S
shenglian zhou 已提交
687

W
wpan 已提交
688
  if (code != 0) {
S
Shenglian Zhou 已提交
689
    tscError("%s", taos_stmt_errstr(stmt));
W
wpan 已提交
690 691 692 693 694
    taos_stmt_close(stmt);
  } else {
    taos_stmt_close(stmt);
  }

S
shenglian zhou 已提交
695
  return code;
S
shenglian zhou 已提交
696 697
}

698 699
static int32_t arrangePointsByChildTableName(TAOS_SML_DATA_POINT* points, int numPoints,
                                             SHashObj* cname2points, SArray* stableSchemas) {
S
shenglian zhou 已提交
700 701 702 703
  for (int32_t i = 0; i < numPoints; ++i) {
    TAOS_SML_DATA_POINT * point = points + i;
    if (!point->childTableName) {
      char childTableName[TSDB_TABLE_NAME_LEN];
704
      int32_t tableNameLen = TSDB_TABLE_NAME_LEN;
705
      getSmlMd5ChildTableName(point, childTableName, &tableNameLen);
S
shenglian zhou 已提交
706 707 708 709
      point->childTableName = calloc(1, tableNameLen+1);
      strncpy(point->childTableName, childTableName, tableNameLen);
      point->childTableName[tableNameLen] = '\0';
    }
S
shenglian zhou 已提交
710

711 712
    SSmlSTableSchema* stableSchema = taosArrayGet(stableSchemas, point->schemaIdx);

S
shenglian zhou 已提交
713 714 715 716
    for (int j = 0; j < point->tagNum; ++j) {
      TAOS_SML_KV* kv =  point->tags + j;
      if (kv->type == TSDB_DATA_TYPE_TIMESTAMP) {
        int64_t ts = *(int64_t*)(kv->value);
717
        ts = convertTimePrecision(ts, TSDB_TIME_PRECISION_NANO, stableSchema->precision);
S
shenglian zhou 已提交
718 719 720 721 722 723 724 725
        *(int64_t*)(kv->value) = ts;
      }
    }

    for (int j = 0; j < point->fieldNum; ++j) {
      TAOS_SML_KV* kv =  point->fields + j;
      if (kv->type == TSDB_DATA_TYPE_TIMESTAMP) {
        int64_t ts = *(int64_t*)(kv->value);
726
        ts = convertTimePrecision(ts, TSDB_TIME_PRECISION_NANO, stableSchema->precision);
S
shenglian zhou 已提交
727 728 729 730
        *(int64_t*)(kv->value) = ts;
      }
    }

S
shenglian zhou 已提交
731 732 733 734 735 736 737 738
    SArray* cTablePoints = NULL;
    SArray** pCTablePoints = taosHashGet(cname2points, point->childTableName, strlen(point->childTableName));
    if (pCTablePoints) {
      cTablePoints = *pCTablePoints;
    } else {
      cTablePoints = taosArrayInit(64, sizeof(point));
      taosHashPut(cname2points, point->childTableName, strlen(point->childTableName), &cTablePoints, POINTER_BYTES);
    }
739
    taosArrayPush(cTablePoints, &point);
740 741
  }

S
shenglian zhou 已提交
742 743 744
  return 0;
}

745 746 747
static int32_t insertPoints(TAOS* taos, TAOS_SML_DATA_POINT* points, int32_t numPoints, SArray* stableSchemas) {
  int32_t code = TSDB_CODE_SUCCESS;

S
shenglian zhou 已提交
748 749
  SHashObj* cname2points = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY),
                                        true, false);
750
  arrangePointsByChildTableName(points, numPoints, cname2points, stableSchemas);
S
shenglian zhou 已提交
751

752
  int isNullColBind = TSDB_TRUE;
S
shenglian zhou 已提交
753 754 755
  SArray** pCTablePoints = taosHashIterate(cname2points, NULL);
  while (pCTablePoints) {
    SArray* cTablePoints = *pCTablePoints;
756 757

    TAOS_SML_DATA_POINT * point = taosArrayGetP(cTablePoints, 0);
758 759 760
    SSmlSTableSchema* sTableSchema = taosArrayGet(stableSchemas, point->schemaIdx);
    size_t numTags = taosArrayGetSize(sTableSchema->tags);
    size_t numCols = taosArrayGetSize(sTableSchema->fields);
761 762 763 764 765 766 767 768 769

    SArray* tagBinds = taosArrayInit(numTags, sizeof(TAOS_BIND));
    taosArraySetSize(tagBinds, numTags);
    for (int j = 0; j < numTags; ++j) {
      TAOS_BIND* bind = taosArrayGet(tagBinds, j);
      bind->is_null = &isNullColBind;
    }
    for (int j = 0; j < point->tagNum; ++j) {
      TAOS_SML_KV* kv =  point->tags + j;
770
      TAOS_BIND* bind = taosArrayGet(tagBinds, kv->fieldSchemaIdx);
771
      bind->buffer_type = kv->type;
772 773
      bind->length = malloc(sizeof(uintptr_t*));
      *bind->length = kv->length;
774 775 776
      bind->buffer = kv->value;
      bind->is_null = NULL;
    }
S
shenglian zhou 已提交
777 778 779 780 781

    size_t rows = taosArrayGetSize(cTablePoints);
    SArray* rowsBind = taosArrayInit(rows, POINTER_BYTES);

    for (int i = 0; i < rows; ++i) {
782
      point = taosArrayGetP(cTablePoints, i);
S
shenglian zhou 已提交
783

S
shenglian zhou 已提交
784
      TAOS_BIND* colBinds = calloc(numCols, sizeof(TAOS_BIND));
785 786 787 788
      if (colBinds == NULL) {
        tscError("taos_sml_insert insert points, failed to allocated memory for TAOS_BIND, "
            "num of rows: %zu, num of cols: %zu", rows, numCols);
      }
789
      for (int j = 0; j < numCols; ++j) {
S
shenglian zhou 已提交
790
        TAOS_BIND* bind = colBinds + j;
791 792 793
        bind->is_null = &isNullColBind;
      }
      for (int j = 0; j < point->fieldNum; ++j) {
S
shenglian zhou 已提交
794
        TAOS_SML_KV* kv = point->fields + j;
795
        TAOS_BIND* bind = colBinds + kv->fieldSchemaIdx;
S
shenglian zhou 已提交
796
        bind->buffer_type = kv->type;
797 798
        bind->length = malloc(sizeof(uintptr_t*));
        *bind->length = kv->length;
S
shenglian zhou 已提交
799
        bind->buffer = kv->value;
800
        bind->is_null = NULL;
S
shenglian zhou 已提交
801 802 803 804
      }
      taosArrayPush(rowsBind, &colBinds);
    }

805 806 807 808 809 810 811 812 813 814
    code = creatChildTableIfNotExists(taos, point->childTableName, point->stableName, sTableSchema->tags, tagBinds);
    if (code == 0) {
      code = insertChildTableBatch(taos, point->childTableName, sTableSchema->fields, rowsBind);
      if (code != 0) {
        tscError("insert into child table %s failed. error %s", point->childTableName, tstrerror(code));
      }
    } else {
      tscError("Create Child Table %s failed, error %s", point->childTableName, tstrerror(code));
    }

S
shenglian zhou 已提交
815 816 817 818 819 820 821 822 823 824 825
    for (int i = 0; i < taosArrayGetSize(tagBinds); ++i) {
      TAOS_BIND* bind = taosArrayGet(tagBinds, i);
      free(bind->length);
    }
    taosArrayDestroy(tagBinds);
    for (int i = 0; i < rows; ++i) {
      TAOS_BIND* colBinds = taosArrayGetP(rowsBind, i);
      for (int j = 0; j < numCols; ++j) {
        TAOS_BIND* bind = colBinds + j;
        free(bind->length);
      }
S
Shenglian Zhou 已提交
826
      free(colBinds);
S
shenglian zhou 已提交
827 828 829
    }
    taosArrayDestroy(rowsBind);
    taosArrayDestroy(cTablePoints);
830 831 832
    if (code != 0) {
      break;
    }
S
shenglian zhou 已提交
833
    pCTablePoints = taosHashIterate(cname2points, pCTablePoints);
834
  }
S
shenglian zhou 已提交
835 836

  taosHashCleanup(cname2points);
837
  return code;
S
shenglian zhou 已提交
838
}
839

S
shenglian zhou 已提交
840
int taos_sml_insert(TAOS* taos, TAOS_SML_DATA_POINT* points, int numPoint) {
S
Shenglian Zhou 已提交
841 842
  tscDebug("taos_sml_insert. number of points: %d", numPoint);

S
shenglian zhou 已提交
843 844
  int32_t code = TSDB_CODE_SUCCESS;

S
shenglian zhou 已提交
845
  SArray* stableSchemas = taosArrayInit(32, sizeof(SSmlSTableSchema)); // SArray<STableColumnsSchema>
S
shenglian zhou 已提交
846 847 848 849 850 851 852 853 854 855 856
  code = buildDataPointSchemas(points, numPoint, stableSchemas);
  if (code != 0) {
    tscError("error building data point schemas : %s", tstrerror(code));
    goto clean_up;
  }

  code = reconcileDBSchemas(taos, stableSchemas);
  if (code != 0) {
    tscError("error change db schema : %s", tstrerror(code));
    goto clean_up;
  }
S
shenglian zhou 已提交
857

858
  code = insertPoints(taos, points, numPoint, stableSchemas);
S
shenglian zhou 已提交
859 860 861 862 863
  if (code != 0) {
    tscError("error insert points : %s", tstrerror(code));
  }

clean_up:
S
shenglian zhou 已提交
864 865 866 867
  for (int i = 0; i < taosArrayGetSize(stableSchemas); ++i) {
    SSmlSTableSchema* schema = taosArrayGet(stableSchemas, i);
    taosArrayDestroy(schema->fields);
    taosArrayDestroy(schema->tags);
868
  }
S
shenglian zhou 已提交
869
  taosArrayDestroy(stableSchemas);
870 871
  return code;
}
S
shenglian zhou 已提交
872

873 874
//=========================================================================

875 876 877 878 879
/*        Field                          Escape charaters
    1: measurement                        Comma,Space
    2: tag_key, tag_value, field_key  Comma,Equal Sign,Space
    3: field_value                    Double quote,Backslash
*/
880
static void escapeSpecialCharacter(uint8_t field, const char **pos) {
881 882 883
  const char *cur = *pos;
  if (*cur != '\\') {
    return;
884
  }
885 886 887 888 889 890
  switch (field) {
    case 1:
      switch (*(cur + 1)) {
        case ',':
        case ' ':
          cur++;
891
          break;
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
        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;
919
  }
920
  *pos = cur;
921
}
922

923
static bool isValidInteger(char *str) {
924 925
  char *c = str;
  if (*c != '+' && *c != '-' && !isdigit(*c)) {
926 927
    return false;
  }
928 929 930 931 932 933
  c++;
  while (*c != '\0') {
    if (!isdigit(*c)) {
      return false;
    }
    c++;
934
  }
935
  return true;
936
}
937

938
static bool isValidFloat(char *str) {
939 940 941 942 943 944 945
  char *c = str;
  uint8_t has_dot, has_exp, has_sign;
  has_dot = 0;
  has_exp = 0;
  has_sign = 0;

  if (*c != '+' && *c != '-' && *c != '.' && !isdigit(*c)) {
946 947
    return false;
  }
948 949
  if (*c == '.' && isdigit(*(c + 1))) {
    has_dot = 1;
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
  c++;
  while (*c != '\0') {
    if (!isdigit(*c)) {
      switch (*c) {
        case '.': {
          if (!has_dot && !has_exp && isdigit(*(c + 1))) {
            has_dot = 1;
          } else {
            return false;
          }
          break;
        }
        case 'e':
        case 'E': {
          if (!has_exp && isdigit(*(c - 1)) &&
              (isdigit(*(c + 1)) ||
               *(c + 1) == '+' ||
               *(c + 1) == '-')) {
            has_exp = 1;
          } else {
            return false;
          }
          break;
        }
        case '+':
        case '-': {
          if (!has_sign && has_exp && isdigit(*(c + 1))) {
            has_sign = 1;
          } else {
            return false;
          }
          break;
        }
        default: {
          return false;
        }
      }
    }
    c++;
  } //while
  return true;
992
}
993

994
static bool isTinyInt(char *pVal, uint16_t len) {
995 996 997 998
  if (len <= 2) {
    return false;
  }
  if (!strcmp(&pVal[len - 2], "i8")) {
999
    //printf("Type is int8(%s)\n", pVal);
1000 1001 1002 1003
    return true;
  }
  return false;
}
1004

1005
static bool isTinyUint(char *pVal, uint16_t len) {
1006 1007 1008 1009 1010
  if (len <= 2) {
    return false;
  }
  if (pVal[0] == '-') {
    return false;
1011
  }
1012
  if (!strcmp(&pVal[len - 2], "u8")) {
1013
    //printf("Type is uint8(%s)\n", pVal);
1014 1015 1016
    return true;
  }
  return false;
1017 1018
}

1019
static bool isSmallInt(char *pVal, uint16_t len) {
1020 1021 1022 1023
  if (len <= 3) {
    return false;
  }
  if (!strcmp(&pVal[len - 3], "i16")) {
1024
    //printf("Type is int16(%s)\n", pVal);
1025
    return true;
1026
  }
1027
  return false;
1028 1029
}

1030
static bool isSmallUint(char *pVal, uint16_t len) {
1031 1032
  if (len <= 3) {
    return false;
1033
  }
1034 1035 1036 1037
  if (pVal[0] == '-') {
    return false;
  }
  if (strcmp(&pVal[len - 3], "u16") == 0) {
1038
    //printf("Type is uint16(%s)\n", pVal);
1039 1040 1041
    return true;
  }
  return false;
1042 1043
}

1044
static bool isInt(char *pVal, uint16_t len) {
1045 1046
  if (len <= 3) {
    return false;
1047
  }
1048
  if (strcmp(&pVal[len - 3], "i32") == 0) {
1049
    //printf("Type is int32(%s)\n", pVal);
1050 1051 1052
    return true;
  }
  return false;
1053 1054
}

1055
static bool isUint(char *pVal, uint16_t len) {
1056 1057 1058 1059 1060 1061 1062
  if (len <= 3) {
    return false;
  }
  if (pVal[0] == '-') {
    return false;
  }
  if (strcmp(&pVal[len - 3], "u32") == 0) {
1063
    //printf("Type is uint32(%s)\n", pVal);
1064 1065 1066
    return true;
  }
  return false;
1067 1068
}

1069
static bool isBigInt(char *pVal, uint16_t len) {
1070 1071
  if (len <= 3) {
    return false;
1072
  }
1073
  if (strcmp(&pVal[len - 3], "i64") == 0) {
1074
    //printf("Type is int64(%s)\n", pVal);
1075 1076 1077
    return true;
  }
  return false;
1078 1079
}

1080
static bool isBigUint(char *pVal, uint16_t len) {
1081 1082 1083 1084 1085
  if (len <= 3) {
    return false;
  }
  if (pVal[0] == '-') {
    return false;
1086
  }
1087
  if (strcmp(&pVal[len - 3], "u64") == 0) {
1088
    //printf("Type is uint64(%s)\n", pVal);
1089 1090 1091
    return true;
  }
  return false;
1092 1093
}

1094
static bool isFloat(char *pVal, uint16_t len) {
1095 1096 1097 1098
  if (len <= 3) {
    return false;
  }
  if (strcmp(&pVal[len - 3], "f32") == 0) {
1099
    //printf("Type is float(%s)\n", pVal);
1100 1101 1102
    return true;
  }
  return false;
1103 1104
}

1105
static bool isDouble(char *pVal, uint16_t len) {
1106 1107 1108 1109
  if (len <= 3) {
    return false;
  }
  if (strcmp(&pVal[len - 3], "f64") == 0) {
1110
    //printf("Type is double(%s)\n", pVal);
1111 1112 1113 1114 1115
    return true;
  }
  return false;
}

1116
static bool isBool(char *pVal, uint16_t len, bool *bVal) {
1117 1118 1119
  if ((len == 1) &&
      (pVal[len - 1] == 't' ||
       pVal[len - 1] == 'T')) {
1120 1121
    //printf("Type is bool(%c)\n", pVal[len - 1]);
    *bVal = true;
1122
    return true;
1123
  }
1124 1125 1126 1127

  if ((len == 1) &&
      (pVal[len - 1] == 'f' ||
       pVal[len - 1] == 'F')) {
1128 1129
    //printf("Type is bool(%c)\n", pVal[len - 1]);
    *bVal = false;
1130
    return true;
1131
  }
1132 1133 1134 1135 1136

  if((len == 4) &&
     (!strcmp(&pVal[len - 4], "true") ||
      !strcmp(&pVal[len - 4], "True") ||
      !strcmp(&pVal[len - 4], "TRUE"))) {
1137 1138
    //printf("Type is bool(%s)\n", &pVal[len - 4]);
    *bVal = true;
1139 1140 1141 1142 1143 1144
    return true;
  }
  if((len == 5) &&
     (!strcmp(&pVal[len - 5], "false") ||
      !strcmp(&pVal[len - 5], "False") ||
      !strcmp(&pVal[len - 5], "FALSE"))) {
1145 1146
    //printf("Type is bool(%s)\n", &pVal[len - 5]);
    *bVal = false;
1147 1148 1149
    return true;
  }
  return false;
1150 1151
}

1152
static bool isBinary(char *pVal, uint16_t len) {
1153 1154 1155 1156 1157 1158
  //binary: "abc"
  if (len < 2) {
    return false;
  }
  //binary
  if (pVal[0] == '"' && pVal[len - 1] == '"') {
1159
    //printf("Type is binary(%s)\n", pVal);
1160 1161 1162 1163
    return true;
  }
  return false;
}
1164

1165
static bool isNchar(char *pVal, uint16_t len) {
1166 1167
  //nchar: L"abc"
  if (len < 3) {
1168 1169
    return false;
  }
1170
  if (pVal[0] == 'L' && pVal[1] == '"' && pVal[len - 1] == '"') {
1171
    //printf("Type is nchar(%s)\n", pVal);
1172
    return true;
1173
  }
1174 1175 1176
  return false;
}

1177
static bool isTimeStamp(char *pVal, uint16_t len, SMLTimeStampType *tsType) {
1178 1179 1180 1181 1182
  if (len == 0) {
    return true;
  }
  if ((len == 1) && pVal[0] == '0') {
    *tsType = SML_TIME_STAMP_NOW;
1183
    //printf("Type is timestamp(%s)\n", pVal);
1184 1185 1186 1187 1188 1189 1190 1191
    return true;
  }
  if (len < 2) {
    return false;
  }
  //No appendix use usec as default
  if (isdigit(pVal[len - 1]) && isdigit(pVal[len - 2])) {
    *tsType = SML_TIME_STAMP_MICRO_SECONDS;
1192
    //printf("Type is timestamp(%s)\n", pVal);
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208
    return true;
  }
  if (pVal[len - 1] == 's') {
    switch (pVal[len - 2]) {
      case 'm':
        *tsType = SML_TIME_STAMP_MILLI_SECONDS;
        break;
      case 'u':
        *tsType = SML_TIME_STAMP_MICRO_SECONDS;
        break;
      case 'n':
        *tsType = SML_TIME_STAMP_NANO_SECONDS;
        break;
      default:
        if (isdigit(pVal[len - 2])) {
          *tsType = SML_TIME_STAMP_SECONDS;
1209
          break;
1210
        } else {
1211 1212 1213
          return false;
        }
    }
1214
    //printf("Type is timestamp(%s)\n", pVal);
1215 1216 1217 1218
    return true;
  }
  return false;
}
1219

1220
//len does not include '\0' from value.
1221 1222
static bool convertSmlValueType(TAOS_SML_KV *pVal, char *value,
                                uint16_t len) {
1223 1224 1225
  if (len <= 0) {
    return false;
  }
G
Ganlin Zhao 已提交
1226

1227
  //integer number
1228
  if (isTinyInt(value, len)) {
1229 1230 1231
    pVal->type = TSDB_DATA_TYPE_TINYINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 2] = '\0';
1232
    if (!isValidInteger(value)) {
1233
      return false;
1234 1235 1236 1237 1238 1239
    }
    pVal->value = calloc(pVal->length, 1);
    int8_t val = (int8_t)strtoll(value, NULL, 10);
    memcpy(pVal->value, &val, pVal->length);
    return true;
  }
1240
  if (isTinyUint(value, len)) {
1241 1242 1243
    pVal->type = TSDB_DATA_TYPE_UTINYINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 2] = '\0';
1244
    if (!isValidInteger(value)) {
1245 1246 1247 1248 1249 1250 1251
      return false;
    }
    pVal->value = calloc(pVal->length, 1);
    uint8_t val = (uint8_t)strtoul(value, NULL, 10);
    memcpy(pVal->value, &val, pVal->length);
    return true;
  }
1252
  if (isSmallInt(value, len)) {
1253 1254 1255
    pVal->type = TSDB_DATA_TYPE_SMALLINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1256
    if (!isValidInteger(value)) {
1257 1258 1259 1260 1261 1262 1263
      return false;
    }
    pVal->value = calloc(pVal->length, 1);
    int16_t val = (int16_t)strtoll(value, NULL, 10);
    memcpy(pVal->value, &val, pVal->length);
    return true;
  }
1264
  if (isSmallUint(value, len)) {
1265 1266 1267
    pVal->type = TSDB_DATA_TYPE_USMALLINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1268
    if (!isValidInteger(value)) {
1269 1270 1271 1272 1273 1274 1275 1276
      return false;
    }
    pVal->value = calloc(pVal->length, 1);
    uint16_t val = (uint16_t)strtoul(value, NULL, 10);
    memcpy(pVal->value, &val, pVal->length);
    //memcpy(pVal->value, &val, pVal->length);
    return true;
  }
1277
  if (isInt(value, len)) {
1278 1279 1280
    pVal->type = TSDB_DATA_TYPE_INT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1281
    if (!isValidInteger(value)) {
1282 1283 1284 1285 1286 1287 1288
      return false;
    }
    pVal->value = calloc(pVal->length, 1);
    int32_t val = (int32_t)strtoll(value, NULL, 10);
    memcpy(pVal->value, &val, pVal->length);
    return true;
  }
1289
  if (isUint(value, len)) {
1290 1291 1292
    pVal->type = TSDB_DATA_TYPE_UINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1293
    if (!isValidInteger(value)) {
1294 1295 1296 1297 1298 1299 1300
      return false;
    }
    pVal->value = calloc(pVal->length, 1);
    uint32_t val = (uint32_t)strtoul(value, NULL, 10);
    memcpy(pVal->value, &val, pVal->length);
    return true;
  }
1301
  if (isBigInt(value, len)) {
1302 1303 1304
    pVal->type = TSDB_DATA_TYPE_BIGINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1305
    if (!isValidInteger(value)) {
1306 1307 1308 1309 1310 1311 1312
      return false;
    }
    pVal->value = calloc(pVal->length, 1);
    int64_t val = (int64_t)strtoll(value, NULL, 10);
    memcpy(pVal->value, &val, pVal->length);
    return true;
  }
1313
  if (isBigUint(value, len)) {
1314 1315 1316
    pVal->type = TSDB_DATA_TYPE_UBIGINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1317
    if (!isValidInteger(value)) {
1318 1319 1320 1321 1322 1323 1324
      return false;
    }
    pVal->value = calloc(pVal->length, 1);
    uint64_t val = (uint64_t)strtoul(value, NULL, 10);
    memcpy(pVal->value, &val, pVal->length);
    return true;
  }
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
  //floating number
  if (isFloat(value, len)) {
    pVal->type = TSDB_DATA_TYPE_FLOAT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
    if (!isValidFloat(value)) {
      return false;
    }
    pVal->value = calloc(pVal->length, 1);
    float val = (float)strtold(value, NULL);
    memcpy(pVal->value, &val, pVal->length);
    return true;
  }
  if (isDouble(value, len)) {
    pVal->type = TSDB_DATA_TYPE_DOUBLE;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
    if (!isValidFloat(value)) {
      return false;
    }
    pVal->value = calloc(pVal->length, 1);
    double val = (double)strtold(value, NULL);
    memcpy(pVal->value, &val, pVal->length);
    return true;
  }
  //binary
  if (isBinary(value, len)) {
    pVal->type = TSDB_DATA_TYPE_BINARY;
    pVal->length = len - 2;
    pVal->value = calloc(pVal->length, 1);
    //copy after "
    memcpy(pVal->value, value + 1, pVal->length);
    return true;
  }
  //nchar
  if (isNchar(value, len)) {
    pVal->type = TSDB_DATA_TYPE_NCHAR;
    pVal->length = len - 3;
    pVal->value = calloc(pVal->length, 1);
    //copy after L"
    memcpy(pVal->value, value + 2, pVal->length);
    return true;
  }
  //bool
  bool bVal;
  if (isBool(value, len, &bVal)) {
    pVal->type = TSDB_DATA_TYPE_BOOL;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->value = calloc(pVal->length, 1);
    memcpy(pVal->value, &bVal, pVal->length);
    return true;
  }
G
Ganlin Zhao 已提交
1377 1378 1379 1380 1381 1382 1383 1384 1385
  //Handle default(no appendix) as float
  if (isValidInteger(value) || isValidFloat(value)) {
    pVal->type = TSDB_DATA_TYPE_FLOAT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    pVal->value = calloc(pVal->length, 1);
    float val = (float)strtold(value, NULL);
    memcpy(pVal->value, &val, pVal->length);
    return true;
  }
1386
  return false;
1387
}
1388

1389 1390
static int32_t getTimeStampValue(char *value, uint16_t len,
                                 SMLTimeStampType type, int64_t *ts) {
1391 1392 1393 1394 1395

  if (len >= 2) {
    for (int i = 0; i < len - 2; ++i) {
      if(!isdigit(value[i])) {
        return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
1396
      }
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
    }
  }
  //No appendix or no timestamp given (len = 0)
  if (len >= 1 && isdigit(value[len - 1]) && type != SML_TIME_STAMP_NOW) {
    type = SML_TIME_STAMP_MICRO_SECONDS;
  }
  if (len != 0) {
    *ts = (int64_t)strtoll(value, NULL, 10);
  } else {
    type = SML_TIME_STAMP_NOW;
  }
  switch (type) {
    case SML_TIME_STAMP_NOW: {
1410
      *ts = taosGetTimestampNs();
1411
      break;
1412 1413
    }
    case SML_TIME_STAMP_SECONDS: {
1414
      *ts = (int64_t)(*ts * 1e9);
1415
      break;
1416 1417
    }
    case SML_TIME_STAMP_MILLI_SECONDS: {
1418
      *ts = convertTimePrecision(*ts, TSDB_TIME_PRECISION_MILLI, TSDB_TIME_PRECISION_NANO);
1419
      break;
1420 1421
    }
    case SML_TIME_STAMP_MICRO_SECONDS: {
1422
      *ts = convertTimePrecision(*ts, TSDB_TIME_PRECISION_MICRO, TSDB_TIME_PRECISION_NANO);
1423
      break;
1424 1425
    }
    case SML_TIME_STAMP_NANO_SECONDS: {
1426
      *ts = *ts * 1;
1427 1428 1429 1430 1431
      break;
    }
    default: {
      return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
    }
1432
  }
1433
  return TSDB_CODE_SUCCESS;
1434 1435
}

1436 1437
static int32_t convertSmlTimeStamp(TAOS_SML_KV *pVal, char *value,
                                   uint16_t len) {
1438 1439 1440
  int32_t ret;
  SMLTimeStampType type;
  int64_t tsVal;
1441

1442
  if (!isTimeStamp(value, len, &type)) {
1443
    return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
1444 1445
  }

1446
  ret = getTimeStampValue(value, len, type, &tsVal);
1447 1448 1449
  if (ret) {
    return ret;
  }
1450
  tscDebug("Timestamp after conversion:%"PRId64, tsVal);
1451 1452 1453 1454 1455 1456 1457 1458

  pVal->type = TSDB_DATA_TYPE_TIMESTAMP;
  pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
  pVal->value = calloc(pVal->length, 1);
  memcpy(pVal->value, &tsVal, pVal->length);
  return TSDB_CODE_SUCCESS;
}

1459
static int32_t parseSmlTimeStamp(TAOS_SML_KV **pTS, const char **index) {
1460
  const char *start, *cur;
1461 1462 1463
  int32_t ret = TSDB_CODE_SUCCESS;
  int len = 0;
  char key[] = "_ts";
1464
  char *value = NULL;
1465

1466
  start = cur = *index;
1467
  *pTS = calloc(1, sizeof(TAOS_SML_KV));
1468

1469
  while(*cur != '\0') {
1470 1471 1472 1473
    cur++;
    len++;
  }

1474
  if (len > 0) {
1475
    value = calloc(len + 1, 1);
1476 1477 1478 1479 1480
    memcpy(value, start, len);
  }

  ret = convertSmlTimeStamp(*pTS, value, len);
  if (ret) {
1481
    free(value);
1482 1483
    free(*pTS);
    return ret;
1484
  }
1485
  free(value);
1486

1487 1488 1489
  (*pTS)->key = calloc(sizeof(key), 1);
  memcpy((*pTS)->key, key, sizeof(key));
  return ret;
1490
}
1491

1492
static int32_t parseSmlKey(TAOS_SML_KV *pKV, const char **index) {
1493 1494 1495 1496
  const char *cur = *index;
  char key[TSDB_COL_NAME_LEN];
  uint16_t len = 0;

G
Ganlin Zhao 已提交
1497 1498 1499
  //key field cannot start with digit
  if (isdigit(*cur)) {
    tscError("Tag key cannnot start with digit\n");
1500
    return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
1501 1502 1503
  }
  while (*cur != '\0') {
    if (len > TSDB_COL_NAME_LEN) {
1504
      tscDebug("Key field cannot exceeds 65 characters");
1505
      return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
1506 1507 1508 1509 1510 1511 1512
    }
    //unescaped '=' identifies a tag key
    if (*cur == '=' && *(cur - 1) != '\\') {
      break;
    }
    //Escape special character
    if (*cur == '\\') {
1513
      escapeSpecialCharacter(2, &cur);
1514
    }
1515 1516 1517 1518 1519
    key[len] = *cur;
    cur++;
    len++;
  }
  key[len] = '\0';
1520

1521 1522
  pKV->key = calloc(len + 1, 1);
  memcpy(pKV->key, key, len + 1);
G
Ganlin Zhao 已提交
1523
  //tscDebug("Key:%s|len:%d", pKV->key, len);
1524
  *index = cur + 1;
1525
  return TSDB_CODE_SUCCESS;
1526
}
1527

1528

1529 1530
static bool parseSmlValue(TAOS_SML_KV *pKV, const char **index,
                          bool *is_last_kv) {
1531 1532
  const char *start, *cur;
  char *value = NULL;
1533
  uint16_t len = 0;
1534 1535
  start = cur = *index;

1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
  while (1) {
    // unescaped ',' or ' ' or '\0' identifies a value
    if ((*cur == ',' || *cur == ' ' || *cur == '\0') && *(cur - 1) != '\\') {
      //unescaped ' ' or '\0' indicates end of value
      *is_last_kv = (*cur == ' ' || *cur == '\0') ? true : false;
      break;
    }
    //Escape special character
    if (*cur == '\\') {
      escapeSpecialCharacter(2, &cur);
    }
1547 1548 1549
    cur++;
    len++;
  }
1550

1551 1552 1553 1554 1555 1556
  value = calloc(len + 1, 1);
  memcpy(value, start, len);
  value[len] = '\0';
  if (!convertSmlValueType(pKV, value, len)) {
    //free previous alocated key field
    free(pKV->key);
1557
    free(value);
1558
    return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
1559
  }
1560
  free(value);
1561

1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
  *index = (*cur == '\0') ? cur : cur + 1;
  return TSDB_CODE_SUCCESS;
}

static int32_t parseSmlMeasurement(TAOS_SML_DATA_POINT *pSml, const char **index,
                                   uint8_t *has_tags) {
  const char *cur = *index;
  uint16_t len = 0;

  pSml->stableName = calloc(TSDB_TABLE_NAME_LEN, 1);
G
Ganlin Zhao 已提交
1572 1573
  if (isdigit(*cur)) {
    tscError("Measurement field cannnot start with digit");
1574
    free(pSml->stableName);
1575
    pSml->stableName = NULL;
1576
    return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
1577 1578
  }

1579 1580 1581 1582
  while (*cur != '\0') {
    if (len > TSDB_TABLE_NAME_LEN) {
      tscError("Measurement field cannot exceeds 193 characters");
      free(pSml->stableName);
1583
      pSml->stableName = NULL;
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607
      return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
    }
    //first unescaped comma or space identifies measurement
    //if space detected first, meaning no tag in the input
    if (*cur == ',' && *(cur - 1) != '\\') {
      *has_tags = 1;
      break;
    }
    if (*cur == ' ' && *(cur - 1) != '\\') {
      break;
    }
    //Comma, Space, Backslash needs to be escaped if any
    if (*cur == '\\') {
      escapeSpecialCharacter(1, &cur);
    }
    pSml->stableName[len] = *cur;
    cur++;
    len++;
  }
  pSml->stableName[len] = '\0';
  *index = cur + 1;
  tscDebug("Stable name in measurement:%s|len:%d", pSml->stableName, len);

  return TSDB_CODE_SUCCESS;
1608
}
1609

1610
static int32_t parseSmlKvPairs(TAOS_SML_KV **pKVs, int *num_kvs,
1611
                               const char **index, bool isField, TAOS_SML_DATA_POINT* smlData) {
1612
  const char *cur = *index;
1613
  int32_t ret = TSDB_CODE_SUCCESS;
1614 1615
  TAOS_SML_KV *pkv;
  bool is_last_kv = false;
1616

1617
  int32_t capacity = 0;
1618
  if (isField) {
1619 1620 1621
    capacity = 64;
    *pKVs = calloc(capacity, sizeof(TAOS_SML_KV));
    // leave space for timestamp;
1622 1623
    pkv = *pKVs;
    pkv++;
1624 1625 1626
  } else {
    capacity = 8;
    *pKVs = calloc(capacity, sizeof(TAOS_SML_KV));
1627 1628
    pkv = *pKVs;
  }
1629

1630
  while (*cur != '\0') {
1631
    ret = parseSmlKey(pkv, &cur);
1632
    if (ret) {
1633
      tscError("Unable to parse key field");
1634 1635
      goto error;
    }
1636
    ret = parseSmlValue(pkv, &cur, &is_last_kv);
1637
    if (ret) {
1638
      tscError("Unable to parse value field");
1639 1640
      goto error;
    }
1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
    if (!isField &&
        (strcasecmp(pkv->key, "ID") == 0) && pkv->type == TSDB_DATA_TYPE_BINARY) {
      smlData->childTableName = malloc( pkv->length + 1);
      memcpy(smlData->childTableName, pkv->value, pkv->length);
      smlData->childTableName[pkv->length] = '\0';
      free(pkv->key);
      free(pkv->value);
    } else {
      *num_kvs += 1;
    }
1651
    if (is_last_kv) {
G
Ganlin Zhao 已提交
1652
      //tscDebug("last key-value field detected");
1653 1654 1655 1656 1657
      goto done;
    }

    //reallocate addtional memory for more kvs
    TAOS_SML_KV *more_kvs = NULL;
1658

1659
    if (isField) {
1660 1661
      if ((*num_kvs + 2) > capacity) {
        capacity *= 3; capacity /= 2;
1662 1663 1664
        more_kvs = realloc(*pKVs, capacity * sizeof(TAOS_SML_KV));
      } else {
        more_kvs = *pKVs;
1665
      }
1666
    } else {
1667 1668
      if ((*num_kvs + 1) > capacity) {
        capacity *= 3; capacity /= 2;
1669 1670 1671
        more_kvs = realloc(*pKVs, capacity * sizeof(TAOS_SML_KV));
      } else {
        more_kvs = *pKVs;
1672
      }
1673
    }
1674

1675
    if (!more_kvs) {
1676 1677
      goto error;
    }
1678 1679 1680 1681 1682 1683 1684 1685 1686
    *pKVs = more_kvs;
    //move pKV points to next TAOS_SML_KV block
    if (isField) {
      pkv = *pKVs + *num_kvs + 1;
    } else {
      pkv = *pKVs + *num_kvs;
    }
  }
  goto done;
1687

1688
error:
1689
  return ret;
1690
done:
1691
  *index = cur;
1692
  return ret;
1693
}
1694

1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
static void moveTimeStampToFirstKv(TAOS_SML_DATA_POINT** smlData, TAOS_SML_KV *ts) {
  TAOS_SML_KV* tsField = (*smlData)->fields;
  tsField->length = ts->length;
  tsField->type = ts->type;
  tsField->value = malloc(ts->length);
  tsField->key = malloc(strlen(ts->key) + 1);
  memcpy(tsField->key, ts->key, strlen(ts->key) + 1);
  memcpy(tsField->value, ts->value, ts->length);
  (*smlData)->fieldNum = (*smlData)->fieldNum + 1;

  free(ts->key);
  free(ts->value);
  free(ts);
1708 1709
}

1710
int32_t tscParseLine(const char* sql, TAOS_SML_DATA_POINT* smlData) {
1711
  const char* index = sql;
1712
  int32_t ret = TSDB_CODE_SUCCESS;
1713 1714 1715
  uint8_t has_tags = 0;
  TAOS_SML_KV *timestamp = NULL;

1716
  ret = parseSmlMeasurement(smlData, &index, &has_tags);
1717
  if (ret) {
1718
    tscError("Unable to parse measurement");
1719
    return ret;
1720
  }
1721
  tscDebug("Parse measurement finished, has_tags:%d", has_tags);
1722 1723 1724

  //Parse Tags
  if (has_tags) {
1725
    ret = parseSmlKvPairs(&smlData->tags, &smlData->tagNum, &index, false, smlData);
1726
    if (ret) {
1727
      tscError("Unable to parse tag");
1728 1729
      return ret;
    }
1730
  }
1731
  tscDebug("Parse tags finished, num of tags:%d", smlData->tagNum);
1732 1733

  //Parse fields
1734
  ret = parseSmlKvPairs(&smlData->fields, &smlData->fieldNum, &index, true, smlData);
1735
  if (ret) {
1736
    tscError("Unable to parse field");
1737
    return ret;
1738
  }
1739
  tscDebug("Parse fields finished, num of fields:%d", smlData->fieldNum);
1740

1741
  //Parse timestamp
1742
  ret = parseSmlTimeStamp(&timestamp, &index);
1743
  if (ret) {
1744
    tscError("Unable to parse timestamp");
1745
    return ret;
1746
  }
1747 1748
  moveTimeStampToFirstKv(&smlData, timestamp);
  tscDebug("Parse timestamp finished");
1749

1750
  return TSDB_CODE_SUCCESS;
1751 1752
}

1753
//=========================================================================
1754

S
shenglian zhou 已提交
1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769
void destroySmlDataPoint(TAOS_SML_DATA_POINT* point) {
  for (int i=0; i<point->tagNum; ++i) {
    free((point->tags+i)->key);
    free((point->tags+i)->value);
  }
  free(point->tags);
  for (int i=0; i<point->fieldNum; ++i) {
    free((point->fields+i)->key);
    free((point->fields+i)->value);
  }
  free(point->fields);
  free(point->stableName);
  free(point->childTableName);
}

1770 1771
int32_t tscParseLines(char* lines[], int numLines, SArray* points, SArray* failedLines) {
  for (int32_t i = 0; i < numLines; ++i) {
1772
    TAOS_SML_DATA_POINT point = {0};
1773 1774
    int32_t code = tscParseLine(lines[i], &point);
    if (code != TSDB_CODE_SUCCESS) {
1775
      tscError("data point line parse failed. line %d : %s", i, lines[i]);
S
shenglian zhou 已提交
1776
      destroySmlDataPoint(&point);
1777 1778 1779 1780 1781
      return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
    } else {
      tscDebug("data point line parse success. line %d", i);
    }

1782 1783 1784 1785 1786
    taosArrayPush(points, &point);
  }
  return 0;
}

1787
int taos_insert_lines(TAOS* taos, char* lines[], int numLines) {
1788
  int32_t code = 0;
1789 1790 1791

  if (numLines <= 0 || numLines > 65536) {
    tscError("taos_insert_lines numLines should be between 1 and 65536. numLines: %d", numLines);
1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
    code = TSDB_CODE_TSC_APP_ERROR;
    return code;
  }

  for (int i = 0; i < numLines; ++i) {
    if (lines[i] == NULL) {
      tscError("taos_insert_lines line %d is NULL", i);
      code = TSDB_CODE_TSC_APP_ERROR;
      return code;
    }
  }

1804
  SArray* lpPoints = taosArrayInit(numLines, sizeof(TAOS_SML_DATA_POINT));
1805 1806 1807 1808
  if (lpPoints == NULL) {
    tscError("taos_insert_lines failed to allocate memory");
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }
1809

1810
  tscDebug("taos_insert_lines begin inserting %d lines, first line: %s", numLines, lines[0]);
1811
  code = tscParseLines(lines, numLines, lpPoints, NULL);
S
shenglian zhou 已提交
1812 1813
  size_t numPoints = taosArrayGetSize(lpPoints);

1814 1815
  if (code != 0) {
    goto cleanup;
1816 1817
  }

1818
  TAOS_SML_DATA_POINT* points = TARRAY_GET_START(lpPoints);
1819 1820 1821 1822
  code = taos_sml_insert(taos, points, (int)numPoints);
  if (code != 0) {
    tscError("taos_sml_insert error: %s", tstrerror((code)));
  }
S
Shenglian Zhou 已提交
1823

1824
cleanup:
1825
  tscDebug("taos_insert_lines finish inserting %d lines. code: %d", numLines, code);
S
Shenglian Zhou 已提交
1826 1827 1828
  for (int i=0; i<numPoints; ++i) {
    destroySmlDataPoint(points+i);
  }
1829 1830

  taosArrayDestroy(lpPoints);
1831
  return code;
1832 1833
}