tscParseInsert.c 47.3 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
static int32_t tscToInteger(SSQLToken *pToken, int64_t *value, char **endPtr) {
45 46 47 48
  if (pToken->n == 0) {
    return TK_ILLEGAL;
  }
  
L
lihui 已提交
49
  errno = 0;
B
Bomin Zhang 已提交
50 51 52 53 54 55 56 57 58 59
  *value = strtoll(pToken->z, endPtr, 0);
  if (**endPtr == 'e' || **endPtr == 'E' || **endPtr == '.') {
    errno = 0;
    double v = round(strtod(pToken->z, endPtr));
    if (v > INT64_MAX || v <= INT64_MIN) {
      errno = ERANGE;
    } else {
      *value = v;
    }
  }
60 61
  
  // not a valid integer number, return error
B
Bomin Zhang 已提交
62
  if (*endPtr - pToken->z != pToken->n) {
63 64
    return TK_ILLEGAL;
  }
S
slguan 已提交
65

H
Haojun Liao 已提交
66
  return pToken->type;
H
hzcheng 已提交
67 68
}

S
slguan 已提交
69
static int32_t tscToDouble(SSQLToken *pToken, double *value, char **endPtr) {
70 71 72 73
  if (pToken->n == 0) {
    return TK_ILLEGAL;
  }
  
L
lihui 已提交
74
  errno = 0;
S
slguan 已提交
75
  *value = strtod(pToken->z, endPtr);
76 77
  
  // not a valid integer number, return error
B
Bomin Zhang 已提交
78
  if ((*endPtr - pToken->z) != pToken->n) {
79 80
    return TK_ILLEGAL;
  }
B
Bomin Zhang 已提交
81 82

  return pToken->type;
S
slguan 已提交
83
}
H
hzcheng 已提交
84

S
slguan 已提交
85 86 87 88 89 90
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 已提交
91

S
slguan 已提交
92
  index = 0;
H
hzcheng 已提交
93

S
slguan 已提交
94
  if (pToken->type == TK_NOW) {
H
hzcheng 已提交
95
    useconds = taosGetTimestamp(timePrec);
S
slguan 已提交
96
  } else if (strncmp(pToken->z, "0", 1) == 0 && pToken->n == 1) {
H
hzcheng 已提交
97
    // do nothing
S
slguan 已提交
98 99
  } else if (pToken->type == TK_INTEGER) {
    useconds = str2int64(pToken->z);
H
hzcheng 已提交
100 101
  } else {
    // strptime("2001-11-12 18:31:01", "%Y-%m-%d %H:%M:%S", &tm);
dengyihao's avatar
dengyihao 已提交
102
    if (taosParseTime(pToken->z, time, pToken->n, timePrec, tsDaylight) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
103
      return tscInvalidSQLErrMsg(error, "invalid timestamp format", pToken->z);
H
hzcheng 已提交
104 105 106 107 108
    }

    return TSDB_CODE_SUCCESS;
  }

S
slguan 已提交
109 110 111 112
  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 已提交
113 114 115 116 117 118 119 120
      *time = useconds;
      return 0;
    }

    break;
  }

  /*
S
slguan 已提交
121 122 123
   * time expression:
   * e.g., now+12a, now-5h
   */
S
slguan 已提交
124 125 126 127
  SSQLToken valueToken;
  index = 0;
  sToken = tStrGetToken(pTokenEnd, &index, false, 0, NULL);
  pTokenEnd += index;
128

S
slguan 已提交
129 130 131 132
  if (sToken.type == TK_MINUS || sToken.type == TK_PLUS) {
    index = 0;
    valueToken = tStrGetToken(pTokenEnd, &index, false, 0, NULL);
    pTokenEnd += index;
133

S
slguan 已提交
134
    if (valueToken.n < 2) {
H
hjxilinx 已提交
135
      return tscInvalidSQLErrMsg(error, "value expected in timestamp", sToken.z);
H
hzcheng 已提交
136 137
    }

S
slguan 已提交
138
    if (getTimestampInUsFromStr(valueToken.z, valueToken.n, &interval) != TSDB_CODE_SUCCESS) {
139
      return TSDB_CODE_TSC_INVALID_SQL;
H
hzcheng 已提交
140
    }
141

H
hzcheng 已提交
142 143 144 145
    if (timePrec == TSDB_TIME_PRECISION_MILLI) {
      interval /= 1000;
    }

S
slguan 已提交
146
    if (sToken.type == TK_PLUS) {
H
hzcheng 已提交
147 148 149 150 151 152 153 154 155 156 157 158
      useconds += interval;
    } else {
      useconds = (useconds >= interval) ? useconds - interval : 0;
    }

    *next = pTokenEnd;
  }

  *time = useconds;
  return TSDB_CODE_SUCCESS;
}

S
slguan 已提交
159
int32_t tsParseOneColumnData(SSchema *pSchema, SSQLToken *pToken, char *payload, char *msg, char **str, bool primaryKey,
S
slguan 已提交
160 161 162
                             int16_t timePrec) {
  int64_t iv;
  int32_t numType;
S
slguan 已提交
163
  char *  endptr = NULL;
164 165
  errno = 0;  // clear the previous existed error information

H
hzcheng 已提交
166 167
  switch (pSchema->type) {
    case TSDB_DATA_TYPE_BOOL: {  // bool
S
slguan 已提交
168 169
      if ((pToken->type == TK_BOOL || pToken->type == TK_STRING) && (pToken->n != 0)) {
        if (strncmp(pToken->z, "true", pToken->n) == 0) {
S
slguan 已提交
170
          *(uint8_t *)payload = TSDB_TRUE;
S
slguan 已提交
171
        } else if (strncmp(pToken->z, "false", pToken->n) == 0) {
S
slguan 已提交
172
          *(uint8_t *)payload = TSDB_FALSE;
S
slguan 已提交
173 174
        } else if (strncasecmp(TSDB_DATA_NULL_STR_L, pToken->z, pToken->n) == 0) {
          *(uint8_t *)payload = TSDB_DATA_BOOL_NULL;
H
hzcheng 已提交
175
        } else {
H
hjxilinx 已提交
176
          return tscInvalidSQLErrMsg(msg, "invalid bool data", pToken->z);
H
hzcheng 已提交
177
        }
S
slguan 已提交
178 179 180 181 182 183 184 185 186
      } 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 已提交
187
        return tscInvalidSQLErrMsg(msg, "invalid bool data", pToken->z);
H
hzcheng 已提交
188 189 190 191
      }
      break;
    }
    case TSDB_DATA_TYPE_TINYINT:
S
slguan 已提交
192 193 194 195 196
      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 已提交
197
      } else {
S
slguan 已提交
198
        numType = tscToInteger(pToken, &iv, &endptr);
L
lihui 已提交
199
        if (TK_ILLEGAL == numType) {
H
hjxilinx 已提交
200
          return tscInvalidSQLErrMsg(msg, "invalid tinyint data", pToken->z);
L
lihui 已提交
201
        } else if (errno == ERANGE || iv > INT8_MAX || iv <= INT8_MIN) {
H
hjxilinx 已提交
202
          return tscInvalidSQLErrMsg(msg, "tinyint data overflow", pToken->z);
H
hzcheng 已提交
203 204
        }

205
        *((int8_t *)payload) = (int8_t)iv;
H
hzcheng 已提交
206 207 208 209 210
      }

      break;

    case TSDB_DATA_TYPE_SMALLINT:
S
slguan 已提交
211 212 213 214 215
      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 已提交
216
      } else {
S
slguan 已提交
217
        numType = tscToInteger(pToken, &iv, &endptr);
L
lihui 已提交
218
        if (TK_ILLEGAL == numType) {
H
hjxilinx 已提交
219
          return tscInvalidSQLErrMsg(msg, "invalid smallint data", pToken->z);
L
lihui 已提交
220
        } else if (errno == ERANGE || iv > INT16_MAX || iv <= INT16_MIN) {
H
hjxilinx 已提交
221
          return tscInvalidSQLErrMsg(msg, "smallint data overflow", pToken->z);
H
hzcheng 已提交
222 223
        }

S
slguan 已提交
224
        *((int16_t *)payload) = (int16_t)iv;
H
hzcheng 已提交
225 226 227 228
      }
      break;

    case TSDB_DATA_TYPE_INT:
S
slguan 已提交
229 230 231 232
      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 已提交
233
        *((int32_t *)payload) = TSDB_DATA_INT_NULL;
