tscParseInsert.c 36.7 KB
Newer Older
H
hzcheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/*
 * 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/>.
 */

#define _DEFAULT_SOURCE /* See feature_test_macros(7) */
#define _GNU_SOURCE

#define _XOPEN_SOURCE

#pragma GCC diagnostic ignored "-Woverflow"
S
slguan 已提交
22
#pragma GCC diagnostic ignored "-Wunused-variable"
H
hzcheng 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

#include <stdio.h>
#include <stdlib.h>

#include <pthread.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <assert.h>
#include <math.h>
#include <string.h>
#include <time.h>
#include <wchar.h>

#include "ihash.h"
S
slguan 已提交
38
#include "os.h"
H
hzcheng 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
#include "tscSecondaryMerge.h"
#include "tscUtil.h"
#include "tschemautil.h"
#include "tsclient.h"
#include "tsqldef.h"
#include "ttypes.h"

#include "tlog.h"
#include "tstoken.h"
#include "ttime.h"

#define INVALID_SQL_RET_MSG(p, ...) \
  do {                              \
    sprintf(p, __VA_ARGS__);        \
    return TSDB_CODE_INVALID_SQL;   \
  } while (0)

S
slguan 已提交
56 57
static void setErrMsg(char *msg, char *sql);
static int32_t tscAllocateMemIfNeed(STableDataBlocks *pDataBlock, int32_t rowSize);
H
hzcheng 已提交
58 59

// get formation
S
slguan 已提交
60
static int32_t getNumericType(const char *data) {
H
hzcheng 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
  if (*data == '-' || *data == '+') {
    data += 1;
  }

  if (data[0] == '0') {
    if (data[1] == 'x' || data[1] == 'X') {
      return TK_HEX;
    } else {
      return TK_OCT;
    }
  } else {
    return TK_INTEGER;
  }
}

S
slguan 已提交
76
static int64_t tscToInteger(char *data, char **endPtr) {
H
hzcheng 已提交
77 78 79 80 81 82 83 84 85 86 87 88
  int32_t numType = getNumericType(data);
  int32_t radix = 10;

  if (numType == TK_HEX) {
    radix = 16;
  } else if (numType == TK_OCT) {
    radix = 8;
  }

  return strtoll(data, endPtr, radix);
}

S
slguan 已提交
89 90
int tsParseTime(char *value, int32_t valuelen, int64_t *time, char **next, char *error, int16_t timePrec) {
  char *  token;
H
hzcheng 已提交
91 92 93 94 95
  int     tokenlen;
  int64_t interval;

  int64_t useconds = 0;

S
slguan 已提交
96
  char *pTokenEnd = *next;
H
hzcheng 已提交
97
  tscGetToken(pTokenEnd, &token, &tokenlen);
P
plum-lihui 已提交
98
  if (tokenlen == 0 && strlen(value) == 0) {
H
hzcheng 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
    INVALID_SQL_RET_MSG(error, "missing time stamp");
  }

  if (strncmp(value, "now", 3) == 0 && valuelen == 3) {
    useconds = taosGetTimestamp(timePrec);
  } else if (strncmp(value, "0", 1) == 0 && valuelen == 1) {
    // do nothing
  } else if (value[4] != '-') {
    for (int32_t i = 0; i < valuelen; ++i) {
      /*
       * filter illegal input.
       * e.g., nw, tt, ff etc.
       */
      if (value[i] < '0' || value[i] > '9') {
        return TSDB_CODE_INVALID_SQL;
      }
    }
    useconds = str2int64(value);
  } else {
    // strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);
    if (taosParseTime(value, time, valuelen, timePrec) != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_INVALID_SQL;
    }

    return TSDB_CODE_SUCCESS;
  }

  for (int k = valuelen; value[k] != '\0'; k++) {
    if (value[k] == ' ' || value[k] == '\t') continue;
    if (value[k] == ',') {
      *next = pTokenEnd;
      *time = useconds;
      return 0;
    }

    break;
  }

  /*
S
slguan 已提交
138 139 140
   * time expression:
   * e.g., now+12a, now-5h
   */
H
hzcheng 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
  pTokenEnd = tscGetToken(pTokenEnd, &token, &tokenlen);
  if (tokenlen && (*token == '+' || *token == '-')) {
    pTokenEnd = tscGetToken(pTokenEnd, &value, &valuelen);
    if (valuelen < 2) {
      strcpy(error, "value is expected");
      return TSDB_CODE_INVALID_SQL;
    }

    if (getTimestampInUsFromStr(value, valuelen, &interval) != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_INVALID_SQL;
    }
    if (timePrec == TSDB_TIME_PRECISION_MILLI) {
      interval /= 1000;
    }

    if (*token == '+') {
      useconds += interval;
    } else {
      useconds = (useconds >= interval) ? useconds - interval : 0;
    }

    *next = pTokenEnd;
  }

  *time = useconds;
  return TSDB_CODE_SUCCESS;
}

