tscParseLineProtocol.c 64.5 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

  //===================================
S
shenglian zhou 已提交
37
  uint32_t fieldSchemaIdx;
S
shenglian zhou 已提交
38 39 40 41 42 43 44
} TAOS_SML_KV;

typedef struct {
  char* stableName;

  char* childTableName;
  TAOS_SML_KV* tags;
S
shenglian zhou 已提交
45
  int32_t tagNum;
S
shenglian zhou 已提交
46 47 48

  // first kv must be timestamp
  TAOS_SML_KV* fields;
S
shenglian zhou 已提交
49
  int32_t fieldNum;
S
shenglian zhou 已提交
50

S
shenglian zhou 已提交
51
  //================================
S
shenglian zhou 已提交
52
  uint32_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;

S
shenglian zhou 已提交
63 64 65 66
typedef struct {
  uint64_t id;

} SSmlLinesInfo;
67 68
//=================================================================================================

S
shenglian zhou 已提交
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
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 已提交
109
static int32_t getFieldBytesFromSmlKv(TAOS_SML_KV* kv, int32_t* bytes, uint64_t id) {
S
shenglian zhou 已提交
110 111 112 113 114 115
  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 已提交
116 117 118
      bool succ = taosMbsToUcs4(kv->value, kv->length, ucs, kv->length * TSDB_NCHAR_SIZE, &bytesNeeded);
      if (!succ) {
        free(ucs);
S
shenglian zhou 已提交
119
        tscError("SML:0x%"PRIx64" convert nchar string to UCS4_LE failed:%s", id, kv->value);
S
Shenglian Zhou 已提交
120 121
        return TSDB_CODE_TSC_INVALID_VALUE;
      }
S
shenglian zhou 已提交
122 123 124 125 126 127 128 129 130
      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 已提交
131
static int32_t buildSmlKvSchema(TAOS_SML_KV* smlKv, SHashObj* hash, SArray* array, SSmlLinesInfo* info) {
S
shenglian zhou 已提交
132
  SSchema* pField = NULL;
133 134
  size_t* pFieldIdx = taosHashGet(hash, smlKv->key, strlen(smlKv->key));
  size_t fieldIdx = -1;
S
Shenglian Zhou 已提交
135
  int32_t code = 0;
136 137 138
  if (pFieldIdx) {
    fieldIdx = *pFieldIdx;
    pField = taosArrayGet(array, fieldIdx);
S
shenglian zhou 已提交
139 140

    if (pField->type != smlKv->type) {
S
shenglian zhou 已提交
141
      tscError("SML:0x%"PRIx64" type mismatch. key %s, type %d. type before %d", info->id, smlKv->key, smlKv->type, pField->type);
S
Shenglian Zhou 已提交
142
      return TSDB_CODE_TSC_INVALID_VALUE;
S
shenglian zhou 已提交
143 144 145
    }

    int32_t bytes = 0;
S
shenglian zhou 已提交
146
    code = getFieldBytesFromSmlKv(smlKv, &bytes, info->id);
S
Shenglian Zhou 已提交
147 148 149
    if (code != 0) {
      return code;
    }
S
shenglian zhou 已提交
150 151 152
    pField->bytes = MAX(pField->bytes, bytes);

  } else {
S
shenglian zhou 已提交
153
    SSchema field = {0};
S
shenglian zhou 已提交
154 155 156 157 158 159
    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 已提交
160
    code = getFieldBytesFromSmlKv(smlKv, &bytes, info->id);
S
Shenglian Zhou 已提交
161 162 163
    if (code != 0) {
      return code;
    }
S
shenglian zhou 已提交
164 165 166
    field.bytes = bytes;

    pField = taosArrayPush(array, &field);
167 168
    fieldIdx = taosArrayGetSize(array) - 1;
    taosHashPut(hash, field.name, tagKeyLen, &fieldIdx, sizeof(fieldIdx));
S
shenglian zhou 已提交
169
  }
170

S
shenglian zhou 已提交
171
  smlKv->fieldSchemaIdx = (uint32_t)fieldIdx;
172

S
shenglian zhou 已提交
173 174 175
  return 0;
}

S
shenglian zhou 已提交
176
static int32_t buildDataPointSchemas(TAOS_SML_DATA_POINT* points, int numPoint, SArray* stableSchemas, SSmlLinesInfo* info) {
S
Shenglian Zhou 已提交
177
  int32_t code = 0;
S
shenglian zhou 已提交
178 179 180 181 182 183
  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);
184
    size_t* pStableIdx = taosHashGet(sname2shema, point->stableName, stableNameLen);
S
shenglian zhou 已提交
185
    SSmlSTableSchema* pStableSchema = NULL;
186 187 188 189
    size_t stableIdx = -1;
    if (pStableIdx) {
      pStableSchema= taosArrayGet(stableSchemas, *pStableIdx);
      stableIdx = *pStableIdx;
S
shenglian zhou 已提交
190 191 192 193 194 195 196 197 198 199
    } 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);
200 201
      stableIdx = taosArrayGetSize(stableSchemas) - 1;
      taosHashPut(sname2shema, schema.sTableName, stableNameLen, &stableIdx, sizeof(size_t));
S
shenglian zhou 已提交
202 203 204 205
    }

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

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

S
shenglian zhou 已提交
222
    point->schemaIdx = (uint32_t)stableIdx;
S
shenglian zhou 已提交
223 224 225 226 227 228 229 230 231 232
  }

  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 已提交
233
  tscDebug("SML:0x%"PRIx64" build point schema succeed. num of super table: %zu", info->id, numStables);
S
Shenglian Zhou 已提交
234 235 236 237 238 239
  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 已提交
240 241 242
  return 0;
}

243
static int32_t generateSchemaAction(SSchema* pointColField, SHashObj* dbAttrHash, SArray* dbAttrArray, bool isTag, char sTableName[],
S
shenglian zhou 已提交
244
                                       SSchemaAction* action, bool* actionNeeded, SSmlLinesInfo* info) {
245 246 247 248
  char fieldNameLowerCase[TSDB_COL_NAME_LEN] = {0};
  strtolower(fieldNameLowerCase, pointColField->name);

  size_t* pDbIndex = taosHashGet(dbAttrHash, fieldNameLowerCase, strlen(fieldNameLowerCase));
249 250 251
  if (pDbIndex) {
    SSchema* dbAttr = taosArrayGet(dbAttrArray, *pDbIndex);
    assert(strcasecmp(dbAttr->name, pointColField->name) == 0);
S
shenglian zhou 已提交
252
    if (pointColField->type != dbAttr->type) {
S
shenglian zhou 已提交
253
      tscError("SML:0x%"PRIx64" point type and db type mismatch. key: %s. point type: %d, db type: %d", info->id, pointColField->name,
S
Shenglian Zhou 已提交
254 255
               pointColField->type, dbAttr->type);
      return TSDB_CODE_TSC_INVALID_VALUE;
S
shenglian zhou 已提交
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
    }

    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 已提交
280 281 282 283
  if (*actionNeeded) {
    tscDebug("SML:0x%" PRIx64 " generate schema action. column name: %s, action: %d", info->id, fieldNameLowerCase,
             action->action);
  }
S
shenglian zhou 已提交
284 285 286
  return 0;
}

S
shenglian zhou 已提交
287
static int32_t buildColumnDescription(SSchema* field,
S
shenglian zhou 已提交
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
                               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 已提交
308

S
shenglian zhou 已提交
309
static int32_t applySchemaAction(TAOS* taos, SSchemaAction* action, SSmlLinesInfo* info) {
S
shenglian zhou 已提交
310 311
  int32_t code = 0;
  int32_t outBytes = 0;
312 313
  char *result = (char *)calloc(1, tsMaxSQLStringLen+1);
  int32_t capacity = tsMaxSQLStringLen +  1;
S
shenglian zhou 已提交
314

S
shenglian zhou 已提交
315
  tscDebug("SML:0x%"PRIx64" apply schema action. action: %d", info->id, action->action);
S
shenglian zhou 已提交
316 317 318 319 320 321
  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 已提交
322
      taos_free_result(res);
S
shenglian zhou 已提交
323 324 325 326 327 328 329 330
      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 已提交
331
      taos_free_result(res);
S
shenglian zhou 已提交
332 333 334 335 336 337 338 339
      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 已提交
340
      taos_free_result(res);
341
      break;
S
shenglian zhou 已提交
342 343 344 345 346 347 348
    }
    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 已提交
349
      taos_free_result(res);
S
shenglian zhou 已提交
350 351 352 353 354
      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 已提交
355
      size_t numCols = taosArrayGetSize(action->createSTable.fields);
S
shenglian zhou 已提交
356 357 358 359 360 361 362
      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;
363

S
shenglian zhou 已提交
364 365
      outBytes = snprintf(pos, freeBytes, ") tags (");
      pos += outBytes; freeBytes -= outBytes;
366

S
shenglian zhou 已提交
367
      size_t numTags = taosArrayGetSize(action->createSTable.tags);
S
shenglian zhou 已提交
368 369 370 371 372 373 374 375 376 377
      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 已提交
378
      taos_free_result(res);
S
shenglian zhou 已提交
379 380
      break;
    }
S
shenglian zhou 已提交
381

S
shenglian zhou 已提交
382 383 384
    default:
      break;
  }