H
hzcheng 已提交
234
      } else {
S
slguan 已提交
235
        numType = tscToInteger(pToken, &iv, &endptr);
L
lihui 已提交
236
        if (TK_ILLEGAL == numType) {
H
hjxilinx 已提交
237
          return tscInvalidSQLErrMsg(msg, "invalid int data", pToken->z);
L
lihui 已提交
238
        } else if (errno == ERANGE || iv > INT32_MAX || iv <= INT32_MIN) {
H
hjxilinx 已提交
239
          return tscInvalidSQLErrMsg(msg, "int data overflow", pToken->z);
H
hzcheng 已提交
240 241
        }

S
slguan 已提交
242
        *((int32_t *)payload) = (int32_t)iv;
H
hzcheng 已提交
243 244 245 246 247
      }

      break;

    case TSDB_DATA_TYPE_BIGINT:
S
slguan 已提交
248 249 250 251
      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 已提交
252
        *((int64_t *)payload) = TSDB_DATA_BIGINT_NULL;
H
hzcheng 已提交
253
      } else {
S
slguan 已提交
254
        numType = tscToInteger(pToken, &iv, &endptr);
L
lihui 已提交
255
        if (TK_ILLEGAL == numType) {
H
hjxilinx 已提交
256
          return tscInvalidSQLErrMsg(msg, "invalid bigint data", pToken->z);
B
Bomin Zhang 已提交
257
        } else if (errno == ERANGE || iv == INT64_MIN) {
H
hjxilinx 已提交
258
          return tscInvalidSQLErrMsg(msg, "bigint data overflow", pToken->z);
H
hzcheng 已提交
259
        }
S
slguan 已提交
260 261

        *((int64_t *)payload) = iv;
H
hzcheng 已提交
262 263 264 265
      }
      break;

    case TSDB_DATA_TYPE_FLOAT:
S
slguan 已提交
266 267 268 269
      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 已提交
270
        *((int32_t *)payload) = TSDB_DATA_FLOAT_NULL;
H
hzcheng 已提交
271
      } else {
S
slguan 已提交
272 273
        double dv;
        if (TK_ILLEGAL == tscToDouble(pToken, &dv, &endptr)) {
H
hjxilinx 已提交
274
          return tscInvalidSQLErrMsg(msg, "illegal float data", pToken->z);
S
slguan 已提交
275 276 277 278
        }

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

S
slguan 已提交
282 283
        if (isinf(fv) || isnan(fv)) {
          *((int32_t *)payload) = TSDB_DATA_FLOAT_NULL;
H
hzcheng 已提交
284
        }
S
slguan 已提交
285 286

        *((float *)payload) = fv;
H
hzcheng 已提交
287 288 289 290
      }
      break;

    case TSDB_DATA_TYPE_DOUBLE:
S
slguan 已提交
291 292 293 294
      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 已提交
295
        *((int64_t *)payload) = TSDB_DATA_DOUBLE_NULL;
H
hzcheng 已提交
296
      } else {
S
slguan 已提交
297 298
        double dv;
        if (TK_ILLEGAL == tscToDouble(pToken, &dv, &endptr)) {
H
hjxilinx 已提交
299
          return tscInvalidSQLErrMsg(msg, "illegal double data", pToken->z);
H
hzcheng 已提交
300 301
        }

S
slguan 已提交
302
        if (((dv == HUGE_VAL || dv == -HUGE_VAL) && errno == ERANGE) || (dv > DBL_MAX || dv < -DBL_MAX)) {
H
hjxilinx 已提交
303
          return tscInvalidSQLErrMsg(msg, "illegal double data", pToken->z);
S
slguan 已提交
304 305 306 307 308 309
        }

        if (isinf(dv) || isnan(dv)) {
          *((int64_t *)payload) = TSDB_DATA_DOUBLE_NULL;
        } else {
          *((double *)payload) = dv;
H
hzcheng 已提交
310 311 312 313 314
        }
      }
      break;

    case TSDB_DATA_TYPE_BINARY:
S
slguan 已提交
315 316
      // binary data cannot be null-terminated char string, otherwise the last char of the string is lost
      if (pToken->type == TK_NULL) {
317
        setVardataNull(payload, TSDB_DATA_TYPE_BINARY);
H
hjxilinx 已提交
318
      } else { // too long values will return invalid sql, not be truncated automatically
H
hjxilinx 已提交
319
        if (pToken->n + VARSTR_HEADER_SIZE > pSchema->bytes) { //todo refactor
H
hjxilinx 已提交
320
          return tscInvalidSQLErrMsg(msg, "string data overflow", pToken->z);
S
slguan 已提交
321
        }
H
hjxilinx 已提交
322
        
323
        STR_WITH_SIZE_TO_VARSTR(payload, pToken->z, pToken->n);
H
hzcheng 已提交
324 325 326 327 328
      }

      break;

    case TSDB_DATA_TYPE_NCHAR:
S
slguan 已提交
329
      if (pToken->type == TK_NULL) {
330
        setVardataNull(payload, TSDB_DATA_TYPE_NCHAR);
H
hzcheng 已提交
331
      } else {
H
hjxilinx 已提交
332
        // if the converted output len is over than pColumnModel->bytes, return error: 'Argument list too long'
333 334
        size_t output = 0;
        if (!taosMbsToUcs4(pToken->z, pToken->n, varDataVal(payload), pSchema->bytes - VARSTR_HEADER_SIZE, &output)) {
H
hjxilinx 已提交
335 336
          char buf[512] = {0};
          snprintf(buf, tListLen(buf), "%s", strerror(errno));
H
hjxilinx 已提交
337
          return tscInvalidSQLErrMsg(msg, buf, pToken->z);
H
hzcheng 已提交
338
        }
339
        
340
        varDataSetLen(payload, output);
H
hzcheng 已提交
341 342 343 344
      }
      break;

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

      break;
    }
  }

H
hjxilinx 已提交
364
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
365 366
}

