tscParseLineProtocol.c 31.8 KB
Newer Older
S
shenglian zhou 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "os.h"
#include "osString.h"
#include "ttype.h"
#include "tmd5.h"
#include "tstrbuild.h"
#include "tname.h"
#include "taos.h"
#include "tsclient.h"
#include "tscLog.h"
#include "hash.h"
#include "tskiplist.h"
#include "tscUtil.h"

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

S
shenglian zhou 已提交
27 28 29 30 31
typedef struct {
  char* key;
  uint8_t type;
  int16_t length;
  char* value;
32 33

  //===================================
S
shenglian zhou 已提交
34
  SSchema* schema;
S
shenglian zhou 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47
} 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 已提交
48 49
  //================================
  SSmlSTableSchema* schema;
S
shenglian zhou 已提交
50 51
} TAOS_SML_DATA_POINT;

52 53
//=================================================================================================

S
shenglian zhou 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67
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;
  }
}

int32_t loadTableMeta(TAOS* taos, char* tableName, SSmlSTableSchema* schema) {
S
shenglian zhou 已提交
68 69 70 71 72
  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);

S
shenglian zhou 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
  int32_t code = 0;

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

  char sql[256];
  snprintf(sql, 256, "describe %s", tableName);
  TAOS_RES* res = taos_query(taos, sql);
  code = taos_errno(res);
  if (code != 0) {
    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;

  SStrToken tableToken = {.z=tableName, .n=strlen(tableName), .type=TK_ID};
  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);

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

125
  tstrncpy(schema->sTableName, tableName, strlen(tableName)+1);
S
shenglian zhou 已提交
126
  schema->precision = tableMeta->tableInfo.precision;
S
shenglian zhou 已提交
127 128
  for (int i=0; i<tableMeta->tableInfo.numOfColumns; ++i) {
    SSchema field;
129
    tstrncpy(field.name, tableMeta->schema[i].name, strlen(tableMeta->schema[i].name)+1);
S
shenglian zhou 已提交
130 131 132 133 134 135 136 137 138
    field.type = tableMeta->schema[i].type;
    field.bytes = tableMeta->schema[i].bytes;
    SSchema* pField = taosArrayPush(schema->fields, &field);
    taosHashPut(schema->fieldHash, field.name, strlen(field.name), &pField, POINTER_BYTES);
  }

  for (int i=0; i<tableMeta->tableInfo.numOfTags; ++i) {
    int j = i + tableMeta->tableInfo.numOfColumns;
    SSchema field;
139
    tstrncpy(field.name, tableMeta->schema[j].name, strlen(tableMeta->schema[j].name)+1);
S
shenglian zhou 已提交
140 141 142 143 144
    field.type = tableMeta->schema[j].type;
    field.bytes = tableMeta->schema[j].bytes;
    SSchema* pField = taosArrayPush(schema->tags, &field);
    taosHashPut(schema->tagHash, field.name, strlen(field.name), &pField, POINTER_BYTES);
  }
145
  free(tableMeta); tableMeta = NULL;
S
shenglian zhou 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
  return code;
}

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;

int32_t getFieldBytesFromSmlKv(TAOS_SML_KV* kv, int32_t* bytes) {
  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;
      //todo check conversion succeed
      taosMbsToUcs4(kv->value, kv->length, ucs, kv->length * TSDB_NCHAR_SIZE, &bytesNeeded);
      free(ucs);
      *bytes =  bytesNeeded + VARSTR_HEADER_SIZE;
    } else if (kv->type == TSDB_DATA_TYPE_BINARY) {
      *bytes = kv->length + VARSTR_HEADER_SIZE;
    }
  }
  return 0;
}