S
Shenglian Zhou 已提交
385

S
shenglian zhou 已提交
386
  free(result);
S
Shenglian Zhou 已提交
387
  if (code != 0) {
S
shenglian zhou 已提交
388
    tscError("SML:0x%"PRIx64 "apply schema action failure. %s", info->id, tstrerror(code));
S
Shenglian Zhou 已提交
389
  }
S
shenglian zhou 已提交
390 391 392
  return code;
}

393
static int32_t destroySmlSTableSchema(SSmlSTableSchema* schema) {
S
shenglian zhou 已提交
394 395 396 397 398 399 400
  taosHashCleanup(schema->tagHash);
  taosHashCleanup(schema->fieldHash);
  taosArrayDestroy(schema->tags);
  taosArrayDestroy(schema->fields);
  return 0;
}

S
shenglian zhou 已提交
401
int32_t loadTableMeta(TAOS* taos, char* tableName, SSmlSTableSchema* schema, SSmlLinesInfo* info) {
S
shenglian zhou 已提交
402 403 404 405 406 407 408 409
  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 已提交
410
  tscDebug("SML:0x%"PRIx64" load table schema. super table name: %s", info->id, tableName);
S
Shenglian Zhou 已提交
411

412 413
  char tableNameLowerCase[TSDB_TABLE_NAME_LEN];
  strtolower(tableNameLowerCase, tableName);
S
Shenglian Zhou 已提交
414

S
shenglian zhou 已提交
415
  char sql[256];
416
  snprintf(sql, 256, "describe %s", tableNameLowerCase);
S
shenglian zhou 已提交
417 418 419
  TAOS_RES* res = taos_query(taos, sql);
  code = taos_errno(res);
  if (code != 0) {
S
shenglian zhou 已提交
420
    tscError("SML:0x%"PRIx64" describe table failure. %s", info->id, taos_errstr(res));
S
shenglian zhou 已提交
421 422 423 424 425 426
    taos_free_result(res);
    return code;
  }
  taos_free_result(res);

  SSqlObj* pSql = calloc(1, sizeof(SSqlObj));
427 428 429 430 431
  if (pSql == NULL){
      tscError("failed to allocate memory, reason:%s", strerror(errno));
      code = TSDB_CODE_TSC_OUT_OF_MEMORY;
      return code;
  }
S
shenglian zhou 已提交
432 433 434 435
  pSql->pTscObj = taos;
  pSql->signature = pSql;
  pSql->fp = NULL;

436 437
  SStrToken tableToken = {.z=tableNameLowerCase, .n=(uint32_t)strlen(tableNameLowerCase), .type=TK_ID};
  tGetToken(tableNameLowerCase, &tableToken.type);
S
shenglian zhou 已提交
438 439 440 441
  // 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");
442
    tscFreeSqlObj(pSql);
S
shenglian zhou 已提交
443 444 445 446 447
    return code;
  }

  SName sname = {0};
  if ((code = tscSetTableFullName(&sname, &tableToken, pSql)) != TSDB_CODE_SUCCESS) {
448
    tscFreeSqlObj(pSql);
S
shenglian zhou 已提交
449 450 451 452 453 454 455 456 457 458 459 460 461 462
    return code;
  }
  char  fullTableName[TSDB_TABLE_FNAME_LEN] = {0};
  memset(fullTableName, 0, tListLen(fullTableName));
  tNameExtractFullName(&sname, fullTableName);
  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);
463
  taosHashGetClone(tscTableMetaMap, fullTableName, strlen(fullTableName), NULL, tableMeta);
S
shenglian zhou 已提交
464 465 466 467 468 469 470 471

  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;
472 473 474
    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 已提交
475 476 477 478 479 480 481 482
  }

  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;
483 484 485
    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 已提交
486
  }
S
shenglian zhou 已提交
487 488
  tscDebug("SML:0x%"PRIx64 "load table meta succeed. %s, columns number: %d, tag number: %d, precision: %d",
           info->id, tableName, tableMeta->tableInfo.numOfColumns, tableMeta->tableInfo.numOfTags, schema->precision);
S
shenglian zhou 已提交
489 490 491 492
  free(tableMeta); tableMeta = NULL;
  return code;
}

S
shenglian zhou 已提交
493
static int32_t modifyDBSchemas(TAOS* taos, SArray* stableSchemas, SSmlLinesInfo* info) {
S
shenglian zhou 已提交
494 495 496 497
  int32_t code = 0;
  size_t numStable = taosArrayGetSize(stableSchemas);
  for (int i = 0; i < numStable; ++i) {
    SSmlSTableSchema* pointSchema = taosArrayGet(stableSchemas, i);
S
shenglian zhou 已提交
498 499
    SSmlSTableSchema  dbSchema;
    memset(&dbSchema, 0, sizeof(SSmlSTableSchema));
S
shenglian zhou 已提交
500

S
shenglian zhou 已提交
501
    code = loadTableMeta(taos, pointSchema->sTableName, &dbSchema, info);
S
shenglian zhou 已提交
502 503 504 505 506 507 508
    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;
S
shenglian zhou 已提交
509 510
      applySchemaAction(taos, &schemaAction, info);
      code = loadTableMeta(taos, pointSchema->sTableName, &dbSchema, info);
S
Shenglian Zhou 已提交
511
      if (code != 0) {
S
shenglian zhou 已提交
512
        tscError("SML:0x%"PRIx64" reconcile point schema failed. can not create %s", info->id, pointSchema->sTableName);
513
        return code;
S
Shenglian Zhou 已提交
514 515 516 517
      } else {
        pointSchema->precision = dbSchema.precision;
        destroySmlSTableSchema(&dbSchema);
      }
S
shenglian zhou 已提交
518 519 520 521 522 523 524 525 526 527 528
    } 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;
S
shenglian zhou 已提交
529 530
        generateSchemaAction(pointTag, dbTagHash, dbSchema.tags, true, pointSchema->sTableName,
                             &schemaAction, &actionNeeded, info);
S
shenglian zhou 已提交
531
        if (actionNeeded) {
S
shenglian zhou 已提交
532
          code = applySchemaAction(taos, &schemaAction, info);
533 534 535 536
          if (code != 0) {
            destroySmlSTableSchema(&dbSchema);
            return code;
          }
S
shenglian zhou 已提交
537 538 539 540 541 542 543 544 545 546 547
        }
      }

      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;
S
shenglian zhou 已提交
548 549
        generateSchemaAction(pointCol, dbFieldHash, dbSchema.fields,false, pointSchema->sTableName,
                             &schemaAction, &actionNeeded, info);
S
shenglian zhou 已提交
550
        if (actionNeeded) {
S
shenglian zhou 已提交
551
          code = applySchemaAction(taos, &schemaAction, info);
552 553 554 555
          if (code != 0) {
            destroySmlSTableSchema(&dbSchema);
            return code;
          }
S
shenglian zhou 已提交
556 557 558 559 560
        }
      }

      pointSchema->precision = dbSchema.precision;

561
      destroySmlSTableSchema(&dbSchema);
S
shenglian zhou 已提交
562
    } else {
S
shenglian zhou 已提交
563
      tscError("SML:0x%"PRIx64" load table meta error: %s", info->id, tstrerror(code));
S
shenglian zhou 已提交
564 565 566 567 568 569
      return code;
    }
  }
  return 0;
}