S
slguan 已提交
367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
/*
 * 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 已提交
387
      return -1;  // client time/server time can not be mixed
388

S
slguan 已提交
389 390 391 392 393 394 395 396 397 398 399 400 401
    } 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 已提交
402
int tsParseOneRowData(char **str, STableDataBlocks *pDataBlocks, SSchema schema[], SParsedDataColInfo *spd, char *error,
403 404
                      int16_t timePrec, int32_t *code, char *tmpTokenBuf) {
  int32_t index = 0;
H
hjxilinx 已提交
405
  SSQLToken sToken = {0};
S
slguan 已提交
406
  char *    payload = pDataBlocks->pData + pDataBlocks->size;
S
slguan 已提交
407

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

S
slguan 已提交
417 418 419 420 421 422 423 424 425
    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;
      }
426

S
slguan 已提交
427
      strcpy(error, "client out of memory");
428
      *code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
hzcheng 已提交
429 430 431
      return -1;
    }

432 433 434
    int16_t type = sToken.type;
    if ((type != TK_NOW && type != TK_INTEGER && type != TK_STRING && type != TK_FLOAT && type != TK_BOOL &&
         type != TK_NULL && type != TK_HEX && type != TK_OCT && type != TK_BIN) || (sToken.n == 0) || (type == TK_RP)) {
H
hjxilinx 已提交
435
      tscInvalidSQLErrMsg(error, "invalid data or symbol", sToken.z);
436
      *code = TSDB_CODE_TSC_INVALID_SQL;
S
slguan 已提交
437
      return -1;
H
hzcheng 已提交
438 439
    }

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

L
[NONE]  
lihui 已提交
457
        tmpTokenBuf[j] = sToken.z[k];
L
[1292]  
lihui 已提交
458 459
        j++;
      }
460
      tmpTokenBuf[j] = 0;
L
[1292]  
lihui 已提交
461
      sToken.z = tmpTokenBuf;
462
      sToken.n -= 2 + cnt;
H
hzcheng 已提交
463 464
    }

S
slguan 已提交
465 466
    bool    isPrimaryKey = (colIndex == PRIMARYKEY_TIMESTAMP_COL_INDEX);
    int32_t ret = tsParseOneColumnData(pSchema, &sToken, start, error, str, isPrimaryKey, timePrec);
S
slguan 已提交
467
    if (ret != TSDB_CODE_SUCCESS) {
468
      *code = TSDB_CODE_TSC_INVALID_SQL;
H
hzcheng 已提交
469 470
      return -1;  // NOTE: here 0 mean error!
    }
471

S
slguan 已提交
472
    if (isPrimaryKey && tsCheckTimestamp(pDataBlocks, start) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
473
      tscInvalidSQLErrMsg(error, "client time/server time can not be mixed up", sToken.z);
474
      *code = TSDB_CODE_TSC_INVALID_TIME_STAMP;
S
slguan 已提交
475
      return -1;
476
    }
H
hzcheng 已提交
477 478
  }

S
slguan 已提交
479
  // 2. set the null value for the columns that do not assign values
480
  if (spd->numOfAssignedCols < spd->numOfCols) {
S
slguan 已提交
481
    char *ptr = payload;
H
hzcheng 已提交
482 483

    for (int32_t i = 0; i < spd->numOfCols; ++i) {
484
      
485
      if (!spd->hasVal[i]) {  // current column do not have any value to insert, set it to null
486 487 488 489 490 491 492 493 494
        if (schema[i].type == TSDB_DATA_TYPE_BINARY) {
          varDataSetLen(ptr, sizeof(int8_t));
          *(uint8_t*) varDataVal(ptr) = TSDB_DATA_BINARY_NULL;
        } else if (schema[i].type == TSDB_DATA_TYPE_NCHAR) {
          varDataSetLen(ptr, sizeof(int32_t));
          *(uint32_t*) varDataVal(ptr) = TSDB_DATA_NCHAR_NULL;
        } else {
          setNull(ptr, schema[i].type, schema[i].bytes);
        }
H
hzcheng 已提交
495
      }
496
      
H
hzcheng 已提交
497 498 499 500 501 502 503 504 505
      ptr += schema[i].bytes;
    }

    rowSize = ptr - payload;
  }

  return rowSize;
}

S
slguan 已提交
506 507 508 509 510 511 512 513 514
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;
  }
515 516
}

H
hjxilinx 已提交
517
int tsParseValues(char **str, STableDataBlocks *pDataBlock, STableMeta *pTableMeta, int maxRows,
518
                  SParsedDataColInfo *spd, char *error, int32_t *code, char *tmpTokenBuf) {
S
slguan 已提交
519 520
  int32_t   index = 0;
  SSQLToken sToken;
H
hzcheng 已提交
521 522 523

  int16_t numOfRows = 0;

H
hjxilinx 已提交
524
  SSchema *pSchema = tscGetTableSchema(pTableMeta);
H
hjxilinx 已提交
525
  STableComInfo tinfo = tscGetTableInfo(pTableMeta);
H
hjxilinx 已提交
526 527
  
  int32_t  precision = tinfo.precision;
S
slguan 已提交
528 529

  if (spd->hasVal[0] == false) {
S
slguan 已提交
530
    strcpy(error, "primary timestamp column can not be null");
531
    *code = TSDB_CODE_TSC_INVALID_SQL;
H
hzcheng 已提交
532 533 534 535
    return -1;
  }

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

S
slguan 已提交
540
    *str += index;
H
hjxilinx 已提交
541
    if (numOfRows >= maxRows || pDataBlock->size + tinfo.rowSize >= pDataBlock->nAllocSize) {
L
lihui 已提交
542
      int32_t tSize;
H
hjxilinx 已提交
543
      int32_t retcode = tscAllocateMemIfNeed(pDataBlock, tinfo.rowSize, &tSize);
L
lihui 已提交
544
      if (retcode != TSDB_CODE_SUCCESS) {  //TODO pass the correct error code to client
S
slguan 已提交
545
        strcpy(error, "client out of memory");
L
lihui 已提交
546
        *code = retcode;
S
slguan 已提交
547 548
        return -1;
      }
L
lihui 已提交
549 550
      ASSERT(tSize > maxRows);
      maxRows = tSize;
H
hzcheng 已提交
551 552
    }

L
[1292]  
lihui 已提交
553
    int32_t len = tsParseOneRowData(str, pDataBlock, pSchema, spd, error, precision, code, tmpTokenBuf);
554
    if (len <= 0) {  // error message has been set in tsParseOneRowData
H
hzcheng 已提交
555 556 557 558 559
      return -1;
    }

    pDataBlock->size += len;

S
slguan 已提交
560 561 562 563
    index = 0;
    sToken = tStrGetToken(*str, &index, false, 0, NULL);
    *str += index;
    if (sToken.n == 0 || sToken.type != TK_RP) {
H
hjxilinx 已提交
564
      tscInvalidSQLErrMsg(error, ") expected", *str);
565
      *code = TSDB_CODE_TSC_INVALID_SQL;
H
hzcheng 已提交
566 567 568 569 570 571 572 573
      return -1;
    }

    numOfRows++;
  }

  if (numOfRows <= 0) {
    strcpy(error, "no any data points");
574
    *code = TSDB_CODE_TSC_INVALID_SQL;
S
slguan 已提交
575 576 577
    return -1;
  } else {
    return numOfRows;
H
hzcheng 已提交
578 579 580
  }
}

S
slguan 已提交
581
static void tscSetAssignedColumnInfo(SParsedDataColInfo *spd, SSchema *pSchema, int32_t numOfCols) {
H
hzcheng 已提交
582
  spd->numOfCols = numOfCols;
583
  spd->numOfAssignedCols = numOfCols;
H
hzcheng 已提交
584 585 586 587 588 589 590 591 592 593 594

  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 已提交
595
int32_t tscAllocateMemIfNeed(STableDataBlocks *pDataBlock, int32_t rowSize, int32_t * numOfRows) {
S
slguan 已提交
596
  size_t    remain = pDataBlock->nAllocSize - pDataBlock->size;
S
slguan 已提交
597
  const int factor = 5;
S
slguan 已提交
598
  uint32_t nAllocSizeOld = pDataBlock->nAllocSize;
L
[#1102]  
lihui 已提交
599
  
H
hzcheng 已提交
600
  // expand the allocated size
S
slguan 已提交
601 602
  if (remain < rowSize * factor) {
    while (remain < rowSize * factor) {
S
slguan 已提交
603
      pDataBlock->nAllocSize = (uint32_t)(pDataBlock->nAllocSize * 1.5);
S
slguan 已提交
604 605
      remain = pDataBlock->nAllocSize - pDataBlock->size;
    }
H
hzcheng 已提交
606

S
slguan 已提交
607 608 609 610 611
    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 已提交
612
      // do nothing, if allocate more memory failed
S
slguan 已提交
613
      pDataBlock->nAllocSize = nAllocSizeOld;
L
[#1102]  
lihui 已提交
614
      *numOfRows = (int32_t)(pDataBlock->nAllocSize - pDataBlock->headerSize) / rowSize;
615
      return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
616
    }
H
hzcheng 已提交
617 618
  }

L
[#1102]  
lihui 已提交
619
  *numOfRows = (int32_t)(pDataBlock->nAllocSize - pDataBlock->headerSize) / rowSize;
L
lihui 已提交
620
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
621 622
}

623 624
static void tsSetBlockInfo(SSubmitBlk *pBlocks, const STableMeta *pTableMeta, int32_t numOfRows) {
  pBlocks->tid = pTableMeta->sid;
H
hjxilinx 已提交
625 626
  pBlocks->uid = pTableMeta->uid;
  pBlocks->sversion = pTableMeta->sversion;
S
slguan 已提交
627
  pBlocks->numOfRows += numOfRows;
H
hzcheng 已提交
628 629
}

S
slguan 已提交
630
// data block is disordered, sort it in ascending order
H
hjxilinx 已提交
631
void tscSortRemoveDataBlockDupRows(STableDataBlocks *dataBuf) {
632
  SSubmitBlk *pBlocks = (SSubmitBlk *)dataBuf->pData;
S
slguan 已提交
633 634

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

S
slguan 已提交
637 638 639 640 641
  // if use server time, this block must be ordered
  if (dataBuf->tsSource == TSDB_USE_SERVER_TS) {
    assert(dataBuf->ordered);
  }

S
slguan 已提交
642
  if (!dataBuf->ordered) {
643
    char *pBlockData = pBlocks->data;
S
slguan 已提交
644
    qsort(pBlockData, pBlocks->numOfRows, dataBuf->rowSize, rowDataCompar);
H
hzcheng 已提交
645

S
slguan 已提交
646 647
    int32_t i = 0;
    int32_t j = 1;
H
hzcheng 已提交
648

S
slguan 已提交
649
    while (j < pBlocks->numOfRows) {
S
slguan 已提交
650 651
      TSKEY ti = *(TSKEY *)(pBlockData + dataBuf->rowSize * i);
      TSKEY tj = *(TSKEY *)(pBlockData + dataBuf->rowSize * j);
H
hzcheng 已提交
652

S
slguan 已提交
653 654 655 656
      if (ti == tj) {
        ++j;
        continue;
      }
H
hzcheng 已提交
657

S
slguan 已提交
658 659 660 661 662 663 664 665 666
      int32_t nextPos = (++i);
      if (nextPos != j) {
        memmove(pBlockData + dataBuf->rowSize * nextPos, pBlockData + dataBuf->rowSize * j, dataBuf->rowSize);
      }

      ++j;
    }

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

S
slguan 已提交
668
    pBlocks->numOfRows = i + 1;
669
    dataBuf->size = sizeof(SSubmitBlk) + dataBuf->rowSize * pBlocks->numOfRows;
S
slguan 已提交
670
  }
S
slguan 已提交
671 672
}

673
static int32_t doParseInsertStatement(SSqlObj *pSql, void *pTableList, char **str, SParsedDataColInfo *spd,
S
slguan 已提交
674
                                      int32_t *totalNum) {
S
slguan 已提交
675
  SSqlCmd *       pCmd = &pSql->cmd;
676
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
677
  STableMeta *    pTableMeta = pTableMetaInfo->pTableMeta;
H
hjxilinx 已提交
678
  STableComInfo tinfo = tscGetTableInfo(pTableMeta);
H
hjxilinx 已提交
679
  
H
hjxilinx 已提交
680
  STableDataBlocks *dataBuf = NULL;
681
  int32_t ret = tscGetDataBlockFromList(pTableList, pCmd->pDataBlocks, pTableMeta->uid, TSDB_DEFAULT_PAYLOAD_SIZE,
682
                                        sizeof(SSubmitBlk), tinfo.rowSize, pTableMetaInfo->name,
H
hjxilinx 已提交
683
                                        pTableMeta, &dataBuf);
H
hjxilinx 已提交
684 685 686 687
  if (ret != TSDB_CODE_SUCCESS) {
    return ret;
  }
  
L
lihui 已提交
688
  int32_t maxNumOfRows;
H
hjxilinx 已提交
689
  ret = tscAllocateMemIfNeed(dataBuf, tinfo.rowSize, &maxNumOfRows);
L
lihui 已提交
690
  if (TSDB_CODE_SUCCESS != ret) {
691
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
S
slguan 已提交
692
  }
693

694
  int32_t code = TSDB_CODE_TSC_INVALID_SQL;
695
  char *  tmpTokenBuf = calloc(1, 4096);  // used for deleting Escape character: \\, \', \"
L
[1292]  
lihui 已提交
696
  if (NULL == tmpTokenBuf) {
697
    return TSDB_CODE_TSC_OUT_OF_MEMORY;
L
[1292]  
lihui 已提交
698
  }
L
lihui 已提交
699

H
hjxilinx 已提交
700
  int32_t numOfRows = tsParseValues(str, dataBuf, pTableMeta, maxNumOfRows, spd, pCmd->payload, &code, tmpTokenBuf);
L
[1292]  
lihui 已提交
701
  free(tmpTokenBuf);
H
hzcheng 已提交
702
  if (numOfRows <= 0) {
L
[1292]  
lihui 已提交
703
    return code;
H
hzcheng 已提交
704 705
  }

S
slguan 已提交
706
  for (uint32_t i = 0; i < dataBuf->numOfParams; ++i) {
707
    SParamInfo *param = dataBuf->params + i;
S
slguan 已提交
708 709
    if (param->idx == -1) {
      param->idx = pCmd->numOfParams++;
710
      param->offset -= sizeof(SSubmitBlk);
S
slguan 已提交
711 712 713
    }
  }

714
  SSubmitBlk *pBlocks = (SSubmitBlk *)(dataBuf->pData);
H
hjxilinx 已提交
715
  tsSetBlockInfo(pBlocks, pTableMeta, numOfRows);
S
slguan 已提交
716

H
hjxilinx 已提交
717
  dataBuf->vgId = pTableMeta->vgroupInfo.vgId;
S
slguan 已提交
718
  dataBuf->numOfTables = 1;
H
hzcheng 已提交
719 720

  /*
S
slguan 已提交
721 722
   * the value of pRes->numOfRows does not affect the true result of AFFECTED ROWS,
   * which is actually returned from server.
H
hzcheng 已提交
723
   */