int32_t addTaosFieldToHashAndArray(TAOS_SML_KV* smlKv, SHashObj* hash, SArray* array) {
  SSchema* pField = NULL;
  SSchema** ppField = taosHashGet(hash, smlKv->key, strlen(smlKv->key));
  if (ppField) {
    pField = *ppField;

    if (pField->type != smlKv->type) {
      //TODO:
      tscError("type mismatch");
      return -1;
    }

    int32_t bytes = 0;
    getFieldBytesFromSmlKv(smlKv, &bytes);
    pField->bytes = MAX(pField->bytes, bytes);

  } else {
S
shenglian zhou 已提交
211
    SSchema field = {0};
S
shenglian zhou 已提交
212 213 214 215 216 217 218 219 220 221 222 223
    size_t tagKeyLen = strlen(smlKv->key);
    strncpy(field.name, smlKv->key, tagKeyLen);
    field.name[tagKeyLen] = '\0';
    field.type = smlKv->type;

    int32_t bytes = 0;
    getFieldBytesFromSmlKv(smlKv, &bytes);
    field.bytes = bytes;

    pField = taosArrayPush(array, &field);
    taosHashPut(hash, field.name, tagKeyLen, &pField, POINTER_BYTES);
  }
224

S
shenglian zhou 已提交
225
  smlKv->schema = pField;
226

S
shenglian zhou 已提交
227 228 229 230 231 232
  return 0;
}

int32_t generateSchemaAction(SSchema* pointColField, SHashObj* dbAttrHash, bool isTag, char sTableName[],
                                       SSchemaAction* action, bool* actionNeeded) {
  SSchema** ppDbAttr = taosHashGet(dbAttrHash, pointColField->name, strlen(pointColField->name));
S
shenglian zhou 已提交
233
  if (ppDbAttr) {
S
shenglian zhou 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
    SSchema* dbAttr = *ppDbAttr;
    if (pointColField->type != dbAttr->type) {
      //todo error
      return -5;
    }

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

int32_t buildColumnDescription(SSchema* field,
                               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;
}

int32_t applySchemaAction(TAOS* taos, SSchemaAction* action) {
  int32_t code = 0;
  int32_t capacity = TSDB_MAX_BINARY_LEN;
  int32_t outBytes = 0;
  char *result = (char *)calloc(1, capacity);

  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);
      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);
      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);
314
      break;
S
shenglian zhou 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    }
    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);
      break;
    }
    case SCHEMA_ACTION_CREATE_STABLE: {
      int n = sprintf(result, "create stable %s (", action->createSTable.sTableName);
      char* pos = result + n; int freeBytes = capacity - n;
      int numCols = taosArrayGetSize(action->createSTable.fields);
      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;
335

S
shenglian zhou 已提交
336 337
      outBytes = snprintf(pos, freeBytes, ") tags (");
      pos += outBytes; freeBytes -= outBytes;
338 339

      int numTags = taosArrayGetSize(action->createSTable.tags);
S
shenglian zhou 已提交
340 341 342 343 344 345 346 347 348 349 350 351
      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);
      break;
    }
S
shenglian zhou 已提交
352

S
shenglian zhou 已提交
353 354 355 356 357 358 359
    default:
      break;
  }
  free(result);
  return code;
}

360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
int32_t getChildTableName(TAOS_SML_DATA_POINT* point, char* tableName, int* tableNameLen) {
  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 已提交
379
                           "tbl_%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", context.digest[0],
380 381 382 383 384 385 386
                           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);
  return 0;
}

S
shenglian zhou 已提交
387
int32_t creatChildTableIfNotExists(TAOS* taos, const char* cTableName, const char* sTableName, SArray* tagsSchema, SArray* tagsBind) {
S
shenglian zhou 已提交
388
  size_t numTags = taosArrayGetSize(tagsSchema);
S
shenglian zhou 已提交
389 390 391
  char sql[TSDB_MAX_BINARY_LEN] = {0};
  int freeBytes = TSDB_MAX_BINARY_LEN;
  sprintf(sql, "create table if not exists %s using %s", cTableName, sTableName);
392

S
shenglian zhou 已提交
393 394 395 396 397 398
  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, ")");
399

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

