tscParseInsert.c 48.9 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 "hash.h"
22
#include "os.h"
H
hzcheng 已提交
23 24 25 26
#include "tscSecondaryMerge.h"
#include "tscUtil.h"
#include "tschemautil.h"
#include "tsclient.h"
27
#include "ttokendef.h"
H
hzcheng 已提交
28
#include "taosdef.h"
H
hzcheng 已提交
29 30 31 32 33

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

S
slguan 已提交
34
enum {
S
slguan 已提交
35 36 37 38
  TSDB_USE_SERVER_TS = 0,
  TSDB_USE_CLI_TS = 1,
};

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

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

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

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

  return numType;
H
hzcheng 已提交
60 61
}

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

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

S
slguan 已提交
73 74 75 76 77 78
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 已提交
79

S
slguan 已提交
80
  index = 0;
H
hzcheng 已提交
81

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

    return TSDB_CODE_SUCCESS;
  }

S
slguan 已提交
97 98 99 100
  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 已提交
101 102 103 104 105 106 107 108
      *time = useconds;
      return 0;
    }

    break;
  }

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

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

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

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

H
hzcheng 已提交
130 131 132 133
    if (timePrec == TSDB_TIME_PRECISION_MILLI) {
      interval /= 1000;
    }

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

    *next = pTokenEnd;
  }

  *time = useconds;
  return TSDB_CODE_SUCCESS;
}

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

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

193
        *((int8_t *)payload) = (int8_t)iv;
H
hzcheng 已提交
194 195 196 197 198
      }

      break;

    case TSDB_DATA_TYPE_SMALLINT:
S
slguan 已提交
199 200 201 202 203
      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 已提交
204
      } else {
S
slguan 已提交
205
        numType = tscToInteger(pToken, &iv, &endptr);
L
lihui 已提交
206
        if (TK_ILLEGAL == numType) {
H
hjxilinx 已提交
207
          return tscInvalidSQLErrMsg(msg, "invalid smallint data", pToken->z);
L
lihui 已提交
208
        } else if (errno == ERANGE || iv > INT16_MAX || iv <= INT16_MIN) {
H
hjxilinx 已提交
209
          return tscInvalidSQLErrMsg(msg, "smallint data overflow", pToken->z);
H
hzcheng 已提交
210 211
        }

S
slguan 已提交
212
        *((int16_t *)payload) = (int16_t)iv;
H
hzcheng 已提交
213 214 215 216
      }
      break;

    case TSDB_DATA_TYPE_INT:
S
slguan 已提交
217 218 219 220
      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 已提交
221
        *((int32_t *)payload) = TSDB_DATA_INT_NULL;
H
hzcheng 已提交
222
      } else {
S
slguan 已提交
223
        numType = tscToInteger(pToken, &iv, &endptr);
L
lihui 已提交
224
        if (TK_ILLEGAL == numType) {
H
hjxilinx 已提交
225
          return tscInvalidSQLErrMsg(msg, "invalid int data", pToken->z);
L
lihui 已提交
226
        } else if (errno == ERANGE || iv > INT32_MAX || iv <= INT32_MIN) {
H
hjxilinx 已提交
227
          return tscInvalidSQLErrMsg(msg, "int data overflow", pToken->z);
H
hzcheng 已提交
228 229
        }

S
slguan 已提交
230
        *((int32_t *)payload) = (int32_t)iv;
H
hzcheng 已提交
231 232 233 234 235
      }

      break;

    case TSDB_DATA_TYPE_BIGINT:
S
slguan 已提交
236 237 238 239
      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 已提交
240
        *((int64_t *)payload) = TSDB_DATA_BIGINT_NULL;
H
hzcheng 已提交
241
      } else {
S
slguan 已提交
242
        numType = tscToInteger(pToken, &iv, &endptr);
L
lihui 已提交
243
        if (TK_ILLEGAL == numType) {
H
hjxilinx 已提交
244
          return tscInvalidSQLErrMsg(msg, "invalid bigint data", pToken->z);
L
lihui 已提交
245
        } else if (errno == ERANGE || iv > INT64_MAX || iv <= INT64_MIN) {
H
hjxilinx 已提交
246
          return tscInvalidSQLErrMsg(msg, "bigint data overflow", pToken->z);
H
hzcheng 已提交
247
        }
S
slguan 已提交
248 249

        *((int64_t *)payload) = iv;
H
hzcheng 已提交
250 251 252 253
      }
      break;

    case TSDB_DATA_TYPE_FLOAT:
S
slguan 已提交
254 255 256 257
      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 已提交
258
        *((int32_t *)payload) = TSDB_DATA_FLOAT_NULL;
H
hzcheng 已提交
259
      } else {
S
slguan 已提交
260 261
        double dv;
        if (TK_ILLEGAL == tscToDouble(pToken, &dv, &endptr)) {
H
hjxilinx 已提交
262
          return tscInvalidSQLErrMsg(msg, "illegal float data", pToken->z);
S
slguan 已提交
263 264 265 266
        }

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

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

        *((float *)payload) = fv;
H
hzcheng 已提交
275 276 277 278
      }
      break;

    case TSDB_DATA_TYPE_DOUBLE:
S
slguan 已提交
279 280 281 282
      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 已提交
283
        *((int64_t *)payload) = TSDB_DATA_DOUBLE_NULL;
H
hzcheng 已提交
284
      } else {
S
slguan 已提交
285 286
        double dv;
        if (TK_ILLEGAL == tscToDouble(pToken, &dv, &endptr)) {
H
hjxilinx 已提交
287
          return tscInvalidSQLErrMsg(msg, "illegal double data", pToken->z);
H
hzcheng 已提交
288 289
        }

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

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

    case TSDB_DATA_TYPE_BINARY:
S
slguan 已提交
303 304
      // binary data cannot be null-terminated char string, otherwise the last char of the string is lost
      if (pToken->type == TK_NULL) {
H
hzcheng 已提交
305
        *payload = TSDB_DATA_BINARY_NULL;
H
hjxilinx 已提交
306
      } else { // too long values will return invalid sql, not be truncated automatically
S
slguan 已提交
307
        if (pToken->n > pSchema->bytes) {
H
hjxilinx 已提交
308
          return tscInvalidSQLErrMsg(msg, "string data overflow", pToken->z);
S
slguan 已提交
309
        }
H
hjxilinx 已提交
310
        
S
slguan 已提交
311
        strncpy(payload, pToken->z, pToken->n);
312 313 314 315
        
        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 已提交
316 317 318 319 320
      }

      break;

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

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

      break;
    }
  }

H
hjxilinx 已提交
354
  return TSDB_CODE_SUCCESS;
H
hzcheng 已提交
355 356
}