S
shenglian zhou 已提交
570 571 572
static int32_t getSmlMd5ChildTableName(TAOS_SML_DATA_POINT* point, char* tableName, int* tableNameLen,
                                       SSmlLinesInfo* info) {
  tscDebug("SML:0x%"PRIx64" taos_sml_insert get child table name through md5", info->id);
573 574 575
  qsort(point->tags, point->tagNum, sizeof(TAOS_SML_KV), compareSmlColKv);

  SStringBuilder sb; memset(&sb, 0, sizeof(sb));
S
shenglian zhou 已提交
576 577 578
  char sTableName[TSDB_TABLE_NAME_LEN] = {0};
  strtolower(sTableName, point->stableName);
  taosStringBuilderAppendString(&sb, sTableName);
579 580 581
  for (int j = 0; j < point->tagNum; ++j) {
    taosStringBuilderAppendChar(&sb, ',');
    TAOS_SML_KV* tagKv = point->tags + j;
S
shenglian zhou 已提交
582 583 584
    char tagName[TSDB_COL_NAME_LEN] = {0};
    strtolower(tagName, tagKv->key);
    taosStringBuilderAppendString(&sb, tagName);
585 586 587 588 589 590 591 592 593 594
    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 已提交
595
                           "t_%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", context.digest[0],
596 597 598 599
                           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 已提交
600
  tscDebug("SML:0x%"PRIx64" child table name: %s", info->id, tableName);
601 602 603
  return 0;
}

604

S
shenglian zhou 已提交
605
static int32_t changeChildTableTagValue(TAOS* taos, const char* cTableName, const char* tagName, TAOS_BIND* bind, SSmlLinesInfo* info) {
606 607 608 609 610 611 612 613
  char sql[512];
  sprintf(sql, "alter table %s set tag %s=?", cTableName, tagName);

  int32_t code;
  TAOS_STMT* stmt = taos_stmt_init(taos);
  code = taos_stmt_prepare(stmt, sql, (unsigned long)strlen(sql));

  if (code != 0) {
S
shenglian zhou 已提交
614
    tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
615 616 617 618 619
    return code;
  }

  code = taos_stmt_bind_param(stmt, bind);
  if (code != 0) {
S
shenglian zhou 已提交
620
    tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
621 622 623 624 625
    return code;
  }

  code = taos_stmt_execute(stmt);
  if (code != 0) {
S
shenglian zhou 已提交
626
    tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
627 628 629 630 631
    return code;
  }

  code = taos_stmt_close(stmt);
  if (code != 0) {
S
shenglian zhou 已提交
632
    tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
633 634 635 636 637
    return code;
  }
  return code;
}

S
shenglian zhou 已提交
638 639
static int32_t creatChildTableIfNotExists(TAOS* taos, const char* cTableName, const char* sTableName,
                                          SArray* tagsSchema, SArray* tagsBind, SSmlLinesInfo* info) {
S
shenglian zhou 已提交
640
  size_t numTags = taosArrayGetSize(tagsSchema);
641
  char* sql = malloc(tsMaxSQLStringLen+1);
642 643 644 645
  if (sql == NULL) {
    tscError("malloc sql memory error");
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }
646
  int freeBytes = tsMaxSQLStringLen + 1;
S
shenglian zhou 已提交
647
  sprintf(sql, "create table if not exists %s using %s", cTableName, sTableName);
648

S
shenglian zhou 已提交
649 650 651 652 653 654
  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, ")");
655

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

S
shenglian zhou 已提交
658
  for (int i = 0; i < numTags; ++i) {
S
shenglian zhou 已提交
659
    snprintf(sql+strlen(sql), freeBytes-strlen(sql), "?,");
S
shenglian zhou 已提交
660
  }
S
shenglian zhou 已提交
661
  snprintf(sql + strlen(sql) - 1, freeBytes-strlen(sql)+1, ")");
662
  sql[strlen(sql)] = '\0';
S
shenglian zhou 已提交
663

S
shenglian zhou 已提交
664
  tscDebug("SML:0x%"PRIx64" create table : %s", info->id, sql);
S
Shenglian Zhou 已提交
665

S
shenglian zhou 已提交
666
  TAOS_STMT* stmt = taos_stmt_init(taos);
667 668 669 670
  if (stmt == NULL) {
    free(sql);
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }
S
shenglian zhou 已提交
671
  int32_t code;
S
shenglian zhou 已提交
672
  code = taos_stmt_prepare(stmt, sql, (unsigned long)strlen(sql));
673 674
  free(sql);

S
shenglian zhou 已提交
675
  if (code != 0) {
676
    tfree(stmt);
S
shenglian zhou 已提交
677
    tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
S
shenglian zhou 已提交
678 679 680 681 682
    return code;
  }

  code = taos_stmt_bind_param(stmt, TARRAY_GET_START(tagsBind));
  if (code != 0) {
683
    tfree(stmt);
S
shenglian zhou 已提交
684
    tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
S
shenglian zhou 已提交
685 686 687 688 689
    return code;
  }

  code = taos_stmt_execute(stmt);
  if (code != 0) {
690
    tfree(stmt);
S
shenglian zhou 已提交
691
    tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
S
shenglian zhou 已提交
692 693
    return code;
  }
S
shenglian zhou 已提交
694

695 696
  code = taos_stmt_close(stmt);
  if (code != 0) {
S
shenglian zhou 已提交
697
    tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
698 699 700
    return code;
  }
  return code;
S
shenglian zhou 已提交
701 702
}

S
shenglian zhou 已提交
703
static int32_t insertChildTableBatch(TAOS* taos,  char* cTableName, SArray* colsSchema, SArray* rowsBind, SSmlLinesInfo* info) {
S
shenglian zhou 已提交
704
  size_t numCols = taosArrayGetSize(colsSchema);
705
  char* sql = malloc(tsMaxSQLStringLen+1);
706 707 708 709 710
  if (sql == NULL) {
    tscError("malloc sql memory error");
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }

711
  int32_t freeBytes = tsMaxSQLStringLen + 1 ;
S
shenglian zhou 已提交
712
  sprintf(sql, "insert into ? (");
713

S
shenglian zhou 已提交
714 715
  for (int i = 0; i < numCols; ++i) {
    SSchema* colSchema = taosArrayGet(colsSchema, i);
S
shenglian zhou 已提交
716
    snprintf(sql+strlen(sql), freeBytes-strlen(sql), "%s,", colSchema->name);
S
shenglian zhou 已提交
717
  }
S
shenglian zhou 已提交
718
  snprintf(sql + strlen(sql)-1, freeBytes-strlen(sql)+1, ") values (");
719

S
shenglian zhou 已提交
720
  for (int i = 0; i < numCols; ++i) {
S
shenglian zhou 已提交
721
    snprintf(sql+strlen(sql), freeBytes-strlen(sql), "?,");
722
  }
S
shenglian zhou 已提交
723
  snprintf(sql + strlen(sql)-1, freeBytes-strlen(sql)+1, ")");
724
  sql[strlen(sql)] = '\0';
725

S
shenglian zhou 已提交
726
  tscDebug("SML:0x%"PRIx64" insert rows into child table %s. num of rows: %zu", info->id, cTableName, taosArrayGetSize(rowsBind));
W
wpan 已提交
727

728 729
  int32_t code = 0;
  int32_t try = 0;
S
shenglian zhou 已提交
730

W
wpan 已提交
731
  TAOS_STMT* stmt = taos_stmt_init(taos);
732
  if (stmt == NULL) {
733
    tfree(sql);
734 735
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }
S
shenglian zhou 已提交
736
  code = taos_stmt_prepare(stmt, sql, (unsigned long)strlen(sql));
737
  tfree(sql);
738

W
wpan 已提交
739
  if (code != 0) {
740
    tfree(stmt);
S
shenglian zhou 已提交
741
    tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
W
wpan 已提交
742 743 744 745
    return code;
  }

  do {
746
    code = taos_stmt_set_tbname(stmt, cTableName);
747
    if (code != 0) {
748
      tfree(stmt);
S
shenglian zhou 已提交
749
      tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
750 751
      return code;
    }
752

753 754 755 756 757
    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) {
758
        tfree(stmt);
S
shenglian zhou 已提交
759
        tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
760 761 762 763
        return code;
      }
      code = taos_stmt_add_batch(stmt);
      if (code != 0) {
764
        tfree(stmt);
S
shenglian zhou 已提交
765
        tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
766 767 768 769 770 771
        return code;
      }
    }

    code = taos_stmt_execute(stmt);
    if (code != 0) {
S
shenglian zhou 已提交
772
      tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
773 774
    }
  } while (code == TSDB_CODE_TDB_TABLE_RECONFIGURE && try++ < TSDB_MAX_REPLICA);
S
shenglian zhou 已提交
775

W
wpan 已提交
776
  if (code != 0) {
S
shenglian zhou 已提交
777
    tscError("SML:0x%"PRIx64" %s", info->id, taos_stmt_errstr(stmt));
W
wpan 已提交
778 779 780 781 782
    taos_stmt_close(stmt);
  } else {
    taos_stmt_close(stmt);
  }

S
shenglian zhou 已提交
783
  return code;
S
shenglian zhou 已提交
784 785
}

786
static int32_t arrangePointsByChildTableName(TAOS_SML_DATA_POINT* points, int numPoints,
S
shenglian zhou 已提交
787
                                             SHashObj* cname2points, SArray* stableSchemas, SSmlLinesInfo* info) {
S
shenglian zhou 已提交
788 789 790 791
  for (int32_t i = 0; i < numPoints; ++i) {
    TAOS_SML_DATA_POINT * point = points + i;
    if (!point->childTableName) {
      char childTableName[TSDB_TABLE_NAME_LEN];
792
      int32_t tableNameLen = TSDB_TABLE_NAME_LEN;
S
shenglian zhou 已提交
793
      getSmlMd5ChildTableName(point, childTableName, &tableNameLen, info);
S
shenglian zhou 已提交
794 795 796 797
      point->childTableName = calloc(1, tableNameLen+1);
      strncpy(point->childTableName, childTableName, tableNameLen);
      point->childTableName[tableNameLen] = '\0';
    }
S
shenglian zhou 已提交
798

799 800
    SSmlSTableSchema* stableSchema = taosArrayGet(stableSchemas, point->schemaIdx);

S
shenglian zhou 已提交
801 802 803 804
    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);
805
        ts = convertTimePrecision(ts, TSDB_TIME_PRECISION_NANO, stableSchema->precision);
S
shenglian zhou 已提交
806 807 808 809 810 811 812 813
        *(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);
814
        ts = convertTimePrecision(ts, TSDB_TIME_PRECISION_NANO, stableSchema->precision);
S
shenglian zhou 已提交
815 816 817 818
        *(int64_t*)(kv->value) = ts;
      }
    }