S
shenglian zhou 已提交
402
  for (int i = 0; i < numTags; ++i) {
S
shenglian zhou 已提交
403
    snprintf(sql+strlen(sql), freeBytes-strlen(sql), "?,");
S
shenglian zhou 已提交
404
  }
S
shenglian zhou 已提交
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
  snprintf(sql + strlen(sql) - 1, freeBytes-strlen(sql)+1, ")");

  TAOS_STMT* stmt = taos_stmt_init(taos);
  int32_t code;
  code = taos_stmt_prepare(stmt, sql, strlen(sql));
  if (code != 0) {
    printf("%s", taos_stmt_errstr(stmt));
    return code;
  }

  code = taos_stmt_bind_param(stmt, TARRAY_GET_START(tagsBind));
  if (code != 0) {
    printf("%s", taos_stmt_errstr(stmt));
    return code;
  }

  code = taos_stmt_execute(stmt);
  if (code != 0) {
    printf("%s", taos_stmt_errstr(stmt));
    return code;
  }
S
shenglian zhou 已提交
426 427 428

  taos_stmt_close(stmt);
  return 0;
S
shenglian zhou 已提交
429 430 431 432
}

int32_t insertBatch(TAOS* taos,  char* cTableName, SArray* colsSchema, SArray* rowsBind) {
  size_t numCols = taosArrayGetSize(colsSchema);
S
shenglian zhou 已提交
433 434
  char sql[4096];
  int32_t freeBytes = 4096;
S
shenglian zhou 已提交
435
  sprintf(sql, "insert into ? (");
436

S
shenglian zhou 已提交
437 438
  for (int i = 0; i < numCols; ++i) {
    SSchema* colSchema = taosArrayGet(colsSchema, i);
S
shenglian zhou 已提交
439
    snprintf(sql+strlen(sql), freeBytes-strlen(sql), "%s,", colSchema->name);
S
shenglian zhou 已提交
440
  }
S
shenglian zhou 已提交
441
  snprintf(sql + strlen(sql)-1, freeBytes-strlen(sql)+1, ") values (");
442

S
shenglian zhou 已提交
443
  for (int i = 0; i < numCols; ++i) {
S
shenglian zhou 已提交
444
    snprintf(sql+strlen(sql), freeBytes-strlen(sql), "?,");
445
  }
S
shenglian zhou 已提交
446
  snprintf(sql + strlen(sql)-1, freeBytes-strlen(sql)+1, ")");
447 448

  TAOS_STMT* stmt = taos_stmt_init(taos);
449 450 451 452 453 454
  int32_t code;
  code = taos_stmt_prepare(stmt, sql, strlen(sql));
  if (code != 0) {
    printf("%s", taos_stmt_errstr(stmt));
    return code;
  }
S
shenglian zhou 已提交
455

S
shenglian zhou 已提交
456
  code = taos_stmt_set_tbname(stmt, cTableName);
457 458 459 460
  if (code != 0) {
    printf("%s", taos_stmt_errstr(stmt));
    return code;
  }
S
shenglian zhou 已提交
461 462
  size_t rows = taosArrayGetSize(rowsBind);
  for (int32_t i = 0; i < rows; ++i) {
S
shenglian zhou 已提交
463 464
    TAOS_BIND* colsBinds = taosArrayGetP(rowsBind, i);
    code = taos_stmt_bind_param(stmt, colsBinds);
465 466 467 468 469 470 471 472 473
    if (code != 0) {
      printf("%s", taos_stmt_errstr(stmt));
      return code;
    }
    code = taos_stmt_add_batch(stmt);
    if (code != 0) {
      printf("%s", taos_stmt_errstr(stmt));
      return code;
    }
S
shenglian zhou 已提交
474
  }
475

476 477 478 479 480
  code = taos_stmt_execute(stmt);
  if (code != 0) {
    printf("%s", taos_stmt_errstr(stmt));
    return code;
  }
S
shenglian zhou 已提交
481 482 483 484


  taos_stmt_close(stmt);
  return code;
S
shenglian zhou 已提交
485 486 487 488 489 490 491 492
}

