clientSml.c 57.6 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};

X
Xiaoyu Wang 已提交
27
void *nodeListGet(NodeList *list, const void *key, int32_t len, _equal_fn_sml fn) {
wmmhello's avatar
wmmhello 已提交
28
  NodeList *tmp = list;
X
Xiaoyu Wang 已提交
29 30 31
  while (tmp) {
    if (fn == NULL) {
      if (tmp->data.used && tmp->data.keyLen == len && memcmp(tmp->data.key, key, len) == 0) {
32 33
        return tmp->data.value;
      }
X
Xiaoyu Wang 已提交
34 35
    } else {
      if (tmp->data.used && fn(tmp->data.key, key) == 0) {
36 37
        return tmp->data.value;
      }
wmmhello's avatar
wmmhello 已提交
38
    }
39

wmmhello's avatar
wmmhello 已提交
40 41 42 43 44
    tmp = tmp->next;
  }
  return NULL;
}

X
Xiaoyu Wang 已提交
45
int nodeListSet(NodeList **list, const void *key, int32_t len, void *value, _equal_fn_sml fn) {
wmmhello's avatar
wmmhello 已提交
46
  NodeList *tmp = *list;
X
Xiaoyu Wang 已提交
47 48 49 50
  while (tmp) {
    if (!tmp->data.used) break;
    if (fn == NULL) {
      if (tmp->data.keyLen == len && memcmp(tmp->data.key, key, len) == 0) {
51 52
        return -1;
      }
X
Xiaoyu Wang 已提交
53 54
    } else {
      if (tmp->data.keyLen == len && fn(tmp->data.key, key) == 0) {
55 56
        return -1;
      }
wmmhello's avatar
wmmhello 已提交
57
    }
58

wmmhello's avatar
wmmhello 已提交
59 60
    tmp = tmp->next;
  }
X
Xiaoyu Wang 已提交
61
  if (tmp) {
wmmhello's avatar
wmmhello 已提交
62 63 64 65
    tmp->data.key = key;
    tmp->data.keyLen = len;
    tmp->data.value = value;
    tmp->data.used = true;
X
Xiaoyu Wang 已提交
66
  } else {
67
    NodeList *newNode = (NodeList *)taosMemoryCalloc(1, sizeof(NodeList));
X
Xiaoyu Wang 已提交
68
    if (newNode == NULL) {
wmmhello's avatar
wmmhello 已提交
69 70 71 72 73 74 75 76 77 78 79 80
      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;
}

X
Xiaoyu Wang 已提交
81
int nodeListSize(NodeList *list) {
wmmhello's avatar
wmmhello 已提交
82
  int cnt = 0;
X
Xiaoyu Wang 已提交
83 84 85 86 87
  while (list) {
    if (list->data.used)
      cnt++;
    else
      break;
wmmhello's avatar
wmmhello 已提交
88 89 90 91
    list = list->next;
  }
  return cnt;
}
wmmhello's avatar
wmmhello 已提交
92

93
inline bool smlDoubleToInt64OverFlow(double num) {
X
Xiaoyu Wang 已提交
94
  if (num >= (double)INT64_MAX || num <= (double)INT64_MIN) return true;
95 96 97
  return false;
}

98
int32_t smlBuildInvalidDataMsg(SSmlMsgBuf *pBuf, const char *msg1, const char *msg2) {
99
  if (pBuf->buf) {
100 101 102 103 104 105 106
    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 已提交
107
  }
wmmhello's avatar
wmmhello 已提交
108 109 110
  return TSDB_CODE_SML_INVALID_DATA;
}

111 112 113 114 115
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;
116
  }
wmmhello's avatar
wmmhello 已提交
117

X
Xiaoyu Wang 已提交
118
  if (unlikely(fromPrecision >= TSDB_TIME_PRECISION_HOURS)) {
119
    int64_t unit = smlToMilli[fromPrecision - TSDB_TIME_PRECISION_HOURS];
X
Xiaoyu Wang 已提交
120
    if (unit > INT64_MAX / tsInt64) {
121 122 123 124
      return -1;
    }
    tsInt64 *= unit;
    fromPrecision = TSDB_TIME_PRECISION_MILLI;
wmmhello's avatar
wmmhello 已提交
125
  }
wmmhello's avatar
wmmhello 已提交
126

127
  return convertTimePrecision(tsInt64, fromPrecision, toPrecision);
wmmhello's avatar
wmmhello 已提交
128 129
}

130 131 132 133 134 135 136
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;
137 138 139
  }
}

X
Xiaoyu Wang 已提交
140
SSmlTableInfo *smlBuildTableInfo(int numRows, const char *measure, int32_t measureLen) {
141 142 143
  SSmlTableInfo *tag = (SSmlTableInfo *)taosMemoryCalloc(sizeof(SSmlTableInfo), 1);
  if (!tag) {
    return NULL;
144 145
  }

146 147
  tag->sTableName = measure;
  tag->sTableNameLen = measureLen;
148

149 150 151 152
  tag->cols = taosArrayInit(numRows, POINTER_BYTES);
  if (tag->cols == NULL) {
    uError("SML:smlBuildTableInfo failed to allocate memory");
    goto cleanup;
153
  }
154

X
Xiaoyu Wang 已提交
155 156 157 158 159
  //  tag->tags = taosArrayInit(16, sizeof(SSmlKv));
  //  if (tag->tags == NULL) {
  //    uError("SML:smlBuildTableInfo failed to allocate memory");
  //    goto cleanup;
  //  }
160 161
  return tag;

X
Xiaoyu Wang 已提交
162
cleanup:
163 164
  taosMemoryFree(tag);
  return NULL;
165 166
}

167
static int32_t smlParseTableName(SArray *tags, char *childTableName) {
X
Xiaoyu Wang 已提交
168
  size_t childTableNameLen = strlen(tsSmlChildTableName);
169 170
  if (childTableNameLen <= 0) return TSDB_CODE_SUCCESS;

X
Xiaoyu Wang 已提交
171
  for (int i = 0; i < taosArrayGetSize(tags); i++) {
172 173 174 175 176 177
    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));
      break;
wmmhello's avatar
wmmhello 已提交
178 179
    }
  }
180

wmmhello's avatar
wmmhello 已提交
181 182 183
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
184
int32_t smlSetCTableName(SSmlTableInfo *oneTable) {
185
  smlParseTableName(oneTable->tags, oneTable->childTableName);
186

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

191 192
    buildChildTableName(&rName);
    taosArrayDestroy(dst);
193
  }
194 195
  return TSDB_CODE_SUCCESS;
}
196

197 198 199 200
SSmlSTableMeta *smlBuildSTableMeta(bool isDataFormat) {
  SSmlSTableMeta *meta = (SSmlSTableMeta *)taosMemoryCalloc(sizeof(SSmlSTableMeta), 1);
  if (!meta) {
    return NULL;
201 202
  }

X
Xiaoyu Wang 已提交
203
  if (unlikely(!isDataFormat)) {
204 205 206 207 208
    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 已提交
209

210 211 212 213 214
    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 已提交
215 216
  }

217 218 219 220
  meta->tags = taosArrayInit(32, sizeof(SSmlKv));
  if (meta->tags == NULL) {
    uError("SML:smlBuildSTableMeta failed to allocate memory");
    goto cleanup;
221 222
  }

223 224 225 226 227 228
  meta->cols = taosArrayInit(32, sizeof(SSmlKv));
  if (meta->cols == NULL) {
    uError("SML:smlBuildSTableMeta failed to allocate memory");
    goto cleanup;
  }
  return meta;
229

X
Xiaoyu Wang 已提交
230
cleanup:
231 232
  taosMemoryFree(meta);
  return NULL;
wmmhello's avatar
wmmhello 已提交
233 234
}

X
Xiaoyu Wang 已提交
235 236 237 238 239 240 241
// 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 已提交
242

X
Xiaoyu Wang 已提交
243 244 245
#define RETURN_FALSE                                 \
  smlBuildInvalidDataMsg(msg, "invalid data", pVal); \
  return false;