S
shenglian zhou 已提交
819 820 821 822 823 824 825 826
    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);
    }
827
    taosArrayPush(cTablePoints, &point);
828 829
  }

S
shenglian zhou 已提交
830 831 832
  return 0;
}

833
static int32_t applyChildTableTags(TAOS* taos, char* cTableName, char* sTableName,
S
shenglian zhou 已提交
834
                                   SSmlSTableSchema* sTableSchema, SArray* cTablePoints, SSmlLinesInfo* info) {
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
  size_t numTags = taosArrayGetSize(sTableSchema->tags);
  size_t rows = taosArrayGetSize(cTablePoints);

  TAOS_SML_KV* tagKVs[TSDB_MAX_TAGS] = {0};
  for (int i= 0; i < rows; ++i) {
    TAOS_SML_DATA_POINT * pDataPoint = taosArrayGetP(cTablePoints, i);
    for (int j = 0; j < pDataPoint->tagNum; ++j) {
      TAOS_SML_KV* kv = pDataPoint->tags + j;
      tagKVs[kv->fieldSchemaIdx] = kv;
    }
  }

  int32_t notNullTagsIndices[TSDB_MAX_TAGS] = {0};
  int32_t numNotNullTags = 0;
  for (int32_t i = 0; i < numTags; ++i) {
    if (tagKVs[i] != NULL) {
      notNullTagsIndices[numNotNullTags] = i;
      ++numNotNullTags;
    }
  }
  
  SArray* tagBinds = taosArrayInit(numTags, sizeof(TAOS_BIND));
  taosArraySetSize(tagBinds, numTags);
  int isNullColBind = TSDB_TRUE;
  for (int j = 0; j < numTags; ++j) {
    TAOS_BIND* bind = taosArrayGet(tagBinds, j);
    bind->is_null = &isNullColBind;
  }
  for (int j = 0; j < numTags; ++j) {
    if (tagKVs[j] == NULL) continue;
    TAOS_SML_KV* kv =  tagKVs[j];
    TAOS_BIND* bind = taosArrayGet(tagBinds, kv->fieldSchemaIdx);
    bind->buffer_type = kv->type;
    bind->length = malloc(sizeof(uintptr_t*));
    *bind->length = kv->length;
    bind->buffer = kv->value;
    bind->is_null = NULL;
  }

  // select tag1,tag2,... from stable where tbname in (ctable)
S
shenglian zhou 已提交
875 876 877
  char* sql = malloc(tsMaxSQLStringLen+1);
  int freeBytes = tsMaxSQLStringLen + 1;
  snprintf(sql, freeBytes, "select tbname, ");
878
  for (int i = 0; i < numNotNullTags ; ++i)  {
S
shenglian zhou 已提交
879
    snprintf(sql + strlen(sql), freeBytes-strlen(sql), "%s,", tagKVs[notNullTagsIndices[i]]->key);
880
  }
S
shenglian zhou 已提交
881
  snprintf(sql + strlen(sql) - 1, freeBytes - strlen(sql) + 1,
882
           " from %s where tbname in (\'%s\')", sTableName, cTableName);
S
shenglian zhou 已提交
883 884
  sql[strlen(sql)] = '\0';

885
  TAOS_RES* result = taos_query(taos, sql);
S
shenglian zhou 已提交
886 887
  free(sql);

888 889
  int32_t code = taos_errno(result);
  if (code != 0) {
S
shenglian zhou 已提交
890
    tscError("SML:0x%"PRIx64" get child table %s tags failed. error string %s", info->id, cTableName, taos_errstr(result));
891 892 893 894 895 896 897 898 899 900
    goto cleanup;
  }

  // check tag value and set tag values if different
  TAOS_ROW row = taos_fetch_row(result);
  if (row != NULL) {
    int numFields = taos_field_count(result);
    TAOS_FIELD* fields = taos_fetch_fields(result);
    int* lengths = taos_fetch_lengths(result);
    for (int i = 1; i < numFields; ++i) {
S
shenglian zhou 已提交
901
      uint8_t dbType = fields[i].type;
902 903 904 905
      int32_t length = lengths[i];
      char* val = row[i];

      TAOS_SML_KV* tagKV = tagKVs[notNullTagsIndices[i-1]];
S
shenglian zhou 已提交
906
      if (tagKV->type != dbType) {
S
shenglian zhou 已提交
907 908
        tscError("SML:0x%"PRIx64" child table %s tag %s type mismatch. point type : %d, db type : %d",
                 info->id, cTableName, tagKV->key, tagKV->type, dbType);
909 910 911
        return TSDB_CODE_TSC_INVALID_VALUE;
      }

S
shenglian zhou 已提交
912 913 914
      assert(tagKV->value);

      if (val == NULL || length != tagKV->length || memcmp(tagKV->value, val, length) != 0) {
915
        TAOS_BIND* bind = taosArrayGet(tagBinds, tagKV->fieldSchemaIdx);
S
shenglian zhou 已提交
916
        code = changeChildTableTagValue(taos, cTableName, tagKV->key, bind, info);
917
        if (code != 0) {
S
shenglian zhou 已提交
918
          tscError("SML:0x%"PRIx64" change child table tag failed. table name %s, tag %s", info->id, cTableName, tagKV->key);
919 920 921 922
          goto cleanup;
        }
      }
    }
S
shenglian zhou 已提交
923
    tscDebug("SML:0x%"PRIx64" successfully applied point tags. child table: %s", info->id, cTableName);
924
  } else {
S
shenglian zhou 已提交
925
    code = creatChildTableIfNotExists(taos, cTableName, sTableName, sTableSchema->tags, tagBinds, info);
926 927 928 929 930 931
    if (code != 0) {
      goto cleanup;
    }
  }

cleanup:
S
shenglian zhou 已提交
932
  taos_free_result(result);
933 934 935 936 937 938 939 940
  for (int i = 0; i < taosArrayGetSize(tagBinds); ++i) {
    TAOS_BIND* bind = taosArrayGet(tagBinds, i);
    free(bind->length);
  }
  taosArrayDestroy(tagBinds);
  return code;
}

S
shenglian zhou 已提交
941 942
static int32_t applyChildTableFields(TAOS* taos, SSmlSTableSchema* sTableSchema, char* cTableName,
                                     SArray* cTablePoints, SSmlLinesInfo* info) {
943 944
  int32_t code = TSDB_CODE_SUCCESS;

945 946 947
  size_t numCols = taosArrayGetSize(sTableSchema->fields);
  size_t rows = taosArrayGetSize(cTablePoints);
  SArray* rowsBind = taosArrayInit(rows, POINTER_BYTES);
S
shenglian zhou 已提交
948

949 950
  for (int i = 0; i < rows; ++i) {
    TAOS_SML_DATA_POINT* point = taosArrayGetP(cTablePoints, i);
951

952 953
    TAOS_BIND* colBinds = calloc(numCols, sizeof(TAOS_BIND));
    if (colBinds == NULL) {
S
shenglian zhou 已提交
954 955
      tscError("SML:0x%"PRIx64" taos_sml_insert insert points, failed to allocated memory for TAOS_BIND, "
               "num of rows: %zu, num of cols: %zu", info->id, rows, numCols);
956 957
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
    }
958

959 960 961
    int isNullColBind = TSDB_TRUE;
    for (int j = 0; j < numCols; ++j) {
      TAOS_BIND* bind = colBinds + j;
962 963
      bind->is_null = &isNullColBind;
    }
964 965 966
    for (int j = 0; j < point->fieldNum; ++j) {
      TAOS_SML_KV* kv = point->fields + j;
      TAOS_BIND* bind = colBinds + kv->fieldSchemaIdx;
967
      bind->buffer_type = kv->type;
968 969
      bind->length = malloc(sizeof(uintptr_t*));
      *bind->length = kv->length;
970 971 972
      bind->buffer = kv->value;
      bind->is_null = NULL;
    }
973 974
    taosArrayPush(rowsBind, &colBinds);
  }
S
shenglian zhou 已提交
975

S
shenglian zhou 已提交
976
  code = insertChildTableBatch(taos, cTableName, sTableSchema->fields, rowsBind, info);
977
  if (code != 0) {
S
shenglian zhou 已提交
978
    tscError("SML:0x%"PRIx64" insert into child table %s failed. error %s", info->id, cTableName, tstrerror(code));
979
  }
S
shenglian zhou 已提交
980

981 982 983 984 985
  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 已提交
986
    }
987 988 989 990 991
    free(colBinds);
  }
  taosArrayDestroy(rowsBind);
  return code;
}
S
shenglian zhou 已提交
992

S
shenglian zhou 已提交
993
static int32_t applyDataPoints(TAOS* taos, TAOS_SML_DATA_POINT* points, int32_t numPoints, SArray* stableSchemas, SSmlLinesInfo* info) {
994
  int32_t code = TSDB_CODE_SUCCESS;
995

996
  SHashObj* cname2points = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, false);
S
shenglian zhou 已提交
997
  arrangePointsByChildTableName(points, numPoints, cname2points, stableSchemas, info);