S
slguan 已提交
169
int32_t tsParseOneColumnData(SSchema *pSchema, char *value, int valuelen, char *payload, char *msg, char **str,
170
                             bool primaryKey, int16_t timePrec) {
H
hzcheng 已提交
171
  int64_t temp;
S
slguan 已提交
172 173
  int32_t nullInt = *(int32_t *)TSDB_DATA_NULL_STR_L;
  char *  endptr = NULL;
H
hzcheng 已提交
174 175 176 177
  errno = 0;  // reset global error code

  switch (pSchema->type) {
    case TSDB_DATA_TYPE_BOOL: {  // bool
S
slguan 已提交
178 179
      if (valuelen == 4 && nullInt == *(int32_t *)value) {
        *(uint8_t *)payload = TSDB_DATA_BOOL_NULL;
H
hzcheng 已提交
180 181
      } else {
        if (strncmp(value, "true", valuelen) == 0) {
S
slguan 已提交
182
          *(uint8_t *)payload = TSDB_TRUE;
H
hzcheng 已提交
183
        } else if (strncmp(value, "false", valuelen) == 0) {
S
slguan 已提交
184
          *(uint8_t *)payload = TSDB_FALSE;
H
hzcheng 已提交
185 186
        } else {
          int64_t v = strtoll(value, NULL, 10);
S
slguan 已提交
187
          *(uint8_t *)payload = (int8_t)((v == 0) ? TSDB_FALSE : TSDB_TRUE);
H
hzcheng 已提交
188 189 190 191 192
        }
      }
      break;
    }
    case TSDB_DATA_TYPE_TINYINT:
S
slguan 已提交
193 194
      if (valuelen == 4 && nullInt == *(int32_t *)value) {
        *((int32_t *)payload) = TSDB_DATA_TINYINT_NULL;
H
hzcheng 已提交
195 196 197 198 199 200 201
      } else {
        int64_t v = tscToInteger(value, &endptr);
        if (errno == ERANGE || v > INT8_MAX || v < INT8_MIN) {
          INVALID_SQL_RET_MSG(msg, "data is overflow");
        }

        int8_t v8 = (int8_t)v;
S
slguan 已提交
202
        if (isNull((char *)&v8, pSchema->type)) {
H
hzcheng 已提交
203 204 205
          INVALID_SQL_RET_MSG(msg, "data is overflow");
        }

S
slguan 已提交
206
        *((int8_t *)payload) = v8;
H
hzcheng 已提交
207 208 209 210 211
      }

      break;

    case TSDB_DATA_TYPE_SMALLINT:
S
slguan 已提交
212 213
      if (valuelen == 4 && nullInt == *(int32_t *)value) {
        *((int32_t *)payload) = TSDB_DATA_SMALLINT_NULL;
H
hzcheng 已提交
214 215 216 217 218 219 220 221
      } else {
        int64_t v = tscToInteger(value, &endptr);

        if (errno == ERANGE || v > INT16_MAX || v < INT16_MIN) {
          INVALID_SQL_RET_MSG(msg, "data is overflow");
        }

        int16_t v16 = (int16_t)v;
S
slguan 已提交
222
        if (isNull((char *)&v16, pSchema->type)) {
H
hzcheng 已提交
223 224 225
          INVALID_SQL_RET_MSG(msg, "data is overflow");
        }

S
slguan 已提交
226
        *((int16_t *)payload) = v16;
H
hzcheng 已提交
227 228 229 230
      }
      break;

    case TSDB_DATA_TYPE_INT:
S
slguan 已提交
231 232
      if (valuelen == 4 && nullInt == *(int32_t *)value) {
        *((int32_t *)payload) = TSDB_DATA_INT_NULL;
H
hzcheng 已提交
233 234 235 236 237 238 239 240
      } else {
        int64_t v = tscToInteger(value, &endptr);

        if (errno == ERANGE || v > INT32_MAX || v < INT32_MIN) {
          INVALID_SQL_RET_MSG(msg, "data is overflow");
        }

        int32_t v32 = (int32_t)v;
S
slguan 已提交
241
        if (isNull((char *)&v32, pSchema->type)) {
H
hzcheng 已提交
242 243 244
          INVALID_SQL_RET_MSG(msg, "data is overflow");
        }

S
slguan 已提交
245
        *((int32_t *)payload) = v32;
H
hzcheng 已提交
246 247 248 249 250
      }

      break;

    case TSDB_DATA_TYPE_BIGINT:
S
slguan 已提交
251 252
      if (valuelen == 4 && nullInt == *(int32_t *)value) {
        *((int64_t *)payload) = TSDB_DATA_BIGINT_NULL;
H
hzcheng 已提交
253 254
      } else {
        int64_t v = tscToInteger(value, &endptr);
S
slguan 已提交
255
        if (isNull((char *)&v, pSchema->type) || errno == ERANGE) {
H
hzcheng 已提交
256 257
          INVALID_SQL_RET_MSG(msg, "data is overflow");
        }
S
slguan 已提交
258
        *((int64_t *)payload) = v;
H
hzcheng 已提交
259 260 261 262
      }
      break;

    case TSDB_DATA_TYPE_FLOAT:
S
slguan 已提交
263 264
      if (valuelen == 4 && nullInt == *(int32_t *)value) {
        *((int32_t *)payload) = TSDB_DATA_FLOAT_NULL;
H
hzcheng 已提交
265 266
      } else {
        float v = (float)strtod(value, &endptr);
S
slguan 已提交
267 268
        if (isNull((char *)&v, pSchema->type) || isinf(v) || isnan(v)) {
          *((int32_t *)payload) = TSDB_DATA_FLOAT_NULL;
H
hzcheng 已提交
269
        } else {
S
slguan 已提交
270
          *((float *)payload) = v;
H
hzcheng 已提交
271 272 273 274 275 276 277 278 279 280 281 282
        }

        if (str != NULL) {
          // This if statement is just for Fanuc case, when a float point number is quoted by
          // quotes, we need to skip the quote. But this is temporary, it should be changed in the future.
          if (*endptr == '\'' || *endptr == '\"') endptr++;
          *str = endptr;
        }
      }
      break;

    case TSDB_DATA_TYPE_DOUBLE:
S
slguan 已提交
283 284
      if (valuelen == 4 && nullInt == *(int32_t *)value) {
        *((int64_t *)payload) = TSDB_DATA_DOUBLE_NULL;
H
hzcheng 已提交
285 286
      } else {
        double v = strtod(value, &endptr);
S
slguan 已提交
287 288
        if (isNull((char *)&v, pSchema->type) || isinf(v) || isnan(v)) {
          *((int32_t *)payload) = TSDB_DATA_FLOAT_NULL;
H
hzcheng 已提交
289
        } else {
S
slguan 已提交
290
          *((double *)payload) = v;
H
hzcheng 已提交
291 292 293 294 295 296 297 298 299 300 301 302
        }

        if (str != NULL) {
          // This if statement is just for Fanuc case, when a float point number is quoted by
          // quotes, we need to skip the quote. But this is temporary, it should be changed in the future.
          if (*endptr == '\'' || *endptr == '\"') endptr++;
          *str = endptr;
        }
      }
      break;

    case TSDB_DATA_TYPE_BINARY:
S
slguan 已提交
303 304 305 306
      /*
       * binary data cannot be null-terminated char string, otherwise the last char of the string is lost
       */
      if (valuelen == 4 && nullInt == *(int32_t *)value) {
H
hzcheng 已提交
307 308 309 310 311 312 313 314 315 316
        *payload = TSDB_DATA_BINARY_NULL;
      } else {
        /* truncate too long string */
        if (valuelen > pSchema->bytes) valuelen = pSchema->bytes;
        strncpy(payload, value, valuelen);
      }

      break;

    case TSDB_DATA_TYPE_NCHAR:
S
slguan 已提交
317 318
      if (valuelen == 4 && nullInt == *(int32_t *)value) {
        *(uint32_t *)payload = TSDB_DATA_NCHAR_NULL;
H
hzcheng 已提交
319 320 321 322 323 324 325 326 327
      } else {
        if (!taosMbsToUcs4(value, valuelen, payload, pSchema->bytes)) {
          sprintf(msg, "%s", strerror(errno));
          return TSDB_CODE_INVALID_SQL;
        }
      }
      break;

    case TSDB_DATA_TYPE_TIMESTAMP: {
S
slguan 已提交
328
      if (valuelen == 4 && nullInt == *(int32_t *)value) {
H
hzcheng 已提交
329
        if (primaryKey) {
S
slguan 已提交
330
          *((int64_t *)payload) = 0;
H
hzcheng 已提交
331
        } else {
S
slguan 已提交
332
          *((int64_t *)payload) = TSDB_DATA_BIGINT_NULL;
H
hzcheng 已提交
333 334 335 336 337
        }
      } else {
        if (tsParseTime(value, valuelen, &temp, str, msg, timePrec) != TSDB_CODE_SUCCESS) {
          return TSDB_CODE_INVALID_SQL;
        }
S
slguan 已提交
338
        *((int64_t *)payload) = temp;
H
hzcheng 已提交
339 340 341 342 343 344 345 346 347 348
      }

      break;
    }
  }

  return 0;
}