wmmhello's avatar
wmmhello 已提交
246

X
Xiaoyu Wang 已提交
247 248 249 250 251 252 253 254 255 256
#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 已提交
257 258
  kvVal->f = (float)result;

X
Xiaoyu Wang 已提交
259 260 261 262 263 264 265 266 267 268 269 270 271
#define SET_BIGINT                                                                                         \
  if (smlDoubleToInt64OverFlow(result)) {                                                                  \
    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;                                                                                        \
    return true;                                                                                           \
  }                                                                                                        \
  kvVal->type = TSDB_DATA_TYPE_BIGINT;                                                                     \
wmmhello's avatar
wmmhello 已提交
272 273
  kvVal->i = (int64_t)result;

X
Xiaoyu Wang 已提交
274 275 276 277 278 279
#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 已提交
280 281
  kvVal->i = result;

X
Xiaoyu Wang 已提交
282 283 284 285 286 287
#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 已提交
288 289
  kvVal->i = result;

X
Xiaoyu Wang 已提交
290 291 292 293 294 295 296 297 298 299 300 301 302
#define SET_UBIGINT                                                                               \
  if (result >= (double)UINT64_MAX || result < 0) {                                               \
    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;                                                                               \
    return true;                                                                                  \
  }                                                                                               \
  kvVal->type = TSDB_DATA_TYPE_UBIGINT;                                                           \
wmmhello's avatar
wmmhello 已提交
303 304
  kvVal->u = result;

X
Xiaoyu Wang 已提交
305 306 307 308 309 310
#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 已提交
311 312
  kvVal->u = result;

X
Xiaoyu Wang 已提交
313 314 315 316 317 318
#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 已提交
319 320
  kvVal->u = result;

X
Xiaoyu Wang 已提交
321 322 323 324 325 326
#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 已提交
327 328
  kvVal->i = result;

X
Xiaoyu Wang 已提交
329 330 331 332 333 334
#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 已提交
335 336
  kvVal->u = result;

337
bool smlParseNumber(SSmlKv *kvVal, SSmlMsgBuf *msg) {
wmmhello's avatar
wmmhello 已提交
338 339
  const char *pVal = kvVal->value;
  int32_t     len = kvVal->length;
X
Xiaoyu Wang 已提交
340
  char       *endptr = NULL;
wmmhello's avatar
wmmhello 已提交
341 342 343 344 345 346 347 348 349
  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 已提交
350 351
    if (endptr[0] == 'f' || endptr[0] == 'F') {
      if (endptr[1] == '6' && endptr[2] == '4') {
wmmhello's avatar
wmmhello 已提交
352
        SET_DOUBLE
X
Xiaoyu Wang 已提交
353
      } else if (endptr[1] == '3' && endptr[2] == '2') {
wmmhello's avatar
wmmhello 已提交
354
        SET_FLOAT
X
Xiaoyu Wang 已提交
355
      } else {
wmmhello's avatar
wmmhello 已提交
356 357
        RETURN_FALSE
      }
X
Xiaoyu Wang 已提交
358 359
    } else if (endptr[0] == 'i' || endptr[0] == 'I') {
      if (endptr[1] == '6' && endptr[2] == '4') {
wmmhello's avatar
wmmhello 已提交
360
        SET_BIGINT
X
Xiaoyu Wang 已提交
361
      } else if (endptr[1] == '3' && endptr[2] == '2') {
wmmhello's avatar
wmmhello 已提交
362
        SET_INT
X
Xiaoyu Wang 已提交
363
      } else if (endptr[1] == '1' && endptr[2] == '6') {
wmmhello's avatar
wmmhello 已提交
364
        SET_SMALL_INT
X
Xiaoyu Wang 已提交
365
      } else {
wmmhello's avatar
wmmhello 已提交
366 367
        RETURN_FALSE
      }
X
Xiaoyu Wang 已提交
368 369
    } else if (endptr[0] == 'u' || endptr[0] == 'U') {
      if (endptr[1] == '6' && endptr[2] == '4') {
wmmhello's avatar
wmmhello 已提交
370
        SET_UBIGINT
X
Xiaoyu Wang 已提交
371
      } else if (endptr[1] == '3' && endptr[2] == '2') {
wmmhello's avatar
wmmhello 已提交
372
        SET_UINT
X
Xiaoyu Wang 已提交
373
      } else if (endptr[1] == '1' && endptr[2] == '6') {
wmmhello's avatar
wmmhello 已提交
374
        SET_USMALL_INT
X
Xiaoyu Wang 已提交
375
      } else {
wmmhello's avatar
wmmhello 已提交
376 377
        RETURN_FALSE
      }
wmmhello's avatar
wmmhello 已提交
378
    } else {
wmmhello's avatar
wmmhello 已提交
379 380
      RETURN_FALSE
    }
X
Xiaoyu Wang 已提交
381 382 383
  } else if (left == 2) {
    if (endptr[0] == 'i' || endptr[0] == 'I') {
      if (endptr[1] == '8') {
wmmhello's avatar
wmmhello 已提交
384
        SET_TINYINT
X
Xiaoyu Wang 已提交
385
      } else {
wmmhello's avatar
wmmhello 已提交
386 387
        RETURN_FALSE
      }
X
Xiaoyu Wang 已提交
388
    } else if (endptr[0] == 'u' || endptr[0] == 'U') {
wmmhello's avatar
wmmhello 已提交
389 390 391 392 393
      if (endptr[1] == '8') {
        SET_UTINYINT
      } else {
        RETURN_FALSE
      }
X
Xiaoyu Wang 已提交
394
    } else {
wmmhello's avatar
wmmhello 已提交
395 396
      RETURN_FALSE
    }
X
Xiaoyu Wang 已提交
397 398
  } else if (left == 1) {
    if (endptr[0] == 'i' || endptr[0] == 'I') {
wmmhello's avatar
wmmhello 已提交
399
      SET_BIGINT
X
Xiaoyu Wang 已提交
400
    } else if (endptr[0] == 'u' || endptr[0] == 'U') {
wmmhello's avatar
wmmhello 已提交
401
      SET_UBIGINT
X
Xiaoyu Wang 已提交
402
    } else {
wmmhello's avatar
wmmhello 已提交
403 404 405 406 407 408 409 410 411
      RETURN_FALSE
    }
  } else {
    RETURN_FALSE;
  }
  return true;
}

