tscParseInsert.c 46.8 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
/*
 * 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

21
#include "os.h"
22 23

#include "hash.h"
H
hzcheng 已提交
24 25 26
#include "tscUtil.h"
#include "tschemautil.h"
#include "tsclient.h"
27
#include "ttokendef.h"
H
hzcheng 已提交
28
#include "taosdef.h"
H
hzcheng 已提交
29

S
slguan 已提交
30
#include "tscLog.h"
H
hjxilinx 已提交
31
#include "tscSubquery.h"
H
hzcheng 已提交
32 33 34
#include "tstoken.h"
#include "ttime.h"

S
slguan 已提交
35
#include "tdataformat.h"
36

S
slguan 已提交
37
enum {
S
slguan 已提交
38 39 40 41
  TSDB_USE_SERVER_TS = 0,
  TSDB_USE_CLI_TS = 1,
};

L
lihui 已提交
42
static int32_t tscAllocateMemIfNeed(STableDataBlocks *pDataBlock, int32_t rowSize, int32_t * numOfRows);
H
hzcheng 已提交
43

S
slguan 已提交
44 45 46 47
static int32_t tscToInteger(SSQLToken *pToken, int64_t *value, char **endPtr) {
  int32_t numType = isValidNumber(pToken);
  if (TK_ILLEGAL == numType) {
    return numType;
H
hzcheng 已提交
48 49 50 51 52 53 54
  }

  int32_t radix = 10;
  if (numType == TK_HEX) {
    radix = 16;
  } else if (numType == TK_OCT) {
    radix = 8;
S
slguan 已提交
55 56
  } else if (numType == TK_BIN) {
    radix = 2;
H
hzcheng 已提交
57 58
  }

L
lihui 已提交
59
  errno = 0;
S
slguan 已提交
60 61 62
  *value = strtoll(pToken->z, endPtr, radix);

  return numType;
H
hzcheng 已提交
63 64
}

S
slguan 已提交
65 66 67 68 69
static int32_t tscToDouble(SSQLToken *pToken, double *value, char **endPtr) {
  int32_t numType = isValidNumber(pToken);
  if (TK_ILLEGAL == numType) {
    return numType;
  }
L
lihui 已提交
70 71

  errno = 0;
S
slguan 已提交
72 73 74
  *value = strtod(pToken->z, endPtr);
  return numType;
}
H
hzcheng 已提交
75

S
slguan 已提交
76 77 78 79 80 81
int tsParseTime(SSQLToken *pToken, int64_t *time, char **next, char *error, int16_t timePrec) {
  int32_t   index = 0;
  SSQLToken sToken;
  int64_t   interval;
  int64_t   useconds = 0;
  char *    pTokenEnd = *next;
H
hzcheng 已提交
82

S
slguan 已提交
83
  index = 0;
H
hzcheng 已提交
84

S
slguan 已提交
85
  if (pToken->type == TK_NOW) {
H
hzcheng 已提交
86
    useconds = taosGetTimestamp(timePrec);
S
slguan 已提交
87
  } else if (strncmp(pToken->z, "0", 1) == 0 && pToken->n == 1) {
H
hzcheng 已提交
88
    // do nothing
S
slguan 已提交
89 90
  } else if (pToken->type == TK_INTEGER) {
    useconds = str2int64(pToken->z);
H
hzcheng 已提交
91 92
  } else {
    // strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);
S
slguan 已提交
93
    if (taosParseTime(pToken->z, time, pToken->n, timePrec) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
94
      return tscInvalidSQLErrMsg(error, "invalid timestamp format", pToken->z);
H
hzcheng 已提交
95 96 97 98 99
    }

    return TSDB_CODE_SUCCESS;
  }

S
slguan 已提交
100 101 102 103
  for (int k = pToken->n; pToken->z[k] != '\0'; k++) {
    if (pToken->z[k] == ' ' || pToken->z[k] == '\t') continue;
    if (pToken->z[k] == ',') {
      *next = pTokenEnd;
H
hzcheng 已提交
104 105 106 107 108 109 110 111
      *time = useconds;
      return 0;
    }

    break;
  }

  /*
S
slguan 已提交
112 113 114
   * time expression:
   * e.g., now+12a, now-5h
   */
S
slguan 已提交
115 116 117 118
  SSQLToken valueToken;
  index = 0;
  sToken = tStrGetToken(pTokenEnd, &index, false, 0, NULL);
  pTokenEnd += index;
119

S
slguan 已提交
120 121 122 123
  if (sToken.type == TK_MINUS || sToken.type == TK_PLUS) {
    index = 0;
    valueToken = tStrGetToken(pTokenEnd, &index, false, 0, NULL);
    pTokenEnd += index;
124

S
slguan 已提交
125
    if (valueToken.n < 2) {
H
hjxilinx 已提交
126
      return tscInvalidSQLErrMsg(error, "value expected in timestamp", sToken.z);
H
hzcheng 已提交
127 128
    }

S
slguan 已提交
129
    if (getTimestampInUsFromStr(valueToken.z, valueToken.n, &interval) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
130 131
      return TSDB_CODE_INVALID_SQL;
    }
132

H
hzcheng 已提交
133 134 135 136
    if (timePrec == TSDB_TIME_PRECISION_MILLI) {
      interval /= 1000;
    }

S
slguan 已提交
137
    if (sToken.type == TK_PLUS) {
H
hzcheng 已提交
138 139 140 141 142 143 144 145 146 147 148 149
      useconds += interval;
    } else {
      useconds = (useconds >= interval) ? useconds - interval : 0;
    }

    *next = pTokenEnd;
  }

  *time = useconds;
  return TSDB_CODE_SUCCESS;
}