// todo merge the error msg function with tSQLParser
S
slguan 已提交
349
static void setErrMsg(char *msg, char *sql) {
350
  const char*   msgFormat = "near \"%s\" syntax error";
H
hzcheng 已提交
351 352 353 354 355 356 357 358
  const int32_t BACKWARD_CHAR_STEP = 15;

  // only extract part of sql string,avoid too long sql string cause stack over flow
  char buf[64] = {0};
  strncpy(buf, (sql - BACKWARD_CHAR_STEP), tListLen(buf) - 1);
  sprintf(msg, msgFormat, buf);
}

S
slguan 已提交
359
int tsParseOneRowData(char **str, STableDataBlocks *pDataBlocks, SSchema schema[], SParsedDataColInfo *spd, char *error,
360
                      int16_t timePrec) {
S
slguan 已提交
361
  char *value = NULL;
H
hzcheng 已提交
362 363
  int   valuelen = 0;

S
slguan 已提交
364 365
  char *payload = pDataBlocks->pData + pDataBlocks->size;

H
hzcheng 已提交
366 367
  /* 1. set the parsed value from sql string */
  int32_t rowSize = 0;
368
  for (int i = 0; i < spd->numOfAssignedCols; ++i) {
H
hzcheng 已提交
369
    /* the start position in data block buffer of current value in sql */
S
slguan 已提交
370
    char *  start = payload + spd->elems[i].offset;
H
hzcheng 已提交
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
    int16_t colIndex = spd->elems[i].colIndex;
    rowSize += schema[colIndex].bytes;

    int sign = 0;
  _again:
    *str = tscGetToken(*str, &value, &valuelen);
    if ((valuelen == 0 && value == NULL) || (valuelen == 1 && value[0] == ')')) {
      setErrMsg(error, *str);
      return -1;
    }

    /* support positive/negative integer/float data format */
    if ((*value == '+' || *value == '-') && valuelen == 1) {
      sign = 1;
      goto _again;
    }

    if (sign) {
      value = value - 1;
      /* backward to include the +/- symbol */
      valuelen++;
    }

    int32_t ret = tsParseOneColumnData(&schema[colIndex], value, valuelen, start, error, str,
395
                                       colIndex == PRIMARYKEY_TIMESTAMP_COL_INDEX, timePrec);
H
hzcheng 已提交
396 397 398
    if (ret != 0) {
      return -1;  // NOTE: here 0 mean error!
    }
399 400

    // once the data block is disordered, we do NOT keep previous timestamp any more
S
slguan 已提交
401 402 403 404
    if (colIndex == PRIMARYKEY_TIMESTAMP_COL_INDEX && pDataBlocks->ordered) {
      TSKEY k = *(TSKEY *)start;
      if (k <= pDataBlocks->prevTS) {
        pDataBlocks->ordered = false;
405 406
      }

S
slguan 已提交
407
      pDataBlocks->prevTS = k;
408
    }
H
hzcheng 已提交
409 410 411
  }

  /*2. set the null value for the rest columns */
412
  if (spd->numOfAssignedCols < spd->numOfCols) {
S
slguan 已提交
413
    char *ptr = payload;
H
hzcheng 已提交
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429

    for (int32_t i = 0; i < spd->numOfCols; ++i) {
      if (!spd->hasVal[i]) {
        /* current column do not have any value to insert, set it to null */
        setNull(ptr, schema[i].type, schema[i].bytes);
      }

      ptr += schema[i].bytes;
    }

    rowSize = ptr - payload;
  }

  return rowSize;
}

S
slguan 已提交
430 431 432 433 434 435 436 437 438
static int32_t rowDataCompar(const void *lhs, const void *rhs) {
  TSKEY left = *(TSKEY *)lhs;
  TSKEY right = *(TSKEY *)rhs;

  if (left == right) {
    return 0;
  } else {
    return left > right ? 1 : -1;
  }
439 440
}

S
slguan 已提交
441 442 443
int tsParseValues(char **str, STableDataBlocks *pDataBlock, SMeterMeta *pMeterMeta, int maxRows,
                  SParsedDataColInfo *spd, char *error) {
  char *token;
H
hzcheng 已提交
444 445 446 447
  int   tokenlen;

  int16_t numOfRows = 0;

S
slguan 已提交
448 449 450 451
  SSchema *pSchema = tsGetSchema(pMeterMeta);
  int32_t  precision = pMeterMeta->precision;

  if (spd->hasVal[0] == false) {
H
hzcheng 已提交
452 453 454 455 456
    sprintf(error, "primary timestamp column can not be null");
    return -1;
  }

  while (1) {
S
slguan 已提交
457
    char *tmp = tscGetToken(*str, &token, &tokenlen);
H
hzcheng 已提交
458 459 460
    if (tokenlen == 0 || *token != '(') break;

    *str = tmp;
S
slguan 已提交
461
    if (numOfRows >= maxRows || pDataBlock->size + pMeterMeta->rowSize >= pDataBlock->nAllocSize) {
H
hzcheng 已提交
462 463 464
      maxRows += tscAllocateMemIfNeed(pDataBlock, pMeterMeta->rowSize);
    }

S
slguan 已提交
465
    int32_t len = tsParseOneRowData(str, pDataBlock, pSchema, spd, error, precision);
H
hzcheng 已提交
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
    if (len <= 0) {
      setErrMsg(error, *str);
      return -1;
    }

    pDataBlock->size += len;

    *str = tscGetToken(*str, &token, &tokenlen);
    if (tokenlen == 0 || *token != ')') {
      setErrMsg(error, *str);
      return -1;
    }

    numOfRows++;
  }

  if (numOfRows <= 0) {
    strcpy(error, "no any data points");
S
slguan 已提交
484 485 486
    return -1;
  } else {
    return numOfRows;
H
hzcheng 已提交
487 488 489
  }
}

S
slguan 已提交
490
void tscAppendDataBlock(SDataBlockList *pList, STableDataBlocks *pBlocks) {
H
hzcheng 已提交
491 492
  if (pList->nSize >= pList->nAlloc) {
    pList->nAlloc = pList->nAlloc << 1;
S
slguan 已提交
493
    pList->pData = realloc(pList->pData, sizeof(void *) * (size_t)pList->nAlloc);
H
hzcheng 已提交
494 495

    // reset allocated memory
S
slguan 已提交
496
    memset(pList->pData + pList->nSize, 0, sizeof(void *) * (pList->nAlloc - pList->nSize));
H
hzcheng 已提交
497 498 499 500 501
  }

  pList->pData[pList->nSize++] = pBlocks;
}

S
slguan 已提交
502
static void tscSetAssignedColumnInfo(SParsedDataColInfo *spd, SSchema *pSchema, int32_t numOfCols) {
H
hzcheng 已提交
503
  spd->numOfCols = numOfCols;
504
  spd->numOfAssignedCols = numOfCols;
H
hzcheng 已提交
505 506 507 508 509 510 511 512 513 514 515

  for (int32_t i = 0; i < numOfCols; ++i) {
    spd->hasVal[i] = true;
    spd->elems[i].colIndex = i;

    if (i > 0) {
      spd->elems[i].offset = spd->elems[i - 1].offset + pSchema[i - 1].bytes;
    }
  }
}