int32_t insertPoints(TAOS* taos, TAOS_SML_DATA_POINT* points, int32_t numPoints) {
  SHashObj* cname2points = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, false);
  for (int32_t i = 0; i < numPoints; ++i) {
    TAOS_SML_DATA_POINT * point = points + i;
    if (!point->childTableName) {
      char childTableName[TSDB_TABLE_NAME_LEN];
493
      int32_t tableNameLen = TSDB_TABLE_NAME_LEN;
S
shenglian zhou 已提交
494 495 496 497 498
      getChildTableName(point, childTableName, &tableNameLen);
      point->childTableName = calloc(1, tableNameLen+1);
      strncpy(point->childTableName, childTableName, tableNameLen);
      point->childTableName[tableNameLen] = '\0';
    }
S
shenglian zhou 已提交
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

    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);
        ts = convertTimePrecision(ts, TSDB_TIME_PRECISION_NANO, point->schema->precision);
        *(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);
        ts = convertTimePrecision(ts, TSDB_TIME_PRECISION_NANO, point->schema->precision);
        *(int64_t*)(kv->value) = ts;
      }
    }

S
shenglian zhou 已提交
518 519 520 521 522 523 524 525
    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);
    }
526
    taosArrayPush(cTablePoints, &point);
527 528
  }

529
  int isNullColBind = TSDB_TRUE;
S
shenglian zhou 已提交
530 531 532
  SArray** pCTablePoints = taosHashIterate(cname2points, NULL);
  while (pCTablePoints) {
    SArray* cTablePoints = *pCTablePoints;
533 534

    TAOS_SML_DATA_POINT * point = taosArrayGetP(cTablePoints, 0);
S
shenglian zhou 已提交
535 536
    int32_t numTags = taosArrayGetSize(point->schema->tags);
    int32_t numCols = taosArrayGetSize(point->schema->fields);
537 538 539 540 541 542 543 544 545 546 547 548

    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;
      int32_t idx = TARRAY_ELEM_IDX(point->schema->tags, kv->schema);
      TAOS_BIND* bind = taosArrayGet(tagBinds, idx);
      bind->buffer_type = kv->type;
549 550
      bind->length = malloc(sizeof(uintptr_t*));
      *bind->length = kv->length;
551 552 553
      bind->buffer = kv->value;
      bind->is_null = NULL;
    }
S
shenglian zhou 已提交
554 555 556 557 558

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

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

S
shenglian zhou 已提交
561
      TAOS_BIND* colBinds = calloc(numCols, sizeof(TAOS_BIND));
562
      for (int j = 0; j < numCols; ++j) {
S
shenglian zhou 已提交
563
        TAOS_BIND* bind = colBinds + j;
564 565 566
        bind->is_null = &isNullColBind;
      }
      for (int j = 0; j < point->fieldNum; ++j) {
S
shenglian zhou 已提交
567 568
        TAOS_SML_KV* kv = point->fields + j;
        int32_t idx = TARRAY_ELEM_IDX(point->schema->fields, kv->schema);
S
shenglian zhou 已提交
569
        TAOS_BIND* bind = colBinds + idx;
S
shenglian zhou 已提交
570
        bind->buffer_type = kv->type;
571 572
        bind->length = malloc(sizeof(uintptr_t*));
        *bind->length = kv->length;
S
shenglian zhou 已提交
573
        bind->buffer = kv->value;
574
        bind->is_null = NULL;
S
shenglian zhou 已提交
575 576 577 578
      }
      taosArrayPush(rowsBind, &colBinds);
    }

S
shenglian zhou 已提交
579
    creatChildTableIfNotExists(taos, point->childTableName, point->stableName, point->schema->tags, tagBinds);
S
shenglian zhou 已提交
580
    insertBatch(taos, point->childTableName, point->schema->fields, rowsBind);
S
shenglian zhou 已提交
581 582

    pCTablePoints = taosHashIterate(cname2points, pCTablePoints);