bool smlParseNumberOld(SSmlKv *kvVal, SSmlMsgBuf *msg) {
wmmhello's avatar
wmmhello 已提交
412
  const char *pVal = kvVal->value;
X
Xiaoyu Wang 已提交
413 414 415 416
  int32_t     len = kvVal->length;
  char       *endptr = NULL;
  double      result = taosStr2Double(pVal, &endptr);
  if (pVal == endptr) {
417
    smlBuildInvalidDataMsg(msg, "invalid data", pVal);
wmmhello's avatar
wmmhello 已提交
418 419 420
    return false;
  }

421
  int32_t left = len - (endptr - pVal);
X
Xiaoyu Wang 已提交
422
  if (left == 0 || (left == 3 && strncasecmp(endptr, "f64", left) == 0)) {
423 424
    kvVal->type = TSDB_DATA_TYPE_DOUBLE;
    kvVal->d = result;
X
Xiaoyu Wang 已提交
425 426
  } else if ((left == 3 && strncasecmp(endptr, "f32", left) == 0)) {
    if (!IS_VALID_FLOAT(result)) {
427 428
      smlBuildInvalidDataMsg(msg, "float out of range[-3.402823466e+38,3.402823466e+38]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
429
    }
430 431
    kvVal->type = TSDB_DATA_TYPE_FLOAT;
    kvVal->f = (float)result;
X
Xiaoyu Wang 已提交
432 433
  } else if ((left == 1 && *endptr == 'i') || (left == 3 && strncasecmp(endptr, "i64", left) == 0)) {
    if (smlDoubleToInt64OverFlow(result)) {
wmmhello's avatar
wmmhello 已提交
434 435
      errno = 0;
      int64_t tmp = taosStr2Int64(pVal, &endptr, 10);
X
Xiaoyu Wang 已提交
436
      if (errno == ERANGE) {
wmmhello's avatar
wmmhello 已提交
437 438 439 440 441 442
        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 已提交
443
    }
444
    kvVal->type = TSDB_DATA_TYPE_BIGINT;
wmmhello's avatar
wmmhello 已提交
445
    kvVal->i = (int64_t)result;
wmmhello's avatar
wmmhello 已提交
446
  } else if ((left == 1 && *endptr == 'u') || (left == 3 && strncasecmp(endptr, "u64", left) == 0)) {
X
Xiaoyu Wang 已提交
447
    if (result >= (double)UINT64_MAX || result < 0) {
wmmhello's avatar
wmmhello 已提交
448 449
      errno = 0;
      uint64_t tmp = taosStr2UInt64(pVal, &endptr, 10);
X
Xiaoyu Wang 已提交
450
      if (errno == ERANGE || result < 0) {
wmmhello's avatar
wmmhello 已提交
451 452 453 454 455 456
        smlBuildInvalidDataMsg(msg, "unsigned big int out of range[0,18446744073709551615]", pVal);
        return false;
      }
      kvVal->type = TSDB_DATA_TYPE_UBIGINT;
      kvVal->u = tmp;
      return true;
457
    }
458
    kvVal->type = TSDB_DATA_TYPE_UBIGINT;
wmmhello's avatar
wmmhello 已提交
459
    kvVal->u = result;
X
Xiaoyu Wang 已提交
460 461
  } else if (left == 3 && strncasecmp(endptr, "i32", left) == 0) {
    if (!IS_VALID_INT(result)) {
462 463
      smlBuildInvalidDataMsg(msg, "int out of range[-2147483648,2147483647]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
464
    }
465 466
    kvVal->type = TSDB_DATA_TYPE_INT;
    kvVal->i = result;
X
Xiaoyu Wang 已提交
467 468
  } else if (left == 3 && strncasecmp(endptr, "u32", left) == 0) {
    if (!IS_VALID_UINT(result)) {
469 470
      smlBuildInvalidDataMsg(msg, "unsigned int out of range[0,4294967295]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
471
    }
472 473
    kvVal->type = TSDB_DATA_TYPE_UINT;
    kvVal->u = result;
X
Xiaoyu Wang 已提交
474 475
  } else if (left == 3 && strncasecmp(endptr, "i16", left) == 0) {
    if (!IS_VALID_SMALLINT(result)) {
476 477
      smlBuildInvalidDataMsg(msg, "small int our of range[-32768,32767]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
478
    }
479 480
    kvVal->type = TSDB_DATA_TYPE_SMALLINT;
    kvVal->i = result;
X
Xiaoyu Wang 已提交
481 482
  } else if (left == 3 && strncasecmp(endptr, "u16", left) == 0) {
    if (!IS_VALID_USMALLINT(result)) {
483 484
      smlBuildInvalidDataMsg(msg, "unsigned small int out of rang[0,65535]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
485
    }
486 487
    kvVal->type = TSDB_DATA_TYPE_USMALLINT;
    kvVal->u = result;
X
Xiaoyu Wang 已提交
488 489
  } else if (left == 2 && strncasecmp(endptr, "i8", left) == 0) {
    if (!IS_VALID_TINYINT(result)) {
490 491
      smlBuildInvalidDataMsg(msg, "tiny int out of range[-128,127]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
492
    }
493 494
    kvVal->type = TSDB_DATA_TYPE_TINYINT;
    kvVal->i = result;
X
Xiaoyu Wang 已提交
495 496
  } else if (left == 2 && strncasecmp(endptr, "u8", left) == 0) {
    if (!IS_VALID_UTINYINT(result)) {
497 498
      smlBuildInvalidDataMsg(msg, "unsigned tiny int out of range[0,255]", pVal);
      return false;
wmmhello's avatar
wmmhello 已提交
499
    }
500 501
    kvVal->type = TSDB_DATA_TYPE_UTINYINT;
    kvVal->u = result;
X
Xiaoyu Wang 已提交
502
  } else {
503
    smlBuildInvalidDataMsg(msg, "invalid data", pVal);
wmmhello's avatar
wmmhello 已提交
504 505
    return false;
  }
506
  return true;
wmmhello's avatar
wmmhello 已提交
507 508
}

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

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

515 516 517 518 519 520 521
  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 已提交
522

523
  int32_t code = catalogGetSTableMeta(info->pCatalog, &conn, &pName, &pTableMeta);
X
Xiaoyu Wang 已提交
524
  if (code != TSDB_CODE_SUCCESS) {
525 526
    return NULL;
  }
527
  return pTableMeta;
wmmhello's avatar
wmmhello 已提交
528
}
wmmhello's avatar
wmmhello 已提交
529

530 531
static int64_t smlGenId() {
  static volatile int64_t linesSmlHandleId = 0;
wmmhello's avatar
wmmhello 已提交
532

533 534 535 536
  int64_t id = 0;
  do {
    id = atomic_add_fetch_64(&linesSmlHandleId, 1);
  } while (id == 0);
537

538
  return id;
539 540
}

541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
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) {
      uError("SML:0x%" PRIx64 " point type and db type mismatch. key: %s. point type: %d, db type: %d", info->id,
             kv->key, colField[*index].type, kv->type);
      return TSDB_CODE_TSC_INVALID_VALUE;
    }

    if ((colField[*index].type == TSDB_DATA_TYPE_VARCHAR &&
         (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 已提交
567
  }
568
  return 0;
569 570
}

571 572 573 574
static int32_t smlFindNearestPowerOf2(int32_t length, uint8_t type) {
  int32_t result = 1;
  while (result <= length) {
    result *= 2;
575
  }
576 577 578 579
  if (type == TSDB_DATA_TYPE_BINARY && result > TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE) {
    result = TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE;
  } else if (type == TSDB_DATA_TYPE_NCHAR && result > (TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE) {
    result = (TSDB_MAX_BINARY_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE;
580
  }
581 582 583 584 585

  if (type == TSDB_DATA_TYPE_NCHAR) {
    result = result * TSDB_NCHAR_SIZE + VARSTR_HEADER_SIZE;
  } else if (type == TSDB_DATA_TYPE_BINARY) {
    result = result + VARSTR_HEADER_SIZE;
586
  }
587
  return result;
588 589
}

590 591 592 593 594 595 596 597 598 599
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;
    }
600
  }
601
  return TSDB_CODE_SUCCESS;
602 603
}

604 605 606 607 608
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);
609 610
  }

611 612 613 614
  if (isTag) {
    i = 0;
  } else {
    i = 1;
615
  }
616 617 618 619 620 621
  for (; i < taosArrayGetSize(cols); i++) {
    SSmlKv *kv = (SSmlKv *)taosArrayGet(cols, i);
    if (taosHashGet(hashTmp, kv->key, kv->keyLen) == NULL) {
      taosHashCleanup(hashTmp);
      return -1;
    }
622
  }
623 624 625
  taosHashCleanup(hashTmp);
  return 0;
}
626

627 628 629 630 631 632
static int32_t getBytes(uint8_t type, int32_t length) {
  if (type == TSDB_DATA_TYPE_BINARY || type == TSDB_DATA_TYPE_NCHAR) {
    return smlFindNearestPowerOf2(length, type);
  } else {
    return tDataTypes[type].bytes;
  }
633 634
}

635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
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;
    smlGenerateSchemaAction(schemaField, schemaHash, kv, isTag, &action, info);
    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);
      uint16_t  newIndex = *index;
      if (isTag) newIndex -= numOfCols;
      SField *field = (SField *)taosArrayGet(results, newIndex);
      field->bytes = getBytes(kv->type, kv->length);
653 654 655 656 657
    }
  }
  return TSDB_CODE_SUCCESS;
}

658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
// 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};

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

  code = buildRequest(info->taos->id, "", 0, NULL, false, &pRequest, 0);
  if (code != TSDB_CODE_SUCCESS) {
675 676
    goto end;
  }