S
slguan 已提交
516
int32_t tscAllocateMemIfNeed(STableDataBlocks *pDataBlock, int32_t rowSize) {
H
hzcheng 已提交
517
  size_t remain = pDataBlock->nAllocSize - pDataBlock->size;
S
slguan 已提交
518
  const int factor = 5;
H
hzcheng 已提交
519 520

  // expand the allocated size
S
slguan 已提交
521 522 523 524
  while (remain < rowSize * factor) {
    pDataBlock->nAllocSize = (uint32_t) (pDataBlock->nAllocSize * 1.5);
    remain = pDataBlock->nAllocSize - pDataBlock->size;
  }
H
hzcheng 已提交
525

S
slguan 已提交
526 527 528 529 530 531 532
  char *tmp = realloc(pDataBlock->pData, (size_t)pDataBlock->nAllocSize);
  if (tmp != NULL) {
    pDataBlock->pData = tmp;
    memset(pDataBlock->pData + pDataBlock->size, 0, pDataBlock->nAllocSize - pDataBlock->size);
  } else {
    assert(false);
    // do nothing
H
hzcheng 已提交
533 534
  }

S
slguan 已提交
535
  return (int32_t)(pDataBlock->nAllocSize - pDataBlock->size) / rowSize;
H
hzcheng 已提交
536 537
}

S
slguan 已提交
538 539 540 541 542
static void tsSetBlockInfo(SShellSubmitBlock *pBlocks, const SMeterMeta *pMeterMeta, int32_t numOfRows) {
  pBlocks->sid = pMeterMeta->sid;
  pBlocks->uid = pMeterMeta->uid;
  pBlocks->sversion = pMeterMeta->sversion;
  pBlocks->numOfRows += numOfRows;
H
hzcheng 已提交
543 544
}

S
slguan 已提交
545 546 547 548 549
int32_t sortRemoveDuplicates(STableDataBlocks *dataBuf, int32_t numOfRows) {
  // data block is disordered, sort it in ascending order
  if (!dataBuf->ordered) {
    char *pBlockData = dataBuf->pData + sizeof(SShellSubmitBlock);
    qsort(pBlockData, numOfRows, dataBuf->rowSize, rowDataCompar);
H
hzcheng 已提交
550

S
slguan 已提交
551 552
    int32_t i = 0;
    int32_t j = 1;
H
hzcheng 已提交
553

S
slguan 已提交
554 555 556
    while (j < numOfRows) {
      TSKEY ti = *(TSKEY *)(pBlockData + dataBuf->rowSize * i);
      TSKEY tj = *(TSKEY *)(pBlockData + dataBuf->rowSize * j);
H
hzcheng 已提交
557

S
slguan 已提交
558 559 560 561
      if (ti == tj) {
        ++j;
        continue;
      }
H
hzcheng 已提交
562

S
slguan 已提交
563 564 565 566 567 568 569 570 571 572
      int32_t nextPos = (++i);
      if (nextPos != j) {
        memmove(pBlockData + dataBuf->rowSize * nextPos, pBlockData + dataBuf->rowSize * j, dataBuf->rowSize);
      }

      ++j;
    }

    numOfRows = i + 1;
    dataBuf->ordered = true;
H
hzcheng 已提交
573 574
  }

S
slguan 已提交
575 576 577 578 579 580 581 582 583 584 585 586
  return numOfRows;
}

static int32_t doParseInsertStatement(SSqlObj *pSql, void *pTableHashList, char **str, SParsedDataColInfo *spd,
                                      int32_t *totalNum) {
  SSqlCmd *   pCmd = &pSql->cmd;
  SMeterMeta *pMeterMeta = pCmd->pMeterMeta;

  STableDataBlocks *dataBuf =
      tscGetDataBlockFromList(pTableHashList, pCmd->pDataBlocks, pMeterMeta->uid, TSDB_DEFAULT_PAYLOAD_SIZE,
                              sizeof(SShellSubmitBlock), pMeterMeta->rowSize, pCmd->name);

H
hzcheng 已提交
587 588
  int32_t maxNumOfRows = tscAllocateMemIfNeed(dataBuf, pMeterMeta->rowSize);

S
slguan 已提交
589
  int32_t numOfRows = tsParseValues(str, dataBuf, pMeterMeta, maxNumOfRows, spd, pCmd->payload);
H
hzcheng 已提交
590 591 592 593
  if (numOfRows <= 0) {
    return TSDB_CODE_INVALID_SQL;
  }

S
slguan 已提交
594
  SShellSubmitBlock *pBlocks = (SShellSubmitBlock *)(dataBuf->pData);
H
hzcheng 已提交
595
  tsSetBlockInfo(pBlocks, pMeterMeta, numOfRows);
S
slguan 已提交
596 597 598

  dataBuf->vgid = pMeterMeta->vgid;
  dataBuf->numOfMeters = 1;
H
hzcheng 已提交
599 600

  /*
S
slguan 已提交
601 602
   * the value of pRes->numOfRows does not affect the true result of AFFECTED ROWS,
   * which is actually returned from server.
H
hzcheng 已提交
603
   */
S
slguan 已提交
604
  *totalNum += numOfRows;
H
hzcheng 已提交
605 606 607
  return TSDB_CODE_SUCCESS;
}