583
  }
S
shenglian zhou 已提交
584 585
  return 0;
}
586

S
shenglian zhou 已提交
587 588 589 590 591 592 593 594
int taos_sml_insert(TAOS* taos, TAOS_SML_DATA_POINT* points, int numPoint) {
  int32_t code = TSDB_CODE_SUCCESS;
  SArray* stableArray = taosArrayInit(32, sizeof(SSmlSTableSchema)); // SArray<STableColumnsSchema>
  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];
595 596
    size_t stableNameLen = strlen(point->stableName);
    SSmlSTableSchema** ppStableSchema = taosHashGet(sname2shema, point->stableName, stableNameLen);
S
shenglian zhou 已提交
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
    SSmlSTableSchema* pStableSchema = NULL;
    if (ppStableSchema) {
      pStableSchema= *ppStableSchema;
    } 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(stableArray, &schema);
      taosHashPut(sname2shema, schema.sTableName, stableNameLen, &pStableSchema, POINTER_BYTES);
    }

    for (int j = 0; j < point->tagNum; ++j) {
      TAOS_SML_KV* tagKv = point->tags + j;
      addTaosFieldToHashAndArray(tagKv, pStableSchema->tagHash, pStableSchema->tags);
    }

    for (int j = 0; j < point->fieldNum; ++j) {
      TAOS_SML_KV* fieldKv = point->fields + j;
      addTaosFieldToHashAndArray(fieldKv, pStableSchema->fieldHash, pStableSchema->fields);
    }

    point->schema = pStableSchema;
624 625
  }

S
shenglian zhou 已提交
626 627 628 629
  size_t numStable = taosArrayGetSize(stableArray);
  for (int i = 0; i < numStable; ++i) {
    SSmlSTableSchema* pointSchema = taosArrayGet(stableArray, i);
    SSmlSTableSchema  dbSchema = {0};
630

S
shenglian zhou 已提交
631
    code = loadTableMeta(taos, pointSchema->sTableName, &dbSchema);
632

S
shenglian zhou 已提交
633 634 635 636 637 638 639
    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 已提交
640 641 642 643
      applySchemaAction(taos, &schemaAction);
      code = loadTableMeta(taos, pointSchema->sTableName, &dbSchema);
      pointSchema->precision = dbSchema.precision;
    } else if (code == TSDB_CODE_SUCCESS) {
S
shenglian zhou 已提交
644 645 646 647 648 649 650
      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) {
651
        SSchema* pointTag = taosArrayGet(pointSchema->tags, j);
S
shenglian zhou 已提交
652
        SSchemaAction schemaAction = {0};
653
        bool actionNeeded = false;
S
shenglian zhou 已提交
654 655
        generateSchemaAction(pointTag, dbTagHash, true, pointSchema->sTableName, &schemaAction, &actionNeeded);
        if (actionNeeded) {
S
shenglian zhou 已提交
656
          applySchemaAction(taos, &schemaAction);
S
shenglian zhou 已提交
657 658
          code = loadTableMeta(taos, pointSchema->sTableName, &dbSchema);
          pointSchema->precision = dbSchema.precision;
S
shenglian zhou 已提交
659 660 661
        }
      }

662 663 664 665 666 667
      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);
S
shenglian zhou 已提交
668
        SSchemaAction schemaAction = {0};
669
        bool actionNeeded = false;
S
shenglian zhou 已提交
670 671
        generateSchemaAction(pointCol, dbFieldHash, false, pointSchema->sTableName, &schemaAction, &actionNeeded);
        if (actionNeeded) {
S
shenglian zhou 已提交
672
          applySchemaAction(taos, &schemaAction);
S
shenglian zhou 已提交
673 674
          code = loadTableMeta(taos, pointSchema->sTableName, &dbSchema);
          pointSchema->precision = dbSchema.precision;
S
shenglian zhou 已提交
675 676
        }
      }