677 678 679 680

  pRequest->syncQuery = true;
  if (!pRequest->pDb) {
    code = TSDB_CODE_PAR_DB_NOT_SPECIFIED;
681 682 683
    goto end;
  }

684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
  if (action == SCHEMA_ACTION_CREATE_STABLE) {
    pReq.colVer = 1;
    pReq.tagVer = 1;
    pReq.suid = 0;
    pReq.source = TD_REQ_FROM_APP;
  } 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;
  } 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;
  }
700

701 702 703 704 705 706 707
  if (pReq.numOfTags == 0) {
    pReq.numOfTags = 1;
    SField field = {0};
    field.type = TSDB_DATA_TYPE_NCHAR;
    field.bytes = 1;
    strcpy(field.name, tsSmlTagName);
    taosArrayPush(pReq.pTags, &field);
708
  }
wmmhello's avatar
wmmhello 已提交
709

710 711 712
  pReq.commentLen = -1;
  pReq.igExists = true;
  tNameExtractFullName(pName, pReq.name);
713

714 715 716 717 718 719 720 721 722
  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);
723

724 725 726 727 728 729
  SQuery pQuery;
  memset(&pQuery, 0, sizeof(pQuery));
  pQuery.execMode = QUERY_EXEC_MODE_RPC;
  pQuery.pCmdMsg = &pCmdMsg;
  pQuery.msgType = pQuery.pCmdMsg->msgType;
  pQuery.stableQuery = true;
730

731
  launchQueryImpl(pRequest, &pQuery, true, NULL);
732

733 734
  if (pRequest->code == TSDB_CODE_SUCCESS) {
    catalogRemoveTableMeta(info->pCatalog, pName);
735
  }
736 737
  code = pRequest->code;
  taosMemoryFree(pCmdMsg.pMsg);
738

X
Xiaoyu Wang 已提交
739
end:
740 741 742 743
  destroyRequest(pRequest);
  tFreeSMCreateStbReq(&pReq);
  return code;
}
744

745
static int32_t smlModifyDBSchemas(SSmlHandle *info) {
X
Xiaoyu Wang 已提交
746
  if (info->dataFormat && !info->needModifySchema) {
747
    return TSDB_CODE_SUCCESS;
748
  }
749 750 751
  int32_t     code = 0;
  SHashObj   *hashTmp = NULL;
  STableMeta *pTableMeta = NULL;
752 753 754 755 756 757 758 759 760

  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);
761

762
  SSmlSTableMeta **tmp = (SSmlSTableMeta **)taosHashIterate(info->superTables, NULL);
763
  while (tmp) {
764
    SSmlSTableMeta *sTableData = *tmp;
765
    bool            needCheckMeta = false;  // for multi thread
766

767 768
    size_t superTableLen = 0;
    void  *superTable = taosHashGetKey(tmp, &superTableLen);
769 770
    memset(pName.tname, 0, TSDB_TABLE_NAME_LEN);
    memcpy(pName.tname, superTable, superTableLen);
771

772
    code = catalogGetSTableMeta(info->pCatalog, &conn, &pName, &pTableMeta);
773

774 775 776 777 778
    if (code == TSDB_CODE_PAR_TABLE_NOT_EXIST || code == TSDB_CODE_MND_STB_NOT_EXIST) {
      SArray *pColumns = taosArrayInit(taosArrayGetSize(sTableData->cols), sizeof(SField));
      SArray *pTags = taosArrayInit(taosArrayGetSize(sTableData->tags), sizeof(SField));
      smlBuildFieldsList(info, NULL, NULL, sTableData->tags, pTags, 0, true);
      smlBuildFieldsList(info, NULL, NULL, sTableData->cols, pColumns, 0, false);
779

780 781 782 783
      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;
784
      }
785 786
      info->cost.numOfCreateSTables++;
      taosMemoryFreeClear(pTableMeta);
787

788 789 790 791
      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;
792
      }
793 794 795 796 797 798
    } 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);
799
      }
800

801 802 803 804
      ESchemaAction action = SCHEMA_ACTION_NULL;
      code = smlProcessSchemaAction(info, pTableMeta->schema, hashTmp, sTableData->tags, &action, true);
      if (code != TSDB_CODE_SUCCESS) {
        goto end;
805
      }
806 807 808 809 810
      if (action != SCHEMA_ACTION_NULL) {
        SArray *pColumns =
            taosArrayInit(taosArrayGetSize(sTableData->cols) + pTableMeta->tableInfo.numOfColumns, sizeof(SField));
        SArray *pTags =
            taosArrayInit(taosArrayGetSize(sTableData->tags) + pTableMeta->tableInfo.numOfTags, sizeof(SField));
811

812 813 814 815 816 817 818 819 820
        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);
821 822
          }
        }
823 824
        smlBuildFieldsList(info, pTableMeta->schema, hashTmp, sTableData->tags, pTags,
                           pTableMeta->tableInfo.numOfColumns, true);
825

826 827 828 829
        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;
830
        }
831

832 833 834 835 836 837 838 839 840
        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 已提交
841
        }
842 843
      }

844 845 846
      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);
847
      }
848 849 850 851
      action = SCHEMA_ACTION_NULL;
      code = smlProcessSchemaAction(info, pTableMeta->schema, hashTmp, sTableData->cols, &action, false);
      if (code != TSDB_CODE_SUCCESS) {
        goto end;
852
      }
853 854 855 856 857
      if (action != SCHEMA_ACTION_NULL) {
        SArray *pColumns =
            taosArrayInit(taosArrayGetSize(sTableData->cols) + pTableMeta->tableInfo.numOfColumns, sizeof(SField));
        SArray *pTags =
            taosArrayInit(taosArrayGetSize(sTableData->tags) + pTableMeta->tableInfo.numOfTags, sizeof(SField));
858

859 860 861 862 863 864 865 866 867 868
        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);
          }
869 870
        }

871 872
        smlBuildFieldsList(info, pTableMeta->schema, hashTmp, sTableData->cols, pColumns,
                           pTableMeta->tableInfo.numOfColumns, false);
873

874 875 876 877
        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;
878
        }
879

880 881 882 883 884 885 886 887 888 889
        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;
890 891
        }
      }
wmmhello's avatar
wmmhello 已提交
892

893 894 895
      needCheckMeta = true;
      taosHashCleanup(hashTmp);
      hashTmp = NULL;
X
Xiaoyu Wang 已提交
896
    } else {
897 898
      uError("SML:0x%" PRIx64 " load table meta error: %s", info->id, tstrerror(code));
      goto end;
wmmhello's avatar
wmmhello 已提交
899
    }
900

901 902 903 904 905 906 907 908 909 910 911
    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;
912 913
      }
    }
914 915 916

    sTableData->tableMeta = pTableMeta;

917
    tmp = (SSmlSTableMeta **)taosHashIterate(info->superTables, tmp);
wmmhello's avatar
wmmhello 已提交
918
  }
919
  return 0;
920

X
Xiaoyu Wang 已提交
921
end:
922 923
  taosHashCleanup(hashTmp);
  taosMemoryFreeClear(pTableMeta);
X
Xiaoyu Wang 已提交
924
  //  catalogRefreshTableMeta(info->pCatalog, &conn, &pName, 1);
925
  return code;
wmmhello's avatar
wmmhello 已提交
926 927
}

928 929 930 931 932 933 934
/*
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;
935
    }
wmmhello's avatar
wmmhello 已提交
936
  }
937 938 939
  return TSDB_CODE_SUCCESS;
}

940 941 942 943 944
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;
945
  }
946 947 948
  ret = smlCheckDupUnit(dumplicateKey, tags, msg);
  if(ret != TSDB_CODE_SUCCESS){
    goto end;
949
  }
950

951 952 953
  end:
  taosHashCleanup(dumplicateKey);
  return ret;
wmmhello's avatar
wmmhello 已提交
954
}
955
*/
wmmhello's avatar
wmmhello 已提交
956