S
slguan 已提交
608 609
static int32_t tscParseSqlForCreateTableOnDemand(char **sqlstr, SSqlObj *pSql) {
  char *  id = NULL;
H
hzcheng 已提交
610 611 612
  int32_t idlen = 0;
  int32_t code = TSDB_CODE_SUCCESS;

S
slguan 已提交
613 614
  SSqlCmd *pCmd = &pSql->cmd;
  char *   sql = *sqlstr;
H
hzcheng 已提交
615 616 617 618 619 620

  sql = tscGetToken(sql, &id, &idlen);

  /* build the token of specified table */
  SSQLToken tableToken = {.z = id, .n = idlen, .type = TK_ID};

S
slguan 已提交
621 622
  char *cstart = NULL;
  char *cend = NULL;
H
hzcheng 已提交
623 624 625 626

  /* skip possibly exists column list */
  sql = tscGetToken(sql, &id, &idlen);
  int32_t numOfColList = 0;
S
slguan 已提交
627
  bool   createTable = false;
H
hzcheng 已提交
628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650

  if (id[0] == '(' && idlen == 1) {
    cstart = &id[0];
    while (1) {
      sql = tscGetToken(sql, &id, &idlen);
      if (id[0] == ')' && idlen == 1) {
        cend = &id[0];
        break;
      }

      ++numOfColList;
    }

    sql = tscGetToken(sql, &id, &idlen);
  }

  if (numOfColList == 0 && cstart != NULL) {
    return TSDB_CODE_INVALID_SQL;
  }

  if (strncmp(id, "using", idlen) == 0 && idlen == 5) {
    /* create table if not exists */
    sql = tscGetToken(sql, &id, &idlen);
S
slguan 已提交
651
    STagData *pTag = (STagData *)pCmd->payload;
S
slguan 已提交
652
    memset(pTag, 0, sizeof(STagData));
H
hzcheng 已提交
653 654 655 656 657 658 659 660 661 662 663

    SSQLToken token1 = {idlen, TK_ID, id};
    setMeterID(pSql, &token1);

    strcpy(pTag->name, pSql->cmd.name);

    code = tscGetMeterMeta(pSql, pTag->name);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

S
slguan 已提交
664 665 666 667 668 669 670 671
    if (!UTIL_METER_IS_METRIC(pCmd)) {
      const char* msg = "create table only from super table is allowed";
      sprintf(pCmd->payload, "%s", msg);
      return TSDB_CODE_INVALID_SQL;
    }

    char *   tagVal = pTag->data;
    SSchema *pTagSchema = tsGetTagSchema(pCmd->pMeterMeta);
H
hzcheng 已提交
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701

    sql = tscGetToken(sql, &id, &idlen);
    if (!(strncmp(id, "tags", idlen) == 0 && idlen == 4)) {
      setErrMsg(pCmd->payload, sql);
      return TSDB_CODE_INVALID_SQL;
    }

    int32_t numOfTagValues = 0;
    while (1) {
      sql = tscGetToken(sql, &id, &idlen);
      if (idlen == 0) {
        break;
      } else if (idlen == 1) {
        if (id[0] == '(') {
          continue;
        }

        if (id[0] == ')') {
          break;
        }

        if (id[0] == '-' || id[0] == '+') {
          sql = tscGetToken(sql, &id, &idlen);

          id -= 1;
          idlen += 1;
        }
      }

      code = tsParseOneColumnData(&pTagSchema[numOfTagValues], id, idlen, tagVal, pCmd->payload, &sql, false,
702
                                  pCmd->pMeterMeta->precision);
H
hzcheng 已提交
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
      if (code != TSDB_CODE_SUCCESS) {
        setErrMsg(pCmd->payload, sql);
        return TSDB_CODE_INVALID_SQL;
      }

      tagVal += pTagSchema[numOfTagValues++].bytes;
    }

    if (numOfTagValues != pCmd->pMeterMeta->numOfTags) {
      setErrMsg(pCmd->payload, sql);
      return TSDB_CODE_INVALID_SQL;
    }

    if (tscValidateName(&tableToken) != TSDB_CODE_SUCCESS) {
      setErrMsg(pCmd->payload, sql);
      return TSDB_CODE_INVALID_SQL;
    }

    int32_t ret = setMeterID(pSql, &tableToken);
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }

    createTable = true;
    code = tscGetMeterMetaEx(pSql, pSql->cmd.name, true);
  } else {
    if (cstart != NULL) {
      sql = cstart;
    } else {
      sql = id;
    }
    code = tscGetMeterMeta(pSql, pCmd->name);
  }

  int32_t len = cend - cstart + 1;
  if (cstart != NULL && createTable == true) {
    /* move the column list to start position of the next accessed points */
W
WangXin 已提交
740
    memmove(sql - len, cstart, len);
H
hzcheng 已提交
741 742 743 744 745 746 747 748
    *sqlstr = sql - len;
  } else {
    *sqlstr = sql;
  }

  return code;
}

S
slguan 已提交
749
int validateTableName(char *tblName, int len) {
H
huili 已提交
750
  char buf[TSDB_METER_ID_LEN] = {0};
S
slguan 已提交
751
  strncpy(buf, tblName, len);
S
slguan 已提交
752

S
slguan 已提交
753
  SSQLToken token = {.n = len, .type = TK_ID, .z = buf};
H
huili 已提交
754
  tSQLGetToken(buf, &token.type);
S
slguan 已提交
755

H
huili 已提交
756 757 758
  return tscValidateName(&token);
}

H
hzcheng 已提交
759 760 761 762 763 764 765 766 767 768
/**
 * usage: insert into table1 values() () table2 values()()
 *
 * @param pCmd
 * @param str
 * @param acct
 * @param db
 * @param pSql
 * @return
 */