S
slguan 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
/*
 * 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 已提交
377
      return -1;  // client time/server time can not be mixed
378

S
slguan 已提交
379 380 381 382 383 384 385 386 387 388 389 390 391
    } 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 已提交
392
int tsParseOneRowData(char **str, STableDataBlocks *pDataBlocks, SSchema schema[], SParsedDataColInfo *spd, char *error,
393 394 395
                      int16_t timePrec, int32_t *code, char *tmpTokenBuf) {
  int32_t index = 0;
  // bool      isPrevOptr; //fang, never used
H
hjxilinx 已提交
396
  SSQLToken sToken = {0};
S
slguan 已提交
397
  char *    payload = pDataBlocks->pData + pDataBlocks->size;
S
slguan 已提交
398

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

S
slguan 已提交
408 409 410 411 412 413 414 415 416
    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;
      }
417

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

S
slguan 已提交
423 424 425
    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 已提交
426
      tscInvalidSQLErrMsg(error, "invalid data or symbol", sToken.z);
L
[1292]  
lihui 已提交
427
      *code = TSDB_CODE_INVALID_SQL;
S
slguan 已提交
428
      return -1;
H
hzcheng 已提交
429 430
    }

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

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

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

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

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

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

      ptr += schema[i].bytes;
    }

    rowSize = ptr - payload;
  }

  return rowSize;
}

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

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

  int16_t numOfRows = 0;

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

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

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

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

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

    pDataBlock->size += len;

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

    numOfRows++;
  }

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

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

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

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

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

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

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

  // size is less than the total size, since duplicated rows may be removed yet.
  assert(pBlocks->numOfRows * dataBuf->rowSize + sizeof(SShellSubmitBlock) == dataBuf->size);

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

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

S
slguan 已提交
629 630
    int32_t i = 0;
    int32_t j = 1;
H
hzcheng 已提交
631

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

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

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

      ++j;
    }

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

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

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

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

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

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

S
slguan 已提交
697
  SShellSubmitBlock *pBlocks = (SShellSubmitBlock *)(dataBuf->pData);
H
hjxilinx 已提交
698
  tsSetBlockInfo(pBlocks, pTableMeta, numOfRows);
S
slguan 已提交
699

H
hjxilinx 已提交
700
  dataBuf->vgid = pTableMeta->vgid;
S
slguan 已提交
701
  dataBuf->numOfTables = 1;
H
hzcheng 已提交
702 703

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

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

S
slguan 已提交
723
  char *sql = *sqlstr;
724

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

S
slguan 已提交
730 731
  char *cstart = NULL;
  char *cend = NULL;
H
hzcheng 已提交
732

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

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

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

      ++numOfColList;
    }

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

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

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

H
hjxilinx 已提交
779
    STableMetaInfo *pSTableMeterMetaInfo = tscGetMetaInfo(pQueryInfo, STABLE_INDEX);
780 781
    setMeterID(pSTableMeterMetaInfo, &sToken, pSql);

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

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

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

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

    // if specify some tags column
    if (sToken.type != TK_LP) {
      tscSetAssignedColumnInfo(&spd, pTagSchema, numOfTags);
    } else {
808 809
      /* insert into tablename (col1, col2,..., coln) using superTableName (tagName1, tagName2, ..., tagNamen)
       * tags(tagVal1, tagVal2, ..., tagValn) values(v1, v2,... vn); */
L
lihui 已提交
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835
      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++];
836
            pElem->offset = offset[t];
L
lihui 已提交
837 838 839 840 841 842
            pElem->colIndex = t;

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

843
            spd.hasVal[t] = true;
L
lihui 已提交
844 845 846 847 848 849 850 851 852 853 854 855 856
            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 已提交
857 858 859 860

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

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

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

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

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

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

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

L
lihui 已提交
899 900 901 902 903
    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 已提交
904 905
    }

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

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

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

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

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

    createTable = true;
H
hjxilinx 已提交
929
    code = tscGetMeterMetaEx(pSql, pTableMetaInfo, true);
H
hjxilinx 已提交
930 931 932 933
    if (TSDB_CODE_ACTION_IN_PROGRESS == code) {
      return code;
    }
    
H
hzcheng 已提交
934 935 936 937
  } else {
    if (cstart != NULL) {
      sql = cstart;
    } else {
S
slguan 已提交
938
      sql = sToken.z;
H
hzcheng 已提交
939
    }
H
hjxilinx 已提交
940
    code = tscGetTableMeta(pSql, pTableMetaInfo);
H
hzcheng 已提交
941 942 943 944 945
  }

  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 已提交
946
    memmove(sql - len, cstart, len);
H
hzcheng 已提交
947 948 949 950 951 952 953 954
    *sqlstr = sql - len;
  } else {
    *sqlstr = sql;
  }

  return code;
}

S
slguan 已提交
955
int validateTableName(char *tblName, int len) {
S
slguan 已提交
956
  char buf[TSDB_TABLE_ID_LEN] = {0};
S
slguan 已提交
957
  strncpy(buf, tblName, len);
S
slguan 已提交
958

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

H
huili 已提交
962 963 964
  return tscValidateName(&token);
}

965 966 967 968 969 970 971 972 973
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 已提交
974 975 976 977 978 979 980 981 982
/**
 * usage: insert into table1 values() () table2 values()()
 *
 * @param str
 * @param acct
 * @param db
 * @param pSql
 * @return
 */