998 999 1000 1001 1002

  SArray** pCTablePoints = taosHashIterate(cname2points, NULL);
  while (pCTablePoints) {
    SArray* cTablePoints = *pCTablePoints;

S
shenglian zhou 已提交
1003

1004 1005
    TAOS_SML_DATA_POINT* point = taosArrayGetP(cTablePoints, 0);
    SSmlSTableSchema*    sTableSchema = taosArrayGet(stableSchemas, point->schemaIdx);
S
shenglian zhou 已提交
1006 1007 1008

    tscDebug("SML:0x%"PRIx64" apply child table tags. child table: %s", info->id, point->childTableName);
    code = applyChildTableTags(taos, point->childTableName, point->stableName, sTableSchema, cTablePoints, info);
1009 1010 1011
    if (code != 0) {
      tscError("apply child table tags failed. child table %s, error %s", point->childTableName, tstrerror(code));
      goto cleanup;
S
shenglian zhou 已提交
1012
    }
S
shenglian zhou 已提交
1013 1014 1015

    tscDebug("SML:0x%"PRIx64" apply child table points. child table: %s", info->id, point->childTableName);
    code = applyChildTableFields(taos, sTableSchema, point->childTableName, cTablePoints, info);
1016
    if (code != 0) {
1017 1018
      tscError("Apply child table fields failed. child table %s, error %s", point->childTableName, tstrerror(code));
      goto cleanup;
1019
    }
1020

S
shenglian zhou 已提交
1021
    tscDebug("SML:0x%"PRIx64" successfully applied data points of child table %s", info->id, point->childTableName);
S
shenglian zhou 已提交
1022

S
shenglian zhou 已提交
1023
    pCTablePoints = taosHashIterate(cname2points, pCTablePoints);
1024
  }
S
shenglian zhou 已提交
1025

1026 1027 1028 1029 1030
cleanup:
  pCTablePoints = taosHashIterate(cname2points, NULL);
  while (pCTablePoints) {
    SArray* pPoints = *pCTablePoints;
    taosArrayDestroy(pPoints);
S
shenglian zhou 已提交
1031
    pCTablePoints = taosHashIterate(cname2points, pCTablePoints);
1032
  }
S
shenglian zhou 已提交
1033
  taosHashCleanup(cname2points);
1034
  return code;
S
shenglian zhou 已提交
1035
}
1036

S
shenglian zhou 已提交
1037 1038
int taos_sml_insert(TAOS* taos, TAOS_SML_DATA_POINT* points, int numPoint, SSmlLinesInfo* info) {
  tscDebug("SML:0x%"PRIx64" taos_sml_insert. number of points: %d", info->id, numPoint);
S
Shenglian Zhou 已提交
1039

S
shenglian zhou 已提交
1040 1041
  int32_t code = TSDB_CODE_SUCCESS;

S
shenglian zhou 已提交
1042
  tscDebug("SML:0x%"PRIx64" build data point schemas", info->id);
S
shenglian zhou 已提交
1043
  SArray* stableSchemas = taosArrayInit(32, sizeof(SSmlSTableSchema)); // SArray<STableColumnsSchema>
S
shenglian zhou 已提交
1044
  code = buildDataPointSchemas(points, numPoint, stableSchemas, info);
S
shenglian zhou 已提交
1045
  if (code != 0) {
S
shenglian zhou 已提交
1046
    tscError("SML:0x%"PRIx64" error building data point schemas : %s", info->id, tstrerror(code));
S
shenglian zhou 已提交
1047 1048 1049
    goto clean_up;
  }

S
shenglian zhou 已提交
1050 1051
  tscDebug("SML:0x%"PRIx64" modify db schemas", info->id);
  code = modifyDBSchemas(taos, stableSchemas, info);
S
shenglian zhou 已提交
1052
  if (code != 0) {
S
shenglian zhou 已提交
1053
    tscError("SML:0x%"PRIx64" error change db schema : %s", info->id, tstrerror(code));
S
shenglian zhou 已提交
1054 1055
    goto clean_up;
  }
S
shenglian zhou 已提交
1056

S
shenglian zhou 已提交
1057 1058
  tscDebug("SML:0x%"PRIx64" apply data points", info->id);
  code = applyDataPoints(taos, points, numPoint, stableSchemas, info);
S
shenglian zhou 已提交
1059
  if (code != 0) {
S
shenglian zhou 已提交
1060
    tscError("SML:0x%"PRIx64" error apply data points : %s", info->id, tstrerror(code));
S
shenglian zhou 已提交
1061 1062 1063
  }

clean_up:
S
shenglian zhou 已提交
1064 1065 1066 1067
  for (int i = 0; i < taosArrayGetSize(stableSchemas); ++i) {
    SSmlSTableSchema* schema = taosArrayGet(stableSchemas, i);
    taosArrayDestroy(schema->fields);
    taosArrayDestroy(schema->tags);
1068
  }
S
shenglian zhou 已提交
1069
  taosArrayDestroy(stableSchemas);
1070 1071
  return code;
}
S
shenglian zhou 已提交
1072

1073 1074
//=========================================================================

1075 1076 1077 1078 1079
/*        Field                          Escape charaters
    1: measurement                        Comma,Space
    2: tag_key, tag_value, field_key  Comma,Equal Sign,Space
    3: field_value                    Double quote,Backslash
*/
1080
static void escapeSpecialCharacter(uint8_t field, const char **pos) {
1081 1082 1083
  const char *cur = *pos;
  if (*cur != '\\') {
    return;
1084
  }
1085 1086 1087 1088 1089 1090
  switch (field) {
    case 1:
      switch (*(cur + 1)) {
        case ',':
        case ' ':
          cur++;
1091
          break;
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118
        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;
1119
  }
1120
  *pos = cur;
1121
}
1122

1123
static bool isValidInteger(char *str) {
1124 1125
  char *c = str;
  if (*c != '+' && *c != '-' && !isdigit(*c)) {
1126 1127
    return false;
  }
1128 1129 1130 1131 1132 1133
  c++;
  while (*c != '\0') {
    if (!isdigit(*c)) {
      return false;
    }
    c++;
1134
  }
1135
  return true;
1136
}
1137

1138
static bool isValidFloat(char *str) {
1139 1140 1141 1142 1143 1144 1145
  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)) {
1146 1147
    return false;
  }
1148 1149
  if (*c == '.' && isdigit(*(c + 1))) {
    has_dot = 1;
1150
  }
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
  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;
1192
}
1193

1194
static bool isTinyInt(char *pVal, uint16_t len) {
1195 1196 1197 1198
  if (len <= 2) {
    return false;
  }
  if (!strcmp(&pVal[len - 2], "i8")) {
1199
    //printf("Type is int8(%s)\n", pVal);
1200 1201 1202 1203
    return true;
  }
  return false;
}
1204

1205
static bool isTinyUint(char *pVal, uint16_t len) {
1206 1207 1208 1209 1210
  if (len <= 2) {
    return false;
  }
  if (pVal[0] == '-') {
    return false;
1211
  }
1212
  if (!strcmp(&pVal[len - 2], "u8")) {
1213
    //printf("Type is uint8(%s)\n", pVal);
1214 1215 1216
    return true;
  }
  return false;
1217 1218
}

1219
static bool isSmallInt(char *pVal, uint16_t len) {
1220 1221 1222 1223
  if (len <= 3) {
    return false;
  }
  if (!strcmp(&pVal[len - 3], "i16")) {
1224
    //printf("Type is int16(%s)\n", pVal);
1225
    return true;
1226
  }
1227
  return false;
1228 1229
}

1230
static bool isSmallUint(char *pVal, uint16_t len) {
1231 1232
  if (len <= 3) {
    return false;
1233
  }
1234 1235 1236 1237
  if (pVal[0] == '-') {
    return false;
  }
  if (strcmp(&pVal[len - 3], "u16") == 0) {
1238
    //printf("Type is uint16(%s)\n", pVal);
1239 1240 1241
    return true;
  }
  return false;
1242 1243
}

1244
static bool isInt(char *pVal, uint16_t len) {
1245 1246
  if (len <= 3) {
    return false;
1247
  }
1248
  if (strcmp(&pVal[len - 3], "i32") == 0) {
1249
    //printf("Type is int32(%s)\n", pVal);
1250 1251 1252
    return true;
  }
  return false;
1253 1254
}

1255
static bool isUint(char *pVal, uint16_t len) {
1256 1257 1258 1259 1260 1261 1262
  if (len <= 3) {
    return false;
  }
  if (pVal[0] == '-') {
    return false;
  }
  if (strcmp(&pVal[len - 3], "u32") == 0) {
1263
    //printf("Type is uint32(%s)\n", pVal);
1264 1265 1266
    return true;
  }
  return false;
1267 1268
}

1269
static bool isBigInt(char *pVal, uint16_t len) {
1270 1271
  if (len <= 3) {
    return false;
1272
  }
1273
  if (strcmp(&pVal[len - 3], "i64") == 0) {
1274
    //printf("Type is int64(%s)\n", pVal);
1275 1276 1277
    return true;
  }
  return false;
1278 1279
}

