clientSml.c 68.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

wmmhello's avatar
wmmhello 已提交
16 17 18 19 20
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

21 22 23 24 25 26
#include "clientSml.h"

int64_t smlToMilli[3] = {3600000LL, 60000LL, 1000LL};
int64_t smlFactorNS[3] = {NANOSECOND_PER_MSEC, NANOSECOND_PER_USEC, 1};
int64_t smlFactorS[3] = {1000LL, 1000000LL, 1000000000LL};

wmmhello's avatar
wmmhello 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
//void *nodeListGet(NodeList *list, const void *key, int32_t len, _equal_fn_sml fn) {
//  NodeList *tmp = list;
//  while (tmp) {
//    if (fn == NULL) {
//      if (tmp->data.used && tmp->data.keyLen == len && memcmp(tmp->data.key, key, len) == 0) {
//        return tmp->data.value;
//      }
//    } else {
//      if (tmp->data.used && fn(tmp->data.key, key) == 0) {
//        return tmp->data.value;
//      }
//    }
//
//    tmp = tmp->next;
//  }
//  return NULL;
//}
//
//int nodeListSet(NodeList **list, const void *key, int32_t len, void *value, _equal_fn_sml fn) {
//  NodeList *tmp = *list;
//  while (tmp) {
//    if (!tmp->data.used) break;
//    if (fn == NULL) {
//      if (tmp->data.keyLen == len && memcmp(tmp->data.key, key, len) == 0) {
//        return -1;
//      }
//    } else {
//      if (tmp->data.keyLen == len && fn(tmp->data.key, key) == 0) {
//        return -1;
//      }
//    }
//
//    tmp = tmp->next;
//  }
//  if (tmp) {
//    tmp->data.key = key;
//    tmp->data.keyLen = len;
//    tmp->data.value = value;
//    tmp->data.used = true;
//  } else {
//    NodeList *newNode = (NodeList *)taosMemoryCalloc(1, sizeof(NodeList));
//    if (newNode == NULL) {
//      return -1;
//    }
//    newNode->data.key = key;
//    newNode->data.keyLen = len;
//    newNode->data.value = value;
//    newNode->data.used = true;
//    newNode->next = *list;
//    *list = newNode;
//  }
//  return 0;
//}
//
//int nodeListSize(NodeList *list) {
//  int cnt = 0;
//  while (list) {
//    if (list->data.used)
//      cnt++;
//    else
//      break;
//    list = list->next;
//  }
//  return cnt;
//}

static int32_t smlCheckAuth(SSmlHandle *info,  SRequestConnInfo* conn, const char* pTabName, AUTH_TYPE type){
  SUserAuthInfo pAuth = {0};
  snprintf(pAuth.user, sizeof(pAuth.user), "%s", info->taos->user);
  if (NULL == pTabName) {
    tNameSetDbName(&pAuth.tbName, info->taos->acctId, info->pRequest->pDb, strlen(info->pRequest->pDb));
  } else {
    toName(info->taos->acctId, info->pRequest->pDb, pTabName, &pAuth.tbName);
wmmhello's avatar
wmmhello 已提交
100
  }
wmmhello's avatar
wmmhello 已提交
101
  pAuth.type = type;
wmmhello's avatar
wmmhello 已提交
102

wmmhello's avatar
wmmhello 已提交
103 104
  int32_t      code = TSDB_CODE_SUCCESS;
  SUserAuthRes authRes = {0};
105

wmmhello's avatar
wmmhello 已提交
106
  code = catalogChkAuth(info->pCatalog, conn, &pAuth, &authRes);
wmmhello's avatar
wmmhello 已提交
107
  nodesDestroyNode(authRes.pCond);
wmmhello's avatar
wmmhello 已提交
108

wmmhello's avatar
wmmhello 已提交
109
  return (code == TSDB_CODE_SUCCESS) ? (authRes.pass ? TSDB_CODE_SUCCESS : TSDB_CODE_PAR_PERMISSION_DENIED) : code;
wmmhello's avatar
wmmhello 已提交
110 111

}
112
inline bool smlDoubleToInt64OverFlow(double num) {
X
Xiaoyu Wang 已提交
113
  if (num >= (double)INT64_MAX || num <= (double)INT64_MIN) return true;
114 115 116
  return false;
}

117
void smlStrReplace(char* src, int32_t len){
118
  if (!tsSmlDot2Underline) return;
119 120 121 122 123 124 125
  for(int i = 0; i < len; i++){
    if(src[i] == '.'){
      src[i] = '_';
    }
  }
}

126
int32_t smlBuildInvalidDataMsg(SSmlMsgBuf *pBuf, const char *msg1, const char *msg2) {
127
  if (pBuf->buf) {
128 129 130 131 132 133 134
    memset(pBuf->buf, 0, pBuf->len);
    if (msg1) strncat(pBuf->buf, msg1, pBuf->len);
    int32_t left = pBuf->len - strlen(pBuf->buf);
    if (left > 2 && msg2) {
      strncat(pBuf->buf, ":", left - 1);
      strncat(pBuf->buf, msg2, left - 2);
    }
wmmhello's avatar
wmmhello 已提交
135
  }
wmmhello's avatar
wmmhello 已提交
136 137 138
  return TSDB_CODE_SML_INVALID_DATA;
}

139 140 141 142 143
int64_t smlGetTimeValue(const char *value, int32_t len, uint8_t fromPrecision, uint8_t toPrecision) {
  char   *endPtr = NULL;
  int64_t tsInt64 = taosStr2Int64(value, &endPtr, 10);
  if (unlikely(value + len != endPtr)) {
    return -1;
144
  }
wmmhello's avatar
wmmhello 已提交
145

X
Xiaoyu Wang 已提交
146
  if (unlikely(fromPrecision >= TSDB_TIME_PRECISION_HOURS)) {
147
    int64_t unit = smlToMilli[fromPrecision - TSDB_TIME_PRECISION_HOURS];
D
dapan1121 已提交
148
    if (tsInt64 != 0 && unit > INT64_MAX / tsInt64) {
149 150 151 152
      return -1;
    }
    tsInt64 *= unit;
    fromPrecision = TSDB_TIME_PRECISION_MILLI;
wmmhello's avatar
wmmhello 已提交
153
  }
wmmhello's avatar
wmmhello 已提交
154

155
  return convertTimePrecision(tsInt64, fromPrecision, toPrecision);
wmmhello's avatar
wmmhello 已提交
156 157
}

158 159 160 161 162 163 164
int8_t smlGetTsTypeByLen(int32_t len) {
  if (len == TSDB_TIME_PRECISION_SEC_DIGITS) {
    return TSDB_TIME_PRECISION_SECONDS;
  } else if (len == TSDB_TIME_PRECISION_MILLI_DIGITS) {
    return TSDB_TIME_PRECISION_MILLI;
  } else {
    return -1;
165 166 167
  }
}

X
Xiaoyu Wang 已提交
168
SSmlTableInfo *smlBuildTableInfo(int numRows, const char *measure, int32_t measureLen) {
169 170 171
  SSmlTableInfo *tag = (SSmlTableInfo *)taosMemoryCalloc(sizeof(SSmlTableInfo), 1);
  if (!tag) {
    return NULL;
172 173
  }

174 175
  tag->sTableName = measure;
  tag->sTableNameLen = measureLen;
176

177 178 179 180
  tag->cols = taosArrayInit(numRows, POINTER_BYTES);
  if (tag->cols == NULL) {
    uError("SML:smlBuildTableInfo failed to allocate memory");
    goto cleanup;
181
  }
182

X
Xiaoyu Wang 已提交
183 184 185 186 187
  //  tag->tags = taosArrayInit(16, sizeof(SSmlKv));
  //  if (tag->tags == NULL) {
  //    uError("SML:smlBuildTableInfo failed to allocate memory");
  //    goto cleanup;
  //  }
188 189
  return tag;

X
Xiaoyu Wang 已提交
190
cleanup:
191 192
  taosMemoryFree(tag);
  return NULL;
193 194
}