S
shenglian zhou 已提交
677 678

      pointSchema->precision = dbSchema.precision;
S
shenglian zhou 已提交
679 680 681
    } else {
      return code;
    }
682 683
  }

S
shenglian zhou 已提交
684
  insertPoints(taos, points, numPoint);
685 686
  return code;
}
S
shenglian zhou 已提交
687 688


S
shenglian zhou 已提交
689 690 691
//todo: table/column length check
//todo: type check
//todo: taosmbs2ucs4 check
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782

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

typedef enum {
  LP_ITEM_TAG,
  LP_ITEM_FIELD
} LPItemKind;

typedef struct  {
  SStrToken keyToken;
  SStrToken valueToken;

  char key[TSDB_COL_NAME_LEN];
  int8_t type;
  int16_t length;

  char* value;
}SLPItem;

typedef struct {
  SStrToken measToken;
  SStrToken tsToken;

  char sTableName[TSDB_TABLE_NAME_LEN];
  SArray* tags;
  SArray* fields;
  int64_t ts;

} SLPPoint;

typedef enum {
  LP_MEASUREMENT,
  LP_TAG_KEY,
  LP_TAG_VALUE,
  LP_FIELD_KEY,
  LP_FIELD_VALUE
} LPPart;

int32_t scanToCommaOrSpace(SStrToken s, int32_t start, int32_t* index, LPPart part) {
  for (int32_t i = start; i < s.n; ++i) {
    if (s.z[i] == ',' || s.z[i] == ' ') {
      *index = i;
      return 0;
    }
  }
  return -1;
}

int32_t scanToEqual(SStrToken s, int32_t start, int32_t* index) {
  for (int32_t i = start; i < s.n; ++i) {
    if (s.z[i] == '=') {
      *index = i;
      return 0;
    }
  }
  return -1;
}

int32_t setPointMeasurement(SLPPoint* point, SStrToken token) {
  point->measToken = token;
  if (point->measToken.n < TSDB_TABLE_NAME_LEN) {
    strncpy(point->sTableName, point->measToken.z, point->measToken.n);
    point->sTableName[point->measToken.n] = '\0';
  }
  return 0;
}

int32_t setItemKey(SLPItem* item, SStrToken key, LPPart part) {
  item->keyToken = key;
  if (item->keyToken.n < TSDB_COL_NAME_LEN) {
    strncpy(item->key, item->keyToken.z, item->keyToken.n);
    item->key[item->keyToken.n] = '\0';
  }
  return 0;
}

int32_t setItemValue(SLPItem* item, SStrToken value, LPPart part) {
  item->valueToken = value;
  return 0;
}

int32_t parseItemValue(SLPItem* item, LPItemKind kind) {
  char* sv = item->valueToken.z;
  char* last = item->valueToken.z + item->valueToken.n - 1;

  if (isdigit(sv[0]) || sv[0] == '-') {
    if (*last == 'i') {
      item->type = TSDB_DATA_TYPE_BIGINT;
      item->length = (int16_t)tDataTypes[item->type].bytes;
      item->value = malloc(item->length);
      char* endptr = NULL;
783
      *(int64_t*)(item->value) = strtoll(sv, &endptr, 10);
784 785 786 787 788
    } else {
      item->type = TSDB_DATA_TYPE_DOUBLE;
      item->length = (int16_t)tDataTypes[item->type].bytes;
      item->value = malloc(item->length);
      char* endptr = NULL;
789
      *(double*)(item->value) = strtold(sv, &endptr);
790 791 792 793 794 795 796
    }
  } else if ((sv[0] == 'L' && sv[1] =='"') || sv[0] == '"' ) {
    if (sv[0] == 'L') {
      item->type = TSDB_DATA_TYPE_NCHAR;
      uint32_t bytes = item->valueToken.n - 3;
      item->length = bytes;
      item->value = malloc(bytes);
797
      memcpy(item->value, sv+2, bytes);
798 799 800 801 802 803 804 805 806 807 808
    } else if (sv[0]=='"'){
      item->type = TSDB_DATA_TYPE_BINARY;
      uint32_t bytes = item->valueToken.n - 2;
      item->length = bytes;
      item->value = malloc(bytes);
      memcpy(item->value, sv+1, bytes);
    }
  } else if (sv[0] == 't' || sv[0] == 'f' || sv[0]=='T' || sv[0] == 'F') {
    item->type = TSDB_DATA_TYPE_BOOL;
    item->length = tDataTypes[item->type].bytes;
    item->value = malloc(tDataTypes[item->type].bytes);
809
    *(uint8_t*)(item->value) = tolower(sv[0])=='t' ? TSDB_TRUE : TSDB_FALSE;
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
  }
  return 0;
}