983
int doParseInsertSql(SSqlObj *pSql, char *str) {
S
slguan 已提交
984
  SSqlCmd *pCmd = &pSql->cmd;
985

S
slguan 已提交
986
  int32_t totalNum = 0;
987 988
  int32_t code = TSDB_CODE_SUCCESS;

H
hjxilinx 已提交
989
  STableMetaInfo *pTableMetaInfo = NULL;
990 991 992 993

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

994
  if (pQueryInfo->numOfTables == 0) {
H
hjxilinx 已提交
995
    pTableMetaInfo = tscAddEmptyMetaInfo(pQueryInfo);
996
  } else {
H
hjxilinx 已提交
997
    pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
998
  }
H
hzcheng 已提交
999

S
slguan 已提交
1000
  if ((code = tscAllocPayload(pCmd, TSDB_PAYLOAD_SIZE)) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
1001 1002 1003
    return code;
  }

H
hjxilinx 已提交
1004
  assert(((NULL == pSql->asyncTblPos) && (NULL == pSql->pTableHashList))
L
lihui 已提交
1005 1006
      || ((NULL != pSql->asyncTblPos) && (NULL != pSql->pTableHashList)));

L
lihui 已提交
1007
  if ((NULL == pSql->asyncTblPos) && (NULL == pSql->pTableHashList)) {
H
hjxilinx 已提交
1008
    pSql->pTableHashList = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), false);
1009

L
lihui 已提交
1010 1011 1012 1013 1014 1015
    pSql->cmd.pDataBlocks = tscCreateBlockArrayList();
    if (NULL == pSql->pTableHashList || NULL == pSql->cmd.pDataBlocks) {
      code = TSDB_CODE_CLI_OUT_OF_MEMORY;
      goto _error_clean;
    }
  } else {
H
hjxilinx 已提交
1016
    assert((NULL != pSql->asyncTblPos) && (NULL != pSql->pTableHashList));
L
lihui 已提交
1017 1018 1019
    str = pSql->asyncTblPos;
  }
  