195
static int32_t smlParseTableName(SArray *tags, char *childTableName) {
X
Xiaoyu Wang 已提交
196
  size_t childTableNameLen = strlen(tsSmlChildTableName);
197 198
  if (childTableNameLen <= 0) return TSDB_CODE_SUCCESS;

X
Xiaoyu Wang 已提交
199
  for (int i = 0; i < taosArrayGetSize(tags); i++) {
200 201 202 203 204
    SSmlKv *tag = (SSmlKv *)taosArrayGet(tags, i);
    // handle child table name
    if (childTableNameLen == tag->keyLen && strncmp(tag->key, tsSmlChildTableName, tag->keyLen) == 0) {
      memset(childTableName, 0, TSDB_TABLE_NAME_LEN);
      strncpy(childTableName, tag->value, (tag->length < TSDB_TABLE_NAME_LEN ? tag->length : TSDB_TABLE_NAME_LEN));
205 206 207
      if(tsSmlDot2Underline){
        smlStrReplace(childTableName, strlen(childTableName));
      }
wmmhello's avatar
wmmhello 已提交
208
      taosArrayRemove(tags, i);
209
      break;
wmmhello's avatar
wmmhello 已提交
210 211
    }
  }
212

wmmhello's avatar
wmmhello 已提交
213 214 215
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
216
int32_t smlSetCTableName(SSmlTableInfo *oneTable) {
217
  smlParseTableName(oneTable->tags, oneTable->childTableName);
218

219
  if (strlen(oneTable->childTableName) == 0) {
X
Xiaoyu Wang 已提交
220
    SArray       *dst = taosArrayDup(oneTable->tags, NULL);
wmmhello's avatar
wmmhello 已提交
221
    RandTableName rName = {dst, oneTable->sTableName, (uint8_t)oneTable->sTableNameLen, oneTable->childTableName};
wmmhello's avatar
wmmhello 已提交
222

223 224
    buildChildTableName(&rName);
    taosArrayDestroy(dst);
225
  }
226 227
  return TSDB_CODE_SUCCESS;
}
228

229 230
void getTableUid(SSmlHandle *info, SSmlLineInfo *currElement, SSmlTableInfo *tinfo) {
  char   key[TSDB_TABLE_NAME_LEN * 2 + 1] = {0};
231 232 233
  size_t nLen = strlen(tinfo->childTableName);
  memcpy(key, currElement->measure, currElement->measureLen);
  memcpy(key + currElement->measureLen + 1, tinfo->childTableName, nLen);
234 235 236
  void *uid =
      taosHashGet(info->tableUids, key,
                  currElement->measureLen + 1 + nLen);  // use \0 as separator for stable name and child table name
237 238 239
  if (uid == NULL) {
    tinfo->uid = info->uid++;
    taosHashPut(info->tableUids, key, currElement->measureLen + 1 + nLen, &tinfo->uid, sizeof(uint64_t));
240 241
  } else {
    tinfo->uid = *(uint64_t *)uid;
242 243 244
  }
}

wmmhello's avatar
wmmhello 已提交
245 246 247 248 249 250
static void smlDestroySTableMeta(void *para) {
  SSmlSTableMeta *meta = *(SSmlSTableMeta**)para;
  taosHashCleanup(meta->tagHash);
  taosHashCleanup(meta->colHash);
  taosArrayDestroy(meta->tags);
  taosArrayDestroy(meta->cols);
wmmhello's avatar
wmmhello 已提交
251
  taosMemoryFreeClear(meta->tableMeta);
wmmhello's avatar
wmmhello 已提交
252 253 254
  taosMemoryFree(meta);
}

255 256 257 258
SSmlSTableMeta *smlBuildSTableMeta(bool isDataFormat) {
  SSmlSTableMeta *meta = (SSmlSTableMeta *)taosMemoryCalloc(sizeof(SSmlSTableMeta), 1);
  if (!meta) {
    return NULL;
259 260
  }

X
Xiaoyu Wang 已提交
261
  if (unlikely(!isDataFormat)) {
262 263 264 265 266
    meta->tagHash = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
    if (meta->tagHash == NULL) {
      uError("SML:smlBuildSTableMeta failed to allocate memory");
      goto cleanup;
    }
wmmhello's avatar
wmmhello 已提交
267

268 269 270 271 272
    meta->colHash = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
    if (meta->colHash == NULL) {
      uError("SML:smlBuildSTableMeta failed to allocate memory");
      goto cleanup;
    }
wmmhello's avatar
wmmhello 已提交
273 274
  }

275 276 277 278
  meta->tags = taosArrayInit(32, sizeof(SSmlKv));
  if (meta->tags == NULL) {
    uError("SML:smlBuildSTableMeta failed to allocate memory");
    goto cleanup;
279 280
  }

281 282 283 284 285 286
  meta->cols = taosArrayInit(32, sizeof(SSmlKv));
  if (meta->cols == NULL) {
    uError("SML:smlBuildSTableMeta failed to allocate memory");
    goto cleanup;
  }
  return meta;
287

X
Xiaoyu Wang 已提交
288
cleanup:
wmmhello's avatar
wmmhello 已提交
289
  smlDestroySTableMeta(meta);
290
  return NULL;
wmmhello's avatar
wmmhello 已提交
291 292
}

X
Xiaoyu Wang 已提交
293 294 295 296 297 298 299
// uint16_t smlCalTypeSum(char* endptr, int32_t left){
//   uint16_t sum = 0;
//   for(int i = 0; i < left; i++){
//     sum += endptr[i];
//   }
//   return sum;
// }
wmmhello's avatar
wmmhello 已提交
300

X
Xiaoyu Wang 已提交
301 302 303
#define RETURN_FALSE                                 \
  smlBuildInvalidDataMsg(msg, "invalid data", pVal); \
  return false;
wmmhello's avatar
wmmhello 已提交
304

X
Xiaoyu Wang 已提交
305 306 307 308 309 310 311 312 313 314
#define SET_DOUBLE                     \
  kvVal->type = TSDB_DATA_TYPE_DOUBLE; \
  kvVal->d = result;

#define SET_FLOAT                                                                              \
  if (!IS_VALID_FLOAT(result)) {                                                               \
    smlBuildInvalidDataMsg(msg, "float out of range[-3.402823466e+38,3.402823466e+38]", pVal); \
    return false;                                                                              \
  }                                                                                            \
  kvVal->type = TSDB_DATA_TYPE_FLOAT;                                                          \
wmmhello's avatar
wmmhello 已提交
315 316
  kvVal->f = (float)result;

X
Xiaoyu Wang 已提交
317
#define SET_BIGINT                                                                                       \
wmmhello's avatar
wmmhello 已提交
318 319 320 321 322 323 324 325
  errno = 0;                                                                                             \
  int64_t tmp = taosStr2Int64(pVal, &endptr, 10);                                                        \
  if (errno == ERANGE) {                                                                                 \
    smlBuildInvalidDataMsg(msg, "big int out of range[-9223372036854775808,9223372036854775807]", pVal); \
    return false;                                                                                        \
  }                                                                                                      \
  kvVal->type = TSDB_DATA_TYPE_BIGINT;                                                                   \
  kvVal->i = tmp;
wmmhello's avatar
wmmhello 已提交
326

X
Xiaoyu Wang 已提交
327 328 329 330 331 332
#define SET_INT                                                                    \
  if (!IS_VALID_INT(result)) {                                                     \
    smlBuildInvalidDataMsg(msg, "int out of range[-2147483648,2147483647]", pVal); \
    return false;                                                                  \
  }                                                                                \
  kvVal->type = TSDB_DATA_TYPE_INT;                                                \
wmmhello's avatar
wmmhello 已提交
333 334
  kvVal->i = result;

X
Xiaoyu Wang 已提交
335 336 337 338 339 340
#define SET_SMALL_INT                                                          \
  if (!IS_VALID_SMALLINT(result)) {                                            \
    smlBuildInvalidDataMsg(msg, "small int our of range[-32768,32767]", pVal); \
    return false;                                                              \
  }                                                                            \
  kvVal->type = TSDB_DATA_TYPE_SMALLINT;                                       \
wmmhello's avatar
wmmhello 已提交
341 342
  kvVal->i = result;

X
Xiaoyu Wang 已提交
343
#define SET_UBIGINT                                                                             \
wmmhello's avatar
wmmhello 已提交
344 345 346 347 348 349 350 351
  errno = 0;                                                                                    \
  uint64_t tmp = taosStr2UInt64(pVal, &endptr, 10);                                             \
  if (errno == ERANGE || result < 0) {                                                          \
    smlBuildInvalidDataMsg(msg, "unsigned big int out of range[0,18446744073709551615]", pVal); \
    return false;                                                                               \
  }                                                                                             \
  kvVal->type = TSDB_DATA_TYPE_UBIGINT;                                                         \
  kvVal->u = tmp;
wmmhello's avatar
wmmhello 已提交
352

X
Xiaoyu Wang 已提交
353 354 355 356 357 358
#define SET_UINT                                                                  \
  if (!IS_VALID_UINT(result)) {                                                   \
    smlBuildInvalidDataMsg(msg, "unsigned int out of range[0,4294967295]", pVal); \
    return false;                                                                 \
  }                                                                               \
  kvVal->type = TSDB_DATA_TYPE_UINT;                                              \
wmmhello's avatar
wmmhello 已提交
359 360
  kvVal->u = result;

X
Xiaoyu Wang 已提交
361 362 363 364 365 366
#define SET_USMALL_INT                                                            \
  if (!IS_VALID_USMALLINT(result)) {                                              \
    smlBuildInvalidDataMsg(msg, "unsigned small int out of rang[0,65535]", pVal); \
    return false;                                                                 \
  }                                                                               \
  kvVal->type = TSDB_DATA_TYPE_USMALLINT;                                         \
wmmhello's avatar
wmmhello 已提交
367 368
  kvVal->u = result;

X
Xiaoyu Wang 已提交
369 370 371 372 373 374
#define SET_TINYINT                                                       \
  if (!IS_VALID_TINYINT(result)) {                                        \
    smlBuildInvalidDataMsg(msg, "tiny int out of range[-128,127]", pVal); \
    return false;                                                         \
  }                                                                       \
  kvVal->type = TSDB_DATA_TYPE_TINYINT;                                   \
wmmhello's avatar
wmmhello 已提交
375 376
  kvVal->i = result;

X
Xiaoyu Wang 已提交
377 378 379 380 381 382
#define SET_UTINYINT                                                            \
  if (!IS_VALID_UTINYINT(result)) {                                             \
    smlBuildInvalidDataMsg(msg, "unsigned tiny int out of range[0,255]", pVal); \
    return false;                                                               \
  }                                                                             \
  kvVal->type = TSDB_DATA_TYPE_UTINYINT;                                        \
wmmhello's avatar
wmmhello 已提交
383 384
  kvVal->u = result;

385
bool smlParseNumber(SSmlKv *kvVal, SSmlMsgBuf *msg) {
wmmhello's avatar
wmmhello 已提交
386 387
  const char *pVal = kvVal->value;
  int32_t     len = kvVal->length;
X
Xiaoyu Wang 已提交
388
  char       *endptr = NULL;
wmmhello's avatar
wmmhello 已提交
389 390 391 392 393 394 395 396 397
  double      result = taosStr2Double(pVal, &endptr);
  if (pVal == endptr) {
    RETURN_FALSE
  }

  int32_t left = len - (endptr - pVal);
  if (left == 0) {
    SET_DOUBLE
  } else if (left == 3) {
X
Xiaoyu Wang 已提交
398 399
    if (endptr[0] == 'f' || endptr[0] == 'F') {
      if (endptr[1] == '6' && endptr[2] == '4') {
wmmhello's avatar
wmmhello 已提交
400
        SET_DOUBLE
X
Xiaoyu Wang 已提交
401
      } else if (endptr[1] == '3' && endptr[2] == '2') {
wmmhello's avatar
wmmhello 已提交
402
        SET_FLOAT
X
Xiaoyu Wang 已提交
403
      } else {
wmmhello's avatar
wmmhello 已提交
404 405
        RETURN_FALSE
      }
X
Xiaoyu Wang 已提交
406 407
    } else if (endptr[0] == 'i' || endptr[0] == 'I') {
      if (endptr[1] == '6' && endptr[2] == '4') {
wmmhello's avatar
wmmhello 已提交
408
        SET_BIGINT
X
Xiaoyu Wang 已提交
409
      } else if (endptr[1] == '3' && endptr[2] == '2') {
wmmhello's avatar
wmmhello 已提交
410
        SET_INT
X
Xiaoyu Wang 已提交
411
      } else if (endptr[1] == '1' && endptr[2] == '6') {
wmmhello's avatar
wmmhello 已提交
412
        SET_SMALL_INT
X
Xiaoyu Wang 已提交
413
      } else {
wmmhello's avatar
wmmhello 已提交
414 415
        RETURN_FALSE
      }
X
Xiaoyu Wang 已提交
416 417
    } else if (endptr[0] == 'u' || endptr[0] == 'U') {
      if (endptr[1] == '6' && endptr[2] == '4') {
wmmhello's avatar
wmmhello 已提交
418
        SET_UBIGINT
X
Xiaoyu Wang 已提交
419
      } else if (endptr[1] == '3' && endptr[2] == '2') {
wmmhello's avatar
wmmhello 已提交
420
        SET_UINT
X
Xiaoyu Wang 已提交
421
      } else if (endptr[1] == '1' && endptr[2] == '6') {
wmmhello's avatar
wmmhello 已提交
422
        SET_USMALL_INT
X
Xiaoyu Wang 已提交
423
      } else {
wmmhello's avatar
wmmhello 已提交
424 425
        RETURN_FALSE
      }
wmmhello's avatar
wmmhello 已提交
426
    } else {
wmmhello's avatar
wmmhello 已提交
427 428
      RETURN_FALSE
    }
X
Xiaoyu Wang 已提交
429 430 431
  } else if (left == 2) {
    if (endptr[0] == 'i' || endptr[0] == 'I') {
      if (endptr[1] == '8') {
wmmhello's avatar
wmmhello 已提交
432
        SET_TINYINT
X
Xiaoyu Wang 已提交
433
      } else {
wmmhello's avatar
wmmhello 已提交
434 435
        RETURN_FALSE
      }
X
Xiaoyu Wang 已提交
436
    } else if (endptr[0] == 'u' || endptr[0] == 'U') {
wmmhello's avatar
wmmhello 已提交
437 438 439 440 441
      if (endptr[1] == '8') {
        SET_UTINYINT
      } else {
        RETURN_FALSE
      }
X
Xiaoyu Wang 已提交
442
    } else {
wmmhello's avatar
wmmhello 已提交
443 444
      RETURN_FALSE
    }
X
Xiaoyu Wang 已提交
445 446
  } else if (left == 1) {
    if (endptr[0] == 'i' || endptr[0] == 'I') {
wmmhello's avatar
wmmhello 已提交
447
      SET_BIGINT
X
Xiaoyu Wang 已提交
448
    } else if (endptr[0] == 'u' || endptr[0] == 'U') {
wmmhello's avatar
wmmhello 已提交
449
      SET_UBIGINT
X
Xiaoyu Wang 已提交
450
    } else {
wmmhello's avatar
wmmhello 已提交
451 452 453 454 455 456 457 458 459
      RETURN_FALSE
    }
  } else {
    RETURN_FALSE;
  }
  return true;
}

bool smlParseNumberOld(SSmlKv *kvVal, SSmlMsgBuf *msg) {
wmmhello's avatar
wmmhello 已提交
460
  const char *pVal = kvVal->value;
X
Xiaoyu Wang 已提交
461 462 463 464
  int32_t     len = kvVal->length;
  char       *endptr = NULL;
  double      result = taosStr2Double(pVal, &endptr);
  if (pVal == endptr) {
465
    smlBuildInvalidDataMsg(msg, "invalid data", pVal);
wmmhello's avatar
wmmhello 已提交
466 467 468
    return false;
  }

469
  int32_t left = len - (endptr - pVal);
X
Xiaoyu Wang 已提交
470
  if (left == 0 || (left == 3 && strncasecmp(endptr, "f64", left) == 0)) {
471 472
    kvVal->type = TSDB_DATA_TYPE_DOUBLE;
    kvVal->d = result;
X
Xiaoyu Wang 已提交
473 474
  } else if ((left == 3 && strncasecmp(endptr, "f32", left) == 0)) {
    if (!IS_VALID_FLOAT(result)) {
475 476
      smlBuildInvalidDataMsg(msg, "float out of range[-3.402823466e+38,3.402823466e+38]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
477
    }
478 479
    kvVal->type = TSDB_DATA_TYPE_FLOAT;
    kvVal->f = (float)result;
X
Xiaoyu Wang 已提交
480 481
  } else if ((left == 1 && *endptr == 'i') || (left == 3 && strncasecmp(endptr, "i64", left) == 0)) {
    if (smlDoubleToInt64OverFlow(result)) {
wmmhello's avatar
wmmhello 已提交
482 483
      errno = 0;
      int64_t tmp = taosStr2Int64(pVal, &endptr, 10);
X
Xiaoyu Wang 已提交
484
      if (errno == ERANGE) {
wmmhello's avatar
wmmhello 已提交
485 486 487 488 489 490
        smlBuildInvalidDataMsg(msg, "big int out of range[-9223372036854775808,9223372036854775807]", pVal);
        return false;
      }
      kvVal->type = TSDB_DATA_TYPE_BIGINT;
      kvVal->i = tmp;
      return true;
wmmhello's avatar
wmmhello 已提交
491
    }
492
    kvVal->type = TSDB_DATA_TYPE_BIGINT;
wmmhello's avatar
wmmhello 已提交
493
    kvVal->i = (int64_t)result;
wmmhello's avatar
wmmhello 已提交
494
  } else if ((left == 1 && *endptr == 'u') || (left == 3 && strncasecmp(endptr, "u64", left) == 0)) {
X
Xiaoyu Wang 已提交
495
    if (result >= (double)UINT64_MAX || result < 0) {
wmmhello's avatar
wmmhello 已提交
496 497
      errno = 0;
      uint64_t tmp = taosStr2UInt64(pVal, &endptr, 10);
X
Xiaoyu Wang 已提交
498
      if (errno == ERANGE || result < 0) {
wmmhello's avatar
wmmhello 已提交
499 500 501 502 503 504
        smlBuildInvalidDataMsg(msg, "unsigned big int out of range[0,18446744073709551615]", pVal);
        return false;
      }
      kvVal->type = TSDB_DATA_TYPE_UBIGINT;
      kvVal->u = tmp;
      return true;
505
    }
506
    kvVal->type = TSDB_DATA_TYPE_UBIGINT;
wmmhello's avatar
wmmhello 已提交
507
    kvVal->u = result;
X
Xiaoyu Wang 已提交
508 509
  } else if (left == 3 && strncasecmp(endptr, "i32", left) == 0) {
    if (!IS_VALID_INT(result)) {
510 511
      smlBuildInvalidDataMsg(msg, "int out of range[-2147483648,2147483647]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
512
    }
513 514
    kvVal->type = TSDB_DATA_TYPE_INT;
    kvVal->i = result;
X
Xiaoyu Wang 已提交
515 516
  } else if (left == 3 && strncasecmp(endptr, "u32", left) == 0) {
    if (!IS_VALID_UINT(result)) {
517 518
      smlBuildInvalidDataMsg(msg, "unsigned int out of range[0,4294967295]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
519
    }
520 521
    kvVal->type = TSDB_DATA_TYPE_UINT;
    kvVal->u = result;
X
Xiaoyu Wang 已提交
522 523
  } else if (left == 3 && strncasecmp(endptr, "i16", left) == 0) {
    if (!IS_VALID_SMALLINT(result)) {
524 525
      smlBuildInvalidDataMsg(msg, "small int our of range[-32768,32767]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
526
    }
527 528
    kvVal->type = TSDB_DATA_TYPE_SMALLINT;
    kvVal->i = result;
X
Xiaoyu Wang 已提交
529 530
  } else if (left == 3 && strncasecmp(endptr, "u16", left) == 0) {
    if (!IS_VALID_USMALLINT(result)) {
531 532
      smlBuildInvalidDataMsg(msg, "unsigned small int out of rang[0,65535]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
533
    }
534 535
    kvVal->type = TSDB_DATA_TYPE_USMALLINT;
    kvVal->u = result;
X
Xiaoyu Wang 已提交
536 537
  } else if (left == 2 && strncasecmp(endptr, "i8", left) == 0) {
    if (!IS_VALID_TINYINT(result)) {
538 539
      smlBuildInvalidDataMsg(msg, "tiny int out of range[-128,127]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
540
    }
541 542
    kvVal->type = TSDB_DATA_TYPE_TINYINT;
    kvVal->i = result;
X
Xiaoyu Wang 已提交
543 544
  } else if (left == 2 && strncasecmp(endptr, "u8", left) == 0) {
    if (!IS_VALID_UTINYINT(result)) {
545 546
      smlBuildInvalidDataMsg(msg, "unsigned tiny int out of range[0,255]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
547
    }
548 549
    kvVal->type = TSDB_DATA_TYPE_UTINYINT;
    kvVal->u = result;
X
Xiaoyu Wang 已提交
550
  } else {
551
    smlBuildInvalidDataMsg(msg, "invalid data", pVal);
wmmhello's avatar
wmmhello 已提交
552 553
    return false;
  }
554
  return true;
wmmhello's avatar
wmmhello 已提交
555 556
}

X
Xiaoyu Wang 已提交
557
STableMeta *smlGetMeta(SSmlHandle *info, const void *measure, int32_t measureLen) {
558
  STableMeta *pTableMeta = NULL;
wmmhello's avatar
wmmhello 已提交
559

560 561
  SName pName = {TSDB_TABLE_NAME_T, info->taos->acctId, {0}, {0}};
  tstrncpy(pName.dbname, info->pRequest->pDb, sizeof(pName.dbname));
wmmhello's avatar
wmmhello 已提交
562

563 564 565 566 567 568 569
  SRequestConnInfo conn = {0};
  conn.pTrans = info->taos->pAppInfo->pTransporter;
  conn.requestId = info->pRequest->requestId;
  conn.requestObjRefId = info->pRequest->self;
  conn.mgmtEps = getEpSet_s(&info->taos->pAppInfo->mgmtEp);
  memset(pName.tname, 0, TSDB_TABLE_NAME_LEN);
  memcpy(pName.tname, measure, measureLen);
wmmhello's avatar
wmmhello 已提交
570

571
  int32_t code = catalogGetSTableMeta(info->pCatalog, &conn, &pName, &pTableMeta);
X
Xiaoyu Wang 已提交
572
  if (code != TSDB_CODE_SUCCESS) {
573 574
    return NULL;
  }
575
  return pTableMeta;
wmmhello's avatar
wmmhello 已提交
576
}
wmmhello's avatar
wmmhello 已提交
577

578 579
static int64_t smlGenId() {
  static volatile int64_t linesSmlHandleId = 0;
wmmhello's avatar
wmmhello 已提交
580

581 582 583 584
  int64_t id = 0;
  do {
    id = atomic_add_fetch_64(&linesSmlHandleId, 1);
  } while (id == 0);
585

586
  return id;
587 588
}

589 590 591 592 593
static int32_t smlGenerateSchemaAction(SSchema *colField, SHashObj *colHash, SSmlKv *kv, bool isTag,
                                       ESchemaAction *action, SSmlHandle *info) {
  uint16_t *index = colHash ? (uint16_t *)taosHashGet(colHash, kv->key, kv->keyLen) : NULL;
  if (index) {
    if (colField[*index].type != kv->type) {
594 595
      uError("SML:0x%" PRIx64 " point type and db type mismatch. db type: %d, point type: %d, key: %s", info->id,
             colField[*index].type, kv->type, kv->key);
596
      return TSDB_CODE_SML_INVALID_DATA;
597 598
    }

D
Dingle Zhang 已提交
599
    if (((colField[*index].type == TSDB_DATA_TYPE_VARCHAR || colField[*index].type == TSDB_DATA_TYPE_GEOMETRY) &&
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
         (colField[*index].bytes - VARSTR_HEADER_SIZE) < kv->length) ||
        (colField[*index].type == TSDB_DATA_TYPE_NCHAR &&
         ((colField[*index].bytes - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE < kv->length))) {
      if (isTag) {
        *action = SCHEMA_ACTION_CHANGE_TAG_SIZE;
      } else {
        *action = SCHEMA_ACTION_CHANGE_COLUMN_SIZE;
      }
    }
  } else {
    if (isTag) {
      *action = SCHEMA_ACTION_ADD_TAG;
    } else {
      *action = SCHEMA_ACTION_ADD_COLUMN;
    }
wmmhello's avatar
wmmhello 已提交
615
  }
616
  return 0;
617 618
}

619
#define BOUNDARY 1024
620 621
static int32_t smlFindNearestPowerOf2(int32_t length, uint8_t type) {
  int32_t result = 1;
622
  if (length >= BOUNDARY) {
623
    result = length;
624
  } else {
625
    while (result <= length) {
K
kailixu 已提交
626
      result <<= 1;
627
    }
628
  }
K
kailixu 已提交
629

D
Dingle Zhang 已提交
630
  if ((type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_GEOMETRY) && result > TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE) {
631
    result = TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE;
K
kailixu 已提交
632 633
  } else if (type == TSDB_DATA_TYPE_NCHAR && result > (TSDB_MAX_NCHAR_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE) {
    result = (TSDB_MAX_NCHAR_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE;
634
  }
635 636 637

  if (type == TSDB_DATA_TYPE_NCHAR) {
    result = result * TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE;
D
Dingle Zhang 已提交
638
  } else if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_GEOMETRY) {
639
    result = result + VARSTR_HEADER_SIZE;
640
  }
641
  return result;
642 643
}

644 645 646 647 648 649 650 651 652 653
static int32_t smlProcessSchemaAction(SSmlHandle *info, SSchema *schemaField, SHashObj *schemaHash, SArray *cols,
                                      ESchemaAction *action, bool isTag) {
  int32_t code = TSDB_CODE_SUCCESS;
  for (int j = 0; j < taosArrayGetSize(cols); ++j) {
    if (j == 0 && !isTag) continue;
    SSmlKv *kv = (SSmlKv *)taosArrayGet(cols, j);
    code = smlGenerateSchemaAction(schemaField, schemaHash, kv, isTag, action, info);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
654
  }
655
  return TSDB_CODE_SUCCESS;
656 657
}

658 659 660 661 662
static int32_t smlCheckMeta(SSchema *schema, int32_t length, SArray *cols, bool isTag) {
  SHashObj *hashTmp = taosHashInit(length, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
  int32_t   i = 0;
  for (; i < length; i++) {
    taosHashPut(hashTmp, schema[i].name, strlen(schema[i].name), &i, SHORT_BYTES);
663 664
  }

665 666 667 668
  if (isTag) {
    i = 0;
  } else {
    i = 1;
669
  }
670 671 672 673 674 675
  for (; i < taosArrayGetSize(cols); i++) {
    SSmlKv *kv = (SSmlKv *)taosArrayGet(cols, i);
    if (taosHashGet(hashTmp, kv->key, kv->keyLen) == NULL) {
      taosHashCleanup(hashTmp);
      return -1;
    }
676
  }
677 678 679
  taosHashCleanup(hashTmp);
  return 0;
}
680

681
static int32_t getBytes(uint8_t type, int32_t length) {
D
Dingle Zhang 已提交
682
  if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR || type == TSDB_DATA_TYPE_GEOMETRY) {
683 684 685 686
    return smlFindNearestPowerOf2(length, type);
  } else {
    return tDataTypes[type].bytes;
  }
687 688
}

689 690 691 692 693
static int32_t smlBuildFieldsList(SSmlHandle *info, SSchema *schemaField, SHashObj *schemaHash, SArray *cols,
                                  SArray *results, int32_t numOfCols, bool isTag) {
  for (int j = 0; j < taosArrayGetSize(cols); ++j) {
    SSmlKv       *kv = (SSmlKv *)taosArrayGet(cols, j);
    ESchemaAction action = SCHEMA_ACTION_NULL;
X
Xiaoyu Wang 已提交
694 695
    int           code = smlGenerateSchemaAction(schemaField, schemaHash, kv, isTag, &action, info);
    if (code != 0) {
D
dapan1121 已提交
696 697
      return code;
    }
698 699 700 701 702 703 704 705
    if (action == SCHEMA_ACTION_ADD_COLUMN || action == SCHEMA_ACTION_ADD_TAG) {
      SField field = {0};
      field.type = kv->type;
      field.bytes = getBytes(kv->type, kv->length);
      memcpy(field.name, kv->key, kv->keyLen);
      taosArrayPush(results, &field);
    } else if (action == SCHEMA_ACTION_CHANGE_COLUMN_SIZE || action == SCHEMA_ACTION_CHANGE_TAG_SIZE) {
      uint16_t *index = (uint16_t *)taosHashGet(schemaHash, kv->key, kv->keyLen);
X
Xiaoyu Wang 已提交
706
      if (index == NULL) {
D
dapan1121 已提交
707 708 709
        uError("smlBuildFieldsList get error, key:%s", kv->key);
        return TSDB_CODE_SML_INVALID_DATA;
      }
X
Xiaoyu Wang 已提交
710
      uint16_t newIndex = *index;
711 712 713
      if (isTag) newIndex -= numOfCols;
      SField *field = (SField *)taosArrayGet(results, newIndex);
      field->bytes = getBytes(kv->type, kv->length);
714 715
    }
  }
716 717 718 719 720 721 722 723

  int32_t maxLen = isTag ? TSDB_MAX_TAGS_LEN : TSDB_MAX_BYTES_PER_ROW;
  int32_t len = 0;
  for (int j = 0; j < taosArrayGetSize(results); ++j) {
    SField *field = taosArrayGet(results, j);
    len += field->bytes;
  }
  if(len > maxLen){
724
    return isTag ? TSDB_CODE_PAR_INVALID_TAGS_LENGTH : TSDB_CODE_PAR_INVALID_ROW_LENGTH;
725 726
  }

727 728 729
  return TSDB_CODE_SUCCESS;
}

730 731 732 733 734 735 736 737
// static int32_t smlSendMetaMsg(SSmlHandle *info, SName *pName, SSmlSTableMeta *sTableData,
//                               int32_t colVer, int32_t tagVer, int8_t source, uint64_t suid){
static int32_t smlSendMetaMsg(SSmlHandle *info, SName *pName, SArray *pColumns, SArray *pTags, STableMeta *pTableMeta,
                              ESchemaAction action) {
  SRequestObj   *pRequest = NULL;
  SMCreateStbReq pReq = {0};
  int32_t        code = TSDB_CODE_SUCCESS;
  SCmdMsgInfo    pCmdMsg = {0};
738
  char          *pSql = NULL;
739 740 741 742 743 744 745 746 747 748 749 750

  // put front for free
  pReq.numOfColumns = taosArrayGetSize(pColumns);
  pReq.pColumns = pColumns;
  pReq.numOfTags = taosArrayGetSize(pTags);
  pReq.pTags = pTags;

  if (action == SCHEMA_ACTION_CREATE_STABLE) {
    pReq.colVer = 1;
    pReq.tagVer = 1;
    pReq.suid = 0;
    pReq.source = TD_REQ_FROM_APP;
751
    pSql = "sml_create_stable";
752 753 754 755 756
  } else if (action == SCHEMA_ACTION_ADD_TAG || action == SCHEMA_ACTION_CHANGE_TAG_SIZE) {
    pReq.colVer = pTableMeta->sversion;
    pReq.tagVer = pTableMeta->tversion + 1;
    pReq.suid = pTableMeta->uid;
    pReq.source = TD_REQ_FROM_TAOX;
757
    pSql = (action == SCHEMA_ACTION_ADD_TAG) ? "sml_add_tag" : "sml_modify_tag_size";
758 759 760 761 762
  } else if (action == SCHEMA_ACTION_ADD_COLUMN || action == SCHEMA_ACTION_CHANGE_COLUMN_SIZE) {
    pReq.colVer = pTableMeta->sversion + 1;
    pReq.tagVer = pTableMeta->tversion;
    pReq.suid = pTableMeta->uid;
    pReq.source = TD_REQ_FROM_TAOX;
763
    pSql = (action == SCHEMA_ACTION_ADD_COLUMN) ? "sml_add_column" : "sml_modify_column_size";
wmmhello's avatar
wmmhello 已提交
764 765 766
  } else{
    uError("SML:0x%" PRIx64 " invalid action:%d", info->id, action);
    goto end;
767 768 769 770 771 772 773 774 775 776 777
  }

  code = buildRequest(info->taos->id, pSql, strlen(pSql), NULL, false, &pRequest, 0);
  if (code != TSDB_CODE_SUCCESS) {
    goto end;
  }

  pRequest->syncQuery = true;
  if (!pRequest->pDb) {
    code = TSDB_CODE_PAR_DB_NOT_SPECIFIED;
    goto end;
778
  }
779

780 781 782 783
  if (pReq.numOfTags == 0) {
    pReq.numOfTags = 1;
    SField field = {0};
    field.type = TSDB_DATA_TYPE_NCHAR;
784
    field.bytes = TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE;
785 786
    strcpy(field.name, tsSmlTagName);
    taosArrayPush(pReq.pTags, &field);
787
  }
wmmhello's avatar
wmmhello 已提交
788

789 790 791
  pReq.commentLen = -1;
  pReq.igExists = true;
  tNameExtractFullName(pName, pReq.name);
792

793 794 795 796 797 798 799 800 801
  pCmdMsg.epSet = getEpSet_s(&info->taos->pAppInfo->mgmtEp);
  pCmdMsg.msgType = TDMT_MND_CREATE_STB;
  pCmdMsg.msgLen = tSerializeSMCreateStbReq(NULL, 0, &pReq);
  pCmdMsg.pMsg = taosMemoryMalloc(pCmdMsg.msgLen);
  if (NULL == pCmdMsg.pMsg) {
    code = TSDB_CODE_OUT_OF_MEMORY;
    goto end;
  }
  tSerializeSMCreateStbReq(pCmdMsg.pMsg, pCmdMsg.msgLen, &pReq);
802

803 804 805 806 807 808
  SQuery pQuery;
  memset(&pQuery, 0, sizeof(pQuery));
  pQuery.execMode = QUERY_EXEC_MODE_RPC;
  pQuery.pCmdMsg = &pCmdMsg;
  pQuery.msgType = pQuery.pCmdMsg->msgType;
  pQuery.stableQuery = true;
809

810
  launchQueryImpl(pRequest, &pQuery, true, NULL);
811

812 813
  if (pRequest->code == TSDB_CODE_SUCCESS) {
    catalogRemoveTableMeta(info->pCatalog, pName);
814
  }
815 816
  code = pRequest->code;
  taosMemoryFree(pCmdMsg.pMsg);
817

X
Xiaoyu Wang 已提交
818
end:
819 820 821 822
  destroyRequest(pRequest);
  tFreeSMCreateStbReq(&pReq);
  return code;
}
823

824
static int32_t smlModifyDBSchemas(SSmlHandle *info) {
X
Xiaoyu Wang 已提交
825 826
  uDebug("SML:0x%" PRIx64 " smlModifyDBSchemas start, format:%d, needModifySchema:%d", info->id, info->dataFormat,
         info->needModifySchema);
X
Xiaoyu Wang 已提交
827
  if (info->dataFormat && !info->needModifySchema) {
828
    return TSDB_CODE_SUCCESS;
829
  }
830 831 832
  int32_t     code = 0;
  SHashObj   *hashTmp = NULL;
  STableMeta *pTableMeta = NULL;
833 834 835 836 837 838 839 840 841

  SName pName = {TSDB_TABLE_NAME_T, info->taos->acctId, {0}, {0}};
  tstrncpy(pName.dbname, info->pRequest->pDb, sizeof(pName.dbname));

  SRequestConnInfo conn = {0};
  conn.pTrans = info->taos->pAppInfo->pTransporter;
  conn.requestId = info->pRequest->requestId;
  conn.requestObjRefId = info->pRequest->self;
  conn.mgmtEps = getEpSet_s(&info->taos->pAppInfo->mgmtEp);
842

843
  SSmlSTableMeta **tmp = (SSmlSTableMeta **)taosHashIterate(info->superTables, NULL);
844
  while (tmp) {
845
    SSmlSTableMeta *sTableData = *tmp;
846
    bool            needCheckMeta = false;  // for multi thread
847

848 849
    size_t superTableLen = 0;
    void  *superTable = taosHashGetKey(tmp, &superTableLen);
850
    char  *measure = taosMemoryMalloc(superTableLen);
wmmhello's avatar
wmmhello 已提交
851 852
    memcpy(measure, superTable, superTableLen);
    PROCESS_SLASH_IN_MEASUREMENT(measure, superTableLen);
853
    smlStrReplace(measure, superTableLen);
854
    memset(pName.tname, 0, TSDB_TABLE_NAME_LEN);
wmmhello's avatar
wmmhello 已提交
855 856
    memcpy(pName.tname, measure, superTableLen);
    taosMemoryFree(measure);
857

858
    code = catalogGetSTableMeta(info->pCatalog, &conn, &pName, &pTableMeta);
859

860
    if (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_MND_STB_NOT_EXIST) {
wmmhello's avatar
wmmhello 已提交
861 862 863 864
      code = smlCheckAuth(info, &conn, NULL, AUTH_TYPE_WRITE);
      if(code != TSDB_CODE_SUCCESS){
        goto end;
      }
D
dapan1121 已提交
865
      uDebug("SML:0x%" PRIx64 " smlModifyDBSchemas create table:%s", info->id, pName.tname);
866 867
      SArray *pColumns = taosArrayInit(taosArrayGetSize(sTableData->cols), sizeof(SField));
      SArray *pTags = taosArrayInit(taosArrayGetSize(sTableData->tags), sizeof(SField));
D
dapan1121 已提交
868 869 870
      code = smlBuildFieldsList(info, NULL, NULL, sTableData->tags, pTags, 0, true);
      if (code != TSDB_CODE_SUCCESS) {
        uError("SML:0x%" PRIx64 " smlBuildFieldsList tag1 failed. %s", info->id, pName.tname);
871 872
        taosArrayDestroy(pColumns);
        taosArrayDestroy(pTags);
D
dapan1121 已提交
873 874 875 876 877
        goto end;
      }
      code = smlBuildFieldsList(info, NULL, NULL, sTableData->cols, pColumns, 0, false);
      if (code != TSDB_CODE_SUCCESS) {
        uError("SML:0x%" PRIx64 " smlBuildFieldsList col1 failed. %s", info->id, pName.tname);
878 879
        taosArrayDestroy(pColumns);
        taosArrayDestroy(pTags);
D
dapan1121 已提交
880 881
        goto end;
      }
882 883 884 885
      code = smlSendMetaMsg(info, &pName, pColumns, pTags, NULL, SCHEMA_ACTION_CREATE_STABLE);
      if (code != TSDB_CODE_SUCCESS) {
        uError("SML:0x%" PRIx64 " smlSendMetaMsg failed. can not create %s", info->id, pName.tname);
        goto end;
886
      }
887 888
      info->cost.numOfCreateSTables++;
      taosMemoryFreeClear(pTableMeta);
889

890 891 892 893
      code = catalogGetSTableMeta(info->pCatalog, &conn, &pName, &pTableMeta);
      if (code != TSDB_CODE_SUCCESS) {
        uError("SML:0x%" PRIx64 " catalogGetSTableMeta failed. super table name %s", info->id, pName.tname);
        goto end;
894
      }
895 896 897 898 899 900
    } else if (code == TSDB_CODE_SUCCESS) {
      hashTmp = taosHashInit(pTableMeta->tableInfo.numOfTags, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true,
                             HASH_NO_LOCK);
      for (uint16_t i = pTableMeta->tableInfo.numOfColumns;
           i < pTableMeta->tableInfo.numOfColumns + pTableMeta->tableInfo.numOfTags; i++) {
        taosHashPut(hashTmp, pTableMeta->schema[i].name, strlen(pTableMeta->schema[i].name), &i, SHORT_BYTES);
901
      }
902

903 904 905 906
      ESchemaAction action = SCHEMA_ACTION_NULL;
      code = smlProcessSchemaAction(info, pTableMeta->schema, hashTmp, sTableData->tags, &action, true);
      if (code != TSDB_CODE_SUCCESS) {
        goto end;
907
      }
908
      if (action != SCHEMA_ACTION_NULL) {
wmmhello's avatar
wmmhello 已提交
909 910 911 912
        code = smlCheckAuth(info, &conn, pName.tname, AUTH_TYPE_WRITE);
        if(code != TSDB_CODE_SUCCESS){
          goto end;
        }
X
Xiaoyu Wang 已提交
913 914
        uDebug("SML:0x%" PRIx64 " smlModifyDBSchemas change table tag, table:%s, action:%d", info->id, pName.tname,
               action);
915 916 917 918
        SArray *pColumns =
            taosArrayInit(taosArrayGetSize(sTableData->cols) + pTableMeta->tableInfo.numOfColumns, sizeof(SField));
        SArray *pTags =
            taosArrayInit(taosArrayGetSize(sTableData->tags) + pTableMeta->tableInfo.numOfTags, sizeof(SField));
919

920 921 922 923 924 925 926 927 928
        for (uint16_t i = 0; i < pTableMeta->tableInfo.numOfColumns + pTableMeta->tableInfo.numOfTags; i++) {
          SField field = {0};
          field.type = pTableMeta->schema[i].type;
          field.bytes = pTableMeta->schema[i].bytes;
          strcpy(field.name, pTableMeta->schema[i].name);
          if (i < pTableMeta->tableInfo.numOfColumns) {
            taosArrayPush(pColumns, &field);
          } else {
            taosArrayPush(pTags, &field);
929 930
          }
        }
D
dapan1121 已提交
931
        code = smlBuildFieldsList(info, pTableMeta->schema, hashTmp, sTableData->tags, pTags,
X
Xiaoyu Wang 已提交
932
                                  pTableMeta->tableInfo.numOfColumns, true);
D
dapan1121 已提交
933 934
        if (code != TSDB_CODE_SUCCESS) {
          uError("SML:0x%" PRIx64 " smlBuildFieldsList tag2 failed. %s", info->id, pName.tname);
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
          taosArrayDestroy(pColumns);
          taosArrayDestroy(pTags);
          goto end;
        }

        if (taosArrayGetSize(pTags) + pTableMeta->tableInfo.numOfColumns > TSDB_MAX_COLUMNS) {
          uError("SML:0x%" PRIx64 " too many columns than 4096", info->id);
          code = TSDB_CODE_PAR_TOO_MANY_COLUMNS;
          taosArrayDestroy(pColumns);
          taosArrayDestroy(pTags);
          goto end;
        }
        if (taosArrayGetSize(pTags) > TSDB_MAX_TAGS) {
          uError("SML:0x%" PRIx64 " too many tags than 128", info->id);
          code = TSDB_CODE_PAR_INVALID_TAGS_NUM;
          taosArrayDestroy(pColumns);
          taosArrayDestroy(pTags);
D
dapan1121 已提交
952 953
          goto end;
        }
954

955 956 957 958
        code = smlSendMetaMsg(info, &pName, pColumns, pTags, pTableMeta, action);
        if (code != TSDB_CODE_SUCCESS) {
          uError("SML:0x%" PRIx64 " smlSendMetaMsg failed. can not create %s", info->id, pName.tname);
          goto end;
959
        }
960

961 962 963 964 965 966 967 968 969
        info->cost.numOfAlterTagSTables++;
        taosMemoryFreeClear(pTableMeta);
        code = catalogRefreshTableMeta(info->pCatalog, &conn, &pName, -1);
        if (code != TSDB_CODE_SUCCESS) {
          goto end;
        }
        code = catalogGetSTableMeta(info->pCatalog, &conn, &pName, &pTableMeta);
        if (code != TSDB_CODE_SUCCESS) {
          goto end;
wmmhello's avatar
wmmhello 已提交
970
        }
971 972
      }

973 974 975
      taosHashClear(hashTmp);
      for (uint16_t i = 0; i < pTableMeta->tableInfo.numOfColumns; i++) {
        taosHashPut(hashTmp, pTableMeta->schema[i].name, strlen(pTableMeta->schema[i].name), &i, SHORT_BYTES);
976
      }
977 978 979 980
      action = SCHEMA_ACTION_NULL;
      code = smlProcessSchemaAction(info, pTableMeta->schema, hashTmp, sTableData->cols, &action, false);
      if (code != TSDB_CODE_SUCCESS) {
        goto end;
981
      }
982
      if (action != SCHEMA_ACTION_NULL) {
wmmhello's avatar
wmmhello 已提交
983 984 985 986
        code = smlCheckAuth(info, &conn, pName.tname, AUTH_TYPE_WRITE);
        if(code != TSDB_CODE_SUCCESS){
          goto end;
        }
X
Xiaoyu Wang 已提交
987 988
        uDebug("SML:0x%" PRIx64 " smlModifyDBSchemas change table col, table:%s, action:%d", info->id, pName.tname,
               action);
989 990 991 992
        SArray *pColumns =
            taosArrayInit(taosArrayGetSize(sTableData->cols) + pTableMeta->tableInfo.numOfColumns, sizeof(SField));
        SArray *pTags =
            taosArrayInit(taosArrayGetSize(sTableData->tags) + pTableMeta->tableInfo.numOfTags, sizeof(SField));
993

994 995 996 997 998 999 1000 1001 1002 1003
        for (uint16_t i = 0; i < pTableMeta->tableInfo.numOfColumns + pTableMeta->tableInfo.numOfTags; i++) {
          SField field = {0};
          field.type = pTableMeta->schema[i].type;
          field.bytes = pTableMeta->schema[i].bytes;
          strcpy(field.name, pTableMeta->schema[i].name);
          if (i < pTableMeta->tableInfo.numOfColumns) {
            taosArrayPush(pColumns, &field);
          } else {
            taosArrayPush(pTags, &field);
          }
1004 1005
        }

D
dapan1121 已提交
1006
        code = smlBuildFieldsList(info, pTableMeta->schema, hashTmp, sTableData->cols, pColumns,
X
Xiaoyu Wang 已提交
1007
                                  pTableMeta->tableInfo.numOfColumns, false);
D
dapan1121 已提交
1008 1009
        if (code != TSDB_CODE_SUCCESS) {
          uError("SML:0x%" PRIx64 " smlBuildFieldsList col2 failed. %s", info->id, pName.tname);
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
          taosArrayDestroy(pColumns);
          taosArrayDestroy(pTags);
          goto end;
        }

        if (taosArrayGetSize(pColumns) + pTableMeta->tableInfo.numOfTags > TSDB_MAX_COLUMNS) {
          uError("SML:0x%" PRIx64 " too many columns than 4096", info->id);
          code = TSDB_CODE_PAR_TOO_MANY_COLUMNS;
          taosArrayDestroy(pColumns);
          taosArrayDestroy(pTags);
D
dapan1121 已提交
1020 1021
          goto end;
        }
1022

1023 1024 1025 1026
        code = smlSendMetaMsg(info, &pName, pColumns, pTags, pTableMeta, action);
        if (code != TSDB_CODE_SUCCESS) {
          uError("SML:0x%" PRIx64 " smlSendMetaMsg failed. can not create %s", info->id, pName.tname);
          goto end;
1027
        }
1028

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
        info->cost.numOfAlterColSTables++;
        taosMemoryFreeClear(pTableMeta);
        code = catalogRefreshTableMeta(info->pCatalog, &conn, &pName, -1);
        if (code != TSDB_CODE_SUCCESS) {
          goto end;
        }
        code = catalogGetSTableMeta(info->pCatalog, &conn, &pName, &pTableMeta);
        if (code != TSDB_CODE_SUCCESS) {
          uError("SML:0x%" PRIx64 " catalogGetSTableMeta failed. super table name %s", info->id, pName.tname);
          goto end;
1039 1040
        }
      }
wmmhello's avatar
wmmhello 已提交
1041

1042 1043 1044
      needCheckMeta = true;
      taosHashCleanup(hashTmp);
      hashTmp = NULL;
X
Xiaoyu Wang 已提交
1045
    } else {
1046 1047
      uError("SML:0x%" PRIx64 " load table meta error: %s", info->id, tstrerror(code));
      goto end;
wmmhello's avatar
wmmhello 已提交
1048
    }
1049

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
    if (needCheckMeta) {
      code = smlCheckMeta(&(pTableMeta->schema[pTableMeta->tableInfo.numOfColumns]), pTableMeta->tableInfo.numOfTags,
                          sTableData->tags, true);
      if (code != TSDB_CODE_SUCCESS) {
        uError("SML:0x%" PRIx64 " check tag failed. super table name %s", info->id, pName.tname);
        goto end;
      }
      code = smlCheckMeta(&(pTableMeta->schema[0]), pTableMeta->tableInfo.numOfColumns, sTableData->cols, false);
      if (code != TSDB_CODE_SUCCESS) {
        uError("SML:0x%" PRIx64 " check cols failed. super table name %s", info->id, pName.tname);
        goto end;
1061 1062
      }
    }
1063

wmmhello's avatar
wmmhello 已提交
1064
    taosMemoryFreeClear(sTableData->tableMeta);
1065
    sTableData->tableMeta = pTableMeta;
X
Xiaoyu Wang 已提交
1066
    uDebug("SML:0x%" PRIx64 "modify schema uid:%" PRIu64 ", sversion:%d, tversion:%d", info->id, pTableMeta->uid,
1067 1068
           pTableMeta->sversion, pTableMeta->tversion);
    tmp = (SSmlSTableMeta **)taosHashIterate(info->superTables, tmp);
wmmhello's avatar
wmmhello 已提交
1069
  }
X
Xiaoyu Wang 已提交
1070 1071
  uDebug("SML:0x%" PRIx64 " smlModifyDBSchemas end success, format:%d, needModifySchema:%d", info->id, info->dataFormat,
         info->needModifySchema);
D
dapan1121 已提交
1072

1073
  return 0;
1074

X
Xiaoyu Wang 已提交
1075
end:
1076
  taosHashCancelIterate(info->superTables, tmp);
1077 1078
  taosHashCleanup(hashTmp);
  taosMemoryFreeClear(pTableMeta);
D
dapan1121 已提交
1079
  catalogRefreshTableMeta(info->pCatalog, &conn, &pName, 1);
X
Xiaoyu Wang 已提交
1080 1081
  uError("SML:0x%" PRIx64 " smlModifyDBSchemas end failed:%d:%s, format:%d, needModifySchema:%d", info->id, code,
         tstrerror(code), info->dataFormat, info->needModifySchema);
D
dapan1121 已提交
1082

1083
  return code;
wmmhello's avatar
wmmhello 已提交
1084 1085
}

1086 1087 1088 1089 1090 1091 1092
/*
static int32_t smlCheckDupUnit(SHashObj *dumplicateKey, SArray *tags, SSmlMsgBuf *msg){
  for(int i = 0; i < taosArrayGetSize(tags); i++) {
    SSmlKv *tag = taosArrayGet(tags, i);
    if (smlCheckDuplicateKey(tag->key, tag->keyLen, dumplicateKey)) {
      smlBuildInvalidDataMsg(msg, "dumplicate key", tag->key);
      return TSDB_CODE_TSC_DUP_NAMES;
1093
    }
wmmhello's avatar
wmmhello 已提交
1094
  }
1095 1096 1097
  return TSDB_CODE_SUCCESS;
}

1098 1099 1100 1101 1102
static int32_t smlJudgeDupColName(SArray *cols, SArray *tags, SSmlMsgBuf *msg) {
  SHashObj *dumplicateKey = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  int ret = smlCheckDupUnit(dumplicateKey, cols, msg);
  if(ret != TSDB_CODE_SUCCESS){
    goto end;
1103
  }
1104 1105 1106
  ret = smlCheckDupUnit(dumplicateKey, tags, msg);
  if(ret != TSDB_CODE_SUCCESS){
    goto end;
1107
  }
1108

1109 1110 1111
  end:
  taosHashCleanup(dumplicateKey);
  return ret;
wmmhello's avatar
wmmhello 已提交
1112
}
1113
*/
wmmhello's avatar
wmmhello 已提交
1114

X
Xiaoyu Wang 已提交
1115
static void smlInsertMeta(SHashObj *metaHash, SArray *metaArray, SArray *cols) {
1116 1117
  for (int16_t i = 0; i < taosArrayGetSize(cols); ++i) {
    SSmlKv *kv = (SSmlKv *)taosArrayGet(cols, i);
X
Xiaoyu Wang 已提交
1118 1119
    int     ret = taosHashPut(metaHash, kv->key, kv->keyLen, &i, SHORT_BYTES);
    if (ret == 0) {
1120 1121
      taosArrayPush(metaArray, kv);
    }
1122
  }
1123
}
wmmhello's avatar
wmmhello 已提交
1124

1125 1126 1127 1128 1129 1130 1131
static int32_t smlUpdateMeta(SHashObj *metaHash, SArray *metaArray, SArray *cols, bool isTag, SSmlMsgBuf *msg) {
  for (int i = 0; i < taosArrayGetSize(cols); ++i) {
    SSmlKv *kv = (SSmlKv *)taosArrayGet(cols, i);

    int16_t *index = (int16_t *)taosHashGet(metaHash, kv->key, kv->keyLen);
    if (index) {
      SSmlKv *value = (SSmlKv *)taosArrayGet(metaArray, *index);
X
Xiaoyu Wang 已提交
1132
      if (isTag) {
1133 1134
        if (kv->length > value->length) {
          value->length = kv->length;
1135
        }
1136 1137 1138 1139 1140
        continue;
      }
      if (kv->type != value->type) {
        smlBuildInvalidDataMsg(msg, "the type is not the same like before", kv->key);
        return TSDB_CODE_SML_NOT_SAME_TYPE;
1141 1142
      }

1143 1144 1145 1146 1147
      if (IS_VAR_DATA_TYPE(kv->type) && (kv->length > value->length)) {  // update string len, if bigger
        value->length = kv->length;
      }
    } else {
      size_t tmp = taosArrayGetSize(metaArray);
X
Xiaoyu Wang 已提交
1148
      if (tmp > INT16_MAX) {
D
dapan1121 已提交
1149
        smlBuildInvalidDataMsg(msg, "too many cols or tags", kv->key);
1150
        uError("too many cols or tags");
D
dapan1121 已提交
1151
        return TSDB_CODE_SML_INVALID_DATA;
1152
      }
1153
      int16_t size = tmp;
X
Xiaoyu Wang 已提交
1154 1155
      int     ret = taosHashPut(metaHash, kv->key, kv->keyLen, &size, SHORT_BYTES);
      if (ret == 0) {
1156
        taosArrayPush(metaArray, kv);
1157 1158 1159 1160
      }
    }
  }

1161 1162
  return TSDB_CODE_SUCCESS;
}
1163

wmmhello's avatar
wmmhello 已提交
1164 1165
void smlDestroyTableInfo(void *para) {
  SSmlTableInfo *tag = *(SSmlTableInfo**)para;
1166 1167 1168 1169
  for (size_t i = 0; i < taosArrayGetSize(tag->cols); i++) {
    SHashObj *kvHash = (SHashObj *)taosArrayGetP(tag->cols, i);
    taosHashCleanup(kvHash);
  }
1170

X
Xiaoyu Wang 已提交
1171 1172 1173 1174 1175
  //  if (info->parseJsonByLib) {
  //    SSmlLineInfo *key = (SSmlLineInfo *)(tag->key);
  //    if (key != NULL) taosMemoryFree(key->tags);
  //  }
  //  taosMemoryFree(tag->key);
1176
  taosArrayDestroy(tag->cols);
wmmhello's avatar
wmmhello 已提交
1177
  taosArrayDestroyEx(tag->tags, freeSSmlKv);
1178 1179
  taosMemoryFree(tag);
}
1180

X
Xiaoyu Wang 已提交
1181
void clearColValArray(SArray *pCols) {
wmmhello's avatar
wmmhello 已提交
1182 1183
  int32_t num = taosArrayGetSize(pCols);
  for (int32_t i = 0; i < num; ++i) {
X
Xiaoyu Wang 已提交
1184
    SColVal *pCol = taosArrayGet(pCols, i);
wmmhello's avatar
wmmhello 已提交
1185 1186 1187 1188 1189 1190
    if (TSDB_DATA_TYPE_NCHAR == pCol->type) {
      taosMemoryFreeClear(pCol->value.pData);
    }
  }
}

1191 1192 1193 1194
void freeSSmlKv(void *data) {
  SSmlKv *kv = (SSmlKv *)data;
  if (kv->keyEscaped) taosMemoryFree((void *)(kv->key));
  if (kv->valueEscaped) taosMemoryFree((void *)(kv->value));
1195
  if (kv->type == TSDB_DATA_TYPE_GEOMETRY) geosFreeBuffer((void *)(kv->value));
wmmhello's avatar
wmmhello 已提交
1196 1197
}

wmmhello's avatar
wmmhello 已提交
1198
void smlDestroyInfo(SSmlHandle *info) {
1199 1200
  if (!info) return;
  qDestroyQuery(info->pQuery);
1201

1202
  // destroy info->childTables
wmmhello's avatar
wmmhello 已提交
1203 1204 1205 1206 1207
//  SSmlTableInfo **oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, NULL);
//  while (oneTable) {
//    smlDestroyTableInfo(oneTable);
//    oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, oneTable);
//  }
1208

1209
  // destroy info->superTables
wmmhello's avatar
wmmhello 已提交
1210 1211 1212 1213 1214
//  SSmlSTableMeta **oneSTable = (SSmlSTableMeta **)taosHashIterate(info->superTables, NULL);
//  while (oneSTable) {
//    smlDestroySTableMeta(*oneSTable);
//    oneSTable = (SSmlSTableMeta **)taosHashIterate(info->superTables, oneSTable);
//  }
1215

1216 1217
  // destroy info->pVgHash
  taosHashCleanup(info->pVgHash);
1218 1219
  taosHashCleanup(info->childTables);
  taosHashCleanup(info->superTables);
1220
  taosHashCleanup(info->tableUids);
wmmhello's avatar
wmmhello 已提交
1221

X
Xiaoyu Wang 已提交
1222
  for (int i = 0; i < taosArrayGetSize(info->tagJsonArray); i++) {
wmmhello's avatar
wmmhello 已提交
1223 1224 1225 1226 1227
    cJSON *tags = (cJSON *)taosArrayGetP(info->tagJsonArray, i);
    cJSON_Delete(tags);
  }
  taosArrayDestroy(info->tagJsonArray);

1228 1229 1230 1231 1232 1233
  for (int i = 0; i < taosArrayGetSize(info->valueJsonArray); i++) {
    cJSON *value = (cJSON *)taosArrayGetP(info->valueJsonArray, i);
    cJSON_Delete(value);
  }
  taosArrayDestroy(info->valueJsonArray);

wmmhello's avatar
wmmhello 已提交
1234
  taosArrayDestroyEx(info->preLineTagKV, freeSSmlKv);
wmmhello's avatar
wmmhello 已提交
1235

X
Xiaoyu Wang 已提交
1236 1237
  if (!info->dataFormat) {
    for (int i = 0; i < info->lineNum; i++) {
wmmhello's avatar
wmmhello 已提交
1238
      taosArrayDestroyEx(info->lines[i].colArray, freeSSmlKv);
X
Xiaoyu Wang 已提交
1239
      if (info->parseJsonByLib) {
wmmhello's avatar
wmmhello 已提交
1240 1241
        taosMemoryFree(info->lines[i].tags);
      }
X
Xiaoyu Wang 已提交
1242
      if (info->lines[i].measureTagsLen != 0) taosMemoryFree(info->lines[i].measureTag);
1243 1244
    }
    taosMemoryFree(info->lines);
wmmhello's avatar
wmmhello 已提交
1245
  }
1246

wmmhello's avatar
wmmhello 已提交
1247
  cJSON_Delete(info->root);
1248 1249
  taosMemoryFreeClear(info);
}
wmmhello's avatar
wmmhello 已提交
1250

wmmhello's avatar
wmmhello 已提交
1251
SSmlHandle *smlBuildSmlInfo(TAOS *taos) {
1252 1253 1254 1255
  int32_t     code = TSDB_CODE_SUCCESS;
  SSmlHandle *info = (SSmlHandle *)taosMemoryCalloc(1, sizeof(SSmlHandle));
  if (NULL == info) {
    return NULL;
1256
  }
X
Xiaoyu Wang 已提交
1257
  if (taos != NULL) {
1258
    info->taos = acquireTscObj(*(int64_t *)taos);
X
Xiaoyu Wang 已提交
1259
    if (info->taos == NULL) {
D
dapan1121 已提交
1260 1261
      goto cleanup;
    }
1262 1263 1264 1265 1266
    code = catalogGetHandle(info->taos->pAppInfo->clusterId, &info->pCatalog);
    if (code != TSDB_CODE_SUCCESS) {
      uError("SML:0x%" PRIx64 " get catalog error %d", info->id, code);
      goto cleanup;
    }
1267
  }
wmmhello's avatar
wmmhello 已提交
1268

1269
  info->pVgHash = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_NO_LOCK);
1270
  info->childTables = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
1271
  info->tableUids = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
1272
  info->superTables = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
wmmhello's avatar
wmmhello 已提交
1273 1274
  taosHashSetFreeFp(info->superTables, smlDestroySTableMeta);
  taosHashSetFreeFp(info->childTables, smlDestroyTableInfo);
1275

1276 1277 1278
  info->id = smlGenId();
  info->pQuery = smlInitHandle();
  info->dataFormat = true;
1279

wmmhello's avatar
wmmhello 已提交
1280
  info->tagJsonArray = taosArrayInit(8, POINTER_BYTES);
1281
  info->valueJsonArray = taosArrayInit(8, POINTER_BYTES);
1282 1283
  info->preLineTagKV = taosArrayInit(8, sizeof(SSmlKv));

1284
  if (NULL == info->pVgHash || NULL == info->childTables || NULL == info->superTables || NULL == info->tableUids) {
1285 1286
    uError("create SSmlHandle failed");
    goto cleanup;
1287 1288
  }

1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
  return info;

cleanup:
  smlDestroyInfo(info);
  return NULL;
}

static int32_t smlPushCols(SArray *colsArray, SArray *cols) {
  SHashObj *kvHash = taosHashInit(32, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), false, HASH_NO_LOCK);
  if (!kvHash) {
    uError("SML:smlDealCols failed to allocate memory");
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  for (size_t i = 0; i < taosArrayGetSize(cols); i++) {
    SSmlKv *kv = (SSmlKv *)taosArrayGet(cols, i);
1304
    terrno = 0;
1305
    taosHashPut(kvHash, kv->key, kv->keyLen, &kv, POINTER_BYTES);
X
Xiaoyu Wang 已提交
1306
    if (terrno == TSDB_CODE_DUP_KEY) {
1307
      taosHashCleanup(kvHash);
X
Xiaoyu Wang 已提交
1308 1309
      return terrno;
    }
1310 1311
  }

1312
  taosArrayPush(colsArray, &kvHash);
1313
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1314
}
1315

1316
static int32_t smlParseLineBottom(SSmlHandle *info) {
X
Xiaoyu Wang 已提交
1317 1318
  uDebug("SML:0x%" PRIx64 " smlParseLineBottom start, format:%d, linenum:%d", info->id, info->dataFormat,
         info->lineNum);
X
Xiaoyu Wang 已提交
1319
  if (info->dataFormat) return TSDB_CODE_SUCCESS;
1320

X
Xiaoyu Wang 已提交
1321 1322
  for (int32_t i = 0; i < info->lineNum; i++) {
    SSmlLineInfo  *elements = info->lines + i;
1323
    SSmlTableInfo *tinfo = NULL;
X
Xiaoyu Wang 已提交
1324
    if (info->protocol == TSDB_SML_LINE_PROTOCOL) {
X
Xiaoyu Wang 已提交
1325 1326 1327
      SSmlTableInfo **tmp =
          (SSmlTableInfo **)taosHashGet(info->childTables, elements->measure, elements->measureTagsLen);
      if (tmp) tinfo = *tmp;
X
Xiaoyu Wang 已提交
1328
    } else if (info->protocol == TSDB_SML_TELNET_PROTOCOL) {
X
Xiaoyu Wang 已提交
1329
      SSmlTableInfo **tmp = (SSmlTableInfo **)taosHashGet(info->childTables, elements->measureTag,
wmmhello's avatar
wmmhello 已提交
1330
                                                          elements->measureLen + elements->tagsLen);
X
Xiaoyu Wang 已提交
1331
      if (tmp) tinfo = *tmp;
X
Xiaoyu Wang 已提交
1332
    } else {
X
Xiaoyu Wang 已提交
1333
      SSmlTableInfo **tmp = (SSmlTableInfo **)taosHashGet(info->childTables, elements->measureTag,
wmmhello's avatar
wmmhello 已提交
1334
                                                          elements->measureLen + elements->tagsLen);
X
Xiaoyu Wang 已提交
1335
      if (tmp) tinfo = *tmp;
1336 1337
    }

X
Xiaoyu Wang 已提交
1338
    if (tinfo == NULL) {
1339 1340 1341
      uError("SML:0x%" PRIx64 "get oneTable failed, line num:%d", info->id, i);
      smlBuildInvalidDataMsg(&info->msgBuf, "get oneTable failed", elements->measure);
      return TSDB_CODE_SML_INVALID_DATA;
1342
    }
wmmhello's avatar
wmmhello 已提交
1343

1344 1345 1346 1347 1348
    if (taosArrayGetSize(tinfo->tags) > TSDB_MAX_TAGS) {
      smlBuildInvalidDataMsg(&info->msgBuf, "too many tags than 128", NULL);
      return TSDB_CODE_PAR_INVALID_TAGS_NUM;
    }

1349 1350 1351
    if (taosArrayGetSize(elements->colArray) + taosArrayGetSize(tinfo->tags) > TSDB_MAX_COLUMNS) {
      smlBuildInvalidDataMsg(&info->msgBuf, "too many columns than 4096", NULL);
      return TSDB_CODE_PAR_TOO_MANY_COLUMNS;
wmmhello's avatar
wmmhello 已提交
1352
    }
wmmhello's avatar
wmmhello 已提交
1353

1354
    int ret = smlPushCols(tinfo->cols, elements->colArray);
X
Xiaoyu Wang 已提交
1355
    if (ret != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
1356 1357 1358
      return ret;
    }

1359 1360
    SSmlSTableMeta **tableMeta =
        (SSmlSTableMeta **)taosHashGet(info->superTables, elements->measure, elements->measureLen);
1361
    if (tableMeta) {  // update meta
X
Xiaoyu Wang 已提交
1362 1363
      uDebug("SML:0x%" PRIx64 " smlParseLineBottom update meta, format:%d, linenum:%d", info->id, info->dataFormat,
             info->lineNum);
1364
      ret = smlUpdateMeta((*tableMeta)->colHash, (*tableMeta)->cols, elements->colArray, false, &info->msgBuf);
1365
      if (ret == TSDB_CODE_SUCCESS) {
1366
        ret = smlUpdateMeta((*tableMeta)->tagHash, (*tableMeta)->tags, tinfo->tags, true, &info->msgBuf);
1367 1368 1369 1370 1371
      }
      if (ret != TSDB_CODE_SUCCESS) {
        uError("SML:0x%" PRIx64 " smlUpdateMeta failed", info->id);
        return ret;
      }
X
Xiaoyu Wang 已提交
1372
    } else {
X
Xiaoyu Wang 已提交
1373 1374 1375 1376 1377
      //      ret = smlJudgeDupColName(elements->colArray, tinfo->tags, &info->msgBuf);
      //      if (ret != TSDB_CODE_SUCCESS) {
      //        uError("SML:0x%" PRIx64 " smlUpdateMeta failed", info->id);
      //        return ret;
      //      }
X
Xiaoyu Wang 已提交
1378 1379
      uDebug("SML:0x%" PRIx64 " smlParseLineBottom add meta, format:%d, linenum:%d", info->id, info->dataFormat,
             info->lineNum);
1380
      SSmlSTableMeta *meta = smlBuildSTableMeta(info->dataFormat);
wmmhello's avatar
wmmhello 已提交
1381 1382 1383
      if(meta == NULL){
        return TSDB_CODE_OUT_OF_MEMORY;
      }
1384
      taosHashPut(info->superTables, elements->measure, elements->measureLen, &meta, POINTER_BYTES);
1385
      terrno = 0;
1386
      smlInsertMeta(meta->tagHash, meta->tags, tinfo->tags);
X
Xiaoyu Wang 已提交
1387 1388 1389
      if (terrno == TSDB_CODE_DUP_KEY) {
        return terrno;
      }
1390
      smlInsertMeta(meta->colHash, meta->cols, elements->colArray);
wmmhello's avatar
wmmhello 已提交
1391
    }
wmmhello's avatar
wmmhello 已提交
1392
  }
D
dapan1121 已提交
1393
  uDebug("SML:0x%" PRIx64 " smlParseLineBottom end, format:%d, linenum:%d", info->id, info->dataFormat, info->lineNum);
1394

wmmhello's avatar
wmmhello 已提交
1395 1396 1397
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
1398
static int32_t smlInsertData(SSmlHandle *info) {
wmmhello's avatar
wmmhello 已提交
1399
  int32_t code = TSDB_CODE_SUCCESS;
D
dapan1121 已提交
1400
  uDebug("SML:0x%" PRIx64 " smlInsertData start, format:%d", info->id, info->dataFormat);
wmmhello's avatar
wmmhello 已提交
1401

X
Xiaoyu Wang 已提交
1402
  if (info->pRequest->dbList == NULL) {
wmmhello's avatar
wmmhello 已提交
1403 1404
    info->pRequest->dbList = taosArrayInit(1, TSDB_DB_FNAME_LEN);
  }
1405
  char *data = (char *)taosArrayReserve(info->pRequest->dbList, 1);
1406 1407 1408
  SName pName = {TSDB_TABLE_NAME_T, info->taos->acctId, {0}, {0}};
  tstrncpy(pName.dbname, info->pRequest->pDb, sizeof(pName.dbname));
  tNameGetFullDbName(&pName, data);
wmmhello's avatar
wmmhello 已提交
1409

1410 1411 1412
  SSmlTableInfo **oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, NULL);
  while (oneTable) {
    SSmlTableInfo *tableData = *oneTable;
1413 1414 1415 1416 1417 1418

    int   measureLen = tableData->sTableNameLen;
    char *measure = (char *)taosMemoryMalloc(tableData->sTableNameLen);
    memcpy(measure, tableData->sTableName, tableData->sTableNameLen);
    PROCESS_SLASH_IN_MEASUREMENT(measure, measureLen);
    smlStrReplace(measure, measureLen);
wmmhello's avatar
wmmhello 已提交
1419 1420
    memset(pName.tname, 0, TSDB_TABLE_NAME_LEN);
    memcpy(pName.tname, measure, measureLen);
D
dapan1121 已提交
1421

X
Xiaoyu Wang 已提交
1422
    if (info->pRequest->tableList == NULL) {
wmmhello's avatar
wmmhello 已提交
1423 1424 1425 1426
      info->pRequest->tableList = taosArrayInit(1, sizeof(SName));
    }
    taosArrayPush(info->pRequest->tableList, &pName);

wmmhello's avatar
wmmhello 已提交
1427
    strcpy(pName.tname, tableData->childTableName);
1428

D
dapan1121 已提交
1429 1430 1431 1432 1433
    SRequestConnInfo conn = {0};
    conn.pTrans = info->taos->pAppInfo->pTransporter;
    conn.requestId = info->pRequest->requestId;
    conn.requestObjRefId = info->pRequest->self;
    conn.mgmtEps = getEpSet_s(&info->taos->pAppInfo->mgmtEp);
X
Xiaoyu Wang 已提交
1434

wmmhello's avatar
wmmhello 已提交
1435 1436
    code = smlCheckAuth(info, &conn, pName.tname, AUTH_TYPE_WRITE);
    if(code != TSDB_CODE_SUCCESS){
1437
      taosMemoryFree(measure);
1438
      taosHashCancelIterate(info->childTables, oneTable);
wmmhello's avatar
wmmhello 已提交
1439 1440 1441
      return code;
    }

wmmhello's avatar
wmmhello 已提交
1442
    SVgroupInfo vg;
D
dapan1121 已提交
1443
    code = catalogGetTableHashVgroup(info->pCatalog, &conn, &pName, &vg);
1444
    if (code != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
1445
      uError("SML:0x%" PRIx64 " catalogGetTableHashVgroup failed. table name: %s", info->id, tableData->childTableName);
1446
      taosMemoryFree(measure);
1447
      taosHashCancelIterate(info->childTables, oneTable);
wmmhello's avatar
wmmhello 已提交
1448 1449
      return code;
    }
X
Xiaoyu Wang 已提交
1450
    taosHashPut(info->pVgHash, (const char *)&vg.vgId, sizeof(vg.vgId), (char *)&vg, sizeof(vg));
wmmhello's avatar
wmmhello 已提交
1451

1452 1453 1454
    SSmlSTableMeta **pMeta =
        (SSmlSTableMeta **)taosHashGet(info->superTables, tableData->sTableName, tableData->sTableNameLen);
    if (unlikely(NULL == pMeta || NULL == (*pMeta)->tableMeta)) {
1455
      uError("SML:0x%" PRIx64 " NULL == pMeta. table name: %s", info->id, tableData->childTableName);
1456
      taosMemoryFree(measure);
1457
      taosHashCancelIterate(info->childTables, oneTable);
1458 1459
      return TSDB_CODE_SML_INTERNAL_ERROR;
    }
wmmhello's avatar
wmmhello 已提交
1460

1461
    // use tablemeta of stable to save vgid and uid of child table
1462 1463
    (*pMeta)->tableMeta->vgId = vg.vgId;
    (*pMeta)->tableMeta->uid = tableData->uid;  // one table merge data block together according uid
X
Xiaoyu Wang 已提交
1464 1465
    uDebug("SML:0x%" PRIx64 " smlInsertData table:%s, uid:%" PRIu64 ", format:%d", info->id, pName.tname,
           tableData->uid, info->dataFormat);
wmmhello's avatar
wmmhello 已提交
1466

X
Xiaoyu Wang 已提交
1467
    code = smlBindData(info->pQuery, info->dataFormat, tableData->tags, (*pMeta)->cols, tableData->cols,
1468 1469
                       (*pMeta)->tableMeta, tableData->childTableName, measure, measureLen, info->ttl, info->msgBuf.buf,
                       info->msgBuf.len);
1470
    taosMemoryFree(measure);
X
Xiaoyu Wang 已提交
1471 1472
    if (code != TSDB_CODE_SUCCESS) {
      uError("SML:0x%" PRIx64 " smlBindData failed", info->id);
1473
      taosHashCancelIterate(info->childTables, oneTable);
wmmhello's avatar
wmmhello 已提交
1474 1475
      return code;
    }
1476
    oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, oneTable);
wmmhello's avatar
wmmhello 已提交
1477
  }
wmmhello's avatar
wmmhello 已提交
1478

wmmhello's avatar
wmmhello 已提交
1479
  code = smlBuildOutput(info->pQuery, info->pVgHash);
1480
  if (code != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
1481
    uError("SML:0x%" PRIx64 " smlBuildOutput failed", info->id);
1482 1483
    return code;
  }
1484 1485
  info->cost.insertRpcTime = taosGetTimestampUs();

1486 1487 1488
  SAppClusterSummary *pActivity = &info->taos->pAppInfo->summary;
  atomic_add_fetch_64((int64_t *)&pActivity->numOfInsertsReq, 1);

wmmhello's avatar
wmmhello 已提交
1489
  launchQueryImpl(info->pRequest, info->pQuery, true, NULL);
X
Xiaoyu Wang 已提交
1490 1491
  uDebug("SML:0x%" PRIx64 " smlInsertData end, format:%d, code:%d,%s", info->id, info->dataFormat, info->pRequest->code,
         tstrerror(info->pRequest->code));
D
dapan1121 已提交
1492

wmmhello's avatar
wmmhello 已提交
1493
  return info->pRequest->code;
wmmhello's avatar
wmmhello 已提交
1494 1495
}

X
Xiaoyu Wang 已提交
1496
static void smlPrintStatisticInfo(SSmlHandle *info) {
1497
  uDebug(
X
Xiaoyu Wang 已提交
1498
      "SML:0x%" PRIx64
D
dapan1121 已提交
1499
      " smlInsertLines result, code:%d, msg:%s, lineNum:%d,stable num:%d,ctable num:%d,create stable num:%d,alter stable tag num:%d,alter stable col num:%d \
X
Xiaoyu Wang 已提交
1500
        parse cost:%" PRId64 ",schema cost:%" PRId64 ",bind cost:%" PRId64 ",rpc cost:%" PRId64 ",total cost:%" PRId64
X
Xiaoyu Wang 已提交
1501
      "",
X
Xiaoyu Wang 已提交
1502 1503 1504 1505 1506
      info->id, info->cost.code, tstrerror(info->cost.code), info->cost.lineNum, info->cost.numOfSTables,
      info->cost.numOfCTables, info->cost.numOfCreateSTables, info->cost.numOfAlterTagSTables,
      info->cost.numOfAlterColSTables, info->cost.schemaTime - info->cost.parseTime,
      info->cost.insertBindTime - info->cost.schemaTime, info->cost.insertRpcTime - info->cost.insertBindTime,
      info->cost.endTime - info->cost.insertRpcTime, info->cost.endTime - info->cost.parseTime);
1507 1508
}

X
Xiaoyu Wang 已提交
1509
int32_t smlClearForRerun(SSmlHandle *info) {
1510 1511
  info->reRun = false;
  // clear info->childTables
wmmhello's avatar
wmmhello 已提交
1512 1513 1514 1515 1516
//  SSmlTableInfo **oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, NULL);
//  while (oneTable) {
//    smlDestroyTableInfo(info, *oneTable);
//    oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, oneTable);
//  }
1517 1518

  // clear info->superTables
wmmhello's avatar
wmmhello 已提交
1519 1520 1521 1522 1523
//  SSmlSTableMeta **oneSTable = (SSmlSTableMeta **)taosHashIterate(info->superTables, NULL);
//  while (oneSTable) {
//    smlDestroySTableMeta(*oneSTable);
//    oneSTable = (SSmlSTableMeta **)taosHashIterate(info->superTables, oneSTable);
//  }
1524

wmmhello's avatar
wmmhello 已提交
1525 1526
  taosHashClear(info->childTables);
  taosHashClear(info->superTables);
1527
  taosHashClear(info->tableUids);
wmmhello's avatar
wmmhello 已提交
1528

X
Xiaoyu Wang 已提交
1529
  if (!info->dataFormat) {
wmmhello's avatar
wmmhello 已提交
1530 1531 1532 1533 1534
    if (unlikely(info->lines != NULL)) {
      uError("SML:0x%" PRIx64 " info->lines != NULL", info->id);
      return TSDB_CODE_SML_INVALID_DATA;
    }
    info->lines = (SSmlLineInfo *)taosMemoryCalloc(info->lineNum, sizeof(SSmlLineInfo));
1535 1536 1537 1538 1539 1540
  }

  memset(&info->preLine, 0, sizeof(SSmlLineInfo));
  info->currSTableMeta = NULL;
  info->currTableDataCtx = NULL;

X
Xiaoyu Wang 已提交
1541
  SVnodeModifyOpStmt *stmt = (SVnodeModifyOpStmt *)(info->pQuery->pRoot);
1542 1543 1544 1545 1546
  stmt->freeHashFunc(stmt->pTableBlockHashObj);
  stmt->pTableBlockHashObj = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_NO_LOCK);
  return TSDB_CODE_SUCCESS;
}

dengyihao's avatar
dengyihao 已提交
1547
static int32_t smlParseLine(SSmlHandle *info, char *lines[], char *rawLine, char *rawLineEnd, int numLines) {
D
dapan1121 已提交
1548
  uDebug("SML:0x%" PRIx64 " smlParseLine start", info->id);
wmmhello's avatar
wmmhello 已提交
1549
  int32_t code = TSDB_CODE_SUCCESS;
1550
  if (info->protocol == TSDB_SML_JSON_PROTOCOL) {
dengyihao's avatar
dengyihao 已提交
1551
    if (lines) {
wmmhello's avatar
wmmhello 已提交
1552
      code = smlParseJSON(info, *lines);
dengyihao's avatar
dengyihao 已提交
1553
    } else if (rawLine) {
wmmhello's avatar
wmmhello 已提交
1554 1555
      code = smlParseJSON(info, rawLine);
    }
1556
    if (code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
1557
      uError("SML:0x%" PRIx64 " smlParseJSON failed:%s", info->id, lines ? *lines : rawLine);
1558 1559
      return code;
    }
wmmhello's avatar
wmmhello 已提交
1560
    return code;
wmmhello's avatar
wmmhello 已提交
1561
  }
wmmhello's avatar
wmmhello 已提交
1562

X
Xiaoyu Wang 已提交
1563
  char   *oldRaw = rawLine;
1564 1565
  int32_t i = 0;
  while (i < numLines) {
wmmhello's avatar
wmmhello 已提交
1566
    char *tmp = NULL;
dengyihao's avatar
dengyihao 已提交
1567 1568
    int   len = 0;
    if (lines) {
wmmhello's avatar
wmmhello 已提交
1569 1570
      tmp = lines[i];
      len = strlen(tmp);
dengyihao's avatar
dengyihao 已提交
1571
    } else if (rawLine) {
wmmhello's avatar
wmmhello 已提交
1572
      tmp = rawLine;
dengyihao's avatar
dengyihao 已提交
1573 1574
      while (rawLine < rawLineEnd) {
        if (*(rawLine++) == '\n') {
wmmhello's avatar
wmmhello 已提交
1575 1576 1577 1578
          break;
        }
        len++;
      }
dengyihao's avatar
dengyihao 已提交
1579
      if (info->protocol == TSDB_SML_LINE_PROTOCOL && tmp[0] == '#') {  // this line is comment
wmmhello's avatar
wmmhello 已提交
1580 1581
        continue;
      }
wmmhello's avatar
wmmhello 已提交
1582 1583
    }

X
Xiaoyu Wang 已提交
1584
    uDebug("SML:0x%" PRIx64 " smlParseLine israw:%d, numLines:%d, protocol:%d, len:%d, sql:%s", info->id,
1585
           info->isRawLine, numLines, info->protocol, len, info->isRawLine ? "rawdata" : tmp);
1586

X
Xiaoyu Wang 已提交
1587
    if (info->protocol == TSDB_SML_LINE_PROTOCOL) {
X
Xiaoyu Wang 已提交
1588
      if (info->dataFormat) {
wmmhello's avatar
wmmhello 已提交
1589 1590
        SSmlLineInfo element = {0};
        code = smlParseInfluxString(info, tmp, tmp + len, &element);
X
Xiaoyu Wang 已提交
1591
      } else {
wmmhello's avatar
wmmhello 已提交
1592 1593
        code = smlParseInfluxString(info, tmp, tmp + len, info->lines + i);
      }
X
Xiaoyu Wang 已提交
1594
    } else if (info->protocol == TSDB_SML_TELNET_PROTOCOL) {
X
Xiaoyu Wang 已提交
1595
      if (info->dataFormat) {
1596 1597
        SSmlLineInfo element = {0};
        code = smlParseTelnetString(info, (char *)tmp, (char *)tmp + len, &element);
X
Xiaoyu Wang 已提交
1598
        if (element.measureTagsLen != 0) taosMemoryFree(element.measureTag);
X
Xiaoyu Wang 已提交
1599
      } else {
1600 1601
        code = smlParseTelnetString(info, (char *)tmp, (char *)tmp + len, info->lines + i);
      }
X
Xiaoyu Wang 已提交
1602
    } else {
1603
      code = TSDB_CODE_SML_INVALID_PROTOCOL_TYPE;
1604
    }
wmmhello's avatar
wmmhello 已提交
1605
    if (code != TSDB_CODE_SUCCESS) {
1606
      uError("SML:0x%" PRIx64 " smlParseLine failed. line %d : %s", info->id, i, info->isRawLine ? "rawdata" : tmp);
1607
      return code;
wmmhello's avatar
wmmhello 已提交
1608
    }
X
Xiaoyu Wang 已提交
1609
    if (info->reRun) {
D
dapan1121 已提交
1610
      uDebug("SML:0x%" PRIx64 " smlParseLine re run", info->id);
1611
      i = 0;
1612
      rawLine = oldRaw;
1613
      code = smlClearForRerun(info);
X
Xiaoyu Wang 已提交
1614
      if (code != TSDB_CODE_SUCCESS) {
1615
        return code;
1616
      }
1617
      continue;
1618
    }
1619
    i++;
wmmhello's avatar
wmmhello 已提交
1620
  }
D
dapan1121 已提交
1621
  uDebug("SML:0x%" PRIx64 " smlParseLine end", info->id);
1622

1623 1624 1625
  return code;
}

dengyihao's avatar
dengyihao 已提交
1626
static int smlProcess(SSmlHandle *info, char *lines[], char *rawLine, char *rawLineEnd, int numLines) {
1627
  int32_t code = TSDB_CODE_SUCCESS;
1628 1629
  int32_t retryNum = 0;

1630 1631
  info->cost.parseTime = taosGetTimestampUs();

wmmhello's avatar
wmmhello 已提交
1632
  code = smlParseLine(info, lines, rawLine, rawLineEnd, numLines);
1633
  if (code != 0) {
X
Xiaoyu Wang 已提交
1634
    uError("SML:0x%" PRIx64 " smlParseLine error : %s", info->id, tstrerror(code));
wmmhello's avatar
wmmhello 已提交
1635
    return code;
1636
  }
1637 1638 1639 1640 1641 1642
  code = smlParseLineBottom(info);
  if (code != 0) {
    uError("SML:0x%" PRIx64 " smlParseLineBottom error : %s", info->id, tstrerror(code));
    return code;
  }

1643
  info->cost.lineNum = info->lineNum;
1644 1645
  info->cost.numOfSTables = taosHashGetSize(info->superTables);
  info->cost.numOfCTables = taosHashGetSize(info->childTables);
1646 1647

  info->cost.schemaTime = taosGetTimestampUs();
1648

X
Xiaoyu Wang 已提交
1649
  do {
1650
    code = smlModifyDBSchemas(info);
wmmhello's avatar
wmmhello 已提交
1651
    if (code != TSDB_CODE_TDB_INVALID_TABLE_SCHEMA_VER && code != TSDB_CODE_SDB_OBJ_CREATING && code != TSDB_CODE_MND_TRANS_CONFLICT) {
1652 1653
      break;
    }
1654
    taosMsleep(100);
D
dapan1121 已提交
1655
    uInfo("SML:0x%" PRIx64 " smlModifyDBSchemas retry code:%s, times:%d", info->id, tstrerror(code), retryNum);
1656
  } while (retryNum++ < taosHashGetSize(info->superTables) * MAX_RETRY_TIMES);
1657

wmmhello's avatar
wmmhello 已提交
1658
  if (code != 0) {
X
Xiaoyu Wang 已提交
1659
    uError("SML:0x%" PRIx64 " smlModifyDBSchemas error : %s", info->id, tstrerror(code));
wmmhello's avatar
wmmhello 已提交
1660
    return code;
wmmhello's avatar
wmmhello 已提交
1661
  }
wmmhello's avatar
wmmhello 已提交
1662

1663
  info->cost.insertBindTime = taosGetTimestampUs();
wmmhello's avatar
wmmhello 已提交
1664 1665
  code = smlInsertData(info);
  if (code != 0) {
X
Xiaoyu Wang 已提交
1666
    uError("SML:0x%" PRIx64 " smlInsertData error : %s", info->id, tstrerror(code));
wmmhello's avatar
wmmhello 已提交
1667
    return code;
wmmhello's avatar
wmmhello 已提交
1668 1669 1670 1671 1672
  }

  return code;
}

1673 1674 1675 1676 1677
void smlSetReqSQL(SRequestObj *request, char *lines[], char *rawLine, char *rawLineEnd) {
  if (tsSlowLogScope & SLOW_LOG_TYPE_INSERT) {
    int32_t len = 0;
    int32_t rlen = 0;
    char* p = NULL;
1678

1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693
    if (lines && lines[0]) {
      len = strlen(lines[0]);
      p = lines[0];
    } else if (rawLine) {
      if (rawLineEnd) {
        len = rawLineEnd - rawLine;
      } else {
        len = strlen(rawLine);
      }
      p = rawLine;
    }

    if (NULL == p) {
      return;
    }
1694

1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
    rlen = TMIN(len, TSDB_MAX_ALLOWED_SQL_LEN);
    rlen = TMAX(rlen, 0);

    char *sql = taosMemoryMalloc(rlen + 1);
    if (NULL == sql) {
      uError("malloc %d for sml sql failed", rlen + 1);
      return;
    }
    memcpy(sql, p, rlen);
    sql[rlen] = 0;

    request->sqlstr = sql;
    request->sqlLen = rlen;
  }
}

X
Xiaoyu Wang 已提交
1711 1712
TAOS_RES *taos_schemaless_insert_inner(TAOS *taos, char *lines[], char *rawLine, char *rawLineEnd, int numLines,
                                       int protocol, int precision, int32_t ttl, int64_t reqid) {
1713
  int32_t code = TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1714 1715 1716
  if (NULL == taos) {
    terrno = TSDB_CODE_TSC_DISCONNECTED;
    return NULL;
1717
  }
wmmhello's avatar
wmmhello 已提交
1718
  SRequestObj *request = NULL;
X
Xiaoyu Wang 已提交
1719 1720 1721
  SSmlHandle  *info = NULL;
  int          cnt = 0;
  while (1) {
wmmhello's avatar
wmmhello 已提交
1722 1723 1724 1725 1726
    request = (SRequestObj *)createRequest(*(int64_t *)taos, TSDB_SQL_INSERT, reqid);
    if (request == NULL) {
      uError("SML:taos_schemaless_insert error request is null");
      return NULL;
    }
1727

wmmhello's avatar
wmmhello 已提交
1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742
    info = smlBuildSmlInfo(taos);
    if (info == NULL) {
      request->code = TSDB_CODE_OUT_OF_MEMORY;
      uError("SML:taos_schemaless_insert error SSmlHandle is null");
      return (TAOS_RES *)request;
    }
    info->pRequest = request;
    info->isRawLine = rawLine != NULL;
    info->ttl = ttl;
    info->precision = precision;
    info->protocol = (TSDB_SML_PROTOCOL_TYPE)protocol;
    info->msgBuf.buf = info->pRequest->msgBuf;
    info->msgBuf.len = ERROR_MSG_BUF_DEFAULT_SIZE;
    info->lineNum = numLines;

1743 1744
    smlSetReqSQL(request, lines, rawLine, rawLineEnd);

wmmhello's avatar
wmmhello 已提交
1745 1746 1747 1748 1749 1750
    SSmlMsgBuf msg = {ERROR_MSG_BUF_DEFAULT_SIZE, request->msgBuf};
    if (request->pDb == NULL) {
      request->code = TSDB_CODE_PAR_DB_NOT_SPECIFIED;
      smlBuildInvalidDataMsg(&msg, "Database not specified", NULL);
      goto end;
    }
1751

wmmhello's avatar
wmmhello 已提交
1752 1753 1754 1755 1756
    if (protocol < TSDB_SML_LINE_PROTOCOL || protocol > TSDB_SML_JSON_PROTOCOL) {
      request->code = TSDB_CODE_SML_INVALID_PROTOCOL_TYPE;
      smlBuildInvalidDataMsg(&msg, "protocol invalidate", NULL);
      goto end;
    }
wmmhello's avatar
wmmhello 已提交
1757

wmmhello's avatar
wmmhello 已提交
1758 1759 1760 1761 1762 1763
    if (protocol == TSDB_SML_LINE_PROTOCOL &&
        (precision < TSDB_SML_TIMESTAMP_NOT_CONFIGURED || precision > TSDB_SML_TIMESTAMP_NANO_SECONDS)) {
      request->code = TSDB_CODE_SML_INVALID_PRECISION_TYPE;
      smlBuildInvalidDataMsg(&msg, "precision invalidate for line protocol", NULL);
      goto end;
    }
wmmhello's avatar
wmmhello 已提交
1764

wmmhello's avatar
wmmhello 已提交
1765 1766 1767 1768 1769 1770 1771
    if (protocol == TSDB_SML_JSON_PROTOCOL) {
      numLines = 1;
    } else if (numLines <= 0) {
      request->code = TSDB_CODE_SML_INVALID_DATA;
      smlBuildInvalidDataMsg(&msg, "line num is invalid", NULL);
      goto end;
    }
1772

wmmhello's avatar
wmmhello 已提交
1773 1774 1775 1776
    code = smlProcess(info, lines, rawLine, rawLineEnd, numLines);
    request->code = code;
    info->cost.endTime = taosGetTimestampUs();
    info->cost.code = code;
1777 1778
    if (NEED_CLIENT_HANDLE_ERROR(code) || code == TSDB_CODE_SDB_OBJ_CREATING ||
        code == TSDB_CODE_PAR_VALUE_TOO_LONG || code == TSDB_CODE_MND_TRANS_CONFLICT) {
X
Xiaoyu Wang 已提交
1779 1780
      if (cnt++ >= 10) {
        uInfo("SML:%" PRIx64 " retry:%d/10 end code:%d, msg:%s", info->id, cnt, code, tstrerror(code));
D
dapan1121 已提交
1781 1782 1783
        break;
      }
      taosMsleep(100);
wmmhello's avatar
wmmhello 已提交
1784
      refreshMeta(request->pTscObj, request);
X
Xiaoyu Wang 已提交
1785 1786
      uInfo("SML:%" PRIx64 " retry:%d/10,ver is old retry or object is creating code:%d, msg:%s", info->id, cnt, code,
            tstrerror(code));
wmmhello's avatar
wmmhello 已提交
1787 1788 1789 1790 1791 1792
      smlDestroyInfo(info);
      info = NULL;
      taos_free_result(request);
      request = NULL;
      continue;
    }
D
dapan1121 已提交
1793
    smlPrintStatisticInfo(info);
wmmhello's avatar
wmmhello 已提交
1794
    break;
wmmhello's avatar
wmmhello 已提交
1795 1796
  }

wmmhello's avatar
wmmhello 已提交
1797
end:
wmmhello's avatar
wmmhello 已提交
1798
  smlDestroyInfo(info);
1799
  return (TAOS_RES *)request;
wmmhello's avatar
wmmhello 已提交
1800
}
wmmhello's avatar
wmmhello 已提交
1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817

/**
 * taos_schemaless_insert() parse and insert data points into database according to
 * different protocol.
 *
 * @param $lines input array may contain multiple lines, each line indicates a data point.
 *               If protocol=2 is used input array should contain single JSON
 *               string(e.g. char *lines[] = {"$JSON_string"}). If need to insert
 *               multiple data points in JSON format, should include them in $JSON_string
 *               as a JSON array.
 * @param $numLines indicates how many data points in $lines.
 *                  If protocol = 2 is used this param will be ignored as $lines should
 *                  contain single JSON string.
 * @param $protocol indicates which protocol to use for parsing:
 *                  0 - influxDB line protocol
 *                  1 - OpenTSDB telnet line protocol
 *                  2 - OpenTSDB JSON format protocol
dengyihao's avatar
dengyihao 已提交
1818
 * @return TAOS_RES
wmmhello's avatar
wmmhello 已提交
1819 1820
 */

1821 1822
TAOS_RES *taos_schemaless_insert_ttl_with_reqid(TAOS *taos, char *lines[], int numLines, int protocol, int precision,
                                                int32_t ttl, int64_t reqid) {
wmmhello's avatar
wmmhello 已提交
1823
  return taos_schemaless_insert_inner(taos, lines, NULL, NULL, numLines, protocol, precision, ttl, reqid);
dengyihao's avatar
dengyihao 已提交
1824 1825
}

1826 1827 1828
TAOS_RES *taos_schemaless_insert(TAOS *taos, char *lines[], int numLines, int protocol, int precision) {
  return taos_schemaless_insert_ttl_with_reqid(taos, lines, numLines, protocol, precision, TSDB_DEFAULT_TABLE_TTL, 0);
}
wmmhello's avatar
wmmhello 已提交
1829

X
Xiaoyu Wang 已提交
1830 1831
TAOS_RES *taos_schemaless_insert_ttl(TAOS *taos, char *lines[], int numLines, int protocol, int precision,
                                     int32_t ttl) {
1832 1833
  return taos_schemaless_insert_ttl_with_reqid(taos, lines, numLines, protocol, precision, ttl, 0);
}
wmmhello's avatar
wmmhello 已提交
1834

X
Xiaoyu Wang 已提交
1835 1836 1837 1838
TAOS_RES *taos_schemaless_insert_with_reqid(TAOS *taos, char *lines[], int numLines, int protocol, int precision,
                                            int64_t reqid) {
  return taos_schemaless_insert_ttl_with_reqid(taos, lines, numLines, protocol, precision, TSDB_DEFAULT_TABLE_TTL,
                                               reqid);
wmmhello's avatar
wmmhello 已提交
1839 1840
}

1841
TAOS_RES *taos_schemaless_insert_raw_ttl_with_reqid(TAOS *taos, char *lines, int len, int32_t *totalRows, int protocol,
1842
                                                    int precision, int32_t ttl, int64_t reqid) {
dengyihao's avatar
dengyihao 已提交
1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
  int numLines = 0;
  *totalRows = 0;
  char *tmp = lines;
  for (int i = 0; i < len; i++) {
    if (lines[i] == '\n' || i == len - 1) {
      numLines++;
      if (tmp[0] != '#' || protocol != TSDB_SML_LINE_PROTOCOL) {  // ignore comment
        (*totalRows)++;
      }
      tmp = lines + i + 1;
    }
  }
wmmhello's avatar
wmmhello 已提交
1855
  return taos_schemaless_insert_inner(taos, NULL, lines, lines + len, *totalRows, protocol, precision, ttl, reqid);
dengyihao's avatar
dengyihao 已提交
1856 1857
}

X
Xiaoyu Wang 已提交
1858 1859 1860 1861
TAOS_RES *taos_schemaless_insert_raw_with_reqid(TAOS *taos, char *lines, int len, int32_t *totalRows, int protocol,
                                                int precision, int64_t reqid) {
  return taos_schemaless_insert_raw_ttl_with_reqid(taos, lines, len, totalRows, protocol, precision,
                                                   TSDB_DEFAULT_TABLE_TTL, reqid);
1862
}
X
Xiaoyu Wang 已提交
1863 1864
TAOS_RES *taos_schemaless_insert_raw_ttl(TAOS *taos, char *lines, int len, int32_t *totalRows, int protocol,
                                         int precision, int32_t ttl) {
1865 1866
  return taos_schemaless_insert_raw_ttl_with_reqid(taos, lines, len, totalRows, protocol, precision, ttl, 0);
}
wmmhello's avatar
wmmhello 已提交
1867

X
Xiaoyu Wang 已提交
1868 1869 1870 1871
TAOS_RES *taos_schemaless_insert_raw(TAOS *taos, char *lines, int len, int32_t *totalRows, int protocol,
                                     int precision) {
  return taos_schemaless_insert_raw_ttl_with_reqid(taos, lines, len, totalRows, protocol, precision,
                                                   TSDB_DEFAULT_TABLE_TTL, 0);
wmmhello's avatar
wmmhello 已提交
1872
}