S
slguan 已提交
150
int32_t tsParseOneColumnData(SSchema *pSchema, SSQLToken *pToken, char *payload, char *msg, char **str, bool primaryKey,
S
slguan 已提交
151 152 153
                             int16_t timePrec) {
  int64_t iv;
  int32_t numType;
S
slguan 已提交
154
  char *  endptr = NULL;
155 156
  errno = 0;  // clear the previous existed error information

H
hzcheng 已提交
157 158
  switch (pSchema->type) {
    case TSDB_DATA_TYPE_BOOL: {  // bool
S
slguan 已提交
159 160
      if ((pToken->type == TK_BOOL || pToken->type == TK_STRING) && (pToken->n != 0)) {
        if (strncmp(pToken->z, "true", pToken->n) == 0) {
S
slguan 已提交
161
          *(uint8_t *)payload = TSDB_TRUE;
S
slguan 已提交
162
        } else if (strncmp(pToken->z, "false", pToken->n) == 0) {
S
slguan 已提交
163
          *(uint8_t *)payload = TSDB_FALSE;
S
slguan 已提交
164 165
        } else if (strncasecmp(TSDB_DATA_NULL_STR_L, pToken->z, pToken->n) == 0) {
          *(uint8_t *)payload = TSDB_DATA_BOOL_NULL;
H
hzcheng 已提交
166
        } else {
H
hjxilinx 已提交
167
          return tscInvalidSQLErrMsg(msg, "invalid bool data", pToken->z);
H
hzcheng 已提交
168
        }
S
slguan 已提交
169 170 171 172 173 174 175 176 177
      } else if (pToken->type == TK_INTEGER) {
        iv = strtoll(pToken->z, NULL, 10);
        *(uint8_t *)payload = (int8_t)((iv == 0) ? TSDB_FALSE : TSDB_TRUE);
      } else if (pToken->type == TK_FLOAT) {
        double dv = strtod(pToken->z, NULL);
        *(uint8_t *)payload = (int8_t)((dv == 0) ? TSDB_FALSE : TSDB_TRUE);
      } else if (pToken->type == TK_NULL) {
        *(uint8_t *)payload = TSDB_DATA_BOOL_NULL;
      } else {
H
hjxilinx 已提交
178
        return tscInvalidSQLErrMsg(msg, "invalid bool data", pToken->z);
H
hzcheng 已提交
179 180 181 182
      }
      break;
    }
    case TSDB_DATA_TYPE_TINYINT:
S
slguan 已提交
183 184 185 186 187
      if (pToken->type == TK_NULL) {
        *((int8_t *)payload) = TSDB_DATA_TINYINT_NULL;
      } else if ((pToken->type == TK_STRING) && (pToken->n != 0) &&
                 (strncasecmp(TSDB_DATA_NULL_STR_L, pToken->z, pToken->n) == 0)) {
        *((int8_t *)payload) = TSDB_DATA_TINYINT_NULL;
H
hzcheng 已提交
188
      } else {
S
slguan 已提交
189
        numType = tscToInteger(pToken, &iv, &endptr);
L
lihui 已提交
190
        if (TK_ILLEGAL == numType) {
H
hjxilinx 已提交
191
          return tscInvalidSQLErrMsg(msg, "invalid tinyint data", pToken->z);
L
lihui 已提交
192
        } else if (errno == ERANGE || iv > INT8_MAX || iv <= INT8_MIN) {
H
hjxilinx 已提交
193
          return tscInvalidSQLErrMsg(msg, "tinyint data overflow", pToken->z);
H
hzcheng 已提交
194 195
        }

196
        *((int8_t *)payload) = (int8_t)iv;
H
hzcheng 已提交
197 198 199 200 201
      }

      break;

    case TSDB_DATA_TYPE_SMALLINT:
S
slguan 已提交
202 203 204 205 206
      if (pToken->type == TK_NULL) {
        *((int16_t *)payload) = TSDB_DATA_SMALLINT_NULL;
      } else if ((pToken->type == TK_STRING) && (pToken->n != 0) &&
                 (strncasecmp(TSDB_DATA_NULL_STR_L, pToken->z, pToken->n) == 0)) {
        *((int16_t *)payload) = TSDB_DATA_SMALLINT_NULL;
H
hzcheng 已提交
207
      } else {
S
slguan 已提交
208
        numType = tscToInteger(pToken, &iv, &endptr);
L
lihui 已提交
209
        if (TK_ILLEGAL == numType) {
H
hjxilinx 已提交
210
          return tscInvalidSQLErrMsg(msg, "invalid smallint data", pToken->z);
L
lihui 已提交
211
        } else if (errno == ERANGE || iv > INT16_MAX || iv <= INT16_MIN) {
H
hjxilinx 已提交
212
          return tscInvalidSQLErrMsg(msg, "smallint data overflow", pToken->z);
H
hzcheng 已提交
213 214
        }

S
slguan 已提交
215
        *((int16_t *)payload) = (int16_t)iv;
H
hzcheng 已提交
216 217 218 219
      }
      break;

    case TSDB_DATA_TYPE_INT:
S
slguan 已提交
220 221 222 223
      if (pToken->type == TK_NULL) {
        *((int32_t *)payload) = TSDB_DATA_INT_NULL;
      } else if ((pToken->type == TK_STRING) && (pToken->n != 0) &&
                 (strncasecmp(TSDB_DATA_NULL_STR_L, pToken->z, pToken->n) == 0)) {
S
slguan 已提交
224
        *((int32_t *)payload) = TSDB_DATA_INT_NULL;
H
hzcheng 已提交
225
      } else {
S
slguan 已提交
226
        numType = tscToInteger(pToken, &iv, &endptr);
L
lihui 已提交
227
        if (TK_ILLEGAL == numType) {
H
hjxilinx 已提交
228
          return tscInvalidSQLErrMsg(msg, "invalid int data", pToken->z);
L
lihui 已提交
229
        } else if (errno == ERANGE || iv > INT32_MAX || iv <= INT32_MIN) {
H
hjxilinx 已提交
230
          return tscInvalidSQLErrMsg(msg, "int data overflow", pToken->z);
H
hzcheng 已提交
231 232
        }

S
slguan 已提交
233
        *((int32_t *)payload) = (int32_t)iv;
H
hzcheng 已提交
234 235 236 237 238
      }

      break;

    case TSDB_DATA_TYPE_BIGINT:
S
slguan 已提交
239 240 241 242
      if (pToken->type == TK_NULL) {
        *((int64_t *)payload) = TSDB_DATA_BIGINT_NULL;
      } else if ((pToken->type == TK_STRING) && (pToken->n != 0) &&
                 (strncasecmp(TSDB_DATA_NULL_STR_L, pToken->z, pToken->n) == 0)) {
S
slguan 已提交
243
        *((int64_t *)payload) = TSDB_DATA_BIGINT_NULL;
H
hzcheng 已提交
244
      } else {
S
slguan 已提交
245
        numType = tscToInteger(pToken, &iv, &endptr);
L
lihui 已提交
246
        if (TK_ILLEGAL == numType) {
H
hjxilinx 已提交
247
          return tscInvalidSQLErrMsg(msg, "invalid bigint data", pToken->z);
L
lihui 已提交
248
        } else if (errno == ERANGE || iv > INT64_MAX || iv <= INT64_MIN) {
H
hjxilinx 已提交
249
          return tscInvalidSQLErrMsg(msg, "bigint data overflow", pToken->z);
H
hzcheng 已提交
250
        }
S
slguan 已提交
251 252

        *((int64_t *)payload) = iv;
H
hzcheng 已提交
253 254 255 256
      }
      break;

    case TSDB_DATA_TYPE_FLOAT:
S
slguan 已提交
257 258 259 260
      if (pToken->type == TK_NULL) {
        *((int32_t *)payload) = TSDB_DATA_FLOAT_NULL;
      } else if ((pToken->type == TK_STRING) && (pToken->n != 0) &&
                 (strncasecmp(TSDB_DATA_NULL_STR_L, pToken->z, pToken->n) == 0)) {
S
slguan 已提交
261
        *((int32_t *)payload) = TSDB_DATA_FLOAT_NULL;
H
hzcheng 已提交
262
      } else {
S
slguan 已提交
263 264
        double dv;
        if (TK_ILLEGAL == tscToDouble(pToken, &dv, &endptr)) {
H
hjxilinx 已提交
265
          return tscInvalidSQLErrMsg(msg, "illegal float data", pToken->z);
S
slguan 已提交
266 267 268 269
        }

        float fv = (float)dv;
        if (((dv == HUGE_VAL || dv == -HUGE_VAL) && errno == ERANGE) || (fv > FLT_MAX || fv < -FLT_MAX)) {
H
hjxilinx 已提交
270
          return tscInvalidSQLErrMsg(msg, "illegal float data", pToken->z);
H
hzcheng 已提交
271 272
        }

S
slguan 已提交
273 274
        if (isinf(fv) || isnan(fv)) {
          *((int32_t *)payload) = TSDB_DATA_FLOAT_NULL;
H
hzcheng 已提交
275
        }
S
slguan 已提交
276 277

        *((float *)payload) = fv;
H
hzcheng 已提交
278 279 280 281
      }
      break;

    case TSDB_DATA_TYPE_DOUBLE:
S
slguan 已提交
282 283 284 285
      if (pToken->type == TK_NULL) {
        *((int64_t *)payload) = TSDB_DATA_DOUBLE_NULL;
      } else if ((pToken->type == TK_STRING) && (pToken->n != 0) &&
                 (strncasecmp(TSDB_DATA_NULL_STR_L, pToken->z, pToken->n) == 0)) {
S
slguan 已提交
286
        *((int64_t *)payload) = TSDB_DATA_DOUBLE_NULL;
H
hzcheng 已提交
287
      } else {
S
slguan 已提交
288 289
        double dv;
        if (TK_ILLEGAL == tscToDouble(pToken, &dv, &endptr)) {
H
hjxilinx 已提交
290
          return tscInvalidSQLErrMsg(msg, "illegal double data", pToken->z);
H
hzcheng 已提交
291 292
        }

S
slguan 已提交
293
        if (((dv == HUGE_VAL || dv == -HUGE_VAL) && errno == ERANGE) || (dv > DBL_MAX || dv < -DBL_MAX)) {
H
hjxilinx 已提交
294
          return tscInvalidSQLErrMsg(msg, "illegal double data", pToken->z);
S
slguan 已提交
295 296 297 298 299 300
        }

        if (isinf(dv) || isnan(dv)) {
          *((int64_t *)payload) = TSDB_DATA_DOUBLE_NULL;
        } else {
          *((double *)payload) = dv;
H
hzcheng 已提交
301 302 303 304 305
        }
      }
      break;

    case TSDB_DATA_TYPE_BINARY:
S
slguan 已提交
306 307
      // binary data cannot be null-terminated char string, otherwise the last char of the string is lost
      if (pToken->type == TK_NULL) {
H
hzcheng 已提交
308
        *payload = TSDB_DATA_BINARY_NULL;
H
hjxilinx 已提交
309
      } else { // too long values will return invalid sql, not be truncated automatically
S
slguan 已提交
310
        if (pToken->n > pSchema->bytes) {
H
hjxilinx 已提交
311
          return tscInvalidSQLErrMsg(msg, "string data overflow", pToken->z);
S
slguan 已提交
312
        }
H
hjxilinx 已提交
313
        
S
slguan 已提交
314
        strncpy(payload, pToken->z, pToken->n);
315 316 317 318
        
        if (pToken->n < pSchema->bytes) {
          payload[pToken->n] = 0;   // add the null-terminated char if the length of the string is shorter than the available space
        }
H
hzcheng 已提交
319 320 321 322 323
      }

      break;

    case TSDB_DATA_TYPE_NCHAR:
S
slguan 已提交
324
      if (pToken->type == TK_NULL) {
S
slguan 已提交
325
        *(uint32_t *)payload = TSDB_DATA_NCHAR_NULL;
H
hzcheng 已提交
326
      } else {
H
hjxilinx 已提交
327
        // if the converted output len is over than pColumnModel->bytes, return error: 'Argument list too long'
S
slguan 已提交
328
        if (!taosMbsToUcs4(pToken->z, pToken->n, payload, pSchema->bytes)) {
H
hjxilinx 已提交
329 330 331 332
          char buf[512] = {0};
          snprintf(buf, 512, "%s", strerror(errno));
          
          return tscInvalidSQLErrMsg(msg, buf, pToken->z);
H
hzcheng 已提交
333 334 335 336 337
        }
      }
      break;

    case TSDB_DATA_TYPE_TIMESTAMP: {
S
slguan 已提交
338
      if (pToken->type == TK_NULL) {
H
hzcheng 已提交
339
        if (primaryKey) {
S
slguan 已提交
340
          *((int64_t *)payload) = 0;
H
hzcheng 已提交
341
        } else {
S
slguan 已提交
342
          *((int64_t *)payload) = TSDB_DATA_BIGINT_NULL;
H
hzcheng 已提交
343 344
        }
      } else {
S
slguan 已提交
345 346
        int64_t temp;
        if (tsParseTime(pToken, &temp, str, msg, timePrec) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
347
          return tscInvalidSQLErrMsg(msg, "invalid timestamp", pToken->z);
H
hzcheng 已提交
348
        }
H
hjxilinx 已提交
349
        
S
slguan 已提交
350
        *((int64_t *)payload) = temp;
H
hzcheng 已提交
351 352 353 354 355 356
      }

      break;
    }
  }

H
hjxilinx 已提交
357
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
358 359
}

S
slguan 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
/*
 * The server time/client time should not be mixed up in one sql string
 * Do not employ sort operation is not involved if server time is used.
 */
static int32_t tsCheckTimestamp(STableDataBlocks *pDataBlocks, const char *start) {
  // once the data block is disordered, we do NOT keep previous timestamp any more
  if (!pDataBlocks->ordered) {
    return TSDB_CODE_SUCCESS;
  }

  TSKEY k = *(TSKEY *)start;

  if (k == 0) {
    if (pDataBlocks->tsSource == TSDB_USE_CLI_TS) {
      return -1;
    } else if (pDataBlocks->tsSource == -1) {
      pDataBlocks->tsSource = TSDB_USE_SERVER_TS;
    }
  } else {
    if (pDataBlocks->tsSource == TSDB_USE_SERVER_TS) {
H
hjxilinx 已提交
380
      return -1;  // client time/server time can not be mixed
381

S
slguan 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394
    } else if (pDataBlocks->tsSource == -1) {
      pDataBlocks->tsSource = TSDB_USE_CLI_TS;
    }
  }

  if (k <= pDataBlocks->prevTS && (pDataBlocks->tsSource == TSDB_USE_CLI_TS)) {
    pDataBlocks->ordered = false;
  }

  pDataBlocks->prevTS = k;
  return TSDB_CODE_SUCCESS;
}