X
Xiaoyu Wang 已提交
957
static void smlInsertMeta(SHashObj *metaHash, SArray *metaArray, SArray *cols) {
958 959
  for (int16_t i = 0; i < taosArrayGetSize(cols); ++i) {
    SSmlKv *kv = (SSmlKv *)taosArrayGet(cols, i);
X
Xiaoyu Wang 已提交
960 961
    int     ret = taosHashPut(metaHash, kv->key, kv->keyLen, &i, SHORT_BYTES);
    if (ret == 0) {
962 963
      taosArrayPush(metaArray, kv);
    }
964
  }
965
}
wmmhello's avatar
wmmhello 已提交
966

967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
static void smlDestroySTableMeta(SSmlSTableMeta *meta) {
  taosHashCleanup(meta->tagHash);
  taosHashCleanup(meta->colHash);
  taosArrayDestroy(meta->tags);
  taosArrayDestroy(meta->cols);
  taosMemoryFree(meta->tableMeta);
  taosMemoryFree(meta);
}

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 已提交
983
      if (isTag) {
984 985
        if (kv->length > value->length) {
          value->length = kv->length;
986
        }
987 988 989 990 991
        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;
992 993
      }

994 995 996 997 998
      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 已提交
999
      if (tmp > INT16_MAX) {
1000 1001 1002
        uError("too many cols or tags");
        return -1;
      }
1003
      int16_t size = tmp;
X
Xiaoyu Wang 已提交
1004 1005
      int     ret = taosHashPut(metaHash, kv->key, kv->keyLen, &size, SHORT_BYTES);
      if (ret == 0) {
1006
        taosArrayPush(metaArray, kv);
1007 1008 1009 1010
      }
    }
  }

1011 1012
  return TSDB_CODE_SUCCESS;
}
1013

1014
void smlDestroyTableInfo(SSmlHandle *info, SSmlTableInfo *tag) {
1015 1016 1017 1018
  for (size_t i = 0; i < taosArrayGetSize(tag->cols); i++) {
    SHashObj *kvHash = (SHashObj *)taosArrayGetP(tag->cols, i);
    taosHashCleanup(kvHash);
  }
1019

X
Xiaoyu Wang 已提交
1020 1021 1022 1023 1024
  //  if (info->parseJsonByLib) {
  //    SSmlLineInfo *key = (SSmlLineInfo *)(tag->key);
  //    if (key != NULL) taosMemoryFree(key->tags);
  //  }
  //  taosMemoryFree(tag->key);
1025 1026 1027 1028
  taosArrayDestroy(tag->cols);
  taosArrayDestroy(tag->tags);
  taosMemoryFree(tag);
}
1029

X
Xiaoyu Wang 已提交
1030
void clearColValArray(SArray *pCols) {
wmmhello's avatar
wmmhello 已提交
1031 1032
  int32_t num = taosArrayGetSize(pCols);
  for (int32_t i = 0; i < num; ++i) {
X
Xiaoyu Wang 已提交
1033
    SColVal *pCol = taosArrayGet(pCols, i);
wmmhello's avatar
wmmhello 已提交
1034 1035 1036 1037 1038 1039
    if (TSDB_DATA_TYPE_NCHAR == pCol->type) {
      taosMemoryFreeClear(pCol->value.pData);
    }
  }
}

wmmhello's avatar
wmmhello 已提交
1040
void smlDestroyInfo(SSmlHandle *info) {
1041 1042
  if (!info) return;
  qDestroyQuery(info->pQuery);
1043

1044
  // destroy info->childTables
1045 1046 1047 1048
  SSmlTableInfo **oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, NULL);
  while (oneTable) {
    smlDestroyTableInfo(info, *oneTable);
    oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, oneTable);
1049 1050
  }

1051
  // destroy info->superTables
1052 1053 1054 1055
  SSmlSTableMeta **oneSTable = (SSmlSTableMeta **)taosHashIterate(info->superTables, NULL);
  while (oneSTable) {
    smlDestroySTableMeta(*oneSTable);
    oneSTable = (SSmlSTableMeta **)taosHashIterate(info->superTables, oneSTable);
1056
  }
1057

1058 1059
  // destroy info->pVgHash
  taosHashCleanup(info->pVgHash);
1060 1061
  taosHashCleanup(info->childTables);
  taosHashCleanup(info->superTables);
wmmhello's avatar
wmmhello 已提交
1062

X
Xiaoyu Wang 已提交
1063
  for (int i = 0; i < taosArrayGetSize(info->tagJsonArray); i++) {
wmmhello's avatar
wmmhello 已提交
1064 1065 1066 1067 1068
    cJSON *tags = (cJSON *)taosArrayGetP(info->tagJsonArray, i);
    cJSON_Delete(tags);
  }
  taosArrayDestroy(info->tagJsonArray);

1069 1070 1071 1072 1073 1074
  for (int i = 0; i < taosArrayGetSize(info->valueJsonArray); i++) {
    cJSON *value = (cJSON *)taosArrayGetP(info->valueJsonArray, i);
    cJSON_Delete(value);
  }
  taosArrayDestroy(info->valueJsonArray);

1075
  taosArrayDestroy(info->preLineTagKV);
wmmhello's avatar
wmmhello 已提交
1076
  taosArrayDestroy(info->maxTagKVs);
1077
  taosArrayDestroy(info->preLineColKV);
wmmhello's avatar
wmmhello 已提交
1078

X
Xiaoyu Wang 已提交
1079 1080
  if (!info->dataFormat) {
    for (int i = 0; i < info->lineNum; i++) {
1081
      taosArrayDestroy(info->lines[i].colArray);
X
Xiaoyu Wang 已提交
1082
      if (info->parseJsonByLib) {
wmmhello's avatar
wmmhello 已提交
1083 1084
        taosMemoryFree(info->lines[i].tags);
      }
X
Xiaoyu Wang 已提交
1085
      if (info->lines[i].measureTagsLen != 0) taosMemoryFree(info->lines[i].measureTag);
1086 1087
    }
    taosMemoryFree(info->lines);
wmmhello's avatar
wmmhello 已提交
1088
  }
1089

wmmhello's avatar
wmmhello 已提交
1090
  cJSON_Delete(info->root);
1091 1092
  taosMemoryFreeClear(info);
}
wmmhello's avatar
wmmhello 已提交
1093

wmmhello's avatar
wmmhello 已提交
1094
SSmlHandle *smlBuildSmlInfo(TAOS *taos) {
1095 1096 1097 1098
  int32_t     code = TSDB_CODE_SUCCESS;
  SSmlHandle *info = (SSmlHandle *)taosMemoryCalloc(1, sizeof(SSmlHandle));
  if (NULL == info) {
    return NULL;
1099
  }
X
Xiaoyu Wang 已提交
1100
  if (taos != NULL) {
1101 1102 1103 1104 1105 1106
    info->taos = acquireTscObj(*(int64_t *)taos);
    code = catalogGetHandle(info->taos->pAppInfo->clusterId, &info->pCatalog);
    if (code != TSDB_CODE_SUCCESS) {
      uError("SML:0x%" PRIx64 " get catalog error %d", info->id, code);
      goto cleanup;
    }
1107
  }
wmmhello's avatar
wmmhello 已提交
1108

1109
  info->pVgHash = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_NO_LOCK);
1110 1111 1112
  info->childTables = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
  info->superTables = taosHashInit(16, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);

1113 1114 1115
  info->id = smlGenId();
  info->pQuery = smlInitHandle();
  info->dataFormat = true;
1116

wmmhello's avatar
wmmhello 已提交
1117
  info->tagJsonArray = taosArrayInit(8, POINTER_BYTES);
1118
  info->valueJsonArray = taosArrayInit(8, POINTER_BYTES);
1119
  info->preLineTagKV = taosArrayInit(8, sizeof(SSmlKv));
wmmhello's avatar
wmmhello 已提交
1120
  info->maxTagKVs = taosArrayInit(8, sizeof(SSmlKv));
1121 1122
  info->preLineColKV = taosArrayInit(8, sizeof(SSmlKv));

wmmhello's avatar
wmmhello 已提交
1123
  if (NULL == info->pVgHash || NULL == info->childTables || NULL == info->superTables) {
1124 1125
    uError("create SSmlHandle failed");
    goto cleanup;
1126 1127
  }