1280
static bool isBigUint(char *pVal, uint16_t len) {
1281 1282 1283 1284 1285
  if (len <= 3) {
    return false;
  }
  if (pVal[0] == '-') {
    return false;
1286
  }
1287
  if (strcmp(&pVal[len - 3], "u64") == 0) {
1288
    //printf("Type is uint64(%s)\n", pVal);
1289 1290 1291
    return true;
  }
  return false;
1292 1293
}

1294
static bool isFloat(char *pVal, uint16_t len) {
1295 1296 1297 1298
  if (len <= 3) {
    return false;
  }
  if (strcmp(&pVal[len - 3], "f32") == 0) {
1299
    //printf("Type is float(%s)\n", pVal);
1300 1301 1302
    return true;
  }
  return false;
1303 1304
}

1305
static bool isDouble(char *pVal, uint16_t len) {
1306 1307 1308 1309
  if (len <= 3) {
    return false;
  }
  if (strcmp(&pVal[len - 3], "f64") == 0) {
1310
    //printf("Type is double(%s)\n", pVal);
1311 1312 1313 1314 1315
    return true;
  }
  return false;
}

1316
static bool isBool(char *pVal, uint16_t len, bool *bVal) {
1317 1318 1319
  if ((len == 1) &&
      (pVal[len - 1] == 't' ||
       pVal[len - 1] == 'T')) {
1320 1321
    //printf("Type is bool(%c)\n", pVal[len - 1]);
    *bVal = true;
1322
    return true;
1323
  }
1324 1325 1326 1327

  if ((len == 1) &&
      (pVal[len - 1] == 'f' ||
       pVal[len - 1] == 'F')) {
1328 1329
    //printf("Type is bool(%c)\n", pVal[len - 1]);
    *bVal = false;
1330
    return true;
1331
  }
1332 1333 1334 1335 1336

  if((len == 4) &&
     (!strcmp(&pVal[len - 4], "true") ||
      !strcmp(&pVal[len - 4], "True") ||
      !strcmp(&pVal[len - 4], "TRUE"))) {
1337 1338
    //printf("Type is bool(%s)\n", &pVal[len - 4]);
    *bVal = true;
1339 1340 1341 1342 1343 1344
    return true;
  }
  if((len == 5) &&
     (!strcmp(&pVal[len - 5], "false") ||
      !strcmp(&pVal[len - 5], "False") ||
      !strcmp(&pVal[len - 5], "FALSE"))) {
1345 1346
    //printf("Type is bool(%s)\n", &pVal[len - 5]);
    *bVal = false;
1347 1348 1349
    return true;
  }
  return false;
1350 1351
}

1352
static bool isBinary(char *pVal, uint16_t len) {
1353 1354 1355 1356 1357 1358
  //binary: "abc"
  if (len < 2) {
    return false;
  }
  //binary
  if (pVal[0] == '"' && pVal[len - 1] == '"') {
1359
    //printf("Type is binary(%s)\n", pVal);
1360 1361 1362 1363
    return true;
  }
  return false;
}
1364

1365
static bool isNchar(char *pVal, uint16_t len) {
1366 1367
  //nchar: L"abc"
  if (len < 3) {
1368 1369
    return false;
  }
1370
  if (pVal[0] == 'L' && pVal[1] == '"' && pVal[len - 1] == '"') {
1371
    //printf("Type is nchar(%s)\n", pVal);
1372
    return true;
1373
  }
1374 1375 1376
  return false;
}

1377
static bool isTimeStamp(char *pVal, uint16_t len, SMLTimeStampType *tsType) {
1378 1379 1380 1381 1382
  if (len == 0) {
    return true;
  }
  if ((len == 1) && pVal[0] == '0') {
    *tsType = SML_TIME_STAMP_NOW;
1383
    //printf("Type is timestamp(%s)\n", pVal);
1384 1385 1386 1387 1388 1389 1390 1391
    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;
1392
    //printf("Type is timestamp(%s)\n", pVal);
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
    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;
1409
          break;
1410
        } else {
1411 1412 1413
          return false;
        }
    }
1414
    //printf("Type is timestamp(%s)\n", pVal);
1415 1416 1417 1418
    return true;
  }
  return false;
}
1419

1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
static bool convertStrToNumber(TAOS_SML_KV *pVal, char*str) {
  errno = 0;
  uint8_t type = pVal->type;
  int16_t length = pVal->length;
  int64_t val_s;
  uint64_t val_u;
  double val_d;

  if (IS_FLOAT_TYPE(type)) {
    val_d = strtod(str, NULL);
  } else {
    if (IS_SIGNED_NUMERIC_TYPE(type)) {
      val_s = strtoll(str, NULL, 10);
    } else {
      val_u = strtoull(str, NULL, 10);
    }
  }

  if (errno == ERANGE) {
1439
    tscError("Converted number out of range");
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
    return false;
  }

  switch (type) {
    case TSDB_DATA_TYPE_TINYINT:
      if (!IS_VALID_TINYINT(val_s)) {
        return false;
      }
      pVal->value = calloc(length, 1);
      *(int8_t *)(pVal->value) = (int8_t)val_s;
      break;
    case TSDB_DATA_TYPE_UTINYINT:
      if (!IS_VALID_UTINYINT(val_u)) {
        return false;
      }
      pVal->value = calloc(length, 1);
      *(uint8_t *)(pVal->value) = (uint8_t)val_u;
      break;
    case TSDB_DATA_TYPE_SMALLINT:
      if (!IS_VALID_SMALLINT(val_s)) {
        return false;
      }
      pVal->value = calloc(length, 1);
      *(int16_t *)(pVal->value) = (int16_t)val_s;
      break;
    case TSDB_DATA_TYPE_USMALLINT:
      if (!IS_VALID_USMALLINT(val_u)) {
        return false;
      }
      pVal->value = calloc(length, 1);
      *(uint16_t *)(pVal->value) = (uint16_t)val_u;
      break;
    case TSDB_DATA_TYPE_INT:
      if (!IS_VALID_INT(val_s)) {
        return false;
      }
      pVal->value = calloc(length, 1);
      *(int32_t *)(pVal->value) = (int32_t)val_s;
      break;
    case TSDB_DATA_TYPE_UINT:
      if (!IS_VALID_UINT(val_u)) {
        return false;
      }
      pVal->value = calloc(length, 1);
      *(uint32_t *)(pVal->value) = (uint32_t)val_u;
      break;
    case TSDB_DATA_TYPE_BIGINT:
      if (!IS_VALID_BIGINT(val_s)) {
        return false;
      }
      pVal->value = calloc(length, 1);
      *(int64_t *)(pVal->value) = (int64_t)val_s;
      break;
    case TSDB_DATA_TYPE_UBIGINT:
      if (!IS_VALID_UBIGINT(val_u)) {
        return false;
      }
      pVal->value = calloc(length, 1);
      *(uint64_t *)(pVal->value) = (uint64_t)val_u;
      break;
    case TSDB_DATA_TYPE_FLOAT:
      if (!IS_VALID_FLOAT(val_d)) {
        return false;
      }
      pVal->value = calloc(length, 1);
      *(float *)(pVal->value) = (float)val_d;
      break;
    case TSDB_DATA_TYPE_DOUBLE:
      if (!IS_VALID_DOUBLE(val_d)) {
        return false;
      }
      pVal->value = calloc(length, 1);
      *(double *)(pVal->value) = (double)val_d;
      break;
    default:
      return false;
  }
  return true;
}
1519
//len does not include '\0' from value.
1520 1521
static bool convertSmlValueType(TAOS_SML_KV *pVal, char *value,
                                uint16_t len) {
1522 1523 1524
  if (len <= 0) {
    return false;
  }
G
Ganlin Zhao 已提交
1525

1526
  //integer number
1527
  if (isTinyInt(value, len)) {
1528 1529 1530
    pVal->type = TSDB_DATA_TYPE_TINYINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 2] = '\0';
1531
    if (!isValidInteger(value) || !convertStrToNumber(pVal, value)) {
1532
      return false;
1533 1534 1535
    }
    return true;
  }
1536
  if (isTinyUint(value, len)) {
1537 1538 1539
    pVal->type = TSDB_DATA_TYPE_UTINYINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 2] = '\0';
1540
    if (!isValidInteger(value) || !convertStrToNumber(pVal, value)) {
1541 1542 1543 1544
      return false;
    }
    return true;
  }
1545
  if (isSmallInt(value, len)) {
1546 1547 1548
    pVal->type = TSDB_DATA_TYPE_SMALLINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1549
    if (!isValidInteger(value) || !convertStrToNumber(pVal, value)) {
1550 1551 1552 1553
      return false;
    }
    return true;
  }
1554
  if (isSmallUint(value, len)) {
1555 1556 1557
    pVal->type = TSDB_DATA_TYPE_USMALLINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1558
    if (!isValidInteger(value) || !convertStrToNumber(pVal, value)) {
1559 1560 1561 1562
      return false;
    }
    return true;
  }
1563
  if (isInt(value, len)) {
1564 1565 1566
    pVal->type = TSDB_DATA_TYPE_INT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1567
    if (!isValidInteger(value) || !convertStrToNumber(pVal, value)) {
1568 1569 1570 1571
      return false;
    }
    return true;
  }