S
slguan 已提交
724
  *totalNum += numOfRows;
H
hzcheng 已提交
725 726 727
  return TSDB_CODE_SUCCESS;
}

728
static int32_t tscCheckIfCreateTable(char **sqlstr, SSqlObj *pSql) {
S
slguan 已提交
729
  int32_t   index = 0;
730 731
  SSQLToken sToken = {0};
  SSQLToken tableToken = {0};
S
slguan 已提交
732
  int32_t   code = TSDB_CODE_SUCCESS;
733 734 735 736 737 738
  
  const int32_t TABLE_INDEX = 0;
  const int32_t STABLE_INDEX = 1;
  
  SSqlCmd *   pCmd = &pSql->cmd;
  SQueryInfo *pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
hzcheng 已提交
739

S
slguan 已提交
740
  char *sql = *sqlstr;
741

S
slguan 已提交
742 743 744 745
  // get the token of specified table
  index = 0;
  tableToken = tStrGetToken(sql, &index, false, 0, NULL);
  sql += index;
H
hzcheng 已提交
746

S
slguan 已提交
747 748
  char *cstart = NULL;
  char *cend = NULL;
H
hzcheng 已提交
749

S
slguan 已提交
750 751 752 753 754
  // skip possibly exists column list
  index = 0;
  sToken = tStrGetToken(sql, &index, false, 0, NULL);
  sql += index;

H
hzcheng 已提交
755
  int32_t numOfColList = 0;
S
slguan 已提交
756
  bool    createTable = false;
H
hzcheng 已提交
757

S
slguan 已提交
758 759 760
  if (sToken.type == TK_LP) {
    cstart = &sToken.z[0];
    index = 0;
H
hzcheng 已提交
761
    while (1) {
S
slguan 已提交
762 763 764
      sToken = tStrGetToken(sql, &index, false, 0, NULL);
      if (sToken.type == TK_RP) {
        cend = &sToken.z[0];
H
hzcheng 已提交
765 766 767 768 769 770
        break;
      }

      ++numOfColList;
    }

S
slguan 已提交
771 772
    sToken = tStrGetToken(sql, &index, false, 0, NULL);
    sql += index;
H
hzcheng 已提交
773 774 775
  }

  if (numOfColList == 0 && cstart != NULL) {
776
    return TSDB_CODE_TSC_INVALID_SQL;
H
hzcheng 已提交
777
  }
778
  
H
hjxilinx 已提交
779
  STableMetaInfo* pTableMetaInfo = tscGetMetaInfo(pQueryInfo, TABLE_INDEX);
780 781
  
  if (sToken.type == TK_USING) {  // create table if not exists according to the super table
S
slguan 已提交
782 783 784 785
    index = 0;
    sToken = tStrGetToken(sql, &index, false, 0, NULL);
    sql += index;

S
slguan 已提交
786
    STagData *pTag = (STagData *)pCmd->payload;
S
slguan 已提交
787
    memset(pTag, 0, sizeof(STagData));
788 789
    
    /*
H
hjxilinx 已提交
790
     * the source super table is moved to the secondary position of the pTableMetaInfo list
791 792
     */
    if (pQueryInfo->numOfTables < 2) {
H
hjxilinx 已提交
793
      tscAddEmptyMetaInfo(pQueryInfo);
794
    }
H
hzcheng 已提交
795

H
hjxilinx 已提交
796
    STableMetaInfo *pSTableMeterMetaInfo = tscGetMetaInfo(pQueryInfo, STABLE_INDEX);
H
Haojun Liao 已提交
797
    tscSetTableFullName(pSTableMeterMetaInfo, &sToken, pSql);
798

B
Bomin Zhang 已提交
799
    tstrncpy(pTag->name, pSTableMeterMetaInfo->name, sizeof(pTag->name));
H
hjxilinx 已提交
800
    code = tscGetTableMeta(pSql, pSTableMeterMetaInfo);
H
hzcheng 已提交
801 802 803 804
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

weixin_48148422's avatar
weixin_48148422 已提交
805
    if (!UTIL_TABLE_IS_SUPER_TABLE(pSTableMeterMetaInfo)) {
H
hjxilinx 已提交
806
      return tscInvalidSQLErrMsg(pCmd->payload, "create table only from super table is allowed", sToken.z);
S
slguan 已提交
807 808
    }

H
hjxilinx 已提交
809
    SSchema *pTagSchema = tscGetTableTagSchema(pSTableMeterMetaInfo->pTableMeta);
H
hjxilinx 已提交
810
    STableComInfo tinfo = tscGetTableInfo(pSTableMeterMetaInfo->pTableMeta);
H
hjxilinx 已提交
811
    
S
slguan 已提交
812 813 814
    index = 0;
    sToken = tStrGetToken(sql, &index, false, 0, NULL);
    sql += index;
L
lihui 已提交
815

816
    SParsedDataColInfo spd = {0};
H
hjxilinx 已提交
817 818
    
    uint8_t numOfTags = tscGetNumOfTags(pSTableMeterMetaInfo->pTableMeta);
L
lihui 已提交
819 820 821 822 823 824
    spd.numOfCols = numOfTags;

    // if specify some tags column
    if (sToken.type != TK_LP) {
      tscSetAssignedColumnInfo(&spd, pTagSchema, numOfTags);
    } else {
825 826
      /* insert into tablename (col1, col2,..., coln) using superTableName (tagName1, tagName2, ..., tagNamen)
       * tags(tagVal1, tagVal2, ..., tagValn) values(v1, v2,... vn); */
L
lihui 已提交
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) {
H
Haojun Liao 已提交
838 839
          strdequote(sToken.z);
          sToken.n = strtrim(sToken.z);
L
lihui 已提交
840 841 842 843 844 845 846 847 848 849 850 851
        }

        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++];
852
            pElem->offset = offset[t];
L
lihui 已提交
853 854 855 856 857 858
            pElem->colIndex = t;

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

859
            spd.hasVal[t] = true;
L
lihui 已提交
860 861 862 863 864 865 866 867 868 869 870 871 872
            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 已提交
873 874 875 876

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

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

S
slguan 已提交
883 884
    uint32_t ignoreTokenTypes = TK_LP;
    uint32_t numOfIgnoreToken = 1;
L
lihui 已提交
885
    for (int i = 0; i < spd.numOfAssignedCols; ++i) {
886
      char *  tagVal = pTag->data + spd.elems[i].offset;
L
lihui 已提交
887
      int16_t colIndex = spd.elems[i].colIndex;
888

S
slguan 已提交
889 890 891 892
      index = 0;
      sToken = tStrGetToken(sql, &index, true, numOfIgnoreToken, &ignoreTokenTypes);
      sql += index;
      if (sToken.n == 0) {
H
hzcheng 已提交
893
        break;
S
slguan 已提交
894 895 896
      } else if (sToken.type == TK_RP) {
        break;
      }
H
hzcheng 已提交
897

S
slguan 已提交
898 899 900 901
      // Remove quotation marks
      if (TK_STRING == sToken.type) {
        sToken.z++;
        sToken.n -= 2;
H
hzcheng 已提交
902 903
      }

H
hjxilinx 已提交
904
      code = tsParseOneColumnData(&pTagSchema[colIndex], &sToken, tagVal, pCmd->payload, &sql, false, tinfo.precision);
H
hzcheng 已提交
905
      if (code != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
906
        return code;
H
hzcheng 已提交
907 908
      }

909 910
      if ((pTagSchema[colIndex].type == TSDB_DATA_TYPE_BINARY || pTagSchema[colIndex].type == TSDB_DATA_TYPE_NCHAR) &&
          sToken.n > pTagSchema[colIndex].bytes) {
H
hjxilinx 已提交
911
        return tscInvalidSQLErrMsg(pCmd->payload, "string too long", sToken.z);
S
slguan 已提交
912
      }
L
lihui 已提交
913
    }
S
slguan 已提交
914

L
lihui 已提交
915 916 917 918 919
    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 已提交
920 921
    }

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