S
slguan 已提交
769 770 771
int tsParseInsertStatement(SSqlObj *pSql, char *str, char *acct, char *db) {
  SSqlCmd *pCmd = &pSql->cmd;

H
hzcheng 已提交
772 773 774 775 776
  pCmd->command = TSDB_SQL_INSERT;
  pCmd->isInsertFromFile = -1;
  pCmd->count = 0;

  pSql->res.numOfRows = 0;
S
slguan 已提交
777
  int32_t totalNum = 0;
H
hzcheng 已提交
778 779 780 781 782

  if (!pSql->pTscObj->writeAuth) {
    return TSDB_CODE_NO_RIGHTS;
  }

S
slguan 已提交
783
  char *id;
H
hzcheng 已提交
784 785 786 787 788 789 790 791 792 793 794 795
  int   idlen;
  int   code = TSDB_CODE_INVALID_SQL;

  str = tscGetToken(str, &id, &idlen);
  if (idlen == 0 || (strncmp(id, "into", 4) != 0 || idlen != 4)) {
    INVALID_SQL_RET_MSG(pCmd->payload, "keyword INTO is expected");
  }

  if ((code = tscAllocPayloadWithSize(pCmd, TSDB_PAYLOAD_SIZE)) != TSDB_CODE_SUCCESS) {
    return code;
  }

S
slguan 已提交
796
  void *pTableHashList = taosInitIntHash(128, sizeof(void *), taosHashInt);
H
hzcheng 已提交
797 798 799 800 801 802

  pSql->cmd.pDataBlocks = tscCreateBlockArrayList();
  tscTrace("%p create data block list for submit data, %p", pSql, pSql->cmd.pDataBlocks);

  while (1) {
    tscGetToken(str, &id, &idlen);
S
slguan 已提交
803

H
hzcheng 已提交
804
    if (idlen == 0) {
S
slguan 已提交
805 806 807 808 809 810
      // parse file, do not release the STableDataBlock
      if (pCmd->isInsertFromFile == 1) {
        goto _clean;
      }

      if (totalNum > 0) {
H
hzcheng 已提交
811 812 813 814 815 816 817
        break;
      } else {  // no data in current sql string, error
        code = TSDB_CODE_INVALID_SQL;
        goto _error_clean;
      }
    }

S
slguan 已提交
818
    // Check if the table name available or not
H
huili 已提交
819 820 821 822 823 824
    if (validateTableName(id, idlen) != TSDB_CODE_SUCCESS) {
      code = TSDB_CODE_INVALID_SQL;
      sprintf(pCmd->payload, "table name is invalid");
      goto _error_clean;
    }

H
hzcheng 已提交
825 826 827 828 829
    SSQLToken token = {idlen, TK_ID, id};
    if ((code = setMeterID(pSql, &token)) != TSDB_CODE_SUCCESS) {
      goto _error_clean;
    }

S
slguan 已提交
830
    void *fp = pSql->fp;
H
hzcheng 已提交
831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
    if ((code = tscParseSqlForCreateTableOnDemand(&str, pSql)) != TSDB_CODE_SUCCESS) {
      if (fp != NULL) {
        goto _clean;
      } else {
        /*
         * for async insert, the free data block operations, which is tscDestroyBlockArrayList,
         * must be executed before launch another threads to get metermeta, since the
         * later ops may manipulate SSqlObj through another thread in getMeterMetaCallback function.
         */
        goto _error_clean;
      }
    }

    if (UTIL_METER_IS_METRIC(pCmd)) {
      code = TSDB_CODE_INVALID_SQL;
      sprintf(pCmd->payload, "insert data into metric is not supported");
      goto _error_clean;
    }

    str = tscGetToken(str, &id, &idlen);
    if (idlen == 0) {
      code = TSDB_CODE_INVALID_SQL;
      sprintf(pCmd->payload, "keyword VALUES or FILE are required");
      goto _error_clean;
    }

    if (strncmp(id, "values", 6) == 0 && idlen == 6) {
      SParsedDataColInfo spd = {0};
S
slguan 已提交
859
      SSchema *          pSchema = tsGetSchema(pCmd->pMeterMeta);
H
hzcheng 已提交
860

861
      tscSetAssignedColumnInfo(&spd, pSchema, pCmd->pMeterMeta->numOfColumns);
H
hzcheng 已提交
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876

      if (pCmd->isInsertFromFile == -1) {
        pCmd->isInsertFromFile = 0;
      } else {
        if (pCmd->isInsertFromFile == 1) {
          code = TSDB_CODE_INVALID_SQL;
          sprintf(pCmd->payload, "keyword VALUES and FILE are not allowed to mix up");
          goto _error_clean;
        }
      }

      /*
       * app here insert data in different vnodes, so we need to set the following
       * data in another submit procedure using async insert routines
       */
S
slguan 已提交
877
      code = doParseInsertStatement(pSql, pTableHashList, &str, &spd, &totalNum);
H
hzcheng 已提交
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899
      if (code != TSDB_CODE_SUCCESS) {
        goto _error_clean;
      }

    } else if (strncmp(id, "file", 4) == 0 && idlen == 4) {
      if (pCmd->isInsertFromFile == -1) {
        pCmd->isInsertFromFile = 1;
      } else {
        if (pCmd->isInsertFromFile == 0) {
          code = TSDB_CODE_INVALID_SQL;
          sprintf(pCmd->payload, "keyword VALUES and FILE are not allowed to mix up");
          goto _error_clean;
        }
      }

      str = tscGetTokenDelimiter(str, &id, &idlen, " ;");
      if (idlen == 0) {
        code = TSDB_CODE_INVALID_SQL;
        sprintf(pCmd->payload, "filename is required following keyword FILE");
        goto _error_clean;
      }

S
slguan 已提交
900 901 902
      char fname[PATH_MAX] = {0};
      strncpy(fname, id, idlen);
      strdequote(fname);
903

H
hzcheng 已提交
904 905 906 907 908 909 910 911 912
      wordexp_t full_path;
      if (wordexp(fname, &full_path, 0) != 0) {
        code = TSDB_CODE_INVALID_SQL;
        sprintf(pCmd->payload, "invalid filename");
        goto _error_clean;
      }
      strcpy(fname, full_path.we_wordv[0]);
      wordfree(&full_path);

S
slguan 已提交
913 914
      STableDataBlocks* pDataBlock = tscCreateDataBlockEx(PATH_MAX, pCmd->pMeterMeta->rowSize, sizeof(SShellSubmitBlock),
                                                          pCmd->name);
H
hzcheng 已提交
915

S
slguan 已提交
916 917
      tscAppendDataBlock(pCmd->pDataBlocks, pDataBlock);
      strcpy(pDataBlock->filename, fname);
H
hzcheng 已提交
918 919 920
      str = id + idlen;
    } else if (idlen == 1 && id[0] == '(') {
      /* insert into tablename(col1, col2,..., coln) values(v1, v2,... vn); */
S
slguan 已提交
921 922
      SMeterMeta *pMeterMeta = pCmd->pMeterMeta;
      SSchema *   pSchema = tsGetSchema(pMeterMeta);
H
hzcheng 已提交
923 924 925 926 927 928 929 930 931

      if (pCmd->isInsertFromFile == -1) {
        pCmd->isInsertFromFile = 0;
      } else if (pCmd->isInsertFromFile == 1) {
        code = TSDB_CODE_INVALID_SQL;
        sprintf(pCmd->payload, "keyword VALUES and FILE are not allowed to mix up");
        goto _error_clean;
      }

932 933
      SParsedDataColInfo spd = {0};
      spd.numOfCols = pMeterMeta->numOfColumns;
H
hzcheng 已提交
934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950

      int16_t offset[TSDB_MAX_COLUMNS] = {0};
      for (int32_t t = 1; t < pMeterMeta->numOfColumns; ++t) {
        offset[t] = offset[t - 1] + pSchema[t - 1].bytes;
      }

      while (1) {
        str = tscGetToken(str, &id, &idlen);
        if (idlen == 1 && id[0] == ')') {
          break;
        }

        bool findColumnIndex = false;

        // todo speedup by using hash list
        for (int32_t t = 0; t < pMeterMeta->numOfColumns; ++t) {
          if (strncmp(id, pSchema[t].name, idlen) == 0 && strlen(pSchema[t].name) == idlen) {
S
slguan 已提交
951
            SParsedColElem *pElem = &spd.elems[spd.numOfAssignedCols++];
H
hzcheng 已提交
952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973
            pElem->offset = offset[t];
            pElem->colIndex = t;

            if (spd.hasVal[t] == true) {
              code = TSDB_CODE_INVALID_SQL;
              sprintf(pCmd->payload, "duplicated column name");
              goto _error_clean;
            }

            spd.hasVal[t] = true;
            findColumnIndex = true;
            break;
          }
        }

        if (!findColumnIndex) {  //
          code = TSDB_CODE_INVALID_SQL;
          sprintf(pCmd->payload, "invalid column name");
          goto _error_clean;
        }
      }

974
      if (spd.numOfAssignedCols == 0 || spd.numOfAssignedCols > pMeterMeta->numOfColumns) {
H
hzcheng 已提交
975 976 977 978 979 980 981 982 983 984 985 986
        code = TSDB_CODE_INVALID_SQL;
        sprintf(pCmd->payload, "column name expected");
        goto _error_clean;
      }

      str = tscGetToken(str, &id, &idlen);
      if (strncmp(id, "values", idlen) != 0 || idlen != 6) {
        code = TSDB_CODE_INVALID_SQL;
        sprintf(pCmd->payload, "keyword VALUES is expected");
        goto _error_clean;
      }

S
slguan 已提交
987
      code = doParseInsertStatement(pSql, pTableHashList, &str, &spd, &totalNum);
H
hzcheng 已提交
988 989 990 991 992 993 994 995 996 997
      if (code != TSDB_CODE_SUCCESS) {
        goto _error_clean;
      }
    } else {
      code = TSDB_CODE_INVALID_SQL;
      sprintf(pCmd->payload, "keyword VALUES or FILE are required");
      goto _error_clean;
    }
  }

S
slguan 已提交
998
  // submit to more than one vnode
H
hzcheng 已提交
999
  if (pCmd->pDataBlocks->nSize > 0) {
S
slguan 已提交
1000 1001
    // merge according to vgid
    tscMergeTableDataBlocks(pCmd, pCmd->pDataBlocks);
H
hzcheng 已提交
1002

S
slguan 已提交
1003 1004 1005
    STableDataBlocks *pDataBlock = pCmd->pDataBlocks->pData[0];
    if ((code = tscCopyDataBlockToPayload(pSql, pDataBlock)) != TSDB_CODE_SUCCESS) {
      goto _error_clean;
H
hzcheng 已提交
1006 1007 1008 1009
    }

    pCmd->vnodeIdx = 1;  // set the next sent data vnode index in data block arraylist
  } else {
S
slguan 已提交
1010
    pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
H
hzcheng 已提交
1011 1012 1013 1014 1015 1016
  }

  code = TSDB_CODE_SUCCESS;
  goto _clean;

_error_clean:
S
slguan 已提交
1017
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
H
hzcheng 已提交
1018 1019

_clean:
S
slguan 已提交
1020
  taosCleanUpIntHash(pTableHashList);
H
hzcheng 已提交
1021 1022 1023
  return code;
}