int32_t compareLPItemKey(const void* p1, const void* p2) {
  const SLPItem* t1 = p1;
  const SLPItem* t2 = p2;
  uint32_t min = (t1->keyToken.n < t2->keyToken.n) ? t1->keyToken.n : t2->keyToken.n;
  int res = strncmp(t1->keyToken.z, t2->keyToken.z, min);
  if (res != 0) {
    return res;
  } else {
    return (int)(t1->keyToken.n) - (int)(t2->keyToken.n);
  }
}

int32_t setPointTimeStamp(SLPPoint* point, SStrToken tsToken) {
  point->tsToken = tsToken;
  return 0;
}

int32_t parsePointTime(SLPPoint* point) {
  if (point->tsToken.n <= 0) {
    point->ts = taosGetTimestampNs();
  } else {
    char* endptr = NULL;
    point->ts = strtoll(point->tsToken.z, &endptr, 10);
  }
  return 0;
}

int32_t tscParseLine(SStrToken line, SLPPoint* point) {
  int32_t pos = 0;

  int32_t start = 0;
  int32_t err = scanToCommaOrSpace(line, start, &pos, LP_MEASUREMENT);
  if (err != 0) {
    tscError("a");
    return err;
  }

  SStrToken measurement = {.z = line.z+start, .n = pos-start};
  setPointMeasurement(point, measurement);
  point->tags = taosArrayInit(64, sizeof(SLPItem));
  start = pos;
  while (line.z[start] == ',') {
    SLPItem item;

    start++;
    err = scanToEqual(line, start, &pos);
    if (err != 0) {
      tscError("b");
      goto error;
    }

    SStrToken tagKey = {.z = line.z + start, .n = pos-start};
    setItemKey(&item, tagKey, LP_TAG_KEY);

    start = pos + 1;
    err = scanToCommaOrSpace(line, start, &pos, LP_TAG_VALUE);
    if (err != 0) {
      tscError("c");
      goto error;
    }

    SStrToken tagValue = {.z = line.z + start, .n = pos-start};
    setItemValue(&item, tagValue, LP_TAG_VALUE);

    parseItemValue(&item, LP_ITEM_TAG);
    taosArrayPush(point->tags, &item);

    start = pos;
  }

  taosArraySort(point->tags, compareLPItemKey);

  point->fields = taosArrayInit(64, sizeof(SLPItem));

  start++;
  do {
    SLPItem item;

    err = scanToEqual(line, start, &pos);
    if (err != 0) {
      goto error;
    }
    SStrToken fieldKey = {.z = line.z + start, .n = pos- start};
    setItemKey(&item, fieldKey, LP_FIELD_KEY);

    start = pos + 1;
    err = scanToCommaOrSpace(line, start, &pos, LP_FIELD_VALUE);
    if (err != 0) {
      goto error;
    }
    SStrToken fieldValue = {.z = line.z + start, .n = pos - start};
    setItemValue(&item, fieldValue, LP_TAG_VALUE);

    parseItemValue(&item, LP_ITEM_FIELD);
    taosArrayPush(point->fields, &item);

    start = pos + 1;
  } while (line.z[pos] == ',');

  taosArraySort(point->fields, compareLPItemKey);

  SStrToken tsToken = {.z = line.z+start, .n = line.n-start};
  setPointTimeStamp(point, tsToken);
  parsePointTime(point);

  goto done;

  error:
  // free array
  return err;
  done:
  return 0;
}