L
lihui 已提交
926
      for (int32_t i = 0; i < spd.numOfCols; ++i) {
927
        if (!spd.hasVal[i]) {  // current tag column do not have any value to insert, set it to null
928 929 930 931 932
          if (pTagSchema[i].type == TSDB_DATA_TYPE_BINARY || pTagSchema[i].type == TSDB_DATA_TYPE_NCHAR) {
            setVardataNull(ptr, pTagSchema[i].type);
          } else {
            setNull(ptr, pTagSchema[i].type, pTagSchema[i].bytes);
          }
L
lihui 已提交
933
        }
934

L
lihui 已提交
935
        ptr += pTagSchema[i].bytes;
936
      }
H
hzcheng 已提交
937 938
    }

939
    // 3. calculate the actual data size of STagData
940
    pCmd->payloadLen = sizeof(pTag->name) + sizeof(pTag->dataLen);
941
    for (int32_t t = 0; t < numOfTags; ++t) {
942
      pTag->dataLen += pTagSchema[t].bytes;
943 944
      pCmd->payloadLen += pTagSchema[t].bytes;
    }
945
    pTag->dataLen = htonl(pTag->dataLen);
946

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

H
Haojun Liao 已提交
951
    int32_t ret = tscSetTableFullName(pTableMetaInfo, &tableToken, pSql);
H
hzcheng 已提交
952 953 954 955 956
    if (ret != TSDB_CODE_SUCCESS) {
      return ret;
    }

    createTable = true;
H
hjxilinx 已提交
957
    code = tscGetMeterMetaEx(pSql, pTableMetaInfo, true);
958
    if (TSDB_CODE_TSC_ACTION_IN_PROGRESS == code) {
H
hjxilinx 已提交
959 960 961
      return code;
    }
    
H
hzcheng 已提交
962 963 964 965
  } else {
    if (cstart != NULL) {
      sql = cstart;
    } else {
S
slguan 已提交
966
      sql = sToken.z;
H
hzcheng 已提交
967
    }
B
Bomin Zhang 已提交
968
    code = tscGetMeterMetaEx(pSql, pTableMetaInfo, false);
H
hjxilinx 已提交
969
    
970
    if (pCmd->curSql == NULL) {
971
      assert(code == TSDB_CODE_TSC_ACTION_IN_PROGRESS);
H
hjxilinx 已提交
972
    }
H
hzcheng 已提交
973 974 975 976 977
  }

  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 已提交
978
    memmove(sql - len, cstart, len);
H
hzcheng 已提交
979 980 981 982 983
    *sqlstr = sql - len;
  } else {
    *sqlstr = sql;
  }

984
  if (*sqlstr == NULL) {
985
    code = TSDB_CODE_TSC_INVALID_SQL;
986 987
  }
  
H
hzcheng 已提交
988 989 990
  return code;
}

H
Hui Li 已提交
991
int validateTableName(char *tblName, int len, SSQLToken* psTblToken) {
S
slguan 已提交
992
  char buf[TSDB_TABLE_ID_LEN] = {0};
B
Bomin Zhang 已提交
993
  tstrncpy(buf, tblName, sizeof(buf));
S
slguan 已提交
994

H
Hui Li 已提交
995 996 997 998
  psTblToken->n    = len;
  psTblToken->type = TK_ID;
  psTblToken->z    = buf;
  tSQLGetToken(buf, &psTblToken->type);
S
slguan 已提交
999

H
Hui Li 已提交
1000
  return tscValidateName(psTblToken);
H
huili 已提交
1001 1002
}

1003 1004 1005 1006 1007 1008 1009 1010 1011
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 已提交
1012 1013 1014 1015 1016 1017 1018 1019 1020
/**
 * usage: insert into table1 values() () table2 values()()
 *
 * @param str
 * @param acct
 * @param db
 * @param pSql
 * @return
 */
H
Haojun Liao 已提交
1021
int tsParseInsertSql(SSqlObj *pSql) {
S
slguan 已提交
1022
  SSqlCmd *pCmd = &pSql->cmd;
H
Haojun Liao 已提交
1023
  char* str = pCmd->curSql;
1024

S
slguan 已提交
1025
  int32_t totalNum = 0;
1026 1027 1028 1029 1030
  int32_t code = TSDB_CODE_SUCCESS;

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

H
Haojun Liao 已提交
1031
  STableMetaInfo *pTableMetaInfo = NULL;
1032
  if (pQueryInfo->numOfTables == 0) {
H
hjxilinx 已提交
1033
    pTableMetaInfo = tscAddEmptyMetaInfo(pQueryInfo);
1034
  } else {
H
hjxilinx 已提交
1035
    pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
1036
  }
H
hzcheng 已提交
1037

H
Haojun Liao 已提交
1038
  // TODO: 2048 is added because TSDB_MAX_TAGS_LEN now is 65536, but TSDB_PAYLOAD_SIZE is 65380
B
Bomin Zhang 已提交
1039
  if ((code = tscAllocPayload(pCmd, TSDB_PAYLOAD_SIZE + 2048)) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
1040 1041 1042
    return code;
  }

H
Haojun Liao 已提交
1043
  if (NULL == pCmd->pTableList) {
1044
    pCmd->pTableList = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false);
1045

L
lihui 已提交
1046
    pSql->cmd.pDataBlocks = tscCreateBlockArrayList();
1047
    if (NULL == pCmd->pTableList || NULL == pSql->cmd.pDataBlocks) {
1048
      code = TSDB_CODE_TSC_OUT_OF_MEMORY;
H
Haojun Liao 已提交
1049
      goto _error;
L
lihui 已提交
1050 1051
    }
  } else {
1052
    str = pCmd->curSql;
L
lihui 已提交
1053 1054
  }
  