1572
  if (isUint(value, len)) {
1573 1574 1575
    pVal->type = TSDB_DATA_TYPE_UINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1576
    if (!isValidInteger(value) || !convertStrToNumber(pVal, value)) {
1577 1578 1579 1580
      return false;
    }
    return true;
  }
1581
  if (isBigInt(value, len)) {
1582 1583 1584
    pVal->type = TSDB_DATA_TYPE_BIGINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1585
    if (!isValidInteger(value) || !convertStrToNumber(pVal, value)) {
1586 1587 1588 1589
      return false;
    }
    return true;
  }
1590
  if (isBigUint(value, len)) {
1591 1592 1593
    pVal->type = TSDB_DATA_TYPE_UBIGINT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1594
    if (!isValidInteger(value) || !convertStrToNumber(pVal, value)) {
1595 1596 1597 1598
      return false;
    }
    return true;
  }
1599 1600 1601 1602 1603
  //floating number
  if (isFloat(value, len)) {
    pVal->type = TSDB_DATA_TYPE_FLOAT;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1604
    if (!isValidFloat(value) || !convertStrToNumber(pVal, value)) {
1605 1606 1607 1608 1609 1610 1611 1612
      return false;
    }
    return true;
  }
  if (isDouble(value, len)) {
    pVal->type = TSDB_DATA_TYPE_DOUBLE;
    pVal->length = (int16_t)tDataTypes[pVal->type].bytes;
    value[len - 3] = '\0';
1613
    if (!isValidFloat(value) || !convertStrToNumber(pVal, value)) {
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
      return false;
    }
    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 已提交
1645 1646 1647 1648
  //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;
1649 1650 1651
    if (!convertStrToNumber(pVal, value)) {
      return false;
    }
G
Ganlin Zhao 已提交
1652 1653
    return true;
  }
1654
  return false;
1655
}
1656

1657 1658
static int32_t getTimeStampValue(char *value, uint16_t len,
                                 SMLTimeStampType type, int64_t *ts) {
1659 1660 1661 1662 1663

  if (len >= 2) {
    for (int i = 0; i < len - 2; ++i) {
      if(!isdigit(value[i])) {
        return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
1664
      }
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677
    }
  }
  //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: {
1678
      *ts = taosGetTimestampNs();
1679
      break;
1680 1681
    }
    case SML_TIME_STAMP_SECONDS: {
1682
      *ts = (int64_t)(*ts * 1e9);
1683
      break;
1684 1685
    }
    case SML_TIME_STAMP_MILLI_SECONDS: {
1686
      *ts = convertTimePrecision(*ts, TSDB_TIME_PRECISION_MILLI, TSDB_TIME_PRECISION_NANO);
1687
      break;
1688 1689
    }
    case SML_TIME_STAMP_MICRO_SECONDS: {
1690
      *ts = convertTimePrecision(*ts, TSDB_TIME_PRECISION_MICRO, TSDB_TIME_PRECISION_NANO);
1691
      break;
1692 1693
    }
    case SML_TIME_STAMP_NANO_SECONDS: {
1694
      *ts = *ts * 1;
1695 1696 1697 1698 1699
      break;
    }
    default: {
      return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
    }
1700
  }
1701
  return TSDB_CODE_SUCCESS;
1702 1703
}

1704 1705
static int32_t convertSmlTimeStamp(TAOS_SML_KV *pVal, char *value,
                                   uint16_t len) {
1706 1707 1708
  int32_t ret;
  SMLTimeStampType type;
  int64_t tsVal;
1709

1710
  if (!isTimeStamp(value, len, &type)) {
1711
    return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
1712 1713
  }

1714
  ret = getTimeStampValue(value, len, type, &tsVal);
1715 1716 1717
  if (ret) {
    return ret;
  }
1718
  tscDebug("Timestamp after conversion:%"PRId64, tsVal);
1719 1720 1721 1722 1723 1724 1725 1726

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

1727
static int32_t parseSmlTimeStamp(TAOS_SML_KV **pTS, const char **index) {
1728
  const char *start, *cur;
1729 1730 1731
  int32_t ret = TSDB_CODE_SUCCESS;
  int len = 0;
  char key[] = "_ts";
1732
  char *value = NULL;
1733

1734
  start = cur = *index;
1735
  *pTS = calloc(1, sizeof(TAOS_SML_KV));
1736

1737
  while(*cur != '\0') {
1738 1739 1740 1741
    cur++;
    len++;
  }

1742
  if (len > 0) {
1743
    value = calloc(len + 1, 1);
1744 1745 1746 1747 1748
    memcpy(value, start, len);
  }

  ret = convertSmlTimeStamp(*pTS, value, len);
  if (ret) {
1749
    free(value);
1750 1751
    free(*pTS);
    return ret;
1752
  }
1753
  free(value);
1754

1755 1756 1757
  (*pTS)->key = calloc(sizeof(key), 1);
  memcpy((*pTS)->key, key, sizeof(key));
  return ret;
1758
}
1759

1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784
static bool checkDuplicateKey(char *key, SHashObj *pHash) {
  char *val = NULL;
  char *cur = key;
  char keyLower[TSDB_COL_NAME_LEN];
  size_t keyLen = 0;
  while(*cur != '\0') {
    keyLower[keyLen] = tolower(*cur);
    keyLen++;
    cur++;
  }
  keyLower[keyLen] = '\0';

  val = taosHashGet(pHash, keyLower, keyLen);
  if (val) {
    tscError("Duplicate key:%s", keyLower);
    return true;
  }

  uint8_t dummy_val = 0;
  taosHashPut(pHash, keyLower, strlen(key), &dummy_val, sizeof(uint8_t));

  return false;
}

static int32_t parseSmlKey(TAOS_SML_KV *pKV, const char **index, SHashObj *pHash) {
1785
  const char *cur = *index;
1786
  char key[TSDB_COL_NAME_LEN + 1];  // +1 to avoid key[len] over write
1787 1788
  uint16_t len = 0;

G
Ganlin Zhao 已提交
1789 1790 1791
  //key field cannot start with digit
  if (isdigit(*cur)) {
    tscError("Tag key cannnot start with digit\n");
1792
    return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
1793 1794 1795
  }
  while (*cur != '\0') {
    if (len > TSDB_COL_NAME_LEN) {
1796
      tscDebug("Key field cannot exceeds 65 characters");
1797
      return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
1798 1799 1800 1801 1802 1803 1804
    }
    //unescaped '=' identifies a tag key
    if (*cur == '=' && *(cur - 1) != '\\') {
      break;
    }
    //Escape special character
    if (*cur == '\\') {
1805
      escapeSpecialCharacter(2, &cur);
1806
    }
1807 1808 1809 1810 1811
    key[len] = *cur;
    cur++;
    len++;
  }
  key[len] = '\0';
1812

1813 1814 1815 1816
  if (checkDuplicateKey(key, pHash)) {
    return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
  }

1817 1818
  pKV->key = calloc(len + 1, 1);
  memcpy(pKV->key, key, len + 1);
G
Ganlin Zhao 已提交
1819
  //tscDebug("Key:%s|len:%d", pKV->key, len);
1820
  *index = cur + 1;
1821
  return TSDB_CODE_SUCCESS;
1822
}
1823

1824

1825 1826
static bool parseSmlValue(TAOS_SML_KV *pKV, const char **index,
                          bool *is_last_kv) {
1827 1828
  const char *start, *cur;
  char *value = NULL;
1829
  uint16_t len = 0;
1830 1831
  start = cur = *index;

1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842
  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);
    }
1843 1844 1845
    cur++;
    len++;
  }
1846

1847 1848 1849 1850 1851 1852
  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);
1853
    pKV->key = NULL;
1854
    free(value);
1855
    return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
1856
  }
1857
  free(value);
1858

1859 1860 1861 1862 1863 1864 1865 1866 1867
  *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;

1868 1869 1870 1871
  pSml->stableName = calloc(TSDB_TABLE_NAME_LEN + 1, 1);    // +1 to avoid 1772 line over write
  if (pSml->stableName == NULL){
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }
G
Ganlin Zhao 已提交
1872 1873
  if (isdigit(*cur)) {
    tscError("Measurement field cannnot start with digit");
1874
    free(pSml->stableName);
1875
    pSml->stableName = NULL;
1876
    return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
1877 1878
  }