1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
  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);
    taosHashPut(kvHash, kv->key, kv->keyLen, &kv, POINTER_BYTES);
1144 1145
  }

1146
  taosArrayPush(colsArray, &kvHash);
1147
  return TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1148
}
1149

1150
static int32_t smlParseLineBottom(SSmlHandle *info) {
X
Xiaoyu Wang 已提交
1151
  if (info->dataFormat) return TSDB_CODE_SUCCESS;
1152

X
Xiaoyu Wang 已提交
1153 1154
  for (int32_t i = 0; i < info->lineNum; i++) {
    SSmlLineInfo  *elements = info->lines + i;
1155
    SSmlTableInfo *tinfo = NULL;
X
Xiaoyu Wang 已提交
1156
    if (info->protocol == TSDB_SML_LINE_PROTOCOL) {
1157
      tinfo = *(SSmlTableInfo **)taosHashGet(info->childTables, elements->measure, elements->measureTagsLen);
X
Xiaoyu Wang 已提交
1158
    } else if (info->protocol == TSDB_SML_TELNET_PROTOCOL) {
X
Xiaoyu Wang 已提交
1159 1160
      tinfo = *(SSmlTableInfo **)taosHashGet(info->childTables, elements->measureTag,
                                             elements->measureLen + elements->tagsLen);
X
Xiaoyu Wang 已提交
1161
    } else {
X
Xiaoyu Wang 已提交
1162 1163
      tinfo = *(SSmlTableInfo **)taosHashGet(info->childTables, elements->measureTag,
                                             elements->measureLen + elements->tagsLen);
1164 1165
    }

X
Xiaoyu Wang 已提交
1166
    if (tinfo == NULL) {
1167 1168 1169
      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;
1170
    }
wmmhello's avatar
wmmhello 已提交
1171

1172 1173 1174 1175 1176
    if (taosArrayGetSize(tinfo->tags) > TSDB_MAX_TAGS) {
      smlBuildInvalidDataMsg(&info->msgBuf, "too many tags than 128", NULL);
      return TSDB_CODE_PAR_INVALID_TAGS_NUM;
    }

1177 1178 1179
    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 已提交
1180
    }
wmmhello's avatar
wmmhello 已提交
1181

1182
    int ret = smlPushCols(tinfo->cols, elements->colArray);
X
Xiaoyu Wang 已提交
1183
    if (ret != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
1184 1185 1186
      return ret;
    }

1187 1188
    SSmlSTableMeta **tableMeta =
        (SSmlSTableMeta **)taosHashGet(info->superTables, elements->measure, elements->measureLen);
1189
    if (tableMeta) {  // update meta
1190
      ret = smlUpdateMeta((*tableMeta)->colHash, (*tableMeta)->cols, elements->colArray, false, &info->msgBuf);
1191
      if (ret == TSDB_CODE_SUCCESS) {
1192
        ret = smlUpdateMeta((*tableMeta)->tagHash, (*tableMeta)->tags, tinfo->tags, true, &info->msgBuf);
1193 1194 1195 1196 1197
      }
      if (ret != TSDB_CODE_SUCCESS) {
        uError("SML:0x%" PRIx64 " smlUpdateMeta failed", info->id);
        return ret;
      }
X
Xiaoyu Wang 已提交
1198
    } else {
X
Xiaoyu Wang 已提交
1199 1200 1201 1202 1203
      //      ret = smlJudgeDupColName(elements->colArray, tinfo->tags, &info->msgBuf);
      //      if (ret != TSDB_CODE_SUCCESS) {
      //        uError("SML:0x%" PRIx64 " smlUpdateMeta failed", info->id);
      //        return ret;
      //      }
wmmhello's avatar
wmmhello 已提交
1204

1205 1206 1207
      SSmlSTableMeta *meta = smlBuildSTableMeta(info->dataFormat);
      smlInsertMeta(meta->tagHash, meta->tags, tinfo->tags);
      smlInsertMeta(meta->colHash, meta->cols, elements->colArray);
1208
      taosHashPut(info->superTables, elements->measure, elements->measureLen, &meta, POINTER_BYTES);
wmmhello's avatar
wmmhello 已提交
1209
    }
wmmhello's avatar
wmmhello 已提交
1210
  }
1211

wmmhello's avatar
wmmhello 已提交
1212 1213 1214
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
1215
static int32_t smlInsertData(SSmlHandle *info) {
wmmhello's avatar
wmmhello 已提交
1216 1217
  int32_t code = TSDB_CODE_SUCCESS;

1218 1219 1220
  SSmlTableInfo **oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, NULL);
  while (oneTable) {
    SSmlTableInfo *tableData = *oneTable;
wmmhello's avatar
wmmhello 已提交
1221 1222

    SName pName = {TSDB_TABLE_NAME_T, info->taos->acctId, {0}, {0}};
wmmhello's avatar
wmmhello 已提交
1223
    tstrncpy(pName.dbname, info->pRequest->pDb, sizeof(pName.dbname));
wmmhello's avatar
wmmhello 已提交
1224
    memcpy(pName.tname, tableData->childTableName, strlen(tableData->childTableName));
D
dapan1121 已提交
1225 1226 1227 1228 1229 1230

    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 已提交
1231

wmmhello's avatar
wmmhello 已提交
1232
    SVgroupInfo vg;
D
dapan1121 已提交
1233
    code = catalogGetTableHashVgroup(info->pCatalog, &conn, &pName, &vg);
1234
    if (code != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
1235
      uError("SML:0x%" PRIx64 " catalogGetTableHashVgroup failed. table name: %s", info->id, tableData->childTableName);
wmmhello's avatar
wmmhello 已提交
1236 1237
      return code;
    }
X
Xiaoyu Wang 已提交
1238
    taosHashPut(info->pVgHash, (const char *)&vg.vgId, sizeof(vg.vgId), (char *)&vg, sizeof(vg));
wmmhello's avatar
wmmhello 已提交
1239

1240 1241 1242
    SSmlSTableMeta **pMeta =
        (SSmlSTableMeta **)taosHashGet(info->superTables, tableData->sTableName, tableData->sTableNameLen);
    if (unlikely(NULL == pMeta || NULL == (*pMeta)->tableMeta)) {
1243 1244 1245
      uError("SML:0x%" PRIx64 " NULL == pMeta. table name: %s", info->id, tableData->childTableName);
      return TSDB_CODE_SML_INTERNAL_ERROR;
    }
wmmhello's avatar
wmmhello 已提交
1246

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

X
Xiaoyu Wang 已提交
1251
    code = smlBindData(info->pQuery, info->dataFormat, tableData->tags, (*pMeta)->cols, tableData->cols,
1252
                       (*pMeta)->tableMeta, tableData->childTableName, tableData->sTableName, tableData->sTableNameLen,
1253
                       info->ttl, info->msgBuf.buf, info->msgBuf.len);
X
Xiaoyu Wang 已提交
1254 1255
    if (code != TSDB_CODE_SUCCESS) {
      uError("SML:0x%" PRIx64 " smlBindData failed", info->id);
wmmhello's avatar
wmmhello 已提交
1256 1257
      return code;
    }
1258
    oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, oneTable);
wmmhello's avatar
wmmhello 已提交
1259
  }
wmmhello's avatar
wmmhello 已提交
1260

wmmhello's avatar
wmmhello 已提交
1261
  code = smlBuildOutput(info->pQuery, info->pVgHash);
1262
  if (code != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
1263
    uError("SML:0x%" PRIx64 " smlBuildOutput failed", info->id);
1264 1265
    return code;
  }
1266 1267
  info->cost.insertRpcTime = taosGetTimestampUs();

1268 1269 1270
  SAppClusterSummary *pActivity = &info->taos->pAppInfo->summary;
  atomic_add_fetch_64((int64_t *)&pActivity->numOfInsertsReq, 1);

wmmhello's avatar
wmmhello 已提交
1271 1272
  launchQueryImpl(info->pRequest, info->pQuery, true, NULL);
  return info->pRequest->code;