H
Haojun Liao 已提交
1055
  tscTrace("%p create data block list for submit data:%p, pTableList:%p", pSql, pCmd->pDataBlocks, pCmd->pTableList);
H
hzcheng 已提交
1056 1057

  while (1) {
1058
    int32_t   index = 0;
S
slguan 已提交
1059
    SSQLToken sToken = tStrGetToken(str, &index, false, 0, NULL);
1060 1061 1062 1063 1064 1065 1066 1067

    // 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 已提交
1068 1069 1070
        goto _clean;
      }

1071 1072 1073 1074 1075
      /*
       * 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) {
1076
        code = TSDB_CODE_TSC_INVALID_SQL;
H
Haojun Liao 已提交
1077
        goto _error;
1078 1079
      } else {
        break;
H
hzcheng 已提交
1080 1081 1082
      }
    }

1083
    pCmd->curSql = sToken.z;
H
Hui Li 已提交
1084
    SSQLToken sTblToken;
S
slguan 已提交
1085
    // Check if the table name available or not
H
Hui Li 已提交
1086
    if (validateTableName(sToken.z, sToken.n, &sTblToken) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1087
      code = tscInvalidSQLErrMsg(pCmd->payload, "table name invalid", sToken.z);
H
Haojun Liao 已提交
1088
      goto _error;
H
huili 已提交
1089 1090
    }

H
Hui Li 已提交
1091
    if ((code = tscSetTableFullName(pTableMetaInfo, &sTblToken, pSql)) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1092
      goto _error;
H
hzcheng 已提交
1093 1094
    }

1095 1096
    if ((code = tscCheckIfCreateTable(&str, pSql)) != TSDB_CODE_SUCCESS) {
      /*
H
Haojun Liao 已提交
1097 1098
       * After retrieving the table meta from server, the sql string will be parsed from the paused position.
       * And during the getTableMetaCallback function, the sql string will be parsed from the paused position.
1099
       */
1100
      if (TSDB_CODE_TSC_ACTION_IN_PROGRESS == code) {
H
hjxilinx 已提交
1101
        return code;
H
hzcheng 已提交
1102
      }
H
hjxilinx 已提交
1103
      
H
Haojun Liao 已提交
1104
      tscError("%p async insert parse error, code:%s", pSql, tstrerror(code));
1105
      pCmd->curSql = NULL;
H
Haojun Liao 已提交
1106
      goto _error;
H
hzcheng 已提交
1107 1108
    }

weixin_48148422's avatar
weixin_48148422 已提交
1109
    if (UTIL_TABLE_IS_SUPER_TABLE(pTableMetaInfo)) {
H
hjxilinx 已提交
1110
      code = tscInvalidSQLErrMsg(pCmd->payload, "insert data into super table is not supported", NULL);
H
Haojun Liao 已提交
1111
      goto _error;
H
hzcheng 已提交
1112 1113
    }

S
slguan 已提交
1114 1115 1116
    index = 0;
    sToken = tStrGetToken(str, &index, false, 0, NULL);
    str += index;
1117

S
slguan 已提交
1118
    if (sToken.n == 0) {
1119
      code = tscInvalidSQLErrMsg(pCmd->payload, "keyword VALUES or FILE required", sToken.z);
H
Haojun Liao 已提交
1120
      goto _error;
H
hzcheng 已提交
1121
    }
H
hjxilinx 已提交
1122
    
H
hjxilinx 已提交
1123
    STableComInfo tinfo = tscGetTableInfo(pTableMetaInfo->pTableMeta);
H
hjxilinx 已提交
1124
    
S
slguan 已提交
1125
    if (sToken.type == TK_VALUES) {
H
hjxilinx 已提交
1126
      SParsedDataColInfo spd = {.numOfCols = tinfo.numOfColumns};
H
hjxilinx 已提交
1127 1128
      
      SSchema *pSchema = tscGetTableSchema(pTableMetaInfo->pTableMeta);
H
hjxilinx 已提交
1129
      tscSetAssignedColumnInfo(&spd, pSchema, tinfo.numOfColumns);
H
hzcheng 已提交
1130

1131
      if (validateDataSource(pCmd, DATA_FROM_SQL_STRING, sToken.z) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1132
        goto _error;
H
hzcheng 已提交
1133 1134 1135 1136 1137 1138
      }

      /*
       * app here insert data in different vnodes, so we need to set the following
       * data in another submit procedure using async insert routines
       */
1139
      code = doParseInsertStatement(pSql, pCmd->pTableList, &str, &spd, &totalNum);
H
hzcheng 已提交
1140
      if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1141
        goto _error;
H
hzcheng 已提交
1142
      }
S
slguan 已提交
1143
    } else if (sToken.type == TK_FILE) {
1144
      if (validateDataSource(pCmd, DATA_FROM_DATA_FILE, sToken.z) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1145
        goto _error;
H
hzcheng 已提交
1146 1147
      }

S
slguan 已提交
1148 1149 1150 1151
      index = 0;
      sToken = tStrGetToken(str, &index, false, 0, NULL);
      str += index;
      if (sToken.n == 0) {
H
hjxilinx 已提交
1152
        code = tscInvalidSQLErrMsg(pCmd->payload, "file path is required following keyword FILE", sToken.z);
H
Haojun Liao 已提交
1153
        goto _error;
H
hzcheng 已提交
1154 1155
      }

S
slguan 已提交
1156
      char fname[PATH_MAX] = {0};
S
slguan 已提交
1157
      strncpy(fname, sToken.z, sToken.n);
S
slguan 已提交
1158
      strdequote(fname);
1159

H
hzcheng 已提交
1160 1161
      wordexp_t full_path;
      if (wordexp(fname, &full_path, 0) != 0) {
H
hjxilinx 已提交
1162
        code = tscInvalidSQLErrMsg(pCmd->payload, "invalid filename", sToken.z);
H
Haojun Liao 已提交
1163
        goto _error;
H
hzcheng 已提交
1164 1165 1166 1167
      }
      strcpy(fname, full_path.we_wordv[0]);
      wordfree(&full_path);

H
hjxilinx 已提交
1168
      STableDataBlocks *pDataBlock = NULL;
H
hjxilinx 已提交
1169
      STableMeta* pTableMeta = pTableMetaInfo->pTableMeta;
1170
      
1171
      int32_t ret = tscCreateDataBlock(PATH_MAX, tinfo.rowSize, sizeof(SSubmitBlk), pTableMetaInfo->name,
H
hjxilinx 已提交
1172
                                       pTableMeta, &pDataBlock);
H
hjxilinx 已提交
1173
      if (ret != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1174
        goto _error;
H
hjxilinx 已提交
1175
      }
1176

S
slguan 已提交
1177 1178
      tscAppendDataBlock(pCmd->pDataBlocks, pDataBlock);
      strcpy(pDataBlock->filename, fname);
S
slguan 已提交
1179
    } else if (sToken.type == TK_LP) {
H
hzcheng 已提交
1180
      /* insert into tablename(col1, col2,..., coln) values(v1, v2,... vn); */
1181
      STableMeta *pTableMeta = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0)->pTableMeta;
H
hjxilinx 已提交
1182
      SSchema *   pSchema = tscGetTableSchema(pTableMeta);
H
hzcheng 已提交
1183

1184
      if (validateDataSource(pCmd, DATA_FROM_SQL_STRING, sToken.z) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1185
        goto _error;
H
hzcheng 已提交
1186 1187
      }

1188
      SParsedDataColInfo spd = {0};
H
hjxilinx 已提交
1189
      spd.numOfCols = tinfo.numOfColumns;
H
hzcheng 已提交
1190 1191

      int16_t offset[TSDB_MAX_COLUMNS] = {0};