int32_t tscParseLines(char* lines[], int numLines, SArray* points, SArray* failedLines) {
  for (int32_t i = 0; i < numLines; ++i) {
    SStrToken tkLine = {.z = lines[i], .n = strlen(lines[i])+1};
    SLPPoint point;
    tscParseLine(tkLine, &point);
    taosArrayPush(points, &point);
  }
  return 0;
}

int taos_insert_by_lines(TAOS* taos, char* lines[], int numLines) {
  SArray* lpPoints = taosArrayInit(numLines, sizeof(SLPPoint));
  tscParseLines(lines, numLines, lpPoints, NULL);

  size_t numPoints = taosArrayGetSize(lpPoints);
  TAOS_SML_DATA_POINT* points = calloc(numPoints, sizeof(TAOS_SML_DATA_POINT));
  for (int i = 0; i < numPoints; ++i) {
    SLPPoint* lpPoint = taosArrayGet(lpPoints, i);
    TAOS_SML_DATA_POINT* point = points+i;
    point->stableName = calloc(1, strlen(lpPoint->sTableName)+1);
    strncpy(point->stableName, lpPoint->sTableName, strlen(lpPoint->sTableName));
    point->stableName[strlen(lpPoint->sTableName)] = '\0';

    size_t lpTagSize = taosArrayGetSize(lpPoint->tags);
    point->tags = calloc(lpTagSize, sizeof(TAOS_SML_KV));
    point->tagNum = lpTagSize;
    for (int j=0; j<lpTagSize; ++j) {
      SLPItem* lpTag = taosArrayGet(lpPoint->tags, j);
      TAOS_SML_KV* tagKv = point->tags + j;

      size_t kenLen = strlen(lpTag->key);
      tagKv->key = calloc(1, kenLen+1);
      strncpy(tagKv->key, lpTag->key, kenLen);
      tagKv->key[kenLen] = '\0';

      tagKv->type = lpTag->type;
      tagKv->length = lpTag->length;
      tagKv->value = malloc(tagKv->length);
      memcpy(tagKv->value, lpTag->value, tagKv->length);
    }

    size_t lpFieldsSize = taosArrayGetSize(lpPoint->fields);
    point->fields = calloc(lpFieldsSize + 1, sizeof(TAOS_SML_KV));
    point->fieldNum = lpFieldsSize + 1;

    TAOS_SML_KV* tsField = point->fields + 0;
    char tsKey[256];
    snprintf(tsKey, 256, "_%s_ts", point->stableName);
    size_t tsKeyLen = strlen(tsKey);
    tsField->key = calloc(1, tsKeyLen+1);
    strncpy(tsField->key, tsKey, tsKeyLen);
    tsField->key[tsKeyLen] = '\0';
    tsField->type = TSDB_DATA_TYPE_TIMESTAMP;
    tsField->length = tDataTypes[TSDB_DATA_TYPE_TIMESTAMP].bytes;
    tsField->value = malloc(tsField->length);
    memcpy(tsField->value, &(lpPoint->ts), tsField->length);

    for (int j=0; j<lpFieldsSize; ++j) {
      SLPItem* lpField = taosArrayGet(lpPoint->fields, j);
      TAOS_SML_KV* fieldKv = point->fields + j + 1;

      size_t kenLen = strlen(lpField->key);
      fieldKv->key = calloc(1, kenLen+1);
      strncpy(fieldKv->key, lpField->key, kenLen);
      fieldKv->key[kenLen] = '\0';

      fieldKv->type = lpField->type;
      fieldKv->length = lpField->length;
      fieldKv->value = malloc(fieldKv->length);
      memcpy(fieldKv->value, lpField->value, fieldKv->length);
    }
  }

  taos_sml_insert(taos, points, numPoints);
  return 0;
}