S
slguan 已提交
395
int tsParseOneRowData(char **str, STableDataBlocks *pDataBlocks, SSchema schema[], SParsedDataColInfo *spd, char *error,
396 397
                      int16_t timePrec, int32_t *code, char *tmpTokenBuf) {
  int32_t index = 0;
H
hjxilinx 已提交
398
  SSQLToken sToken = {0};
S
slguan 已提交
399
  char *    payload = pDataBlocks->pData + pDataBlocks->size;
S
slguan 已提交
400

S
slguan 已提交
401
  // 1. set the parsed value from sql string
H
hzcheng 已提交
402
  int32_t rowSize = 0;
403
  for (int i = 0; i < spd->numOfAssignedCols; ++i) {
S
slguan 已提交
404
    // the start position in data block buffer of current value in sql
405 406
    char *   start = payload + spd->elems[i].offset;
    int16_t  colIndex = spd->elems[i].colIndex;
S
slguan 已提交
407
    SSchema *pSchema = schema + colIndex;
S
slguan 已提交
408
    rowSize += pSchema->bytes;
H
hzcheng 已提交
409

S
slguan 已提交
410 411 412 413 414 415 416 417 418
    index = 0;
    sToken = tStrGetToken(*str, &index, true, 0, NULL);
    *str += index;

    if (sToken.type == TK_QUESTION) {
      uint32_t offset = start - pDataBlocks->pData;
      if (tscAddParamToDataBlock(pDataBlocks, pSchema->type, (uint8_t)timePrec, pSchema->bytes, offset) != NULL) {
        continue;
      }
419

S
slguan 已提交
420
      strcpy(error, "client out of memory");
L
[1292]  
lihui 已提交
421
      *code = TSDB_CODE_CLI_OUT_OF_MEMORY;
H
hzcheng 已提交
422 423 424
      return -1;
    }

S
slguan 已提交
425 426 427
    if (((sToken.type != TK_NOW) && (sToken.type != TK_INTEGER) && (sToken.type != TK_STRING) &&
         (sToken.type != TK_FLOAT) && (sToken.type != TK_BOOL) && (sToken.type != TK_NULL)) ||
        (sToken.n == 0) || (sToken.type == TK_RP)) {
H
hjxilinx 已提交
428
      tscInvalidSQLErrMsg(error, "invalid data or symbol", sToken.z);
L
[1292]  
lihui 已提交
429
      *code = TSDB_CODE_INVALID_SQL;
S
slguan 已提交
430
      return -1;
H
hzcheng 已提交
431 432
    }

S
slguan 已提交
433 434
    // Remove quotation marks
    if (TK_STRING == sToken.type) {
L
[1292]  
lihui 已提交
435
      // delete escape character: \\, \', \"
436
      char    delim = sToken.z[0];
L
[1292]  
lihui 已提交
437 438
      int32_t cnt = 0;
      int32_t j = 0;
439
      for (int32_t k = 1; k < sToken.n - 1; ++k) {
F
fang 已提交
440 441
        if (sToken.z[k] == delim || sToken.z[k] == '\\') {
          if (sToken.z[k + 1] == delim) {
L
[1292]  
lihui 已提交
442
            cnt++;
L
lihui 已提交
443 444 445
            tmpTokenBuf[j] = sToken.z[k + 1];
            j++;
            k++;
L
[1292]  
lihui 已提交
446 447 448
            continue;
          }
        }
449

L
[NONE]  
lihui 已提交
450
        tmpTokenBuf[j] = sToken.z[k];
L
[1292]  
lihui 已提交
451 452
        j++;
      }
453
      tmpTokenBuf[j] = 0;
L
[1292]  
lihui 已提交
454
      sToken.z = tmpTokenBuf;
455
      sToken.n -= 2 + cnt;
H
hzcheng 已提交
456 457
    }

S
slguan 已提交
458 459
    bool    isPrimaryKey = (colIndex == PRIMARYKEY_TIMESTAMP_COL_INDEX);
    int32_t ret = tsParseOneColumnData(pSchema, &sToken, start, error, str, isPrimaryKey, timePrec);
S
slguan 已提交
460
    if (ret != TSDB_CODE_SUCCESS) {
L
[1292]  
lihui 已提交
461
      *code = TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
462 463
      return -1;  // NOTE: here 0 mean error!
    }
464

S
slguan 已提交
465
    if (isPrimaryKey && tsCheckTimestamp(pDataBlocks, start) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
466
      tscInvalidSQLErrMsg(error, "client time/server time can not be mixed up", sToken.z);
L
[1292]  
lihui 已提交
467
      *code = TSDB_CODE_INVALID_TIME_STAMP;
S
slguan 已提交
468
      return -1;
469
    }
H
hzcheng 已提交
470 471
  }

S
slguan 已提交
472
  // 2. set the null value for the columns that do not assign values
473
  if (spd->numOfAssignedCols < spd->numOfCols) {
S
slguan 已提交
474
    char *ptr = payload;
H
hzcheng 已提交
475 476

    for (int32_t i = 0; i < spd->numOfCols; ++i) {
477
      if (!spd->hasVal[i]) {  // current column do not have any value to insert, set it to null
H
hzcheng 已提交
478 479 480 481 482 483 484 485 486 487 488 489
        setNull(ptr, schema[i].type, schema[i].bytes);
      }

      ptr += schema[i].bytes;
    }

    rowSize = ptr - payload;
  }

  return rowSize;
}

S
slguan 已提交
490 491 492 493 494 495 496 497 498
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;
  }
499 500
}

H
hjxilinx 已提交
501
int tsParseValues(char **str, STableDataBlocks *pDataBlock, STableMeta *pTableMeta, int maxRows,
502
                  SParsedDataColInfo *spd, char *error, int32_t *code, char *tmpTokenBuf) {
S
slguan 已提交
503 504
  int32_t   index = 0;
  SSQLToken sToken;
H
hzcheng 已提交
505 506 507

  int16_t numOfRows = 0;

H
hjxilinx 已提交
508
  SSchema *pSchema = tscGetTableSchema(pTableMeta);
H
hjxilinx 已提交
509
  STableComInfo tinfo = tscGetTableInfo(pTableMeta);
H
hjxilinx 已提交
510 511
  
  int32_t  precision = tinfo.precision;
S
slguan 已提交
512 513

  if (spd->hasVal[0] == false) {
S
slguan 已提交
514
    strcpy(error, "primary timestamp column can not be null");
L
[1292]  
lihui 已提交
515
    *code = TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
516 517 518 519
    return -1;
  }

  while (1) {
S
slguan 已提交
520 521 522
    index = 0;
    sToken = tStrGetToken(*str, &index, false, 0, NULL);
    if (sToken.n == 0 || sToken.type != TK_LP) break;
H
hzcheng 已提交
523

S
slguan 已提交
524
    *str += index;
H
hjxilinx 已提交
525
    if (numOfRows >= maxRows || pDataBlock->size + tinfo.rowSize >= pDataBlock->nAllocSize) {
L
lihui 已提交
526
      int32_t tSize;
H
hjxilinx 已提交
527
      int32_t retcode = tscAllocateMemIfNeed(pDataBlock, tinfo.rowSize, &tSize);
L
lihui 已提交
528
      if (retcode != TSDB_CODE_SUCCESS) {  //TODO pass the correct error code to client
S
slguan 已提交
529
        strcpy(error, "client out of memory");
L
lihui 已提交
530
        *code = retcode;
S
slguan 已提交
531 532
        return -1;
      }
L
lihui 已提交
533 534
      ASSERT(tSize > maxRows);
      maxRows = tSize;
H
hzcheng 已提交
535 536
    }

L
[1292]  
lihui 已提交
537
    int32_t len = tsParseOneRowData(str, pDataBlock, pSchema, spd, error, precision, code, tmpTokenBuf);
538
    if (len <= 0) {  // error message has been set in tsParseOneRowData
H
hzcheng 已提交
539 540 541 542 543
      return -1;
    }

    pDataBlock->size += len;

S
slguan 已提交
544 545 546 547
    index = 0;
    sToken = tStrGetToken(*str, &index, false, 0, NULL);
    *str += index;
    if (sToken.n == 0 || sToken.type != TK_RP) {
H
hjxilinx 已提交
548
      tscInvalidSQLErrMsg(error, ") expected", *str);
L
[1292]  
lihui 已提交
549
      *code = TSDB_CODE_INVALID_SQL;
H
hzcheng 已提交
550 551 552 553 554 555 556 557
      return -1;
    }

    numOfRows++;
  }

  if (numOfRows <= 0) {
    strcpy(error, "no any data points");
L
[1292]  
lihui 已提交
558
    *code = TSDB_CODE_INVALID_SQL;
S
slguan 已提交
559 560 561
    return -1;
  } else {
    return numOfRows;
H
hzcheng 已提交
562 563 564
  }
}