H
hjxilinx 已提交
1192
      for (int32_t t = 1; t < tinfo.numOfColumns; ++t) {
H
hzcheng 已提交
1193 1194 1195 1196
        offset[t] = offset[t - 1] + pSchema[t - 1].bytes;
      }

      while (1) {
S
slguan 已提交
1197 1198 1199 1200 1201
        index = 0;
        sToken = tStrGetToken(str, &index, false, 0, NULL);
        str += index;

        if (TK_STRING == sToken.type) {
H
Haojun Liao 已提交
1202 1203
          strdequote(sToken.z);
          sToken.n = strtrim(sToken.z);
S
slguan 已提交
1204 1205 1206
        }

        if (sToken.type == TK_RP) {
H
hzcheng 已提交
1207 1208 1209 1210 1211 1212
          break;
        }

        bool findColumnIndex = false;

        // todo speedup by using hash list
H
hjxilinx 已提交
1213
        for (int32_t t = 0; t < tinfo.numOfColumns; ++t) {
S
slguan 已提交
1214
          if (strncmp(sToken.z, pSchema[t].name, sToken.n) == 0 && strlen(pSchema[t].name) == sToken.n) {
S
slguan 已提交
1215
            SParsedColElem *pElem = &spd.elems[spd.numOfAssignedCols++];
H
hzcheng 已提交
1216 1217 1218 1219
            pElem->offset = offset[t];
            pElem->colIndex = t;

            if (spd.hasVal[t] == true) {
H
hjxilinx 已提交
1220
              code = tscInvalidSQLErrMsg(pCmd->payload, "duplicated column name", sToken.z);
H
Haojun Liao 已提交
1221
              goto _error;
H
hzcheng 已提交
1222 1223 1224 1225 1226 1227 1228 1229
            }

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

S
slguan 已提交
1230
        if (!findColumnIndex) {
H
hjxilinx 已提交
1231
          code = tscInvalidSQLErrMsg(pCmd->payload, "invalid column name", sToken.z);
H
Haojun Liao 已提交
1232
          goto _error;
H
hzcheng 已提交
1233 1234 1235
        }
      }

H
hjxilinx 已提交
1236
      if (spd.numOfAssignedCols == 0 || spd.numOfAssignedCols > tinfo.numOfColumns) {
H
hjxilinx 已提交
1237
        code = tscInvalidSQLErrMsg(pCmd->payload, "column name expected", sToken.z);
H
Haojun Liao 已提交
1238
        goto _error;
H
hzcheng 已提交
1239 1240
      }

S
slguan 已提交
1241 1242 1243 1244 1245
      index = 0;
      sToken = tStrGetToken(str, &index, false, 0, NULL);
      str += index;

      if (sToken.type != TK_VALUES) {
H
hjxilinx 已提交
1246
        code = tscInvalidSQLErrMsg(pCmd->payload, "keyword VALUES is expected", sToken.z);
H
Haojun Liao 已提交
1247
        goto _error;
H
hzcheng 已提交
1248 1249
      }

1250
      code = doParseInsertStatement(pSql, pCmd->pTableList, &str, &spd, &totalNum);
H
hzcheng 已提交
1251
      if (code != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1252
        goto _error;
H
hzcheng 已提交
1253 1254
      }
    } else {
H
hjxilinx 已提交
1255
      code = tscInvalidSQLErrMsg(pCmd->payload, "keyword VALUES or FILE are required", sToken.z);
H
Haojun Liao 已提交
1256
      goto _error;
H
hzcheng 已提交
1257 1258 1259
    }
  }

S
slguan 已提交
1260 1261 1262 1263
  // we need to keep the data blocks if there are parameters in the sql
  if (pCmd->numOfParams > 0) {
    goto _clean;
  }
1264

H
hjxilinx 已提交
1265
  if (pCmd->pDataBlocks->nSize > 0) { // merge according to vgId
S
slguan 已提交
1266
    if ((code = tscMergeTableDataBlocks(pSql, pCmd->pDataBlocks)) != TSDB_CODE_SUCCESS) {
H
Haojun Liao 已提交
1267
      goto _error;
S
slguan 已提交
1268
    }
H
hzcheng 已提交
1269
  } else {
S
slguan 已提交
1270
    pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
H
hzcheng 已提交
1271 1272 1273 1274 1275
  }

  code = TSDB_CODE_SUCCESS;
  goto _clean;

H
Haojun Liao 已提交
1276
_error:
S
slguan 已提交
1277
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
H
hzcheng 已提交
1278 1279

_clean:
1280 1281
  taosHashCleanup(pCmd->pTableList);
  pCmd->pTableList = NULL;
H
hjxilinx 已提交
1282
  
1283 1284
  pCmd->curSql    = NULL;
  pCmd->parseFinished  = 1;
H
hjxilinx 已提交
1285
  
H
hzcheng 已提交
1286 1287 1288
  return code;
}

H
Haojun Liao 已提交
1289
int tsInsertInitialCheck(SSqlObj *pSql) {
S
slguan 已提交
1290
  if (!pSql->pTscObj->writeAuth) {
1291
    return TSDB_CODE_TSC_NO_WRITE_AUTH;
S
slguan 已提交
1292
  }
H
hzcheng 已提交
1293

H
hjxilinx 已提交
1294
  int32_t  index = 0;
S
slguan 已提交
1295
  SSqlCmd *pCmd = &pSql->cmd;
1296 1297

  SSQLToken sToken = tStrGetToken(pSql->sqlstr, &index, false, 0, NULL);
H
hjxilinx 已提交
1298
  assert(sToken.type == TK_INSERT || sToken.type == TK_IMPORT);
1299 1300 1301

  pCmd->count = 0;
  pCmd->command = TSDB_SQL_INSERT;
1302
  pSql->res.numOfRows = 0;
1303 1304

  SQueryInfo *pQueryInfo = NULL;
1305
  tscGetQueryInfoDetailSafely(pCmd, pCmd->clauseIndex, &pQueryInfo);
1306

H
Haojun Liao 已提交
1307
  TSDB_QUERY_SET_TYPE(pQueryInfo->type, TSDB_QUERY_TYPE_INSERT | pCmd->insertType);
1308 1309

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

H
Haojun Liao 已提交
1314 1315
  pCmd->curSql = sToken.z + sToken.n;
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1316 1317
}

H
Haojun Liao 已提交
1318
int tsParseSql(SSqlObj *pSql, bool initial) {
H
hzcheng 已提交
1319
  int32_t ret = TSDB_CODE_SUCCESS;
H
Haojun Liao 已提交
1320
  SSqlCmd* pCmd = &pSql->cmd;
H
Haojun Liao 已提交
1321

H
Haojun Liao 已提交
1322
  if ((!pCmd->parseFinished) && (!initial)) {
H
Haojun Liao 已提交
1323
    tscTrace("%p resume to parse sql: %s", pSql, pCmd->curSql);
H
[TD-98]  
hjxilinx 已提交
1324
  }
L
lihui 已提交
1325
  
H
hjxilinx 已提交
1326
  if (tscIsInsertData(pSql->sqlstr)) {
H
hzcheng 已提交
1327
    /*
1328 1329
     * 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 已提交
1330
     */
H
Haojun Liao 已提交
1331
    if (initial && (pSql->cmd.insertType != TSDB_QUERY_TYPE_STMT_INSERT)) {
H
[TD-98]  
hjxilinx 已提交
1332
      pSql->fetchFp = pSql->fp;
H
hjxilinx 已提交
1333
      pSql->fp = (void(*)())tscHandleMultivnodeInsert;
H
hzcheng 已提交
1334
    }
H
Haojun Liao 已提交
1335
    
H
Haojun Liao 已提交
1336
    if (initial && ((ret = tsInsertInitialCheck(pSql)) != TSDB_CODE_SUCCESS)) {
H
Haojun Liao 已提交
1337 1338 1339
      return ret;
    }
    
1340
    ret = tsParseInsertSql(pSql);
H
hzcheng 已提交
1341
  } else {
S
slguan 已提交
1342
    ret = tscAllocPayload(&pSql->cmd, TSDB_DEFAULT_PAYLOAD_SIZE);
1343 1344 1345
    if (TSDB_CODE_SUCCESS != ret) {
      return ret;
    }
H
Haojun Liao 已提交
1346

1347
    SSqlInfo SQLInfo = qSQLParse(pSql->sqlstr);
H
hzcheng 已提交
1348 1349 1350 1351 1352
    ret = tscToSQLCmd(pSql, &SQLInfo);
    SQLInfoDestroy(&SQLInfo);
  }

  /*
1353
   * the pRes->code may be modified or released by another thread in tscTableMetaCallBack function,
H
Haojun Liao 已提交
1354 1355 1356
   * so do NOT use pRes->code to determine if the getTableMeta function
   * invokes new threads to get data from mgmt node or simply retrieves data from cache.
   * do NOT assign return code to pRes->code for the same reason since it may be released by another thread already.
H
hzcheng 已提交
1357 1358 1359 1360
   */
  return ret;
}