1879 1880 1881 1882
  while (*cur != '\0') {
    if (len > TSDB_TABLE_NAME_LEN) {
      tscError("Measurement field cannot exceeds 193 characters");
      free(pSml->stableName);
1883
      pSml->stableName = NULL;
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
      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;
1908
}
1909

1910 1911 1912 1913
//Table name can only contain digits(0-9),alphebet(a-z),underscore(_)
static int32_t isValidChildTableName(const char *pTbName, int16_t len) {
  const char *cur = pTbName;
  for (int i = 0; i < len; ++i) {
1914
    if(!isdigit(cur[i]) && !isalpha(cur[i]) && (cur[i] != '_')) {
1915 1916 1917 1918 1919 1920 1921
      return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
    }
  }
  return TSDB_CODE_SUCCESS;
}


1922
static int32_t parseSmlKvPairs(TAOS_SML_KV **pKVs, int *num_kvs,
1923 1924
                               const char **index, bool isField,
                               TAOS_SML_DATA_POINT* smlData, SHashObj *pHash) {
1925
  const char *cur = *index;
1926
  int32_t ret = TSDB_CODE_SUCCESS;
1927 1928
  TAOS_SML_KV *pkv;
  bool is_last_kv = false;
1929

1930
  int32_t capacity = 0;
1931
  if (isField) {
1932 1933 1934
    capacity = 64;
    *pKVs = calloc(capacity, sizeof(TAOS_SML_KV));
    // leave space for timestamp;
1935 1936
    pkv = *pKVs;
    pkv++;
1937 1938 1939
  } else {
    capacity = 8;
    *pKVs = calloc(capacity, sizeof(TAOS_SML_KV));
1940 1941
    pkv = *pKVs;
  }
1942

1943
  while (*cur != '\0') {
1944
    ret = parseSmlKey(pkv, &cur, pHash);
1945
    if (ret) {
1946
      tscError("Unable to parse key field");
1947 1948
      goto error;
    }
1949
    ret = parseSmlValue(pkv, &cur, &is_last_kv);
1950
    if (ret) {
1951
      tscError("Unable to parse value field");
1952 1953
      goto error;
    }
1954 1955
    if (!isField &&
        (strcasecmp(pkv->key, "ID") == 0) && pkv->type == TSDB_DATA_TYPE_BINARY) {
1956
      ret = isValidChildTableName(pkv->value, pkv->length);
1957
      if (ret) {
1958 1959
        goto error;
      }
1960 1961 1962 1963 1964 1965 1966 1967
      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;
    }
1968
    if (is_last_kv) {
G
Ganlin Zhao 已提交
1969
      //tscDebug("last key-value field detected");
1970 1971 1972 1973 1974
      goto done;
    }

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

1976
    if (isField) {
1977 1978
      if ((*num_kvs + 2) > capacity) {
        capacity *= 3; capacity /= 2;
1979 1980 1981
        more_kvs = realloc(*pKVs, capacity * sizeof(TAOS_SML_KV));
      } else {
        more_kvs = *pKVs;
1982
      }
1983
    } else {
1984 1985
      if ((*num_kvs + 1) > capacity) {
        capacity *= 3; capacity /= 2;
1986 1987 1988
        more_kvs = realloc(*pKVs, capacity * sizeof(TAOS_SML_KV));
      } else {
        more_kvs = *pKVs;
1989
      }
1990
    }
1991

1992
    if (!more_kvs) {
1993 1994
      goto error;
    }
1995 1996 1997 1998 1999 2000 2001 2002 2003
    *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;
2004

2005
error:
2006
  return ret;
2007
done:
2008
  *index = cur;
2009
  return ret;
2010
}
2011

2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024
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);
2025 2026
}

2027
int32_t tscParseLine(const char* sql, TAOS_SML_DATA_POINT* smlData) {
2028
  const char* index = sql;
2029
  int32_t ret = TSDB_CODE_SUCCESS;
2030 2031
  uint8_t has_tags = 0;
  TAOS_SML_KV *timestamp = NULL;
2032
  SHashObj *keyHashTable = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, false);
2033

2034
  ret = parseSmlMeasurement(smlData, &index, &has_tags);
2035
  if (ret) {
2036
    tscError("Unable to parse measurement");
2037
    taosHashCleanup(keyHashTable);
2038
    return ret;
2039
  }
2040
  tscDebug("Parse measurement finished, has_tags:%d", has_tags);
2041 2042 2043

  //Parse Tags
  if (has_tags) {
2044
    ret = parseSmlKvPairs(&smlData->tags, &smlData->tagNum, &index, false, smlData, keyHashTable);
2045
    if (ret) {
2046
      tscError("Unable to parse tag");
2047
      taosHashCleanup(keyHashTable);
2048 2049
      return ret;
    }
2050
  }
2051
  tscDebug("Parse tags finished, num of tags:%d", smlData->tagNum);
2052 2053

  //Parse fields
2054
  ret = parseSmlKvPairs(&smlData->fields, &smlData->fieldNum, &index, true, smlData, keyHashTable);
2055
  if (ret) {
2056
    tscError("Unable to parse field");
2057
    taosHashCleanup(keyHashTable);
2058
    return ret;
2059
  }
2060
  tscDebug("Parse fields finished, num of fields:%d", smlData->fieldNum);
2061
  taosHashCleanup(keyHashTable);
2062

2063
  //Parse timestamp
2064
  ret = parseSmlTimeStamp(&timestamp, &index);
2065
  if (ret) {
2066
    tscError("Unable to parse timestamp");
2067
    return ret;
2068
  }
2069 2070
  moveTimeStampToFirstKv(&smlData, timestamp);
  tscDebug("Parse timestamp finished");
2071

2072
  return TSDB_CODE_SUCCESS;
2073 2074
}

2075
//=========================================================================
2076

S
shenglian zhou 已提交
2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088
static uint64_t linesSmlHandleId = 0;

uint64_t genLinesSmlId() {
  uint64_t id;

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

  return id;
}

S
shenglian zhou 已提交
2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
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);
}

S
shenglian zhou 已提交
2104
int32_t tscParseLines(char* lines[], int numLines, SArray* points, SArray* failedLines, SSmlLinesInfo* info) {
2105
  for (int32_t i = 0; i < numLines; ++i) {
2106
    TAOS_SML_DATA_POINT point = {0};
2107 2108
    int32_t code = tscParseLine(lines[i], &point);
    if (code != TSDB_CODE_SUCCESS) {
S
shenglian zhou 已提交
2109
      tscError("SML:0x%"PRIx64" data point line parse failed. line %d : %s", info->id, i, lines[i]);
S
shenglian zhou 已提交
2110
      destroySmlDataPoint(&point);
2111 2112
      return TSDB_CODE_TSC_LINE_SYNTAX_ERROR;
    } else {
S
shenglian zhou 已提交
2113
      tscDebug("SML:0x%"PRIx64" data point line parse success. line %d", info->id, i);
2114 2115
    }

2116 2117 2118 2119 2120
    taosArrayPush(points, &point);
  }
  return 0;
}

2121
int taos_insert_lines(TAOS* taos, char* lines[], int numLines) {
2122
  int32_t code = 0;
2123

S
shenglian zhou 已提交
2124 2125 2126
  SSmlLinesInfo* info = calloc(1, sizeof(SSmlLinesInfo));
  info->id = genLinesSmlId();

2127
  if (numLines <= 0 || numLines > 65536) {
S
shenglian zhou 已提交
2128
    tscError("SML:0x%"PRIx64" taos_insert_lines numLines should be between 1 and 65536. numLines: %d", info->id, numLines);
2129 2130 2131 2132 2133 2134
    code = TSDB_CODE_TSC_APP_ERROR;
    return code;
  }

  for (int i = 0; i < numLines; ++i) {
    if (lines[i] == NULL) {
S
shenglian zhou 已提交
2135 2136
      tscError("SML:0x%"PRIx64" taos_insert_lines line %d is NULL", info->id, i);
      free(info);
2137 2138 2139 2140 2141
      code = TSDB_CODE_TSC_APP_ERROR;
      return code;
    }
  }

2142
  SArray* lpPoints = taosArrayInit(numLines, sizeof(TAOS_SML_DATA_POINT));
2143
  if (lpPoints == NULL) {
S
shenglian zhou 已提交
2144 2145
    tscError("SML:0x%"PRIx64" taos_insert_lines failed to allocate memory", info->id);
    free(info);
2146 2147
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
  }
2148

S
shenglian zhou 已提交
2149 2150
  tscDebug("SML:0x%"PRIx64" taos_insert_lines begin inserting %d lines, first line: %s", info->id, numLines, lines[0]);
  code = tscParseLines(lines, numLines, lpPoints, NULL, info);
S
shenglian zhou 已提交
2151 2152
  size_t numPoints = taosArrayGetSize(lpPoints);

2153 2154
  if (code != 0) {
    goto cleanup;
2155 2156
  }

2157
  TAOS_SML_DATA_POINT* points = TARRAY_GET_START(lpPoints);
S
shenglian zhou 已提交
2158
  code = taos_sml_insert(taos, points, (int)numPoints, info);
2159
  if (code != 0) {
S
shenglian zhou 已提交
2160
    tscError("SML:0x%"PRIx64" taos_sml_insert error: %s", info->id, tstrerror((code)));
2161
  }
S
Shenglian Zhou 已提交
2162

2163
cleanup:
S
shenglian zhou 已提交
2164
  tscDebug("SML:0x%"PRIx64" taos_insert_lines finish inserting %d lines. code: %d", info->id, numLines, code);
2165 2166
  points = TARRAY_GET_START(lpPoints);
  numPoints = taosArrayGetSize(lpPoints);
S
Shenglian Zhou 已提交
2167 2168 2169
  for (int i=0; i<numPoints; ++i) {
    destroySmlDataPoint(points+i);
  }
2170 2171

  taosArrayDestroy(lpPoints);
S
shenglian zhou 已提交
2172 2173

  free(info);
2174
  return code;
2175 2176
}