S
slguan 已提交
1024 1025
int tsParseImportStatement(SSqlObj *pSql, char *str, char *acct, char *db) {
  SSqlCmd *pCmd = &pSql->cmd;
H
hzcheng 已提交
1026
  pCmd->order.order = TSQL_SO_ASC;
S
slguan 已提交
1027
  return tsParseInsertStatement(pSql, str, acct, db);
H
hzcheng 已提交
1028 1029
}

S
slguan 已提交
1030 1031
int tsParseInsertSql(SSqlObj *pSql, char *sql, char *acct, char *db) {
  char *verb;
H
hzcheng 已提交
1032 1033 1034
  int   verblen;
  int   code = TSDB_CODE_INVALID_SQL;

S
slguan 已提交
1035
  SSqlCmd *pCmd = &pSql->cmd;
H
hzcheng 已提交
1036 1037 1038 1039 1040 1041
  tscCleanSqlCmd(pCmd);

  sql = tscGetToken(sql, &verb, &verblen);

  if (verblen) {
    if (strncmp(verb, "insert", 6) == 0 && verblen == 6) {
S
slguan 已提交
1042
      code = tsParseInsertStatement(pSql, sql, acct, db);
H
hzcheng 已提交
1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055
    } else if (strncmp(verb, "import", 6) == 0 && verblen == 6) {
      code = tsParseImportStatement(pSql, sql, acct, db);
    } else {
      verb[verblen] = 0;
      sprintf(pCmd->payload, "invalid keyword:%s", verb);
    }
  } else {
    sprintf(pCmd->payload, "no any keywords");
  }

  return code;
}

S
slguan 已提交
1056
int tsParseSql(SSqlObj *pSql, char *acct, char *db, bool multiVnodeInsertion) {
H
hzcheng 已提交
1057 1058 1059 1060
  int32_t ret = TSDB_CODE_SUCCESS;

  if (tscIsInsertOrImportData(pSql->sqlstr)) {
    /*
S
slguan 已提交
1061 1062 1063
     * only for async multi-vnode insertion
     * Set the fp before parse the sql string, in case of getmetermeta failed, in which
     * the error handle callback function can rightfully restore the user defined function (fp)
H
hzcheng 已提交
1064 1065 1066 1067 1068
     */
    if (pSql->fp != NULL && multiVnodeInsertion) {
      assert(pSql->fetchFp == NULL);
      pSql->fetchFp = pSql->fp;

S
slguan 已提交
1069
      /* replace user defined callback function with multi-insert proxy function */
H
hzcheng 已提交
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
      pSql->fp = tscAsyncInsertMultiVnodesProxy;
    }

    ret = tsParseInsertSql(pSql, pSql->sqlstr, acct, db);
  } else {
    SSqlInfo SQLInfo = {0};
    tSQLParse(&SQLInfo, pSql->sqlstr);
    ret = tscToSQLCmd(pSql, &SQLInfo);
    SQLInfoDestroy(&SQLInfo);
  }

  /*
   * the pRes->code may be modified or even released by another thread in tscMeterMetaCallBack
   * function, so do NOT use pRes->code to determine if the getMeterMeta/getMetricMeta function
   * invokes new threads to get data from mnode or simply retrieves data from cache.
   *
   * do NOT assign return code to pRes->code for the same reason for it may be released by another thread
   * pRes->code = ret;
   */
  return ret;
}

S
slguan 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135
static int doPackSendDataBlock(SSqlObj* pSql, int32_t numOfRows, STableDataBlocks* pTableDataBlocks) {
  int32_t code = TSDB_CODE_SUCCESS;
  SSqlCmd* pCmd = &pSql->cmd;

  SMeterMeta* pMeterMeta = pCmd->pMeterMeta;

  SShellSubmitBlock *pBlocks = (SShellSubmitBlock *)(pTableDataBlocks->pData);
  tsSetBlockInfo(pBlocks, pMeterMeta, numOfRows);

  tscMergeTableDataBlocks(pCmd, pCmd->pDataBlocks);

  // the pDataBlock is different from the pTableDataBlocks
  STableDataBlocks *pDataBlock = pCmd->pDataBlocks->pData[0];
  if ((code = tscCopyDataBlockToPayload(pSql, pDataBlock)) != TSDB_CODE_SUCCESS) {
    return code;
  }

  if ((code = tscProcessSql(pSql)) != TSDB_CODE_SUCCESS) {
    return code;
  }

  return TSDB_CODE_SUCCESS;
}