L
[#1083]  
lihui 已提交
1020
  tscTrace("%p create data block list for submit data:%p, asyncTblPos:%p, pTableHashList:%p", pSql, pSql->cmd.pDataBlocks, pSql->asyncTblPos, pSql->pTableHashList);
H
hzcheng 已提交
1021 1022

  while (1) {
1023
    int32_t   index = 0;
S
slguan 已提交
1024
    SSQLToken sToken = tStrGetToken(str, &index, false, 0, NULL);
1025 1026 1027 1028 1029 1030 1031 1032

    // 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 已提交
1033 1034 1035
        goto _clean;
      }

1036 1037 1038 1039 1040
      /*
       * 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 已提交
1041 1042
        code = TSDB_CODE_INVALID_SQL;
        goto _error_clean;
1043 1044
      } else {
        break;
H
hzcheng 已提交
1045 1046 1047
      }
    }

L
lihui 已提交
1048 1049
    pSql->asyncTblPos = sToken.z;

S
slguan 已提交
1050
    // Check if the table name available or not
S
slguan 已提交
1051
    if (validateTableName(sToken.z, sToken.n) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1052
      code = tscInvalidSQLErrMsg(pCmd->payload, "table name invalid", sToken.z);
H
huili 已提交
1053 1054 1055
      goto _error_clean;
    }

H
hjxilinx 已提交
1056
    if ((code = setMeterID(pTableMetaInfo, &sToken, pSql)) != TSDB_CODE_SUCCESS) {
H
hzcheng 已提交
1057 1058 1059
      goto _error_clean;
    }

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

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

S
slguan 已提交
1089 1090 1091
    index = 0;
    sToken = tStrGetToken(str, &index, false, 0, NULL);
    str += index;
1092

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

H
hjxilinx 已提交
1106
      tscSetAssignedColumnInfo(&spd, pSchema, numOfCols);
H
hzcheng 已提交
1107

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

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

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

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

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

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

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

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

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

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

      while (1) {
S
slguan 已提交
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
        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 已提交
1185 1186 1187 1188 1189 1190
          break;
        }

        bool findColumnIndex = false;

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

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

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

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

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

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

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

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

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

S
slguan 已提交
1243
  // submit to more than one vnode
H
hzcheng 已提交
1244
  if (pCmd->pDataBlocks->nSize > 0) {
S
slguan 已提交
1245
    // merge according to vgid
S
slguan 已提交
1246 1247 1248
    if ((code = tscMergeTableDataBlocks(pSql, pCmd->pDataBlocks)) != TSDB_CODE_SUCCESS) {
      goto _error_clean;
    }
H
hzcheng 已提交
1249

S
slguan 已提交
1250 1251 1252
    STableDataBlocks *pDataBlock = pCmd->pDataBlocks->pData[0];
    if ((code = tscCopyDataBlockToPayload(pSql, pDataBlock)) != TSDB_CODE_SUCCESS) {
      goto _error_clean;
H
hzcheng 已提交
1253 1254
    }

1255
    pTableMetaInfo = tscGetTableMetaInfoFromCmd(&pSql->cmd, 0, 0);
1256

S
slguan 已提交
1257
    // set the next sent data vnode index in data block arraylist
H
hjxilinx 已提交
1258
    pTableMetaInfo->vnodeIndex = 1;
H
hzcheng 已提交
1259
  } else {
S
slguan 已提交
1260
    pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
H
hzcheng 已提交
1261 1262 1263 1264 1265 1266
  }

  code = TSDB_CODE_SUCCESS;
  goto _clean;

_error_clean:
S
slguan 已提交
1267
  pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);
H
hzcheng 已提交
1268 1269

_clean:
H
hjxilinx 已提交
1270
  taosHashCleanup(pSql->pTableHashList);
H
hjxilinx 已提交
1271
  
L
lihui 已提交
1272
  pSql->pTableHashList = NULL;
L
[1078]  
lihui 已提交
1273
  pSql->asyncTblPos    = NULL;
L
[#1083]  
lihui 已提交
1274
  pCmd->isParseFinish  = 1;
H
hjxilinx 已提交
1275
  
H
hzcheng 已提交
1276 1277 1278
  return code;
}

1279
int tsParseInsertSql(SSqlObj *pSql) {
S
slguan 已提交
1280 1281 1282
  if (!pSql->pTscObj->writeAuth) {
    return TSDB_CODE_NO_RIGHTS;
  }
H
hzcheng 已提交
1283

H
hjxilinx 已提交
1284
  int32_t  index = 0;
S
slguan 已提交
1285
  SSqlCmd *pCmd = &pSql->cmd;
1286 1287

  SSQLToken sToken = tStrGetToken(pSql->sqlstr, &index, false, 0, NULL);
H
hjxilinx 已提交
1288
  assert(sToken.type == TK_INSERT || sToken.type == TK_IMPORT);
1289 1290 1291 1292 1293

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

  SQueryInfo *pQueryInfo = NULL;
1294
  tscGetQueryInfoDetailSafely(pCmd, pCmd->clauseIndex, &pQueryInfo);
1295

1296 1297
  uint16_t type = (sToken.type == TK_INSERT)? TSDB_QUERY_TYPE_INSERT:TSDB_QUERY_TYPE_IMPORT;
  TSDB_QUERY_SET_TYPE(pQueryInfo->type, type);
1298 1299

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

H
hjxilinx 已提交
1304
  pSql->res.numOfRows = 0;
1305
  return doParseInsertSql(pSql, pSql->sqlstr + index);
H
hzcheng 已提交
1306 1307
}

1308
int tsParseSql(SSqlObj *pSql, bool multiVnodeInsertion) {
H
hzcheng 已提交
1309
  int32_t ret = TSDB_CODE_SUCCESS;
S
slguan 已提交
1310

L
lihui 已提交
1311 1312
  if (NULL == pSql->asyncTblPos) {
    tscCleanSqlCmd(&pSql->cmd);
1313 1314
  } else {
    tscTrace("continue parse sql: %s", pSql->asyncTblPos);
L
lihui 已提交
1315
  }
L
lihui 已提交
1316
  
H
hzcheng 已提交
1317 1318
  if (tscIsInsertOrImportData(pSql->sqlstr)) {
    /*
S
slguan 已提交
1319 1320 1321
     * only for async multi-vnode insertion
     * Set the fp before parse the sql string, in case of getmetermeta failed, in which
     * the error handle callback function can rightfully restore the user defined function (fp)
H
hzcheng 已提交
1322 1323 1324 1325
     */
    if (pSql->fp != NULL && multiVnodeInsertion) {
      pSql->fetchFp = pSql->fp;

S
slguan 已提交
1326
      // replace user defined callback function with multi-insert proxy function
H
hjxilinx 已提交
1327
      pSql->fp = (void(*)())launchMultivnodeInsert;
H
hzcheng 已提交
1328 1329
    }

1330
    ret = tsParseInsertSql(pSql);
H
hzcheng 已提交
1331
  } else {
S
slguan 已提交
1332 1333
    ret = tscAllocPayload(&pSql->cmd, TSDB_DEFAULT_PAYLOAD_SIZE);
    if (TSDB_CODE_SUCCESS != ret) return ret;
1334

H
hzcheng 已提交
1335 1336
    SSqlInfo SQLInfo = {0};
    tSQLParse(&SQLInfo, pSql->sqlstr);
S
slguan 已提交
1337

H
hzcheng 已提交
1338 1339 1340 1341 1342
    ret = tscToSQLCmd(pSql, &SQLInfo);
    SQLInfoDestroy(&SQLInfo);
  }

  /*
H
hjxilinx 已提交
1343
   * the pRes->code may be modified or even released by another thread in tscTableMetaCallBack
H
hzcheng 已提交
1344 1345 1346 1347 1348 1349 1350 1351 1352
   * function, so do NOT use pRes->code to determine if the getMeterMeta/getMetricMeta function
   * invokes new threads to get data from mnode or simply retrieves data from cache.
   *
   * do NOT assign return code to pRes->code for the same reason for it may be released by another thread
   * pRes->code = ret;
   */
  return ret;
}