S
slguan 已提交
565
static void tscSetAssignedColumnInfo(SParsedDataColInfo *spd, SSchema *pSchema, int32_t numOfCols) {
H
hzcheng 已提交
566
  spd->numOfCols = numOfCols;
567
  spd->numOfAssignedCols = numOfCols;
H
hzcheng 已提交
568 569 570 571 572 573 574 575 576 577 578

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

L
lihui 已提交
579
int32_t tscAllocateMemIfNeed(STableDataBlocks *pDataBlock, int32_t rowSize, int32_t * numOfRows) {
S
slguan 已提交
580
  size_t    remain = pDataBlock->nAllocSize - pDataBlock->size;
S
slguan 已提交
581
  const int factor = 5;
S
slguan 已提交
582
  uint32_t nAllocSizeOld = pDataBlock->nAllocSize;
L
[#1102]  
lihui 已提交
583 584
  assert(pDataBlock->headerSize >= 0);
  
H
hzcheng 已提交
585
  // expand the allocated size
S
slguan 已提交
586 587
  if (remain < rowSize * factor) {
    while (remain < rowSize * factor) {
S
slguan 已提交
588
      pDataBlock->nAllocSize = (uint32_t)(pDataBlock->nAllocSize * 1.5);
S
slguan 已提交
589 590
      remain = pDataBlock->nAllocSize - pDataBlock->size;
    }
H
hzcheng 已提交
591

S
slguan 已提交
592 593 594 595 596
    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 {
H
hjxilinx 已提交
597
      // do nothing, if allocate more memory failed
S
slguan 已提交
598
      pDataBlock->nAllocSize = nAllocSizeOld;
L
[#1102]  
lihui 已提交
599
      *numOfRows = (int32_t)(pDataBlock->nAllocSize - pDataBlock->headerSize) / rowSize;
L
lihui 已提交
600
      return TSDB_CODE_CLI_OUT_OF_MEMORY;
S
slguan 已提交
601
    }
H
hzcheng 已提交
602 603
  }

L
[#1102]  
lihui 已提交
604
  *numOfRows = (int32_t)(pDataBlock->nAllocSize - pDataBlock->headerSize) / rowSize;
L
lihui 已提交
605
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
606 607
}

608 609
static void tsSetBlockInfo(SSubmitBlk *pBlocks, const STableMeta *pTableMeta, int32_t numOfRows) {
  pBlocks->tid = pTableMeta->sid;
H
hjxilinx 已提交
610 611
  pBlocks->uid = pTableMeta->uid;
  pBlocks->sversion = pTableMeta->sversion;
S
slguan 已提交
612
  pBlocks->numOfRows += numOfRows;
H
hzcheng 已提交
613 614
}

S
slguan 已提交
615
// data block is disordered, sort it in ascending order
H
hjxilinx 已提交
616
void tscSortRemoveDataBlockDupRows(STableDataBlocks *dataBuf) {
617
  SSubmitBlk *pBlocks = (SSubmitBlk *)dataBuf->pData;
S
slguan 已提交
618 619

  // size is less than the total size, since duplicated rows may be removed yet.
620
  assert(pBlocks->numOfRows * dataBuf->rowSize + sizeof(SSubmitBlk) == dataBuf->size);
S
slguan 已提交
621

S
slguan 已提交
622 623 624 625 626
  // if use server time, this block must be ordered
  if (dataBuf->tsSource == TSDB_USE_SERVER_TS) {
    assert(dataBuf->ordered);
  }

S
slguan 已提交
627
  if (!dataBuf->ordered) {
628
    char *pBlockData = pBlocks->data;
S
slguan 已提交
629
    qsort(pBlockData, pBlocks->numOfRows, dataBuf->rowSize, rowDataCompar);
H
hzcheng 已提交
630

S
slguan 已提交
631 632
    int32_t i = 0;
    int32_t j = 1;
H
hzcheng 已提交
633

S
slguan 已提交
634
    while (j < pBlocks->numOfRows) {
S
slguan 已提交
635 636
      TSKEY ti = *(TSKEY *)(pBlockData + dataBuf->rowSize * i);
      TSKEY tj = *(TSKEY *)(pBlockData + dataBuf->rowSize * j);
H
hzcheng 已提交
637

S
slguan 已提交
638 639 640 641
      if (ti == tj) {
        ++j;
        continue;
      }
H
hzcheng 已提交
642

S
slguan 已提交
643 644 645 646 647 648 649 650 651
      int32_t nextPos = (++i);
      if (nextPos != j) {
        memmove(pBlockData + dataBuf->rowSize * nextPos, pBlockData + dataBuf->rowSize * j, dataBuf->rowSize);
      }

      ++j;
    }

    dataBuf->ordered = true;
H
hzcheng 已提交
652

S
slguan 已提交
653
    pBlocks->numOfRows = i + 1;
654
    dataBuf->size = sizeof(SSubmitBlk) + dataBuf->rowSize * pBlocks->numOfRows;
S
slguan 已提交
655
  }
S
slguan 已提交
656 657
}

658
static int32_t doParseInsertStatement(SSqlObj *pSql, void *pTableList, char **str, SParsedDataColInfo *spd,
S
slguan 已提交
659
                                      int32_t *totalNum) {
S
slguan 已提交
660
  SSqlCmd *       pCmd = &pSql->cmd;
661
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
662
  STableMeta *    pTableMeta = pTableMetaInfo->pTableMeta;
H
hjxilinx 已提交
663
  STableComInfo tinfo = tscGetTableInfo(pTableMeta);
H
hjxilinx 已提交
664
  
H
hjxilinx 已提交
665
  STableDataBlocks *dataBuf = NULL;
666
  int32_t ret = tscGetDataBlockFromList(pTableList, pCmd->pDataBlocks, pTableMeta->uid, TSDB_DEFAULT_PAYLOAD_SIZE,
667
                                        sizeof(SSubmitBlk), tinfo.rowSize, pTableMetaInfo->name,
H
hjxilinx 已提交
668
                                        pTableMeta, &dataBuf);
H
hjxilinx 已提交
669 670 671 672
  if (ret != TSDB_CODE_SUCCESS) {
    return ret;
  }
  
L
lihui 已提交
673
  int32_t maxNumOfRows;
H
hjxilinx 已提交
674
  ret = tscAllocateMemIfNeed(dataBuf, tinfo.rowSize, &maxNumOfRows);
L
lihui 已提交
675
  if (TSDB_CODE_SUCCESS != ret) {
S
slguan 已提交
676 677
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
678

L
[1292]  
lihui 已提交
679
  int32_t code = TSDB_CODE_INVALID_SQL;
680
  char *  tmpTokenBuf = calloc(1, 4096);  // used for deleting Escape character: \\, \', \"
L
[1292]  
lihui 已提交
681 682 683
  if (NULL == tmpTokenBuf) {
    return TSDB_CODE_CLI_OUT_OF_MEMORY;
  }
L
lihui 已提交
684

H
hjxilinx 已提交
685
  int32_t numOfRows = tsParseValues(str, dataBuf, pTableMeta, maxNumOfRows, spd, pCmd->payload, &code, tmpTokenBuf);
L
[1292]  
lihui 已提交
686
  free(tmpTokenBuf);
H
hzcheng 已提交
687
  if (numOfRows <= 0) {
L
[1292]  
lihui 已提交
688
    return code;
H
hzcheng 已提交
689 690
  }

S
slguan 已提交
691
  for (uint32_t i = 0; i < dataBuf->numOfParams; ++i) {
692
    SParamInfo *param = dataBuf->params + i;
S
slguan 已提交
693 694
    if (param->idx == -1) {
      param->idx = pCmd->numOfParams++;
695
      param->offset -= sizeof(SSubmitBlk);
S
slguan 已提交
696 697 698
    }
  }

699
  SSubmitBlk *pBlocks = (SSubmitBlk *)(dataBuf->pData);
H
hjxilinx 已提交
700
  tsSetBlockInfo(pBlocks, pTableMeta, numOfRows);
S
slguan 已提交
701

H
hjxilinx 已提交
702
  dataBuf->vgId = pTableMeta->vgroupInfo.vgId;
S
slguan 已提交
703
  dataBuf->numOfTables = 1;
H
hzcheng 已提交
704 705

  /*
S
slguan 已提交
706 707
   * the value of pRes->numOfRows does not affect the true result of AFFECTED ROWS,
   * which is actually returned from server.
H
hzcheng 已提交
708
   */
S
slguan 已提交
709
  *totalNum += numOfRows;
H
hzcheng 已提交
710 711 712
  return TSDB_CODE_SUCCESS;
}

713
static int32_t tscCheckIfCreateTable(char **sqlstr, SSqlObj *pSql) {
S
slguan 已提交
714
  int32_t   index = 0;
715 716
  SSQLToken sToken = {0};
  SSQLToken tableToken = {0};
S
slguan 已提交
717
  int32_t   code = TSDB_CODE_SUCCESS;
718 719 720 721 722 723
  
  const int32_t TABLE_INDEX = 0;
  const int32_t STABLE_INDEX = 1;
  
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
hzcheng 已提交
724

S
slguan 已提交
725
  char *sql = *sqlstr;
726

S
slguan 已提交
727 728 729 730
  // get the token of specified table
  index = 0;
  tableToken = tStrGetToken(sql, &index, false, 0, NULL);
  sql += index;
H
hzcheng 已提交
731

S
slguan 已提交
732 733
  char *cstart = NULL;
  char *cend = NULL;
H
hzcheng 已提交
734

S
slguan 已提交
735 736 737 738 739
  // skip possibly exists column list
  index = 0;
  sToken = tStrGetToken(sql, &index, false, 0, NULL);
  sql += index;

H
hzcheng 已提交
740
  int32_t numOfColList = 0;
S
slguan 已提交
741
  bool    createTable = false;
H
hzcheng 已提交
742

S
slguan 已提交
743 744 745
  if (sToken.type == TK_LP) {
    cstart = &sToken.z[0];
    index = 0;
H
hzcheng 已提交
746
    while (1) {
S
slguan 已提交
747 748 749
      sToken = tStrGetToken(sql, &index, false, 0, NULL);
      if (sToken.type == TK_RP) {
        cend = &sToken.z[0];
H
hzcheng 已提交
750 751 752 753 754 755
        break;
      }

      ++numOfColList;
    }

S
slguan 已提交
756 757
    sToken = tStrGetToken(sql, &index, false, 0, NULL);
    sql += index;
H
hzcheng 已提交
758 759 760 761 762
  }

  if (numOfColList == 0 && cstart != NULL) {
    return TSDB_CODE_INVALID_SQL;
  }
763
  
H
hjxilinx 已提交
764
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, TABLE_INDEX);
765 766
  
  if (sToken.type == TK_USING) {  // create table if not exists according to the super table
S
slguan 已提交
767 768 769 770
    index = 0;
    sToken = tStrGetToken(sql, &index, false, 0, NULL);
    sql += index;

S
slguan 已提交
771
    STagData *pTag = (STagData *)pCmd->payload;
S
slguan 已提交
772
    memset(pTag, 0, sizeof(STagData));
773 774
    
    /*
H
hjxilinx 已提交
775
     * the source super table is moved to the secondary position of the pTableMetaInfo list
776 777
     */
    if (pQueryInfo->numOfTables < 2) {
H
hjxilinx 已提交
778
      tscAddEmptyMetaInfo(pQueryInfo);
779
    }
H
hzcheng 已提交
780

H
hjxilinx 已提交
781
    STableMetaInfo *pSTableMeterMetaInfo = tscGetMetaInfo(pQueryInfo, STABLE_INDEX);
H
hjxilinx 已提交
782
    tscSetTableId(pSTableMeterMetaInfo, &sToken, pSql);
783

S
slguan 已提交
784
    strncpy(pTag->name, pSTableMeterMetaInfo->name, TSDB_TABLE_ID_LEN);
H
hjxilinx 已提交
785
    code = tscGetTableMeta(pSql, pSTableMeterMetaInfo);
H
hzcheng 已提交
786 787 788 789
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

H
hjxilinx 已提交
790
    if (!UTIL_TABLE_IS_SUPERTABLE(pSTableMeterMetaInfo)) {
H
hjxilinx 已提交
791
      return tscInvalidSQLErrMsg(pCmd->payload, "create table only from super table is allowed", sToken.z);
S
slguan 已提交
792 793
    }

H
hjxilinx 已提交
794
    SSchema *pTagSchema = tscGetTableTagSchema(pSTableMeterMetaInfo->pTableMeta);
H
hjxilinx 已提交
795
    STableComInfo tinfo = tscGetTableInfo(pSTableMeterMetaInfo->pTableMeta);
H
hjxilinx 已提交
796
    
S
slguan 已提交
797 798 799
    index = 0;
    sToken = tStrGetToken(sql, &index, false, 0, NULL);
    sql += index;
L
lihui 已提交
800

801
    SParsedDataColInfo spd = {0};
H
hjxilinx 已提交
802 803
    
    uint8_t numOfTags = tscGetNumOfTags(pSTableMeterMetaInfo->pTableMeta);
L
lihui 已提交
804 805 806 807 808 809
    spd.numOfCols = numOfTags;

    // if specify some tags column
    if (sToken.type != TK_LP) {
      tscSetAssignedColumnInfo(&spd, pTagSchema, numOfTags);
    } else {
810 811
      /* insert into tablename (col1, col2,..., coln) using superTableName (tagName1, tagName2, ..., tagNamen)
       * tags(tagVal1, tagVal2, ..., tagValn) values(v1, v2,... vn); */
L
lihui 已提交
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837
      int16_t offset[TSDB_MAX_COLUMNS] = {0};
      for (int32_t t = 1; t < numOfTags; ++t) {
        offset[t] = offset[t - 1] + pTagSchema[t - 1].bytes;
      }

      while (1) {
        index = 0;
        sToken = tStrGetToken(sql, &index, false, 0, NULL);
        sql += index;

        if (TK_STRING == sToken.type) {
          sToken.n = strdequote(sToken.z);
          strtrim(sToken.z);
          sToken.n = (uint32_t)strlen(sToken.z);
        }

        if (sToken.type == TK_RP) {
          break;
        }

        bool findColumnIndex = false;

        // todo speedup by using hash list
        for (int32_t t = 0; t < numOfTags; ++t) {
          if (strncmp(sToken.z, pTagSchema[t].name, sToken.n) == 0 && strlen(pTagSchema[t].name) == sToken.n) {
            SParsedColElem *pElem = &spd.elems[spd.numOfAssignedCols++];
838
            pElem->offset = offset[t];
L
lihui 已提交
839 840 841 842 843 844
            pElem->colIndex = t;

            if (spd.hasVal[t] == true) {
              return tscInvalidSQLErrMsg(pCmd->payload, "duplicated tag name", sToken.z);
            }

845
            spd.hasVal[t] = true;
L
lihui 已提交
846 847 848 849 850 851 852 853 854 855 856 857 858
            findColumnIndex = true;
            break;
          }
        }

        if (!findColumnIndex) {
          return tscInvalidSQLErrMsg(pCmd->payload, "invalid tag name", sToken.z);
        }
      }

      if (spd.numOfAssignedCols == 0 || spd.numOfAssignedCols > numOfTags) {
        return tscInvalidSQLErrMsg(pCmd->payload, "tag name expected", sToken.z);
      }
L
lihui 已提交
859 860 861 862

      index = 0;
      sToken = tStrGetToken(sql, &index, false, 0, NULL);
      sql += index;
L
lihui 已提交
863
    }
864

S
slguan 已提交
865
    if (sToken.type != TK_TAGS) {
L
lihui 已提交
866
      return tscInvalidSQLErrMsg(pCmd->payload, "keyword TAGS expected", sToken.z);
H
hzcheng 已提交
867 868
    }

S
slguan 已提交
869 870
    uint32_t ignoreTokenTypes = TK_LP;
    uint32_t numOfIgnoreToken = 1;
L
lihui 已提交
871
    for (int i = 0; i < spd.numOfAssignedCols; ++i) {
872
      char *  tagVal = pTag->data + spd.elems[i].offset;
L
lihui 已提交
873
      int16_t colIndex = spd.elems[i].colIndex;
874

S
slguan 已提交
875 876 877 878
      index = 0;
      sToken = tStrGetToken(sql, &index, true, numOfIgnoreToken, &ignoreTokenTypes);
      sql += index;
      if (sToken.n == 0) {
H
hzcheng 已提交
879
        break;
S
slguan 已提交
880 881 882
      } else if (sToken.type == TK_RP) {
        break;
      }
H
hzcheng 已提交
883

S
slguan 已提交
884 885 886 887
      // Remove quotation marks
      if (TK_STRING == sToken.type) {
        sToken.z++;
        sToken.n -= 2;
H
hzcheng 已提交
888 889
      }

H
hjxilinx 已提交
890
      code = tsParseOneColumnData(&pTagSchema[colIndex], &sToken, tagVal, pCmd->payload, &sql, false, tinfo.precision);
H
hzcheng 已提交
891
      if (code != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
892
        return code;
H
hzcheng 已提交
893 894
      }

895 896
      if ((pTagSchema[colIndex].type == TSDB_DATA_TYPE_BINARY || pTagSchema[colIndex].type == TSDB_DATA_TYPE_NCHAR) &&
          sToken.n > pTagSchema[colIndex].bytes) {
H
hjxilinx 已提交
897
        return tscInvalidSQLErrMsg(pCmd->payload, "string too long", sToken.z);
S
slguan 已提交
898
      }
L
lihui 已提交
899
    }
S
slguan 已提交
900

L
lihui 已提交
901 902 903 904 905
    index = 0;
    sToken = tStrGetToken(sql, &index, false, 0, NULL);
    sql += index;
    if (sToken.n == 0 || sToken.type != TK_RP) {
      return tscInvalidSQLErrMsg(pCmd->payload, ") expected", sToken.z);
H
hzcheng 已提交
906 907
    }

L
lihui 已提交
908 909 910
    // 2. set the null value for the columns that do not assign values
    if (spd.numOfAssignedCols < spd.numOfCols) {
      char *ptr = pTag->data;
911

L
lihui 已提交
912
      for (int32_t i = 0; i < spd.numOfCols; ++i) {
913
        if (!spd.hasVal[i]) {  // current tag column do not have any value to insert, set it to null
L
lihui 已提交
914 915
          setNull(ptr, pTagSchema[i].type, pTagSchema[i].bytes);
        }
916

L
lihui 已提交
917
        ptr += pTagSchema[i].bytes;
918
      }
H
hzcheng 已提交
919 920 921
    }

    if (tscValidateName(&tableToken) != TSDB_CODE_SUCCESS) {
L
lihui 已提交
922
      return tscInvalidSQLErrMsg(pCmd->payload, "invalid table name", *sqlstr);
H
hzcheng 已提交
923 924
    }

H
hjxilinx 已提交
925
    int32_t ret = tscSetTableId(pTableMetaInfo, &tableToken, pSql);
H
hzcheng 已提交
926 927 928 929 930
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }

    createTable = true;
H
hjxilinx 已提交
931
    code = tscGetMeterMetaEx(pSql, pTableMetaInfo, true);
H
hjxilinx 已提交
932 933 934 935
    if (TSDB_CODE_ACTION_IN_PROGRESS == code) {
      return code;
    }
    
H
hzcheng 已提交
936 937 938 939
  } else {
    if (cstart != NULL) {
      sql = cstart;
    } else {
S
slguan 已提交
940
      sql = sToken.z;
H
hzcheng 已提交
941
    }
H
hjxilinx 已提交
942
    code = tscGetTableMeta(pSql, pTableMetaInfo);
H
hjxilinx 已提交
943
    
944
    if (pCmd->curSql == NULL) {
H
hjxilinx 已提交
945 946
      assert(code == TSDB_CODE_ACTION_IN_PROGRESS);
    }
H
hzcheng 已提交
947 948 949 950 951
  }

  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 已提交
952
    memmove(sql - len, cstart, len);
H
hzcheng 已提交
953 954 955 956 957 958 959 960
    *sqlstr = sql - len;
  } else {
    *sqlstr = sql;
  }

  return code;
}

S
slguan 已提交
961
int validateTableName(char *tblName, int len) {
S
slguan 已提交
962
  char buf[TSDB_TABLE_ID_LEN] = {0};
S
slguan 已提交
963
  strncpy(buf, tblName, len);
S
slguan 已提交
964

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

H
huili 已提交
968 969 970
  return tscValidateName(&token);
}

971 972 973 974 975 976 977 978 979
static int32_t validateDataSource(SSqlCmd *pCmd, int8_t type, const char *sql) {
  if (pCmd->dataSourceType != 0 && pCmd->dataSourceType != type) {
    return tscInvalidSQLErrMsg(pCmd->payload, "keyword VALUES and FILE are not allowed to mix up", sql);
  }

  pCmd->dataSourceType = type;
  return TSDB_CODE_SUCCESS;
}

H
hzcheng 已提交
980 981 982 983 984 985 986 987 988
/**
 * usage: insert into table1 values() () table2 values()()
 *
 * @param str
 * @param acct
 * @param db
 * @param pSql
 * @return
 */
989
int doParseInsertSql(SSqlObj *pSql, char *str) {
S
slguan 已提交
990
  SSqlCmd *pCmd = &pSql->cmd;
991

S
slguan 已提交
992
  int32_t totalNum = 0;
993 994
  int32_t code = TSDB_CODE_SUCCESS;

H
hjxilinx 已提交
995
  STableMetaInfo *pTableMetaInfo = NULL;
996 997 998 999

  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
  assert(pQueryInfo != NULL);

1000
  if (pQueryInfo->numOfTables == 0) {
H
hjxilinx 已提交
1001
    pTableMetaInfo = tscAddEmptyMetaInfo(pQueryInfo);
1002
  } else {
H
hjxilinx 已提交
1003
    pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
1004
  }
H
hzcheng 已提交
1005

S
slguan 已提交
1006
  if ((code = tscAllocPayload(pCmd, TSDB_PAYLOAD_SIZE)) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
1007 1008 1009
    return code;
  }

1010 1011
  assert(((NULL == pCmd->curSql) && (NULL == pCmd->pTableList))
      || ((NULL != pCmd->curSql) && (NULL != pCmd->pTableList)));
L
lihui 已提交
1012

1013 1014
  if ((NULL == pCmd->curSql) && (NULL == pCmd->pTableList)) {
    pCmd->pTableList = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false);
1015

L
lihui 已提交
1016
    pSql->cmd.pDataBlocks = tscCreateBlockArrayList();
1017
    if (NULL == pCmd->pTableList || NULL == pSql->cmd.pDataBlocks) {
L
lihui 已提交
1018 1019 1020 1021
      code = TSDB_CODE_CLI_OUT_OF_MEMORY;
      goto _error_clean;
    }
  } else {
1022 1023
    assert((NULL != pCmd->curSql) && (NULL != pCmd->pTableList));
    str = pCmd->curSql;
L
lihui 已提交
1024 1025
  }
  
1026
  tscTrace("%p create data block list for submit data:%p, curSql:%p, pTableList:%p", pSql, pSql->cmd.pDataBlocks, pCmd->curSql, pCmd->pTableList);
H
hzcheng 已提交
1027 1028

  while (1) {
1029
    int32_t   index = 0;
S
slguan 已提交
1030
    SSQLToken sToken = tStrGetToken(str, &index, false, 0, NULL);
1031 1032 1033 1034 1035 1036 1037 1038

    // no data in the sql string anymore.
    if (sToken.n == 0) {
      /*
       * if the data is from the data file, no data has been generated yet. So, there no data to
       * merge or submit, save the file path and parse the file in other routines.
       */
      if (pCmd->dataSourceType == DATA_FROM_DATA_FILE) {
S
slguan 已提交
1039 1040 1041
        goto _clean;
      }

1042 1043 1044 1045 1046
      /*
       * if no data has been generated during parsing the sql string, error msg will return
       * Otherwise, create the first submit block and submit to virtual node.
       */
      if (totalNum == 0) {
H
hzcheng 已提交
1047 1048
        code = TSDB_CODE_INVALID_SQL;
        goto _error_clean;
1049 1050
      } else {
        break;
H
hzcheng 已提交
1051 1052 1053
      }
    }

1054
    pCmd->curSql = sToken.z;
L
lihui 已提交
1055

S
slguan 已提交
1056
    // Check if the table name available or not
S
slguan 已提交
1057
    if (validateTableName(sToken.z, sToken.n) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1058
      code = tscInvalidSQLErrMsg(pCmd->payload, "table name invalid", sToken.z);
H
huili 已提交
1059 1060 1061
      goto _error_clean;
    }

H
hjxilinx 已提交
1062
    if ((code = tscSetTableId(pTableMetaInfo, &sToken, pSql)) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
1063 1064 1065
      goto _error_clean;
    }

1066
    ptrdiff_t pos = pCmd->curSql - pSql->sqlstr;
1067
    
1068 1069
    if ((code = tscCheckIfCreateTable(&str, pSql)) != TSDB_CODE_SUCCESS) {
      /*
H
hjxilinx 已提交
1070 1071
       * For async insert, after get the table meta from server, the sql string will not be
       * parsed using the new table meta to avoid the overhead cause by get table meta data information.
1072 1073 1074
       * And during the getMeterMetaCallback function, the sql string will be parsed from the
       * interrupted position.
       */
H
hjxilinx 已提交
1075
      if (TSDB_CODE_ACTION_IN_PROGRESS == code) {
1076
        tscTrace("%p waiting for get table meta during insert, then resume from offset: %" PRId64 " , %s", pSql,
1077
            pos, pCmd->curSql);
H
hjxilinx 已提交
1078
        return code;
H
hzcheng 已提交
1079
      }
H
hjxilinx 已提交
1080
      
H
hjxilinx 已提交
1081
      // todo add to return
1082
      tscError("%p async insert parse error, code:%d, %s", pSql, code, tstrerror(code));
1083
      pCmd->curSql = NULL;
H
hjxilinx 已提交
1084
      goto _error_clean;       // TODO: should _clean or _error_clean to async flow ????
H
hzcheng 已提交
1085 1086
    }

H
hjxilinx 已提交
1087
    if (UTIL_TABLE_IS_SUPERTABLE(pTableMetaInfo)) {
H
hjxilinx 已提交
1088
      code = tscInvalidSQLErrMsg(pCmd->payload, "insert data into super table is not supported", NULL);
H
hzcheng 已提交
1089 1090 1091
      goto _error_clean;
    }

S
slguan 已提交
1092 1093 1094
    index = 0;
    sToken = tStrGetToken(str, &index, false, 0, NULL);
    str += index;
1095

S
slguan 已提交
1096
    if (sToken.n == 0) {
1097
      code = tscInvalidSQLErrMsg(pCmd->payload, "keyword VALUES or FILE required", sToken.z);
H
hzcheng 已提交
1098 1099
      goto _error_clean;
    }
H
hjxilinx 已提交
1100
    
H
hjxilinx 已提交
1101
    STableComInfo tinfo = tscGetTableInfo(pTableMetaInfo->pTableMeta);
H
hjxilinx 已提交
1102
    
S
slguan 已提交
1103
    if (sToken.type == TK_VALUES) {
H
hjxilinx 已提交
1104
      SParsedDataColInfo spd = {.numOfCols = tinfo.numOfColumns};
H
hjxilinx 已提交
1105 1106
      
      SSchema *pSchema = tscGetTableSchema(pTableMetaInfo->pTableMeta);
H
hjxilinx 已提交
1107
      tscSetAssignedColumnInfo(&spd, pSchema, tinfo.numOfColumns);
H
hzcheng 已提交
1108

1109 1110
      if (validateDataSource(pCmd, DATA_FROM_SQL_STRING, sToken.z) != TSDB_CODE_SUCCESS) {
        goto _error_clean;
H
hzcheng 已提交
1111 1112 1113 1114 1115 1116
      }

      /*
       * app here insert data in different vnodes, so we need to set the following
       * data in another submit procedure using async insert routines
       */
1117
      code = doParseInsertStatement(pSql, pCmd->pTableList, &str, &spd, &totalNum);
H
hzcheng 已提交
1118 1119 1120
      if (code != TSDB_CODE_SUCCESS) {
        goto _error_clean;
      }
S
slguan 已提交
1121
    } else if (sToken.type == TK_FILE) {
1122 1123
      if (validateDataSource(pCmd, DATA_FROM_DATA_FILE, sToken.z) != TSDB_CODE_SUCCESS) {
        goto _error_clean;
H
hzcheng 已提交
1124 1125
      }

S
slguan 已提交
1126 1127 1128 1129
      index = 0;
      sToken = tStrGetToken(str, &index, false, 0, NULL);
      str += index;
      if (sToken.n == 0) {
H
hjxilinx 已提交
1130
        code = tscInvalidSQLErrMsg(pCmd->payload, "file path is required following keyword FILE", sToken.z);
H
hzcheng 已提交
1131 1132 1133
        goto _error_clean;
      }

S
slguan 已提交
1134
      char fname[PATH_MAX] = {0};
S
slguan 已提交
1135
      strncpy(fname, sToken.z, sToken.n);
S
slguan 已提交
1136
      strdequote(fname);
1137

H
hzcheng 已提交
1138 1139
      wordexp_t full_path;
      if (wordexp(fname, &full_path, 0) != 0) {
H
hjxilinx 已提交
1140
        code = tscInvalidSQLErrMsg(pCmd->payload, "invalid filename", sToken.z);
H
hzcheng 已提交
1141 1142 1143 1144 1145
        goto _error_clean;
      }
      strcpy(fname, full_path.we_wordv[0]);
      wordfree(&full_path);

H
hjxilinx 已提交
1146
      STableDataBlocks *pDataBlock = NULL;
H
hjxilinx 已提交
1147
      STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;
1148
      
1149
      int32_t ret = tscCreateDataBlock(PATH_MAX, tinfo.rowSize, sizeof(SSubmitBlk), pTableMetaInfo->name,
H
hjxilinx 已提交
1150
                                       pTableMeta, &pDataBlock);
H
hjxilinx 已提交
1151 1152 1153
      if (ret != TSDB_CODE_SUCCESS) {
        goto _error_clean;
      }
1154

S
slguan 已提交
1155 1156
      tscAppendDataBlock(pCmd->pDataBlocks, pDataBlock);
      strcpy(pDataBlock->filename, fname);
S
slguan 已提交
1157
    } else if (sToken.type == TK_LP) {
H
hzcheng 已提交
1158
      /* insert into tablename(col1, col2,..., coln) values(v1, v2,... vn); */
1159
      STableMeta *pTableMeta = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0)->pTableMeta;
H
hjxilinx 已提交
1160
      SSchema *   pSchema = tscGetTableSchema(pTableMeta);
H
hzcheng 已提交
1161

1162
      if (validateDataSource(pCmd, DATA_FROM_SQL_STRING, sToken.z) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
1163 1164 1165
        goto _error_clean;
      }

1166
      SParsedDataColInfo spd = {0};
H
hjxilinx 已提交
1167
      spd.numOfCols = tinfo.numOfColumns;
H
hzcheng 已提交
1168 1169

      int16_t offset[TSDB_MAX_COLUMNS] = {0};
H
hjxilinx 已提交
1170
      for (int32_t t = 1; t < tinfo.numOfColumns; ++t) {
H
hzcheng 已提交
1171 1172 1173 1174
        offset[t] = offset[t - 1] + pSchema[t - 1].bytes;
      }

      while (1) {
S
slguan 已提交
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
        index = 0;
        sToken = tStrGetToken(str, &index, false, 0, NULL);
        str += index;

        if (TK_STRING == sToken.type) {
          sToken.n = strdequote(sToken.z);
          strtrim(sToken.z);
          sToken.n = (uint32_t)strlen(sToken.z);
        }

        if (sToken.type == TK_RP) {
H
hzcheng 已提交
1186 1187 1188 1189 1190 1191
          break;
        }

        bool findColumnIndex = false;

        // todo speedup by using hash list
H
hjxilinx 已提交
1192
        for (int32_t t = 0; t < tinfo.numOfColumns; ++t) {
S
slguan 已提交
1193
          if (strncmp(sToken.z, pSchema[t].name, sToken.n) == 0 && strlen(pSchema[t].name) == sToken.n) {
S
slguan 已提交
1194
            SParsedColElem *pElem = &spd.elems[spd.numOfAssignedCols++];
H
hzcheng 已提交
1195 1196 1197 1198
            pElem->offset = offset[t];
            pElem->colIndex = t;

            if (spd.hasVal[t] == true) {
H
hjxilinx 已提交
1199
              code = tscInvalidSQLErrMsg(pCmd->payload, "duplicated column name", sToken.z);
H
hzcheng 已提交
1200 1201 1202 1203 1204 1205 1206 1207 1208
              goto _error_clean;
            }

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

S
slguan 已提交
1209
        if (!findColumnIndex) {
H
hjxilinx 已提交
1210
          code = tscInvalidSQLErrMsg(pCmd->payload, "invalid column name", sToken.z);
H
hzcheng 已提交
1211 1212 1213 1214
          goto _error_clean;
        }
      }

H
hjxilinx 已提交
1215
      if (spd.numOfAssignedCols == 0 || spd.numOfAssignedCols > tinfo.numOfColumns) {
H
hjxilinx 已提交
1216
        code = tscInvalidSQLErrMsg(pCmd->payload, "column name expected", sToken.z);
H
hzcheng 已提交
1217 1218 1219
        goto _error_clean;
      }

S
slguan 已提交
1220 1221 1222 1223 1224
      index = 0;
      sToken = tStrGetToken(str, &index, false, 0, NULL);
      str += index;

      if (sToken.type != TK_VALUES) {
H
hjxilinx 已提交
1225
        code = tscInvalidSQLErrMsg(pCmd->payload, "keyword VALUES is expected", sToken.z);
H
hzcheng 已提交
1226 1227 1228
        goto _error_clean;
      }

1229
      code = doParseInsertStatement(pSql, pCmd->pTableList, &str, &spd, &totalNum);
H
hzcheng 已提交
1230 1231 1232 1233
      if (code != TSDB_CODE_SUCCESS) {
        goto _error_clean;
      }
    } else {
H
hjxilinx 已提交
1234
      code = tscInvalidSQLErrMsg(pCmd->payload, "keyword VALUES or FILE are required", sToken.z);
H
hzcheng 已提交
1235 1236 1237 1238
      goto _error_clean;
    }
  }

S
slguan 已提交
1239 1240 1241 1242
  // we need to keep the data blocks if there are parameters in the sql
  if (pCmd->numOfParams > 0) {
    goto _clean;
  }
1243

H
hjxilinx 已提交
1244
  if (pCmd->pDataBlocks->nSize > 0) { // merge according to vgId
S
slguan 已提交
1245 1246 1247
    if ((code = tscMergeTableDataBlocks(pSql, pCmd->pDataBlocks)) != TSDB_CODE_SUCCESS) {
      goto _error_clean;
    }
H
hzcheng 已提交
1248
  } else {
S
slguan 已提交
1249
    pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
H
hzcheng 已提交
1250 1251 1252 1253 1254 1255
  }

  code = TSDB_CODE_SUCCESS;
  goto _clean;

_error_clean:
S
slguan 已提交
1256
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
H
hzcheng 已提交
1257 1258

_clean:
1259 1260
  taosHashCleanup(pCmd->pTableList);
  pCmd->pTableList = NULL;
H
hjxilinx 已提交
1261
  
1262 1263
  pCmd->curSql    = NULL;
  pCmd->parseFinished  = 1;
H
hjxilinx 已提交
1264
  
H
hzcheng 已提交
1265 1266 1267
  return code;
}

1268
int tsParseInsertSql(SSqlObj *pSql) {
S
slguan 已提交
1269 1270 1271
  if (!pSql->pTscObj->writeAuth) {
    return TSDB_CODE_NO_RIGHTS;
  }
H
hzcheng 已提交
1272

H
hjxilinx 已提交
1273
  int32_t  index = 0;
S
slguan 已提交
1274
  SSqlCmd *pCmd = &pSql->cmd;
1275 1276

  SSQLToken sToken = tStrGetToken(pSql->sqlstr, &index, false, 0, NULL);
H
hjxilinx 已提交
1277
  assert(sToken.type == TK_INSERT || sToken.type == TK_IMPORT);
1278 1279 1280 1281 1282

  pCmd->count = 0;
  pCmd->command = TSDB_SQL_INSERT;

  SQueryInfo *pQueryInfo = NULL;
1283
  tscGetQueryInfoDetailSafely(pCmd, pCmd->clauseIndex, &pQueryInfo);
1284

1285 1286
  uint16_t type = (sToken.type == TK_INSERT)? TSDB_QUERY_TYPE_INSERT:TSDB_QUERY_TYPE_IMPORT;
  TSDB_QUERY_SET_TYPE(pQueryInfo->type, type);
1287 1288

  sToken = tStrGetToken(pSql->sqlstr, &index, false, 0, NULL);
S
slguan 已提交
1289
  if (sToken.type != TK_INTO) {
H
hjxilinx 已提交
1290
    return tscInvalidSQLErrMsg(pCmd->payload, "keyword INTO is expected", sToken.z);
S
slguan 已提交
1291
  }
1292

H
hjxilinx 已提交
1293
  pSql->res.numOfRows = 0;
1294
  return doParseInsertSql(pSql, pSql->sqlstr + index);
H
hzcheng 已提交
1295 1296
}

H
[TD-98]  
hjxilinx 已提交
1297
int tsParseSql(SSqlObj *pSql, bool initialParse) {
H
hzcheng 已提交
1298
  int32_t ret = TSDB_CODE_SUCCESS;
H
[TD-98]  
hjxilinx 已提交
1299 1300 1301 1302 1303
  
  if (initialParse) {
    char* p = pSql->sqlstr;
    pSql->sqlstr = NULL;
    
H
hjxilinx 已提交
1304
    tscPartiallyFreeSqlObj(pSql);
H
[TD-98]  
hjxilinx 已提交
1305 1306
    pSql->sqlstr = p;
  } else {
1307
    tscTrace("continue parse sql: %s", pSql->cmd.curSql);
H
[TD-98]  
hjxilinx 已提交
1308
  }
L
lihui 已提交
1309
  
H
hzcheng 已提交
1310 1311
  if (tscIsInsertOrImportData(pSql->sqlstr)) {
    /*
1312 1313
     * Set the fp before parse the sql string, in case of getTableMeta failed, in which
     * the error handle callback function can rightfully restore the user-defined callback function (fp).
H
hzcheng 已提交
1314
     */
H
[TD-98]  
hjxilinx 已提交
1315 1316
    if (initialParse) {
      pSql->fetchFp = pSql->fp;
H
hjxilinx 已提交
1317
      pSql->fp = (void(*)())tscHandleMultivnodeInsert;
H
hzcheng 已提交
1318 1319
    }

1320
    ret = tsParseInsertSql(pSql);
H
hzcheng 已提交
1321
  } else {
S
slguan 已提交
1322
    ret = tscAllocPayload(&pSql->cmd, TSDB_DEFAULT_PAYLOAD_SIZE);
1323 1324 1325 1326
    if (TSDB_CODE_SUCCESS != ret) {
      return ret;
    }
    
H
hzcheng 已提交
1327 1328
    SSqlInfo SQLInfo = {0};
    tSQLParse(&SQLInfo, pSql->sqlstr);
S
slguan 已提交
1329

H
hzcheng 已提交
1330 1331 1332 1333 1334
    ret = tscToSQLCmd(pSql, &SQLInfo);
    SQLInfoDestroy(&SQLInfo);
  }

  /*
1335 1336 1337
   * the pRes->code may be modified or released by another thread in tscTableMetaCallBack function,
   * so do NOT use pRes->code to determine if the getTableMeta/getMetricMeta function
   * invokes new threads to get data from mgmt node or simply retrieves data from cache.
H
hzcheng 已提交
1338
   *
1339
   * do NOT assign return code to pRes->code for the same reason since it may be released by another thread
H
hzcheng 已提交
1340 1341 1342 1343 1344
   * pRes->code = ret;
   */
  return ret;
}

S
slguan 已提交
1345 1346 1347
static int doPackSendDataBlock(SSqlObj *pSql, int32_t numOfRows, STableDataBlocks *pTableDataBlocks) {
  int32_t  code = TSDB_CODE_SUCCESS;
  SSqlCmd *pCmd = &pSql->cmd;
S
slguan 已提交
1348

1349
  assert(pCmd->numOfClause == 1);
1350
  STableMeta *pTableMeta = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0)->pTableMeta;
S
slguan 已提交
1351

1352
  SSubmitBlk *pBlocks = (SSubmitBlk *)(pTableDataBlocks->pData);
H
hjxilinx 已提交
1353
  tsSetBlockInfo(pBlocks, pTableMeta, numOfRows);
S
slguan 已提交
1354

S
slguan 已提交
1355 1356 1357
  if ((code = tscMergeTableDataBlocks(pSql, pCmd->pDataBlocks)) != TSDB_CODE_SUCCESS) {
    return code;
  }
S
slguan 已提交
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371

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

L
[1292]  
lihui 已提交
1372
static int tscInsertDataFromFile(SSqlObj *pSql, FILE *fp, char *tmpTokenBuf) {
S
slguan 已提交
1373 1374 1375 1376
  size_t          readLen = 0;
  char *          line = NULL;
  size_t          n = 0;
  int             len = 0;
L
lihui 已提交
1377
  int32_t         maxRows = 0;
S
slguan 已提交
1378 1379 1380 1381
  SSqlCmd *       pCmd = &pSql->cmd;
  int             numOfRows = 0;
  int32_t         code = 0;
  int             nrows = 0;
1382
  
1383
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1384
  STableMeta *    pTableMeta = pTableMetaInfo->pTableMeta;
H
hjxilinx 已提交
1385
  STableComInfo tinfo = tscGetTableInfo(pTableMeta);
H
hjxilinx 已提交
1386
  
1387 1388
  assert(pCmd->numOfClause == 1);
  
H
hjxilinx 已提交
1389
  int32_t rowSize = tinfo.rowSize;
S
slguan 已提交
1390 1391

  pCmd->pDataBlocks = tscCreateBlockArrayList();
H
hjxilinx 已提交
1392
  STableDataBlocks *pTableDataBlock = NULL;
1393
  int32_t           ret = tscCreateDataBlock(TSDB_PAYLOAD_SIZE, rowSize, sizeof(SSubmitBlk),
H
hjxilinx 已提交
1394
                                   pTableMetaInfo->name, pTableMeta, &pTableDataBlock);
H
hjxilinx 已提交
1395 1396 1397
  if (ret != TSDB_CODE_SUCCESS) {
    return -1;
  }
1398

S
slguan 已提交
1399 1400
  tscAppendDataBlock(pCmd->pDataBlocks, pTableDataBlock);

L
lihui 已提交
1401 1402
  code = tscAllocateMemIfNeed(pTableDataBlock, rowSize, &maxRows);
  if (TSDB_CODE_SUCCESS != code) return -1;
H
hzcheng 已提交
1403 1404

  int                count = 0;
H
hjxilinx 已提交
1405 1406
  SParsedDataColInfo spd = {.numOfCols = tinfo.numOfColumns};
  SSchema *          pSchema = tscGetTableSchema(pTableMeta);
H
hzcheng 已提交
1407

H
hjxilinx 已提交
1408
  tscSetAssignedColumnInfo(&spd, pSchema, tinfo.numOfColumns);
H
hzcheng 已提交
1409

H
huili 已提交
1410
  while ((readLen = getline(&line, &n, fp)) != -1) {
H
hzcheng 已提交
1411 1412
    // line[--readLen] = '\0';
    if (('\r' == line[readLen - 1]) || ('\n' == line[readLen - 1])) line[--readLen] = 0;
1413
    if (readLen == 0) continue;  // fang, <= to ==
H
huili 已提交
1414

S
slguan 已提交
1415
    char *lineptr = line;
H
hzcheng 已提交
1416
    strtolower(line, line);
H
hjxilinx 已提交
1417
    
H
hjxilinx 已提交
1418
    len = tsParseOneRowData(&lineptr, pTableDataBlock, pSchema, &spd, pCmd->payload, tinfo.precision, &code, tmpTokenBuf);
S
slguan 已提交
1419
    if (len <= 0 || pTableDataBlock->numOfParams > 0) {
L
[1292]  
lihui 已提交
1420 1421
      pSql->res.code = code;
      return (-code);
S
slguan 已提交
1422
    }
1423

S
slguan 已提交
1424
    pTableDataBlock->size += len;
H
hzcheng 已提交
1425 1426 1427 1428

    count++;
    nrows++;
    if (count >= maxRows) {
S
slguan 已提交
1429 1430
      if ((code = doPackSendDataBlock(pSql, count, pTableDataBlock)) != TSDB_CODE_SUCCESS) {
        return -code;
H
hzcheng 已提交
1431
      }
S
slguan 已提交
1432 1433

      pTableDataBlock = pCmd->pDataBlocks->pData[0];
1434
      pTableDataBlock->size = sizeof(SSubmitBlk);
H
hjxilinx 已提交
1435
      pTableDataBlock->rowSize = tinfo.rowSize;
S
slguan 已提交
1436

H
hzcheng 已提交
1437
      numOfRows += pSql->res.numOfRows;
S
slguan 已提交
1438
      pSql->res.numOfRows = 0;
H
hzcheng 已提交
1439 1440 1441 1442 1443
      count = 0;
    }
  }

  if (count > 0) {
S
slguan 已提交
1444 1445
    if ((code = doPackSendDataBlock(pSql, count, pTableDataBlock)) != TSDB_CODE_SUCCESS) {
      return -code;
H
hzcheng 已提交
1446
    }
S
slguan 已提交
1447

H
hzcheng 已提交
1448
    numOfRows += pSql->res.numOfRows;
S
slguan 已提交
1449
    pSql->res.numOfRows = 0;
H
hzcheng 已提交
1450 1451 1452
  }

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

H
hzcheng 已提交
1454 1455 1456
  return numOfRows;
}

1457
void tscProcessMultiVnodesInsertFromFile(SSqlObj *pSql) {
S
slguan 已提交
1458
  SSqlCmd *pCmd = &pSql->cmd;
H
hzcheng 已提交
1459 1460 1461 1462
  if (pCmd->command != TSDB_SQL_INSERT) {
    return;
  }

1463
  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
hjxilinx 已提交
1464
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
1465

S
slguan 已提交
1466 1467
  STableDataBlocks *pDataBlock = NULL;
  int32_t           affected_rows = 0;
H
hzcheng 已提交
1468

1469
  assert(pCmd->dataSourceType == DATA_FROM_DATA_FILE && pCmd->pDataBlocks != NULL);
S
slguan 已提交
1470 1471
  SDataBlockList *pDataBlockList = pCmd->pDataBlocks;
  pCmd->pDataBlocks = NULL;
H
hzcheng 已提交
1472

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

S
slguan 已提交
1475 1476
  for (int32_t i = 0; i < pDataBlockList->nSize; ++i) {
    pDataBlock = pDataBlockList->pData[i];
H
hzcheng 已提交
1477 1478 1479
    if (pDataBlock == NULL) {
      continue;
    }
1480

S
slguan 已提交
1481 1482 1483 1484
    if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, TSDB_PAYLOAD_SIZE)) {
      tscError("%p failed to malloc when insert file", pSql);
      continue;
    }
H
hzcheng 已提交
1485 1486
    pCmd->count = 1;

S
slguan 已提交
1487 1488 1489
    strncpy(path, pDataBlock->filename, PATH_MAX);

    FILE *fp = fopen(path, "r");
H
hzcheng 已提交
1490
    if (fp == NULL) {
S
slguan 已提交
1491
      tscError("%p failed to open file %s to load data from file, reason:%s", pSql, path, strerror(errno));
H
hzcheng 已提交
1492 1493 1494
      continue;
    }

H
hjxilinx 已提交
1495
    strncpy(pTableMetaInfo->name, pDataBlock->tableId, TSDB_TABLE_ID_LEN);
S
slguan 已提交
1496 1497
    memset(pDataBlock->pData, 0, pDataBlock->nAllocSize);

H
hjxilinx 已提交
1498
    int32_t ret = tscGetTableMeta(pSql, pTableMetaInfo);
S
slguan 已提交
1499 1500 1501 1502
    if (ret != TSDB_CODE_SUCCESS) {
      tscError("%p get meter meta failed, abort", pSql);
      continue;
    }
1503 1504

    char *tmpTokenBuf = calloc(1, 4096);  // used for deleting Escape character: \\, \', \"
L
[1292]  
lihui 已提交
1505 1506 1507 1508
    if (NULL == tmpTokenBuf) {
      tscError("%p calloc failed", pSql);
      continue;
    }
S
slguan 已提交
1509

L
[1292]  
lihui 已提交
1510 1511
    int nrows = tscInsertDataFromFile(pSql, fp, tmpTokenBuf);
    free(tmpTokenBuf);
1512

S
slguan 已提交
1513 1514
    pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);

H
hzcheng 已提交
1515 1516
    if (nrows < 0) {
      fclose(fp);
S
slguan 已提交
1517
      tscTrace("%p no records(%d) in file %s", pSql, nrows, path);
H
hzcheng 已提交
1518 1519 1520
      continue;
    }

S
slguan 已提交
1521
    fclose(fp);
H
hzcheng 已提交
1522 1523
    affected_rows += nrows;

S
slguan 已提交
1524
    tscTrace("%p Insert data %d records from file %s", pSql, nrows, path);
H
hzcheng 已提交
1525 1526 1527 1528 1529
  }

  pSql->res.numOfRows = affected_rows;

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