wmmhello's avatar
wmmhello 已提交
1273 1274
}

X
Xiaoyu Wang 已提交
1275
static void smlPrintStatisticInfo(SSmlHandle *info) {
X
Xiaoyu Wang 已提交
1276 1277 1278
  uError(
      "SML:0x%" PRIx64
      " smlInsertLines result, code:%d,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 已提交
1279
        parse cost:%" PRId64 ",schema cost:%" PRId64 ",bind cost:%" PRId64 ",rpc cost:%" PRId64 ",total cost:%" PRId64
X
Xiaoyu Wang 已提交
1280 1281 1282 1283 1284 1285
      "",
      info->id, 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);
1286 1287
}

X
Xiaoyu Wang 已提交
1288
int32_t smlClearForRerun(SSmlHandle *info) {
1289 1290
  info->reRun = false;
  // clear info->childTables
1291 1292 1293 1294
  SSmlTableInfo **oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, NULL);
  while (oneTable) {
    smlDestroyTableInfo(info, *oneTable);
    oneTable = (SSmlTableInfo **)taosHashIterate(info->childTables, oneTable);
1295 1296 1297
  }

  // clear info->superTables
1298 1299 1300 1301
  SSmlSTableMeta **oneSTable = (SSmlSTableMeta **)taosHashIterate(info->superTables, NULL);
  while (oneSTable) {
    smlDestroySTableMeta(*oneSTable);
    oneSTable = (SSmlSTableMeta **)taosHashIterate(info->superTables, oneSTable);
1302 1303
  }

wmmhello's avatar
wmmhello 已提交
1304 1305 1306
  taosHashClear(info->childTables);
  taosHashClear(info->superTables);

X
Xiaoyu Wang 已提交
1307
  if (!info->dataFormat) {
wmmhello's avatar
wmmhello 已提交
1308 1309 1310 1311 1312
    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));
1313 1314 1315 1316 1317 1318
  }

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

X
Xiaoyu Wang 已提交
1319
  SVnodeModifyOpStmt *stmt = (SVnodeModifyOpStmt *)(info->pQuery->pRoot);
1320 1321 1322 1323 1324
  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 已提交
1325
static int32_t smlParseLine(SSmlHandle *info, char *lines[], char *rawLine, char *rawLineEnd, int numLines) {
wmmhello's avatar
wmmhello 已提交
1326
  int32_t code = TSDB_CODE_SUCCESS;
1327
  if (info->protocol == TSDB_SML_JSON_PROTOCOL) {
dengyihao's avatar
dengyihao 已提交
1328
    if (lines) {
wmmhello's avatar
wmmhello 已提交
1329
      code = smlParseJSON(info, *lines);
dengyihao's avatar
dengyihao 已提交
1330
    } else if (rawLine) {
wmmhello's avatar
wmmhello 已提交
1331 1332
      code = smlParseJSON(info, rawLine);
    }
1333
    if (code != TSDB_CODE_SUCCESS) {
dengyihao's avatar
dengyihao 已提交
1334
      uError("SML:0x%" PRIx64 " smlParseJSON failed:%s", info->id, lines ? *lines : rawLine);
1335 1336
      return code;
    }
wmmhello's avatar
wmmhello 已提交
1337
    return code;
wmmhello's avatar
wmmhello 已提交
1338
  }
wmmhello's avatar
wmmhello 已提交
1339

X
Xiaoyu Wang 已提交
1340
  char   *oldRaw = rawLine;
1341 1342
  int32_t i = 0;
  while (i < numLines) {
wmmhello's avatar
wmmhello 已提交
1343
    char *tmp = NULL;
dengyihao's avatar
dengyihao 已提交
1344 1345
    int   len = 0;
    if (lines) {
wmmhello's avatar
wmmhello 已提交
1346 1347
      tmp = lines[i];
      len = strlen(tmp);
dengyihao's avatar
dengyihao 已提交
1348
    } else if (rawLine) {
wmmhello's avatar
wmmhello 已提交
1349
      tmp = rawLine;
dengyihao's avatar
dengyihao 已提交
1350 1351
      while (rawLine < rawLineEnd) {
        if (*(rawLine++) == '\n') {
wmmhello's avatar
wmmhello 已提交
1352 1353 1354 1355
          break;
        }
        len++;
      }
dengyihao's avatar
dengyihao 已提交
1356
      if (info->protocol == TSDB_SML_LINE_PROTOCOL && tmp[0] == '#') {  // this line is comment
wmmhello's avatar
wmmhello 已提交
1357 1358
        continue;
      }
wmmhello's avatar
wmmhello 已提交
1359 1360
    }

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

X
Xiaoyu Wang 已提交
1364
    if (info->protocol == TSDB_SML_LINE_PROTOCOL) {
X
Xiaoyu Wang 已提交
1365
      if (info->dataFormat) {
wmmhello's avatar
wmmhello 已提交
1366 1367
        SSmlLineInfo element = {0};
        code = smlParseInfluxString(info, tmp, tmp + len, &element);
X
Xiaoyu Wang 已提交
1368
      } else {
wmmhello's avatar
wmmhello 已提交
1369 1370
        code = smlParseInfluxString(info, tmp, tmp + len, info->lines + i);
      }
X
Xiaoyu Wang 已提交
1371
    } else if (info->protocol == TSDB_SML_TELNET_PROTOCOL) {
X
Xiaoyu Wang 已提交
1372
      if (info->dataFormat) {
1373 1374
        SSmlLineInfo element = {0};
        code = smlParseTelnetString(info, (char *)tmp, (char *)tmp + len, &element);
X
Xiaoyu Wang 已提交
1375
        if (element.measureTagsLen != 0) taosMemoryFree(element.measureTag);
X
Xiaoyu Wang 已提交
1376
      } else {
1377 1378
        code = smlParseTelnetString(info, (char *)tmp, (char *)tmp + len, info->lines + i);
      }
X
Xiaoyu Wang 已提交
1379
    } else {
1380
      code = TSDB_CODE_SML_INVALID_PROTOCOL_TYPE;
1381
    }
wmmhello's avatar
wmmhello 已提交
1382
    if (code != TSDB_CODE_SUCCESS) {
wmmhello's avatar
wmmhello 已提交
1383
      uError("SML:0x%" PRIx64 " smlParseLine failed. line %d : %s", info->id, i, tmp);
1384
      return code;
wmmhello's avatar
wmmhello 已提交
1385
    }
X
Xiaoyu Wang 已提交
1386
    if (info->reRun) {
1387
      i = 0;
1388
      rawLine = oldRaw;
1389
      code = smlClearForRerun(info);
X
Xiaoyu Wang 已提交
1390
      if (code != TSDB_CODE_SUCCESS) {
1391
        return code;
1392
      }
1393
      continue;
1394
    }
1395
    i++;
wmmhello's avatar
wmmhello 已提交
1396
  }
1397

1398 1399 1400
  return code;
}