S
slguan 已提交
1353 1354 1355
static int doPackSendDataBlock(SSqlObj *pSql, int32_t numOfRows, STableDataBlocks *pTableDataBlocks) {
  int32_t  code = TSDB_CODE_SUCCESS;
  SSqlCmd *pCmd = &pSql->cmd;
S
slguan 已提交
1356

1357
  assert(pCmd->numOfClause == 1);
1358
  STableMeta *pTableMeta = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0)->pTableMeta;
S
slguan 已提交
1359 1360

  SShellSubmitBlock *pBlocks = (SShellSubmitBlock *)(pTableDataBlocks->pData);
H
hjxilinx 已提交
1361
  tsSetBlockInfo(pBlocks, pTableMeta, numOfRows);
S
slguan 已提交
1362

S
slguan 已提交
1363 1364 1365
  if ((code = tscMergeTableDataBlocks(pSql, pCmd->pDataBlocks)) != TSDB_CODE_SUCCESS) {
    return code;
  }
S
slguan 已提交
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379

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

  pCmd->pDataBlocks = tscCreateBlockArrayList();
H
hjxilinx 已提交
1400
  STableDataBlocks *pTableDataBlock = NULL;
1401
  int32_t           ret = tscCreateDataBlock(TSDB_PAYLOAD_SIZE, rowSize, sizeof(SShellSubmitBlock),
H
hjxilinx 已提交
1402
                                   pTableMetaInfo->name, pTableMeta, &pTableDataBlock);
H
hjxilinx 已提交
1403 1404 1405
  if (ret != TSDB_CODE_SUCCESS) {
    return -1;
  }
1406

S
slguan 已提交
1407 1408
  tscAppendDataBlock(pCmd->pDataBlocks, pTableDataBlock);

L
lihui 已提交
1409 1410
  code = tscAllocateMemIfNeed(pTableDataBlock, rowSize, &maxRows);
  if (TSDB_CODE_SUCCESS != code) return -1;
H
hzcheng 已提交
1411 1412

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

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