S
slguan 已提交
1361 1362 1363
static int doPackSendDataBlock(SSqlObj *pSql, int32_t numOfRows, STableDataBlocks *pTableDataBlocks) {
  int32_t  code = TSDB_CODE_SUCCESS;
  SSqlCmd *pCmd = &pSql->cmd;
S
slguan 已提交
1364

1365
  assert(pCmd->numOfClause == 1);
1366
  STableMeta *pTableMeta = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0)->pTableMeta;
S
slguan 已提交
1367

1368
  SSubmitBlk *pBlocks = (SSubmitBlk *)(pTableDataBlocks->pData);
H
hjxilinx 已提交
1369
  tsSetBlockInfo(pBlocks, pTableMeta, numOfRows);
S
slguan 已提交
1370

S
slguan 已提交
1371 1372 1373
  if ((code = tscMergeTableDataBlocks(pSql, pCmd->pDataBlocks)) != TSDB_CODE_SUCCESS) {
    return code;
  }
S
slguan 已提交
1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387

  // 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 已提交
1388
static int tscInsertDataFromFile(SSqlObj *pSql, FILE *fp, char *tmpTokenBuf) {
S
slguan 已提交
1389 1390 1391 1392
  size_t          readLen = 0;
  char *          line = NULL;
  size_t          n = 0;
  int             len = 0;
L
lihui 已提交
1393
  int32_t         maxRows = 0;
S
slguan 已提交
1394 1395 1396 1397
  SSqlCmd *       pCmd = &pSql->cmd;
  int             numOfRows = 0;
  int32_t         code = 0;
  int             nrows = 0;
1398
  
1399
  STableMetaInfo *pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
H
hjxilinx 已提交
1400
  STableMeta *    pTableMeta = pTableMetaInfo->pTableMeta;
H
hjxilinx 已提交
1401
  STableComInfo tinfo = tscGetTableInfo(pTableMeta);
H
hjxilinx 已提交
1402
  
1403 1404
  assert(pCmd->numOfClause == 1);
  
H
hjxilinx 已提交
1405
  int32_t rowSize = tinfo.rowSize;
S
slguan 已提交
1406 1407

  pCmd->pDataBlocks = tscCreateBlockArrayList();
H
hjxilinx 已提交
1408
  STableDataBlocks *pTableDataBlock = NULL;
1409
  int32_t           ret = tscCreateDataBlock(TSDB_PAYLOAD_SIZE, rowSize, sizeof(SSubmitBlk),
H
hjxilinx 已提交
1410
                                   pTableMetaInfo->name, pTableMeta, &pTableDataBlock);
H
hjxilinx 已提交
1411 1412 1413
  if (ret != TSDB_CODE_SUCCESS) {
    return -1;
  }
1414

S
slguan 已提交
1415 1416
  tscAppendDataBlock(pCmd->pDataBlocks, pTableDataBlock);

L
lihui 已提交
1417 1418
  code = tscAllocateMemIfNeed(pTableDataBlock, rowSize, &maxRows);
  if (TSDB_CODE_SUCCESS != code) return -1;
H
hzcheng 已提交
1419 1420

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

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

H
huili 已提交
1426
  while ((readLen = getline(&line, &n, fp)) != -1) {
H
hzcheng 已提交
1427 1428
    // line[--readLen] = '\0';
    if (('\r' == line[readLen - 1]) || ('\n' == line[readLen - 1])) line[--readLen] = 0;
1429
    if (readLen == 0) continue;  // fang, <= to ==
H
huili 已提交
1430

S
slguan 已提交
1431
    char *lineptr = line;
H
hzcheng 已提交
1432
    strtolower(line, line);
H
hjxilinx 已提交
1433
    
H
hjxilinx 已提交
1434
    len = tsParseOneRowData(&lineptr, pTableDataBlock, pSchema, &spd, pCmd->payload, tinfo.precision, &code, tmpTokenBuf);
S
slguan 已提交
1435
    if (len <= 0 || pTableDataBlock->numOfParams > 0) {
L
[1292]  
lihui 已提交
1436 1437
      pSql->res.code = code;
      return (-code);
S
slguan 已提交
1438
    }
1439

S
slguan 已提交
1440
    pTableDataBlock->size += len;
H
hzcheng 已提交
1441 1442 1443 1444

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

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

H
hzcheng 已提交
1453
      numOfRows += pSql->res.numOfRows;
S
slguan 已提交
1454
      pSql->res.numOfRows = 0;
H
hzcheng 已提交
1455 1456 1457 1458 1459
      count = 0;
    }
  }

  if (count > 0) {
S
slguan 已提交
1460 1461
    if ((code = doPackSendDataBlock(pSql, count, pTableDataBlock)) != TSDB_CODE_SUCCESS) {
      return -code;
H
hzcheng 已提交
1462
    }
S
slguan 已提交
1463

H
hzcheng 已提交
1464
    numOfRows += pSql->res.numOfRows;
S
slguan 已提交
1465
    pSql->res.numOfRows = 0;
H
hzcheng 已提交
1466 1467 1468
  }

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

H
hzcheng 已提交
1470 1471 1472
  return numOfRows;
}

1473
void tscProcessMultiVnodesInsertFromFile(SSqlObj *pSql) {
S
slguan 已提交
1474
  SSqlCmd *pCmd = &pSql->cmd;
H
hzcheng 已提交
1475 1476 1477 1478
  if (pCmd->command != TSDB_SQL_INSERT) {
    return;
  }

1479
  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
hjxilinx 已提交
1480
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
1481

S
slguan 已提交
1482 1483
  STableDataBlocks *pDataBlock = NULL;
  int32_t           affected_rows = 0;
H
hzcheng 已提交
1484

1485
  assert(pCmd->dataSourceType == DATA_FROM_DATA_FILE && pCmd->pDataBlocks != NULL);
S
slguan 已提交
1486 1487
  SDataBlockList *pDataBlockList = pCmd->pDataBlocks;
  pCmd->pDataBlocks = NULL;
H
hzcheng 已提交
1488

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

S
slguan 已提交
1491 1492
  for (int32_t i = 0; i < pDataBlockList->nSize; ++i) {
    pDataBlock = pDataBlockList->pData[i];
H
hzcheng 已提交
1493 1494 1495
    if (pDataBlock == NULL) {
      continue;
    }
1496

S
slguan 已提交
1497 1498 1499 1500
    if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, TSDB_PAYLOAD_SIZE)) {
      tscError("%p failed to malloc when insert file", pSql);
      continue;
    }
H
hzcheng 已提交
1501 1502
    pCmd->count = 1;

B
Bomin Zhang 已提交
1503
    tstrncpy(path, pDataBlock->filename, sizeof(path));
S
slguan 已提交
1504 1505

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

B
Bomin Zhang 已提交
1511
    tstrncpy(pTableMetaInfo->name, pDataBlock->tableId, sizeof(pTableMetaInfo->name));
S
slguan 已提交
1512 1513
    memset(pDataBlock->pData, 0, pDataBlock->nAllocSize);

H
hjxilinx 已提交
1514
    int32_t ret = tscGetTableMeta(pSql, pTableMetaInfo);
S
slguan 已提交
1515 1516 1517 1518
    if (ret != TSDB_CODE_SUCCESS) {
      tscError("%p get meter meta failed, abort", pSql);
      continue;
    }
1519 1520

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

L
[1292]  
lihui 已提交
1526 1527
    int nrows = tscInsertDataFromFile(pSql, fp, tmpTokenBuf);
    free(tmpTokenBuf);
1528

S
slguan 已提交
1529 1530
    pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);

H
hzcheng 已提交
1531 1532
    if (nrows < 0) {
      fclose(fp);
S
slguan 已提交
1533
      tscTrace("%p no records(%d) in file %s", pSql, nrows, path);
H
hzcheng 已提交
1534 1535 1536
      continue;
    }

S
slguan 已提交
1537
    fclose(fp);
H
hzcheng 已提交
1538 1539
    affected_rows += nrows;

S
slguan 已提交
1540
    tscTrace("%p Insert data %d records from file %s", pSql, nrows, path);
H
hzcheng 已提交
1541 1542 1543 1544 1545
  }

  pSql->res.numOfRows = affected_rows;

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