dengyihao's avatar
dengyihao 已提交
1401
static int smlProcess(SSmlHandle *info, char *lines[], char *rawLine, char *rawLineEnd, int numLines) {
1402
  int32_t code = TSDB_CODE_SUCCESS;
1403 1404
  int32_t retryNum = 0;

1405 1406
  info->cost.parseTime = taosGetTimestampUs();

wmmhello's avatar
wmmhello 已提交
1407
  code = smlParseLine(info, lines, rawLine, rawLineEnd, numLines);
1408
  if (code != 0) {
X
Xiaoyu Wang 已提交
1409
    uError("SML:0x%" PRIx64 " smlParseLine error : %s", info->id, tstrerror(code));
wmmhello's avatar
wmmhello 已提交
1410
    return code;
1411
  }
1412 1413 1414 1415 1416 1417
  code = smlParseLineBottom(info);
  if (code != 0) {
    uError("SML:0x%" PRIx64 " smlParseLineBottom error : %s", info->id, tstrerror(code));
    return code;
  }

1418
  info->cost.lineNum = info->lineNum;
1419 1420
  info->cost.numOfSTables = taosHashGetSize(info->superTables);
  info->cost.numOfCTables = taosHashGetSize(info->childTables);
1421 1422

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

X
Xiaoyu Wang 已提交
1424
  do {
1425 1426
    code = smlModifyDBSchemas(info);
    if (code == 0) break;
1427
  } while (retryNum++ < taosHashGetSize(info->superTables) * MAX_RETRY_TIMES);
1428

wmmhello's avatar
wmmhello 已提交
1429
  if (code != 0) {
X
Xiaoyu Wang 已提交
1430
    uError("SML:0x%" PRIx64 " smlModifyDBSchemas error : %s", info->id, tstrerror(code));
wmmhello's avatar
wmmhello 已提交
1431
    return code;
wmmhello's avatar
wmmhello 已提交
1432
  }
wmmhello's avatar
wmmhello 已提交
1433

1434
  info->cost.insertBindTime = taosGetTimestampUs();
wmmhello's avatar
wmmhello 已提交
1435 1436
  code = smlInsertData(info);
  if (code != 0) {
X
Xiaoyu Wang 已提交
1437
    uError("SML:0x%" PRIx64 " smlInsertData error : %s", info->id, tstrerror(code));
wmmhello's avatar
wmmhello 已提交
1438
    return code;
wmmhello's avatar
wmmhello 已提交
1439 1440 1441 1442 1443
  }

  return code;
}

X
Xiaoyu Wang 已提交
1444 1445
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) {
1446
  int32_t code = TSDB_CODE_SUCCESS;
wmmhello's avatar
wmmhello 已提交
1447 1448 1449
  if (NULL == taos) {
    terrno = TSDB_CODE_TSC_DISCONNECTED;
    return NULL;
1450
  }
1451

wmmhello's avatar
wmmhello 已提交
1452 1453 1454 1455
  SRequestObj *request = (SRequestObj *)createRequest(*(int64_t *)taos, TSDB_SQL_INSERT, reqid);
  if (request == NULL) {
    uError("SML:taos_schemaless_insert error request is null");
    return NULL;
wmmhello's avatar
wmmhello 已提交
1456
  }
1457

wmmhello's avatar
wmmhello 已提交
1458 1459 1460 1461
  SSmlHandle *info = smlBuildSmlInfo(taos);
  if (info == NULL) {
    request->code = TSDB_CODE_OUT_OF_MEMORY;
    uError("SML:taos_schemaless_insert error SSmlHandle is null");
1462
    return (TAOS_RES *)request;
wmmhello's avatar
wmmhello 已提交
1463
  }
wmmhello's avatar
wmmhello 已提交
1464 1465
  info->pRequest = request;
  info->isRawLine = rawLine != NULL;
X
Xiaoyu Wang 已提交
1466
  info->ttl = ttl;
wmmhello's avatar
wmmhello 已提交
1467
  info->precision = precision;
1468
  info->protocol = (TSDB_SML_PROTOCOL_TYPE)protocol;
wmmhello's avatar
wmmhello 已提交
1469 1470 1471
  info->msgBuf.buf = info->pRequest->msgBuf;
  info->msgBuf.len = ERROR_MSG_BUF_DEFAULT_SIZE;
  info->lineNum = numLines;
wmmhello's avatar
wmmhello 已提交
1472

wmmhello's avatar
wmmhello 已提交
1473
  SSmlMsgBuf msg = {ERROR_MSG_BUF_DEFAULT_SIZE, request->msgBuf};
wmmhello's avatar
wmmhello 已提交
1474 1475 1476
  if (request->pDb == NULL) {
    request->code = TSDB_CODE_PAR_DB_NOT_SPECIFIED;
    smlBuildInvalidDataMsg(&msg, "Database not specified", NULL);
wmmhello's avatar
wmmhello 已提交
1477 1478 1479
    goto end;
  }

X
Xiaoyu Wang 已提交
1480
  if (protocol < TSDB_SML_LINE_PROTOCOL || protocol > TSDB_SML_JSON_PROTOCOL) {
1481
    request->code = TSDB_CODE_SML_INVALID_PROTOCOL_TYPE;
wmmhello's avatar
wmmhello 已提交
1482
    smlBuildInvalidDataMsg(&msg, "protocol invalidate", NULL);
1483
    goto end;
wmmhello's avatar
wmmhello 已提交
1484 1485
  }

X
Xiaoyu Wang 已提交
1486 1487
  if (protocol == TSDB_SML_LINE_PROTOCOL &&
      (precision < TSDB_SML_TIMESTAMP_NOT_CONFIGURED || precision > TSDB_SML_TIMESTAMP_NANO_SECONDS)) {
1488
    request->code = TSDB_CODE_SML_INVALID_PRECISION_TYPE;
wmmhello's avatar
wmmhello 已提交
1489
    smlBuildInvalidDataMsg(&msg, "precision invalidate for line protocol", NULL);
1490 1491 1492
    goto end;
  }

1493
  if (protocol == TSDB_SML_JSON_PROTOCOL) {
wmmhello's avatar
wmmhello 已提交
1494
    numLines = 1;
1495
  } else if (numLines <= 0) {
wmmhello's avatar
wmmhello 已提交
1496 1497 1498 1499 1500
    request->code = TSDB_CODE_SML_INVALID_DATA;
    smlBuildInvalidDataMsg(&msg, "line num is invalid", NULL);
    goto end;
  }

1501
  code = smlProcess(info, lines, rawLine, rawLineEnd, numLines);
wmmhello's avatar
wmmhello 已提交
1502 1503 1504
  request->code = code;
  info->cost.endTime = taosGetTimestampUs();
  info->cost.code = code;
1505
  smlPrintStatisticInfo(info);
1506

wmmhello's avatar
wmmhello 已提交
1507
end:
wmmhello's avatar
wmmhello 已提交
1508
  smlDestroyInfo(info);
1509
  return (TAOS_RES *)request;
wmmhello's avatar
wmmhello 已提交
1510
}
wmmhello's avatar
wmmhello 已提交
1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527

/**
 * 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 已提交
1528
 * @return TAOS_RES
wmmhello's avatar
wmmhello 已提交
1529 1530
 */

1531 1532
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 已提交
1533
  return taos_schemaless_insert_inner(taos, lines, NULL, NULL, numLines, protocol, precision, ttl, reqid);
dengyihao's avatar
dengyihao 已提交
1534 1535
}

1536 1537 1538
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 已提交
1539

X
Xiaoyu Wang 已提交
1540 1541
TAOS_RES *taos_schemaless_insert_ttl(TAOS *taos, char *lines[], int numLines, int protocol, int precision,
                                     int32_t ttl) {
1542 1543
  return taos_schemaless_insert_ttl_with_reqid(taos, lines, numLines, protocol, precision, ttl, 0);
}
wmmhello's avatar
wmmhello 已提交
1544

X
Xiaoyu Wang 已提交
1545 1546 1547 1548
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 已提交
1549 1550
}

1551
TAOS_RES *taos_schemaless_insert_raw_ttl_with_reqid(TAOS *taos, char *lines, int len, int32_t *totalRows, int protocol,
1552
                                                    int precision, int32_t ttl, int64_t reqid) {
dengyihao's avatar
dengyihao 已提交
1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
  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 已提交
1565
  return taos_schemaless_insert_inner(taos, NULL, lines, lines + len, *totalRows, protocol, precision, ttl, reqid);
dengyihao's avatar
dengyihao 已提交
1566 1567
}

X
Xiaoyu Wang 已提交
1568 1569 1570 1571
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);
1572
}
X
Xiaoyu Wang 已提交
1573 1574
TAOS_RES *taos_schemaless_insert_raw_ttl(TAOS *taos, char *lines, int len, int32_t *totalRows, int protocol,
                                         int precision, int32_t ttl) {
1575 1576
  return taos_schemaless_insert_raw_ttl_with_reqid(taos, lines, len, totalRows, protocol, precision, ttl, 0);
}
wmmhello's avatar
wmmhello 已提交
1577

X
Xiaoyu Wang 已提交
1578 1579 1580 1581
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 已提交
1582
}