static int tscInsertDataFromFile(SSqlObj *pSql, FILE *fp) {
  int         readLen = 0;
  char *      line = NULL;
  size_t      n = 0;
  int         len = 0;
  uint32_t    maxRows = 0;
  SSqlCmd *   pCmd = &pSql->cmd;
  SMeterMeta *pMeterMeta = pCmd->pMeterMeta;
  int         numOfRows = 0;
  int32_t     rowSize = pMeterMeta->rowSize;
  int32_t     code = 0;
  int         nrows = 0;

  pCmd->pDataBlocks = tscCreateBlockArrayList();
  STableDataBlocks* pTableDataBlock = tscCreateDataBlockEx(TSDB_PAYLOAD_SIZE, pMeterMeta->rowSize,
                                                           sizeof(SShellSubmitBlock), pCmd->name);

  tscAppendDataBlock(pCmd->pDataBlocks, pTableDataBlock);

  maxRows = tscAllocateMemIfNeed(pTableDataBlock, rowSize);
H
hzcheng 已提交
1136 1137 1138
  if (maxRows < 1) return -1;

  int                count = 0;
S
slguan 已提交
1139 1140
  SParsedDataColInfo spd = {.numOfCols = pCmd->pMeterMeta->numOfColumns};
  SSchema *          pSchema = tsGetSchema(pCmd->pMeterMeta);
H
hzcheng 已提交
1141

1142
  tscSetAssignedColumnInfo(&spd, pSchema, pCmd->pMeterMeta->numOfColumns);
H
hzcheng 已提交
1143

H
huili 已提交
1144
  while ((readLen = getline(&line, &n, fp)) != -1) {
H
hzcheng 已提交
1145 1146
    // line[--readLen] = '\0';
    if (('\r' == line[readLen - 1]) || ('\n' == line[readLen - 1])) line[--readLen] = 0;
1147
    if (readLen <= 0) continue;
H
huili 已提交
1148

S
slguan 已提交
1149
    char *lineptr = line;
H
hzcheng 已提交
1150
    strtolower(line, line);
S
slguan 已提交
1151 1152

    len = tsParseOneRowData(&lineptr, pTableDataBlock, pSchema, &spd, pCmd->payload, pMeterMeta->precision);
H
hzcheng 已提交
1153
    if (len <= 0) return -1;
S
slguan 已提交
1154 1155

    pTableDataBlock->size += len;
H
hzcheng 已提交
1156 1157 1158 1159

    count++;
    nrows++;
    if (count >= maxRows) {
S
slguan 已提交
1160 1161
      if ((code = doPackSendDataBlock(pSql, count, pTableDataBlock)) != TSDB_CODE_SUCCESS) {
        return -code;
H
hzcheng 已提交
1162
      }
S
slguan 已提交
1163 1164 1165 1166 1167

      pTableDataBlock = pCmd->pDataBlocks->pData[0];
      pTableDataBlock->size = sizeof(SShellSubmitBlock);
      pTableDataBlock->rowSize = pMeterMeta->rowSize;

H
hzcheng 已提交
1168
      numOfRows += pSql->res.numOfRows;
S
slguan 已提交
1169
      pSql->res.numOfRows = 0;
H
hzcheng 已提交
1170 1171 1172 1173 1174
      count = 0;
    }
  }

  if (count > 0) {
S
slguan 已提交
1175 1176
    if ((code = doPackSendDataBlock(pSql, count, pTableDataBlock)) != TSDB_CODE_SUCCESS) {
      return -code;
H
hzcheng 已提交
1177
    }
S
slguan 已提交
1178

H
hzcheng 已提交
1179
    numOfRows += pSql->res.numOfRows;
S
slguan 已提交
1180
    pSql->res.numOfRows = 0;
H
hzcheng 已提交
1181 1182 1183
  }

  if (line) tfree(line);
S
slguan 已提交
1184

H
hzcheng 已提交
1185 1186 1187 1188 1189 1190 1191 1192 1193
  return numOfRows;
}

/* multi-vnodes insertion in sync query model
 *
 * modify history
 * 2019.05.10 lihui
 * Remove the code for importing records from files
 */
S
slguan 已提交
1194 1195
void tscProcessMultiVnodesInsert(SSqlObj *pSql) {
  SSqlCmd *pCmd = &pSql->cmd;
H
hzcheng 已提交
1196 1197 1198 1199
  if (pCmd->command != TSDB_SQL_INSERT) {
    return;
  }

S
slguan 已提交
1200 1201 1202
  STableDataBlocks *pDataBlock = NULL;
  int32_t           affected_rows = 0;
  int32_t           code = TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1203 1204 1205 1206 1207

  /* the first block has been sent to server in processSQL function */
  assert(pCmd->isInsertFromFile != -1 && pCmd->vnodeIdx >= 1 && pCmd->pDataBlocks != NULL);

  if (pCmd->vnodeIdx < pCmd->pDataBlocks->nSize) {
S
slguan 已提交
1208
    SDataBlockList *pDataBlocks = pCmd->pDataBlocks;
H
hzcheng 已提交
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225

    for (int32_t i = pCmd->vnodeIdx; i < pDataBlocks->nSize; ++i) {
      pDataBlock = pDataBlocks->pData[i];
      if (pDataBlock == NULL) {
        continue;
      }

      if ((code = tscCopyDataBlockToPayload(pSql, pDataBlock)) != TSDB_CODE_SUCCESS) {
        tscTrace("%p build submit data block failed, vnodeIdx:%d, total:%d", pSql, pCmd->vnodeIdx, pDataBlocks->nSize);
        continue;
      }

      tscProcessSql(pSql);
    }
  }

  // all data have been submit to vnode, release data blocks
S
slguan 已提交
1226
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
H
hzcheng 已提交
1227 1228 1229
}

/* multi-vnodes insertion in sync query model */
S
slguan 已提交
1230 1231
void tscProcessMultiVnodesInsertForFile(SSqlObj *pSql) {
  SSqlCmd *pCmd = &pSql->cmd;
H
hzcheng 已提交
1232 1233 1234 1235
  if (pCmd->command != TSDB_SQL_INSERT) {
    return;
  }

S
slguan 已提交
1236 1237
  STableDataBlocks *pDataBlock = NULL;
  int32_t           affected_rows = 0;
H
hzcheng 已提交
1238

S
slguan 已提交
1239 1240 1241
  assert(pCmd->isInsertFromFile == 1 && pCmd->pDataBlocks != NULL);
  SDataBlockList *pDataBlockList = pCmd->pDataBlocks;
  pCmd->pDataBlocks = NULL;
H
hzcheng 已提交
1242

S
slguan 已提交
1243
  char            path[PATH_MAX] = {0};
H
hzcheng 已提交
1244

S
slguan 已提交
1245 1246
  for (int32_t i = 0; i < pDataBlockList->nSize; ++i) {
    pDataBlock = pDataBlockList->pData[i];
H
hzcheng 已提交
1247 1248 1249 1250 1251 1252 1253
    if (pDataBlock == NULL) {
      continue;
    }

    tscAllocPayloadWithSize(pCmd, TSDB_PAYLOAD_SIZE);
    pCmd->count = 1;

S
slguan 已提交
1254 1255 1256
    strncpy(path, pDataBlock->filename, PATH_MAX);

    FILE *fp = fopen(path, "r");
H
hzcheng 已提交
1257
    if (fp == NULL) {
S
slguan 已提交
1258 1259
      tscError("%p failed to open file %s to load data from file, reason:%s", pSql, path,
               strerror(errno));
H
hzcheng 已提交
1260 1261 1262 1263
      continue;
    }

    strcpy(pCmd->name, pDataBlock->meterId);
S
slguan 已提交
1264 1265 1266 1267 1268 1269 1270 1271
    memset(pDataBlock->pData, 0, pDataBlock->nAllocSize);

    int32_t ret = tscGetMeterMeta(pSql, pCmd->name);
    if (ret != TSDB_CODE_SUCCESS) {
      tscError("%p get meter meta failed, abort", pSql);
      continue;
    }

H
hzcheng 已提交
1272
    int nrows = tscInsertDataFromFile(pSql, fp);
S
slguan 已提交
1273 1274
    pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);

H
hzcheng 已提交
1275 1276
    if (nrows < 0) {
      fclose(fp);
S
slguan 已提交
1277
      tscTrace("%p no records in file %s", pSql, path);
H
hzcheng 已提交
1278 1279 1280
      continue;
    }

S
slguan 已提交
1281
    fclose(fp);
H
hzcheng 已提交
1282 1283
    affected_rows += nrows;

S
slguan 已提交
1284
    tscTrace("%p Insert data %d records from file %s", pSql, nrows, path);
H
hzcheng 已提交
1285 1286 1287 1288 1289
  }

  pSql->res.numOfRows = affected_rows;

  // all data have been submit to vnode, release data blocks
S
slguan 已提交
1290 1291
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
  tscDestroyBlockArrayList(pDataBlockList);
H
hzcheng 已提交
1292
}