H
huili 已提交
1418
  while ((readLen = getline(&line, &n, fp)) != -1) {
H
hzcheng 已提交
1419 1420
    // line[--readLen] = '\0';
    if (('\r' == line[readLen - 1]) || ('\n' == line[readLen - 1])) line[--readLen] = 0;
1421
    if (readLen == 0) continue;  // fang, <= to ==
H
huili 已提交
1422

S
slguan 已提交
1423
    char *lineptr = line;
H
hzcheng 已提交
1424
    strtolower(line, line);
H
hjxilinx 已提交
1425
    
H
hjxilinx 已提交
1426
    len = tsParseOneRowData(&lineptr, pTableDataBlock, pSchema, &spd, pCmd->payload, tinfo.precision, &code, tmpTokenBuf);
S
slguan 已提交
1427
    if (len <= 0 || pTableDataBlock->numOfParams > 0) {
L
[1292]  
lihui 已提交
1428 1429
      pSql->res.code = code;
      return (-code);
S
slguan 已提交
1430
    }
1431

S
slguan 已提交
1432
    pTableDataBlock->size += len;
H
hzcheng 已提交
1433 1434 1435 1436

    count++;
    nrows++;
    if (count >= maxRows) {
S
slguan 已提交
1437 1438
      if ((code = doPackSendDataBlock(pSql, count, pTableDataBlock)) != TSDB_CODE_SUCCESS) {
        return -code;
H
hzcheng 已提交
1439
      }
S
slguan 已提交
1440 1441 1442

      pTableDataBlock = pCmd->pDataBlocks->pData[0];
      pTableDataBlock->size = sizeof(SShellSubmitBlock);
H
hjxilinx 已提交
1443
      pTableDataBlock->rowSize = tinfo.rowSize;
S
slguan 已提交
1444

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

  if (count > 0) {
S
slguan 已提交
1452 1453
    if ((code = doPackSendDataBlock(pSql, count, pTableDataBlock)) != TSDB_CODE_SUCCESS) {
      return -code;
H
hzcheng 已提交
1454
    }
S
slguan 已提交
1455

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

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

H
hzcheng 已提交
1462 1463 1464 1465 1466 1467 1468 1469 1470
  return numOfRows;
}

/* multi-vnodes insertion in sync query model
 *
 * modify history
 * 2019.05.10 lihui
 * Remove the code for importing records from files
 */
S
slguan 已提交
1471 1472
void tscProcessMultiVnodesInsert(SSqlObj *pSql) {
  SSqlCmd *pCmd = &pSql->cmd;
S
slguan 已提交
1473 1474

  // not insert/import, return directly
H
hzcheng 已提交
1475 1476 1477 1478
  if (pCmd->command != TSDB_SQL_INSERT) {
    return;
  }

S
slguan 已提交
1479 1480 1481 1482 1483
  // SSqlCmd may have been released
  if (pCmd->pDataBlocks == NULL) {
    return;
  }

S
slguan 已提交
1484
  STableDataBlocks *pDataBlock = NULL;
1485
  STableMetaInfo *  pTableMetaInfo = tscGetTableMetaInfoFromCmd(pCmd, pCmd->clauseIndex, 0);
1486 1487
  assert(pCmd->numOfClause == 1);
  
S
slguan 已提交
1488
  int32_t           code = TSDB_CODE_SUCCESS;
H
hzcheng 已提交
1489 1490

  /* the first block has been sent to server in processSQL function */
H
hjxilinx 已提交
1491
  assert(pTableMetaInfo->vnodeIndex >= 1 && pCmd->pDataBlocks != NULL);
H
hzcheng 已提交
1492

H
hjxilinx 已提交
1493
  if (pTableMetaInfo->vnodeIndex < pCmd->pDataBlocks->nSize) {
S
slguan 已提交
1494
    SDataBlockList *pDataBlocks = pCmd->pDataBlocks;
H
hzcheng 已提交
1495

H
hjxilinx 已提交
1496
    for (int32_t i = pTableMetaInfo->vnodeIndex; i < pDataBlocks->nSize; ++i) {
H
hzcheng 已提交
1497 1498 1499 1500 1501 1502
      pDataBlock = pDataBlocks->pData[i];
      if (pDataBlock == NULL) {
        continue;
      }

      if ((code = tscCopyDataBlockToPayload(pSql, pDataBlock)) != TSDB_CODE_SUCCESS) {
H
hjxilinx 已提交
1503
        tscTrace("%p build submit data block failed, vnodeIdx:%d, total:%d", pSql, pTableMetaInfo->vnodeIndex,
1504
                 pDataBlocks->nSize);
H
hzcheng 已提交
1505 1506 1507 1508 1509 1510 1511 1512
        continue;
      }

      tscProcessSql(pSql);
    }
  }

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

S
slguan 已提交
1516
// multi-vnodes insertion in sync query model
1517
void tscProcessMultiVnodesInsertFromFile(SSqlObj *pSql) {
S
slguan 已提交
1518
  SSqlCmd *pCmd = &pSql->cmd;
H
hzcheng 已提交
1519 1520 1521 1522
  if (pCmd->command != TSDB_SQL_INSERT) {
    return;
  }

1523
  SQueryInfo *    pQueryInfo = tscGetQueryInfoDetail(pCmd, 0);
H
hjxilinx 已提交
1524
  STableMetaInfo *pTableMetaInfo = tscGetMetaInfo(pQueryInfo, 0);
1525

S
slguan 已提交
1526 1527
  STableDataBlocks *pDataBlock = NULL;
  int32_t           affected_rows = 0;
H
hzcheng 已提交
1528

1529
  assert(pCmd->dataSourceType == DATA_FROM_DATA_FILE && pCmd->pDataBlocks != NULL);
S
slguan 已提交
1530 1531
  SDataBlockList *pDataBlockList = pCmd->pDataBlocks;
  pCmd->pDataBlocks = NULL;
H
hzcheng 已提交
1532

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

S
slguan 已提交
1535 1536
  for (int32_t i = 0; i < pDataBlockList->nSize; ++i) {
    pDataBlock = pDataBlockList->pData[i];
H
hzcheng 已提交
1537 1538 1539
    if (pDataBlock == NULL) {
      continue;
    }
1540

S
slguan 已提交
1541 1542 1543 1544
    if (TSDB_CODE_SUCCESS != tscAllocPayload(pCmd, TSDB_PAYLOAD_SIZE)) {
      tscError("%p failed to malloc when insert file", pSql);
      continue;
    }
H
hzcheng 已提交
1545 1546
    pCmd->count = 1;

S
slguan 已提交
1547 1548 1549
    strncpy(path, pDataBlock->filename, PATH_MAX);

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

H
hjxilinx 已提交
1555
    strncpy(pTableMetaInfo->name, pDataBlock->tableId, TSDB_TABLE_ID_LEN);
S
slguan 已提交
1556 1557
    memset(pDataBlock->pData, 0, pDataBlock->nAllocSize);

H
hjxilinx 已提交
1558
    int32_t ret = tscGetTableMeta(pSql, pTableMetaInfo);
S
slguan 已提交
1559 1560 1561 1562
    if (ret != TSDB_CODE_SUCCESS) {
      tscError("%p get meter meta failed, abort", pSql);
      continue;
    }
1563 1564

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

L
[1292]  
lihui 已提交
1570 1571
    int nrows = tscInsertDataFromFile(pSql, fp, tmpTokenBuf);
    free(tmpTokenBuf);
1572

S
slguan 已提交
1573 1574
    pCmd->pDataBlocks = tscDestroyBlockArrayList(pCmd->pDataBlocks);

H
hzcheng 已提交
1575 1576
    if (nrows < 0) {
      fclose(fp);
S
slguan 已提交
1577
      tscTrace("%p no records(%d) in file %s", pSql, nrows, path);
H
hzcheng 已提交
1578 1579 1580
      continue;
    }

S
slguan 已提交
1581
    fclose(fp);
H
hzcheng 已提交
1582 1583
    affected_rows += nrows;

S
slguan 已提交
1584
    tscTrace("%p Insert data %d records from file %s", pSql, nrows, path);
H
hzcheng 已提交
1585 1586 1587 1588 1589
  }

  pSql->res.numOfRows = affected_rows;

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