parInsertSql.c 77.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (c) 2019 TAOS Data, Inc. <jhtao@taosdata.com>
 *
 * This program is free software: you can use, redistribute, and/or modify
 * it under the terms of the GNU Affero General Public License, version 3
 * or later ("AGPL"), as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

X
Xiaoyu Wang 已提交
16
#include "parInsertUtil.h"
X
Xiaoyu Wang 已提交
17
#include "parToken.h"
18
#include "scalar.h"
19 20
#include "tglobal.h"
#include "ttime.h"
D
Dingle Zhang 已提交
21
#include "geosWrapper.h"
22

X
Xiaoyu Wang 已提交
23 24 25 26 27
#define NEXT_TOKEN_WITH_PREV(pSql, token)           \
  do {                                              \
    int32_t index = 0;                              \
    token = tStrGetToken(pSql, &index, true, NULL); \
    pSql += index;                                  \
X
Xiaoyu Wang 已提交
28 29
  } while (0)

X
Xiaoyu Wang 已提交
30 31 32 33 34 35 36 37 38 39
#define NEXT_TOKEN_WITH_PREV_EXT(pSql, token, pIgnoreComma) \
  do {                                                      \
    int32_t index = 0;                                      \
    token = tStrGetToken(pSql, &index, true, pIgnoreComma); \
    pSql += index;                                          \
  } while (0)

#define NEXT_TOKEN_KEEP_SQL(pSql, token, index)      \
  do {                                               \
    token = tStrGetToken(pSql, &index, false, NULL); \
40 41
  } while (0)

X
Xiaoyu Wang 已提交
42 43 44 45 46 47 48 49
#define NEXT_VALID_TOKEN(pSql, token)           \
  do {                                          \
    (token).n = tGetToken(pSql, &(token).type); \
    (token).z = (char*)pSql;                    \
    pSql += (token).n;                          \
  } while (TK_NK_SPACE == (token).type)

typedef struct SInsertParseContext {
X
Xiaoyu Wang 已提交
50 51 52 53 54 55 56
  SParseContext* pComCxt;
  SMsgBuf        msg;
  char           tmpTokenBuf[TSDB_MAX_BYTES_PER_ROW];
  SBoundColInfo  tags;  // for stmt
  bool           missCache;
  bool           usingDuplicateTable;
  bool           forceUpdate;
X
Xiaoyu Wang 已提交
57
  bool           needTableTagVal;
X
Xiaoyu Wang 已提交
58
} SInsertParseContext;
59

H
refact  
Hongze Cheng 已提交
60
typedef int32_t (*_row_append_fn_t)(SMsgBuf* pMsgBuf, const void* value, int32_t len, void* param);
X
Xiaoyu Wang 已提交
61 62 63 64

static uint8_t TRUE_VALUE = (uint8_t)TSDB_TRUE;
static uint8_t FALSE_VALUE = (uint8_t)TSDB_FALSE;

X
Xiaoyu Wang 已提交
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
static bool isNullStr(SToken* pToken) {
  return ((pToken->type == TK_NK_STRING) && (strlen(TSDB_DATA_NULL_STR_L) == pToken->n) &&
          (strncasecmp(TSDB_DATA_NULL_STR_L, pToken->z, pToken->n) == 0));
}

static bool isNullValue(int8_t dataType, SToken* pToken) {
  return TK_NULL == pToken->type || (!IS_STR_DATA_TYPE(dataType) && isNullStr(pToken));
}

static FORCE_INLINE int32_t toDouble(SToken* pToken, double* value, char** endPtr) {
  errno = 0;
  *value = taosStr2Double(pToken->z, endPtr);

  // not a valid integer number, return error
  if ((*endPtr - pToken->z) != pToken->n) {
    return TK_NK_ILLEGAL;
  }

  return pToken->type;
}

static int32_t skipInsertInto(const char** pSql, SMsgBuf* pMsg) {
  SToken token;
  NEXT_TOKEN(*pSql, token);
  if (TK_INSERT != token.type && TK_IMPORT != token.type) {
    return buildSyntaxErrMsg(pMsg, "keyword INSERT is expected", token.z);
91
  }
X
Xiaoyu Wang 已提交
92 93 94
  NEXT_TOKEN(*pSql, token);
  if (TK_INTO != token.type) {
    return buildSyntaxErrMsg(pMsg, "keyword INTO is expected", token.z);
95 96 97 98
  }
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
99 100 101 102 103 104 105 106 107 108 109 110 111
static int32_t skipParentheses(SInsertParseContext* pCxt, const char** pSql) {
  SToken  token;
  int32_t expectRightParenthesis = 1;
  while (1) {
    NEXT_TOKEN(*pSql, token);
    if (TK_NK_LP == token.type) {
      ++expectRightParenthesis;
    } else if (TK_NK_RP == token.type && 0 == --expectRightParenthesis) {
      break;
    }
    if (0 == token.n) {
      return buildSyntaxErrMsg(&pCxt->msg, ") expected", NULL);
    }
112
  }
X
Xiaoyu Wang 已提交
113 114
  return TSDB_CODE_SUCCESS;
}
D
dapan1121 已提交
115

X
Xiaoyu Wang 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128
static int32_t skipTableOptions(SInsertParseContext* pCxt, const char** pSql) {
  do {
    int32_t index = 0;
    SToken  token;
    NEXT_TOKEN_KEEP_SQL(*pSql, token, index);
    if (TK_TTL == token.type || TK_COMMENT == token.type) {
      *pSql += index;
      NEXT_TOKEN_WITH_PREV(*pSql, token);
    } else {
      break;
    }
  } while (1);
  return TSDB_CODE_SUCCESS;
129 130
}

X
Xiaoyu Wang 已提交
131 132 133 134 135 136 137 138 139 140 141 142
// pSql -> stb_name [(tag1_name, ...)] TAGS (tag1_value, ...)
static int32_t ignoreUsingClause(SInsertParseContext* pCxt, const char** pSql) {
  int32_t code = TSDB_CODE_SUCCESS;
  SToken  token;
  NEXT_TOKEN(*pSql, token);

  NEXT_TOKEN(*pSql, token);
  if (TK_NK_LP == token.type) {
    code = skipParentheses(pCxt, pSql);
    if (TSDB_CODE_SUCCESS == code) {
      NEXT_TOKEN(*pSql, token);
    }
143
  }
X
Xiaoyu Wang 已提交
144

X
Xiaoyu Wang 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158
  // pSql -> TAGS (tag1_value, ...)
  if (TSDB_CODE_SUCCESS == code) {
    if (TK_TAGS != token.type) {
      code = buildSyntaxErrMsg(&pCxt->msg, "TAGS is expected", token.z);
    } else {
      NEXT_TOKEN(*pSql, token);
    }
  }
  if (TSDB_CODE_SUCCESS == code) {
    if (TK_NK_LP != token.type) {
      code = buildSyntaxErrMsg(&pCxt->msg, "( is expected", token.z);
    } else {
      code = skipParentheses(pCxt, pSql);
    }
159 160
  }

X
Xiaoyu Wang 已提交
161 162
  if (TSDB_CODE_SUCCESS == code) {
    code = skipTableOptions(pCxt, pSql);
163
  }
X
Xiaoyu Wang 已提交
164 165

  return code;
166
}
D
dapan 已提交
167

X
Xiaoyu Wang 已提交
168
static int32_t parseDuplicateUsingClause(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, bool* pDuplicate) {
X
Xiaoyu Wang 已提交
169 170 171 172 173 174 175 176 177 178 179
  *pDuplicate = false;

  char tbFName[TSDB_TABLE_FNAME_LEN];
  tNameExtractFullName(&pStmt->targetTableName, tbFName);
  STableMeta** pMeta = taosHashGet(pStmt->pSubTableHashObj, tbFName, strlen(tbFName));
  if (NULL != pMeta) {
    *pDuplicate = true;
    int32_t code = ignoreUsingClause(pCxt, &pStmt->pSql);
    if (TSDB_CODE_SUCCESS == code) {
      return cloneTableMeta(*pMeta, &pStmt->pTableMeta);
    }
D
stmt  
dapan1121 已提交
180
  }
X
Xiaoyu Wang 已提交
181

H
refact  
Hongze Cheng 已提交
182
  return TSDB_CODE_SUCCESS;
D
stmt  
dapan1121 已提交
183 184
}

X
Xiaoyu Wang 已提交
185
// pStmt->pSql -> field1_name, ...)
X
Xiaoyu Wang 已提交
186 187 188 189 190
static int32_t parseBoundColumns(SInsertParseContext* pCxt, const char** pSql, bool isTags, SSchema* pSchema,
                                 SBoundColInfo* pBoundInfo) {
  bool* pUseCols = taosMemoryCalloc(pBoundInfo->numOfCols, sizeof(bool));
  if (NULL == pUseCols) {
    return TSDB_CODE_OUT_OF_MEMORY;
X
Xiaoyu Wang 已提交
191
  }
D
stmt  
dapan1121 已提交
192

X
Xiaoyu Wang 已提交
193 194
  pBoundInfo->numOfBound = 0;

D
dapan1121 已提交
195
  int16_t lastColIdx = -1;  // last column found
X
Xiaoyu Wang 已提交
196 197 198
  int32_t code = TSDB_CODE_SUCCESS;
  while (TSDB_CODE_SUCCESS == code) {
    SToken token;
X
Xiaoyu Wang 已提交
199 200 201 202 203 204 205 206 207 208 209
    NEXT_TOKEN(*pSql, token);

    if (TK_NK_RP == token.type) {
      break;
    }

    char tmpTokenBuf[TSDB_COL_NAME_LEN + 2] = {0};  // used for deleting Escape character backstick(`)
    strncpy(tmpTokenBuf, token.z, token.n);
    token.z = tmpTokenBuf;
    token.n = strdequote(token.z);

D
dapan1121 已提交
210 211
    int16_t t = lastColIdx + 1;
    int16_t index = insFindCol(&token, t, pBoundInfo->numOfCols, pSchema);
X
Xiaoyu Wang 已提交
212 213 214 215
    if (index < 0 && t > 0) {
      index = insFindCol(&token, 0, t, pSchema);
    }
    if (index < 0) {
X
Xiaoyu Wang 已提交
216 217 218 219 220 221 222 223
      code = generateSyntaxErrMsg(&pCxt->msg, TSDB_CODE_PAR_INVALID_COLUMN, token.z);
    } else if (pUseCols[index]) {
      code = buildSyntaxErrMsg(&pCxt->msg, "duplicated column name", token.z);
    } else {
      lastColIdx = index;
      pUseCols[index] = true;
      pBoundInfo->pColIndex[pBoundInfo->numOfBound] = index;
      ++pBoundInfo->numOfBound;
X
Xiaoyu Wang 已提交
224 225 226
    }
  }

X
Xiaoyu Wang 已提交
227 228
  if (TSDB_CODE_SUCCESS == code && !isTags && !pUseCols[0]) {
    code = buildInvalidOperationMsg(&pCxt->msg, "primary timestamp column can not be null");
X
Xiaoyu Wang 已提交
229 230
  }

X
Xiaoyu Wang 已提交
231
  taosMemoryFree(pUseCols);
X
Xiaoyu Wang 已提交
232

X
Xiaoyu Wang 已提交
233
  return code;
X
Xiaoyu Wang 已提交
234 235
}

X
Xiaoyu Wang 已提交
236 237 238 239 240
static int parseTime(const char** end, SToken* pToken, int16_t timePrec, int64_t* time, SMsgBuf* pMsgBuf) {
  int32_t     index = 0;
  int64_t     interval;
  int64_t     ts = 0;
  const char* pTokenEnd = *end;
241 242

  if (pToken->type == TK_NOW) {
243
    ts = taosGetTimestamp(timePrec);
244 245
  } else if (pToken->type == TK_TODAY) {
    ts = taosGetTimestampToday(timePrec);
246
  } else if (pToken->type == TK_NK_INTEGER) {
X
Xiaoyu Wang 已提交
247 248 249
    if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &ts)) {
      return buildSyntaxErrMsg(pMsgBuf, "invalid timestamp format", pToken->z);
    }
H
refact  
Hongze Cheng 已提交
250
  } else {  // parse the RFC-3339/ISO-8601 timestamp format string
S
os env  
Shengliang Guan 已提交
251
    if (taosParseTime(pToken->z, time, pToken->n, timePrec, tsDaylight) != TSDB_CODE_SUCCESS) {
252
      return buildSyntaxErrMsg(pMsgBuf, "invalid timestamp format", pToken->z);
253 254 255 256 257 258 259
    }

    return TSDB_CODE_SUCCESS;
  }

  for (int k = pToken->n; pToken->z[k] != '\0'; k++) {
    if (pToken->z[k] == ' ' || pToken->z[k] == '\t') continue;
H
refact  
Hongze Cheng 已提交
260
    if (pToken->z[k] == '(' && pToken->z[k + 1] == ')') {  // for insert NOW()/TODAY()
261 262 263 264
      *end = pTokenEnd = &pToken->z[k + 2];
      k++;
      continue;
    }
265
    if (pToken->z[k] == ',') {
266 267
      *end = pTokenEnd;
      *time = ts;
268 269 270 271 272 273 274 275 276 277 278
      return 0;
    }

    break;
  }

  /*
   * time expression:
   * e.g., now+12a, now-5h
   */
  index = 0;
X
Xiaoyu Wang 已提交
279
  SToken token = tStrGetToken(pTokenEnd, &index, false, NULL);
280 281
  pTokenEnd += index;

X
Xiaoyu Wang 已提交
282
  if (token.type == TK_NK_MINUS || token.type == TK_NK_PLUS) {
283
    index = 0;
X
Xiaoyu Wang 已提交
284
    SToken valueToken = tStrGetToken(pTokenEnd, &index, false, NULL);
285 286 287
    pTokenEnd += index;

    if (valueToken.n < 2) {
X
Xiaoyu Wang 已提交
288
      return buildSyntaxErrMsg(pMsgBuf, "value expected in timestamp", token.z);
289 290 291 292 293 294 295
    }

    char unit = 0;
    if (parseAbsoluteDuration(valueToken.z, valueToken.n, &interval, &unit, timePrec) != TSDB_CODE_SUCCESS) {
      return TSDB_CODE_TSC_INVALID_OPERATION;
    }

X
Xiaoyu Wang 已提交
296
    if (token.type == TK_NK_PLUS) {
297
      ts += interval;
298
    } else {
299
      ts = ts - interval;
300 301
    }

302
    *end = pTokenEnd;
303 304
  }

305
  *time = ts;
306 307
  return TSDB_CODE_SUCCESS;
}
308

D
Dingle Zhang 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
// need to call geosFreeBuffer(*output) later
static int parseGeometry(SToken *pToken, unsigned char **output, size_t *size) {
  int32_t code = TSDB_CODE_FAILED;

  //[ToDo] support to parse WKB as well as WKT
  if (pToken->type == TK_NK_STRING) {
    code = initCtxGeomFromText();
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }

    code = doGeomFromText(pToken->z, output, size);
    if (code != TSDB_CODE_SUCCESS) {
      return code;
    }
  }

  return code;
}

X
Xiaoyu Wang 已提交
329 330
static int32_t parseTagToken(const char** end, SToken* pToken, SSchema* pSchema, int16_t timePrec, STagVal* val,
                             SMsgBuf* pMsgBuf) {
X
Xiaoyu Wang 已提交
331 332 333
  int64_t  iv;
  uint64_t uv;
  char*    endptr = NULL;
334
  int32_t  code = TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
335

336
  if (isNullValue(pSchema->type, pToken)) {
X
Xiaoyu Wang 已提交
337
    if (TSDB_DATA_TYPE_TIMESTAMP == pSchema->type && PRIMARYKEY_TIMESTAMP_COL_ID == pSchema->colId) {
D
stmt  
dapan1121 已提交
338
      return buildSyntaxErrMsg(pMsgBuf, "primary timestamp should not be null", pToken->z);
X
Xiaoyu Wang 已提交
339 340
    }

X
Xiaoyu Wang 已提交
341
    return TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
342 343
  }

X
Xiaoyu Wang 已提交
344 345 346
  //  strcpy(val->colName, pSchema->name);
  val->cid = pSchema->colId;
  val->type = pSchema->type;
X
Xiaoyu Wang 已提交
347

X
Xiaoyu Wang 已提交
348 349
  switch (pSchema->type) {
    case TSDB_DATA_TYPE_BOOL: {
350
      if ((pToken->type == TK_NK_BOOL || pToken->type == TK_NK_STRING) && (pToken->n != 0)) {
X
Xiaoyu Wang 已提交
351
        if (strncmp(pToken->z, "true", pToken->n) == 0) {
X
Xiaoyu Wang 已提交
352
          *(int8_t*)(&val->i64) = TRUE_VALUE;
X
Xiaoyu Wang 已提交
353
        } else if (strncmp(pToken->z, "false", pToken->n) == 0) {
X
Xiaoyu Wang 已提交
354
          *(int8_t*)(&val->i64) = FALSE_VALUE;
X
Xiaoyu Wang 已提交
355 356 357
        } else {
          return buildSyntaxErrMsg(pMsgBuf, "invalid bool data", pToken->z);
        }
358
      } else if (pToken->type == TK_NK_INTEGER) {
X
Xiaoyu Wang 已提交
359
        *(int8_t*)(&val->i64) = ((taosStr2Int64(pToken->z, NULL, 10) == 0) ? FALSE_VALUE : TRUE_VALUE);
360
      } else if (pToken->type == TK_NK_FLOAT) {
X
Xiaoyu Wang 已提交
361
        *(int8_t*)(&val->i64) = ((taosStr2Double(pToken->z, NULL) == 0) ? FALSE_VALUE : TRUE_VALUE);
X
Xiaoyu Wang 已提交
362 363 364
      } else {
        return buildSyntaxErrMsg(pMsgBuf, "invalid bool data", pToken->z);
      }
X
Xiaoyu Wang 已提交
365
      break;
X
Xiaoyu Wang 已提交
366 367 368
    }

    case TSDB_DATA_TYPE_TINYINT: {
X
Xiaoyu Wang 已提交
369
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &iv)) {
X
Xiaoyu Wang 已提交
370 371 372 373 374
        return buildSyntaxErrMsg(pMsgBuf, "invalid tinyint data", pToken->z);
      } else if (!IS_VALID_TINYINT(iv)) {
        return buildSyntaxErrMsg(pMsgBuf, "tinyint data overflow", pToken->z);
      }

X
Xiaoyu Wang 已提交
375 376
      *(int8_t*)(&val->i64) = iv;
      break;
X
Xiaoyu Wang 已提交
377 378
    }

H
refact  
Hongze Cheng 已提交
379
    case TSDB_DATA_TYPE_UTINYINT: {
X
Xiaoyu Wang 已提交
380
      if (TSDB_CODE_SUCCESS != toUInteger(pToken->z, pToken->n, 10, &uv)) {
X
Xiaoyu Wang 已提交
381
        return buildSyntaxErrMsg(pMsgBuf, "invalid unsigned tinyint data", pToken->z);
X
Xiaoyu Wang 已提交
382
      } else if (uv > UINT8_MAX) {
X
Xiaoyu Wang 已提交
383 384
        return buildSyntaxErrMsg(pMsgBuf, "unsigned tinyint data overflow", pToken->z);
      }
X
Xiaoyu Wang 已提交
385 386
      *(uint8_t*)(&val->i64) = uv;
      break;
X
Xiaoyu Wang 已提交
387 388 389
    }

    case TSDB_DATA_TYPE_SMALLINT: {
X
Xiaoyu Wang 已提交
390
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &iv)) {
X
Xiaoyu Wang 已提交
391 392 393 394
        return buildSyntaxErrMsg(pMsgBuf, "invalid smallint data", pToken->z);
      } else if (!IS_VALID_SMALLINT(iv)) {
        return buildSyntaxErrMsg(pMsgBuf, "smallint data overflow", pToken->z);
      }
X
Xiaoyu Wang 已提交
395 396
      *(int16_t*)(&val->i64) = iv;
      break;
X
Xiaoyu Wang 已提交
397 398 399
    }

    case TSDB_DATA_TYPE_USMALLINT: {
X
Xiaoyu Wang 已提交
400
      if (TSDB_CODE_SUCCESS != toUInteger(pToken->z, pToken->n, 10, &uv)) {
X
Xiaoyu Wang 已提交
401
        return buildSyntaxErrMsg(pMsgBuf, "invalid unsigned smallint data", pToken->z);
X
Xiaoyu Wang 已提交
402
      } else if (uv > UINT16_MAX) {
X
Xiaoyu Wang 已提交
403 404
        return buildSyntaxErrMsg(pMsgBuf, "unsigned smallint data overflow", pToken->z);
      }
X
Xiaoyu Wang 已提交
405 406
      *(uint16_t*)(&val->i64) = uv;
      break;
X
Xiaoyu Wang 已提交
407 408 409
    }

    case TSDB_DATA_TYPE_INT: {
X
Xiaoyu Wang 已提交
410
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &iv)) {
X
Xiaoyu Wang 已提交
411 412 413 414
        return buildSyntaxErrMsg(pMsgBuf, "invalid int data", pToken->z);
      } else if (!IS_VALID_INT(iv)) {
        return buildSyntaxErrMsg(pMsgBuf, "int data overflow", pToken->z);
      }
X
Xiaoyu Wang 已提交
415 416
      *(int32_t*)(&val->i64) = iv;
      break;
X
Xiaoyu Wang 已提交
417 418 419
    }

    case TSDB_DATA_TYPE_UINT: {
X
Xiaoyu Wang 已提交
420
      if (TSDB_CODE_SUCCESS != toUInteger(pToken->z, pToken->n, 10, &uv)) {
X
Xiaoyu Wang 已提交
421
        return buildSyntaxErrMsg(pMsgBuf, "invalid unsigned int data", pToken->z);
X
Xiaoyu Wang 已提交
422
      } else if (uv > UINT32_MAX) {
X
Xiaoyu Wang 已提交
423 424
        return buildSyntaxErrMsg(pMsgBuf, "unsigned int data overflow", pToken->z);
      }
X
Xiaoyu Wang 已提交
425 426
      *(uint32_t*)(&val->i64) = uv;
      break;
X
Xiaoyu Wang 已提交
427 428 429
    }

    case TSDB_DATA_TYPE_BIGINT: {
X
Xiaoyu Wang 已提交
430
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &iv)) {
X
Xiaoyu Wang 已提交
431 432
        return buildSyntaxErrMsg(pMsgBuf, "invalid bigint data", pToken->z);
      }
X
Xiaoyu Wang 已提交
433 434
      val->i64 = iv;
      break;
X
Xiaoyu Wang 已提交
435 436 437
    }

    case TSDB_DATA_TYPE_UBIGINT: {
X
Xiaoyu Wang 已提交
438
      if (TSDB_CODE_SUCCESS != toUInteger(pToken->z, pToken->n, 10, &uv)) {
X
Xiaoyu Wang 已提交
439 440
        return buildSyntaxErrMsg(pMsgBuf, "invalid unsigned bigint data", pToken->z);
      }
X
Xiaoyu Wang 已提交
441 442
      *(uint64_t*)(&val->i64) = uv;
      break;
X
Xiaoyu Wang 已提交
443 444 445 446
    }

    case TSDB_DATA_TYPE_FLOAT: {
      double dv;
447
      if (TK_NK_ILLEGAL == toDouble(pToken, &dv, &endptr)) {
X
Xiaoyu Wang 已提交
448 449
        return buildSyntaxErrMsg(pMsgBuf, "illegal float data", pToken->z);
      }
H
refact  
Hongze Cheng 已提交
450 451
      if (((dv == HUGE_VAL || dv == -HUGE_VAL) && errno == ERANGE) || dv > FLT_MAX || dv < -FLT_MAX || isinf(dv) ||
          isnan(dv)) {
X
Xiaoyu Wang 已提交
452 453
        return buildSyntaxErrMsg(pMsgBuf, "illegal float data", pToken->z);
      }
X
Xiaoyu Wang 已提交
454 455
      *(float*)(&val->i64) = dv;
      break;
X
Xiaoyu Wang 已提交
456 457 458 459
    }

    case TSDB_DATA_TYPE_DOUBLE: {
      double dv;
460
      if (TK_NK_ILLEGAL == toDouble(pToken, &dv, &endptr)) {
X
Xiaoyu Wang 已提交
461 462 463 464 465
        return buildSyntaxErrMsg(pMsgBuf, "illegal double data", pToken->z);
      }
      if (((dv == HUGE_VAL || dv == -HUGE_VAL) && errno == ERANGE) || isinf(dv) || isnan(dv)) {
        return buildSyntaxErrMsg(pMsgBuf, "illegal double data", pToken->z);
      }
X
Xiaoyu Wang 已提交
466 467 468

      *(double*)(&val->i64) = dv;
      break;
X
Xiaoyu Wang 已提交
469 470
    }

471
    case TSDB_DATA_TYPE_BINARY: {
X
Xiaoyu Wang 已提交
472 473
      // Too long values will raise the invalid sql error message
      if (pToken->n + VARSTR_HEADER_SIZE > pSchema->bytes) {
D
dapan1121 已提交
474
        return generateSyntaxErrMsg(pMsgBuf, TSDB_CODE_PAR_VALUE_TOO_LONG, pSchema->name);
X
Xiaoyu Wang 已提交
475
      }
476
      val->pData = taosStrdup(pToken->z);
X
Xiaoyu Wang 已提交
477 478
      val->nData = pToken->n;
      break;
X
Xiaoyu Wang 已提交
479 480
    }

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
    case TSDB_DATA_TYPE_GEOMETRY: {
      unsigned char* output = NULL;
      size_t         size = 0;

      code = parseGeometry(pToken, &output, &size);
      if (code != TSDB_CODE_SUCCESS) {
        code = buildSyntaxErrMsg(pMsgBuf, getThreadLocalGeosCtx()->errMsg, pToken->z);
      } else if (size + VARSTR_HEADER_SIZE > pSchema->bytes) {
        // Too long values will raise the invalid sql error message
        code = generateSyntaxErrMsg(pMsgBuf, TSDB_CODE_PAR_VALUE_TOO_LONG, pSchema->name);
      } else {
        val->pData = taosMemoryMalloc(size);
        if (NULL == val->pData) {
          code = TSDB_CODE_OUT_OF_MEMORY;
        } else {
          memcpy(val->pData, output, size);
          val->nData = size;
        }
      }

      geosFreeBuffer(output);
      break;
    }

X
Xiaoyu Wang 已提交
505
    case TSDB_DATA_TYPE_NCHAR: {
X
Xiaoyu Wang 已提交
506 507 508 509 510 511 512 513 514 515 516 517 518 519
      int32_t output = 0;
      void*   p = taosMemoryCalloc(1, pSchema->bytes - VARSTR_HEADER_SIZE);
      if (p == NULL) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      if (!taosMbsToUcs4(pToken->z, pToken->n, (TdUcs4*)(p), pSchema->bytes - VARSTR_HEADER_SIZE, &output)) {
        if (errno == E2BIG) {
          taosMemoryFree(p);
          return generateSyntaxErrMsg(pMsgBuf, TSDB_CODE_PAR_VALUE_TOO_LONG, pSchema->name);
        }
        char buf[512] = {0};
        snprintf(buf, tListLen(buf), " taosMbsToUcs4 error:%s", strerror(errno));
        taosMemoryFree(p);
        return buildSyntaxErrMsg(pMsgBuf, buf, pToken->z);
520
      }
X
Xiaoyu Wang 已提交
521 522 523
      val->pData = p;
      val->nData = output;
      break;
524
    }
X
Xiaoyu Wang 已提交
525
    case TSDB_DATA_TYPE_TIMESTAMP: {
X
Xiaoyu Wang 已提交
526
      if (parseTime(end, pToken, timePrec, &iv, pMsgBuf) != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
527 528 529
        return buildSyntaxErrMsg(pMsgBuf, "invalid timestamp", pToken->z);
      }

X
Xiaoyu Wang 已提交
530 531
      val->i64 = iv;
      break;
X
Xiaoyu Wang 已提交
532 533 534
    }
  }

535
  return code;
X
Xiaoyu Wang 已提交
536 537
}

X
Xiaoyu Wang 已提交
538 539
// input pStmt->pSql:  [(tag1_name, ...)] TAGS (tag1_value, ...) ...
// output pStmt->pSql: TAGS (tag1_value, ...) ...
X
Xiaoyu Wang 已提交
540
static int32_t parseBoundTagsClause(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
541
  insInitBoundColsInfo(getNumOfTags(pStmt->pTableMeta), &pCxt->tags);
542

X
Xiaoyu Wang 已提交
543 544 545 546 547
  SToken  token;
  int32_t index = 0;
  NEXT_TOKEN_KEEP_SQL(pStmt->pSql, token, index);
  if (TK_NK_LP != token.type) {
    return TSDB_CODE_SUCCESS;
548 549
  }

X
Xiaoyu Wang 已提交
550
  pStmt->pSql += index;
X
Xiaoyu Wang 已提交
551
  return parseBoundColumns(pCxt, &pStmt->pSql, true, getTableTagSchema(pStmt->pTableMeta), &pCxt->tags);
X
Xiaoyu Wang 已提交
552
}
553

X
Xiaoyu Wang 已提交
554
static int32_t parseTagValue(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, SSchema* pTagSchema, SToken* pToken,
X
Xiaoyu Wang 已提交
555 556 557 558 559 560 561 562
                             SArray* pTagName, SArray* pTagVals, STag** pTag) {
  if (!isNullValue(pTagSchema->type, pToken)) {
    taosArrayPush(pTagName, pTagSchema->name);
  }

  if (pTagSchema->type == TSDB_DATA_TYPE_JSON) {
    if (pToken->n > (TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE) {
      return buildSyntaxErrMsg(&pCxt->msg, "json string too long than 4095", pToken->z);
563 564
    }

X
Xiaoyu Wang 已提交
565 566 567 568 569 570
    if (isNullValue(pTagSchema->type, pToken)) {
      return tTagNew(pTagVals, 1, true, pTag);
    } else {
      return parseJsontoTagData(pToken->z, pTagVals, pTag, &pCxt->msg);
    }
  }
571

X
Xiaoyu Wang 已提交
572 573 574 575 576 577 578 579 580 581
  STagVal val = {0};
  int32_t code =
      parseTagToken(&pStmt->pSql, pToken, pTagSchema, pStmt->pTableMeta->tableInfo.precision, &val, &pCxt->msg);
  if (TSDB_CODE_SUCCESS == code) {
    taosArrayPush(pTagVals, &val);
  }

  return code;
}

X
Xiaoyu Wang 已提交
582
static int32_t buildCreateTbReq(SVnodeModifyOpStmt* pStmt, STag* pTag, SArray* pTagName) {
X
Xiaoyu Wang 已提交
583 584 585 586
  pStmt->pCreateTblReq = taosMemoryCalloc(1, sizeof(SVCreateTbReq));
  if (NULL == pStmt->pCreateTblReq) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
X
Xiaoyu Wang 已提交
587
  insBuildCreateTbReq(pStmt->pCreateTblReq, pStmt->targetTableName.tname, pTag, pStmt->pTableMeta->suid,
X
Xiaoyu Wang 已提交
588 589
                      pStmt->usingTableName.tname, pTagName, pStmt->pTableMeta->tableInfo.numOfTags,
                      TSDB_DEFAULT_TABLE_TTL);
X
Xiaoyu Wang 已提交
590
  return TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
}

static int32_t checkAndTrimValue(SToken* pToken, char* tmpTokenBuf, SMsgBuf* pMsgBuf) {
  if ((pToken->type != TK_NOW && pToken->type != TK_TODAY && pToken->type != TK_NK_INTEGER &&
       pToken->type != TK_NK_STRING && pToken->type != TK_NK_FLOAT && pToken->type != TK_NK_BOOL &&
       pToken->type != TK_NULL && pToken->type != TK_NK_HEX && pToken->type != TK_NK_OCT &&
       pToken->type != TK_NK_BIN) ||
      (pToken->n == 0) || (pToken->type == TK_NK_RP)) {
    return buildSyntaxErrMsg(pMsgBuf, "invalid data or symbol", pToken->z);
  }

  // Remove quotation marks
  if (TK_NK_STRING == pToken->type) {
    if (pToken->n >= TSDB_MAX_BYTES_PER_ROW) {
      return buildSyntaxErrMsg(pMsgBuf, "too long string", pToken->z);
606
    }
X
Xiaoyu Wang 已提交
607 608 609 610 611 612 613 614 615

    int32_t len = trimString(pToken->z, pToken->n, tmpTokenBuf, TSDB_MAX_BYTES_PER_ROW);
    pToken->z = tmpTokenBuf;
    pToken->n = len;
  }

  return TSDB_CODE_SUCCESS;
}

616 617 618 619 620 621 622 623 624 625 626
typedef struct SRewriteTagCondCxt {
  SArray* pTagVals;
  SArray* pTagName;
  int32_t code;
} SRewriteTagCondCxt;

static int32_t rewriteTagCondColumnImpl(STagVal* pVal, SNode** pNode) {
  SValueNode* pValue = (SValueNode*)nodesMakeNode(QUERY_NODE_VALUE);
  if (NULL == pValue) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
X
Xiaoyu Wang 已提交
627 628 629 630 631

  pValue->node.resType = ((SColumnNode*)*pNode)->node.resType;
  nodesDestroyNode(*pNode);
  *pNode = (SNode*)pValue;

632 633 634
  switch (pVal->type) {
    case TSDB_DATA_TYPE_BOOL:
      pValue->datum.b = *(int8_t*)(&pVal->i64);
X
Xiaoyu Wang 已提交
635
      *(bool*)&pValue->typeData = pValue->datum.b;
636 637 638
      break;
    case TSDB_DATA_TYPE_TINYINT:
      pValue->datum.i = *(int8_t*)(&pVal->i64);
X
Xiaoyu Wang 已提交
639
      *(int8_t*)&pValue->typeData = pValue->datum.i;
640 641 642
      break;
    case TSDB_DATA_TYPE_SMALLINT:
      pValue->datum.i = *(int16_t*)(&pVal->i64);
X
Xiaoyu Wang 已提交
643
      *(int16_t*)&pValue->typeData = pValue->datum.i;
644 645 646
      break;
    case TSDB_DATA_TYPE_INT:
      pValue->datum.i = *(int32_t*)(&pVal->i64);
X
Xiaoyu Wang 已提交
647
      *(int32_t*)&pValue->typeData = pValue->datum.i;
648 649 650
      break;
    case TSDB_DATA_TYPE_BIGINT:
      pValue->datum.i = pVal->i64;
X
Xiaoyu Wang 已提交
651
      pValue->typeData = pValue->datum.i;
652 653 654
      break;
    case TSDB_DATA_TYPE_FLOAT:
      pValue->datum.d = *(float*)(&pVal->i64);
X
Xiaoyu Wang 已提交
655
      *(float*)&pValue->typeData = pValue->datum.d;
656 657 658
      break;
    case TSDB_DATA_TYPE_DOUBLE:
      pValue->datum.d = *(double*)(&pVal->i64);
X
Xiaoyu Wang 已提交
659
      *(double*)&pValue->typeData = pValue->datum.d;
660 661 662 663 664 665 666 667 668 669 670 671
      break;
    case TSDB_DATA_TYPE_VARCHAR:
    case TSDB_DATA_TYPE_NCHAR:
      pValue->datum.p = taosMemoryCalloc(1, pVal->nData + VARSTR_HEADER_SIZE);
      if (NULL == pValue->datum.p) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      varDataSetLen(pValue->datum.p, pVal->nData);
      memcpy(varDataVal(pValue->datum.p), pVal->pData, pVal->nData);
      break;
    case TSDB_DATA_TYPE_TIMESTAMP:
      pValue->datum.i = pVal->i64;
X
Xiaoyu Wang 已提交
672
      pValue->typeData = pValue->datum.i;
673 674 675
      break;
    case TSDB_DATA_TYPE_UTINYINT:
      pValue->datum.i = *(uint8_t*)(&pVal->i64);
X
Xiaoyu Wang 已提交
676
      *(uint8_t*)&pValue->typeData = pValue->datum.i;
677 678 679
      break;
    case TSDB_DATA_TYPE_USMALLINT:
      pValue->datum.i = *(uint16_t*)(&pVal->i64);
X
Xiaoyu Wang 已提交
680
      *(uint16_t*)&pValue->typeData = pValue->datum.i;
681 682 683
      break;
    case TSDB_DATA_TYPE_UINT:
      pValue->datum.i = *(uint32_t*)(&pVal->i64);
X
Xiaoyu Wang 已提交
684
      *(uint32_t*)&pValue->typeData = pValue->datum.i;
685 686 687
      break;
    case TSDB_DATA_TYPE_UBIGINT:
      pValue->datum.i = *(uint64_t*)(&pVal->i64);
X
Xiaoyu Wang 已提交
688
      *(uint64_t*)&pValue->typeData = pValue->datum.i;
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
      break;
    case TSDB_DATA_TYPE_JSON:
    case TSDB_DATA_TYPE_VARBINARY:
    case TSDB_DATA_TYPE_DECIMAL:
    case TSDB_DATA_TYPE_BLOB:
    case TSDB_DATA_TYPE_MEDIUMBLOB:
    default:
      return TSDB_CODE_FAILED;
  }
  return TSDB_CODE_SUCCESS;
}

static int32_t rewriteTagCondColumn(SArray* pTagVals, SArray* pTagName, SNode** pNode) {
  SColumnNode* pCol = (SColumnNode*)*pNode;
  int32_t      ntags = taosArrayGetSize(pTagName);
  for (int32_t i = 0; i < ntags; ++i) {
    char* pTagColName = taosArrayGet(pTagName, i);
    if (0 == strcmp(pTagColName, pCol->colName)) {
      return rewriteTagCondColumnImpl(taosArrayGet(pTagVals, i), pNode);
    }
  }
  return TSDB_CODE_PAR_PERMISSION_DENIED;
}

static EDealRes rewriteTagCond(SNode** pNode, void* pContext) {
  if (QUERY_NODE_COLUMN == nodeType(*pNode)) {
    SRewriteTagCondCxt* pCxt = pContext;
    pCxt->code = rewriteTagCondColumn(pCxt->pTagVals, pCxt->pTagName, pNode);
    return (TSDB_CODE_SUCCESS == pCxt->code ? DEAL_RES_IGNORE_CHILD : DEAL_RES_ERROR);
  }
  return DEAL_RES_CONTINUE;
}

static int32_t setTagVal(SArray* pTagVals, SArray* pTagName, SNode* pCond) {
  SRewriteTagCondCxt cxt = {.code = TSDB_CODE_SUCCESS, .pTagVals = pTagVals, .pTagName = pTagName};
  nodesRewriteExpr(&pCond, rewriteTagCond, &cxt);
  return cxt.code;
}

static int32_t checkTagCondResult(SNode* pResult) {
  return (QUERY_NODE_VALUE == nodeType(pResult) && ((SValueNode*)pResult)->datum.b) ? TSDB_CODE_SUCCESS
                                                                                    : TSDB_CODE_PAR_PERMISSION_DENIED;
}

X
Xiaoyu Wang 已提交
733 734
static int32_t checkSubtablePrivilege(SArray* pTagVals, SArray* pTagName, SNode** pCond) {
  int32_t code = setTagVal(pTagVals, pTagName, *pCond);
735
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
736
    code = scalarCalculateConstants(*pCond, pCond);
737 738
  }
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
739
    code = checkTagCondResult(*pCond);
740
  }
X
Xiaoyu Wang 已提交
741
  NODES_DESTORY_NODE(*pCond);
742 743 744
  return code;
}

X
Xiaoyu Wang 已提交
745
// pSql -> tag1_value, ...)
X
Xiaoyu Wang 已提交
746
static int32_t parseTagsClauseImpl(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
  int32_t  code = TSDB_CODE_SUCCESS;
  SSchema* pSchema = getTableTagSchema(pStmt->pTableMeta);
  SArray*  pTagVals = taosArrayInit(pCxt->tags.numOfBound, sizeof(STagVal));
  SArray*  pTagName = taosArrayInit(8, TSDB_COL_NAME_LEN);
  SToken   token;
  bool     isParseBindParam = false;
  bool     isJson = false;
  STag*    pTag = NULL;
  for (int i = 0; TSDB_CODE_SUCCESS == code && i < pCxt->tags.numOfBound; ++i) {
    NEXT_TOKEN_WITH_PREV(pStmt->pSql, token);

    if (token.type == TK_NK_QUESTION) {
      isParseBindParam = true;
      if (NULL == pCxt->pComCxt->pStmtCb) {
        code = buildSyntaxErrMsg(&pCxt->msg, "? only used in stmt", token.z);
        break;
      }

      continue;
766
    }
X
Xiaoyu Wang 已提交
767 768 769 770

    if (isParseBindParam) {
      code = buildInvalidOperationMsg(&pCxt->msg, "no mix usage for ? and tag values");
      break;
771
    }
X
Xiaoyu Wang 已提交
772

X
Xiaoyu Wang 已提交
773
    SSchema* pTagSchema = &pSchema[pCxt->tags.pColIndex[i]];
X
Xiaoyu Wang 已提交
774 775 776 777
    isJson = pTagSchema->type == TSDB_DATA_TYPE_JSON;
    code = checkAndTrimValue(&token, pCxt->tmpTokenBuf, &pCxt->msg);
    if (TSDB_CODE_SUCCESS == code) {
      code = parseTagValue(pCxt, pStmt, pTagSchema, &token, pTagName, pTagVals, &pTag);
C
Cary Xu 已提交
778
    }
779 780
  }

X
Xiaoyu Wang 已提交
781 782 783 784
  if (TSDB_CODE_SUCCESS == code && NULL != pStmt->pTagCond) {
    code = checkSubtablePrivilege(pTagVals, pTagName, &pStmt->pTagCond);
  }

X
Xiaoyu Wang 已提交
785 786 787
  if (TSDB_CODE_SUCCESS == code && !isParseBindParam && !isJson) {
    code = tTagNew(pTagVals, 1, false, &pTag);
  }
788

X
Xiaoyu Wang 已提交
789
  if (TSDB_CODE_SUCCESS == code && !isParseBindParam) {
X
Xiaoyu Wang 已提交
790
    code = buildCreateTbReq(pStmt, pTag, pTagName);
X
Xiaoyu Wang 已提交
791 792 793 794 795 796 797
    pTag = NULL;
  }

  for (int i = 0; i < taosArrayGetSize(pTagVals); ++i) {
    STagVal* p = (STagVal*)taosArrayGet(pTagVals, i);
    if (IS_VAR_DATA_TYPE(p->type)) {
      taosMemoryFreeClear(p->pData);
798
    }
X
Xiaoyu Wang 已提交
799 800 801 802 803 804 805 806 807
  }
  taosArrayDestroy(pTagVals);
  taosArrayDestroy(pTagName);
  tTagFree(pTag);
  return code;
}

// input pStmt->pSql:  TAGS (tag1_value, ...) [table_options] ...
// output pStmt->pSql: [table_options] ...
X
Xiaoyu Wang 已提交
808
static int32_t parseTagsClause(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
  SToken token;
  NEXT_TOKEN(pStmt->pSql, token);
  if (TK_TAGS != token.type) {
    return buildSyntaxErrMsg(&pCxt->msg, "TAGS is expected", token.z);
  }

  NEXT_TOKEN(pStmt->pSql, token);
  if (TK_NK_LP != token.type) {
    return buildSyntaxErrMsg(&pCxt->msg, "( is expected", token.z);
  }

  int32_t code = parseTagsClauseImpl(pCxt, pStmt);
  if (TSDB_CODE_SUCCESS == code) {
    NEXT_VALID_TOKEN(pStmt->pSql, token);
    if (TK_NK_COMMA == token.type) {
      code = generateSyntaxErrMsg(&pCxt->msg, TSDB_CODE_PAR_TAGS_NOT_MATCHED);
    } else if (TK_NK_RP != token.type) {
      code = buildSyntaxErrMsg(&pCxt->msg, ") is expected", token.z);
827 828
    }
  }
X
Xiaoyu Wang 已提交
829 830
  return code;
}
831

X
Xiaoyu Wang 已提交
832
static int32_t storeTableMeta(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
833
  pStmt->pTableMeta->suid = pStmt->pTableMeta->uid;
X
Xiaoyu Wang 已提交
834 835 836 837 838 839
  pStmt->pTableMeta->uid = pStmt->totalTbNum;
  pStmt->pTableMeta->tableType = TSDB_CHILD_TABLE;

  STableMeta* pBackup = NULL;
  if (TSDB_CODE_SUCCESS != cloneTableMeta(pStmt->pTableMeta, &pBackup)) {
    return TSDB_CODE_OUT_OF_MEMORY;
840
  }
841

X
Xiaoyu Wang 已提交
842 843 844 845 846
  char tbFName[TSDB_TABLE_FNAME_LEN];
  tNameExtractFullName(&pStmt->targetTableName, tbFName);
  return taosHashPut(pStmt->pSubTableHashObj, tbFName, strlen(tbFName), &pBackup, POINTER_BYTES);
}

X
Xiaoyu Wang 已提交
847
static int32_t parseTableOptions(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
848 849 850 851 852 853 854 855 856 857
  do {
    int32_t index = 0;
    SToken  token;
    NEXT_TOKEN_KEEP_SQL(pStmt->pSql, token, index);
    if (TK_TTL == token.type) {
      pStmt->pSql += index;
      NEXT_TOKEN_WITH_PREV(pStmt->pSql, token);
      if (TK_NK_INTEGER != token.type) {
        return buildSyntaxErrMsg(&pCxt->msg, "Invalid option ttl", token.z);
      }
X
Xiaoyu Wang 已提交
858 859
      pStmt->pCreateTblReq->ttl = taosStr2Int32(token.z, NULL, 10);
      if (pStmt->pCreateTblReq->ttl < 0) {
X
Xiaoyu Wang 已提交
860 861 862 863 864 865 866 867 868 869 870 871
        return buildSyntaxErrMsg(&pCxt->msg, "Invalid option ttl", token.z);
      }
    } else if (TK_COMMENT == token.type) {
      pStmt->pSql += index;
      NEXT_TOKEN(pStmt->pSql, token);
      if (TK_NK_STRING != token.type) {
        return buildSyntaxErrMsg(&pCxt->msg, "Invalid option comment", token.z);
      }
      if (token.n >= TSDB_TB_COMMENT_LEN) {
        return buildSyntaxErrMsg(&pCxt->msg, "comment too long", token.z);
      }
      int32_t len = trimString(token.z, token.n, pCxt->tmpTokenBuf, TSDB_TB_COMMENT_LEN);
X
Xiaoyu Wang 已提交
872 873
      pStmt->pCreateTblReq->comment = strndup(pCxt->tmpTokenBuf, len);
      if (NULL == pStmt->pCreateTblReq->comment) {
X
Xiaoyu Wang 已提交
874 875
        return TSDB_CODE_OUT_OF_MEMORY;
      }
X
Xiaoyu Wang 已提交
876
      pStmt->pCreateTblReq->commentLen = len;
X
Xiaoyu Wang 已提交
877 878 879 880
    } else {
      break;
    }
  } while (1);
881 882 883
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
884 885 886 887 888 889
// input pStmt->pSql:
//   1. [(tag1_name, ...)] ...
//   2. VALUES ... | FILE ...
// output pStmt->pSql:
//   1. [(field1_name, ...)]
//   2. VALUES ... | FILE ...
X
Xiaoyu Wang 已提交
890
static int32_t parseUsingClauseBottom(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
891
  if (!pStmt->usingTableProcessing || pCxt->usingDuplicateTable) {
X
Xiaoyu Wang 已提交
892 893
    return TSDB_CODE_SUCCESS;
  }
wmmhello's avatar
wmmhello 已提交
894

X
Xiaoyu Wang 已提交
895 896 897 898 899 900 901 902 903 904 905
  int32_t code = parseBoundTagsClause(pCxt, pStmt);
  if (TSDB_CODE_SUCCESS == code) {
    code = parseTagsClause(pCxt, pStmt);
  }
  if (TSDB_CODE_SUCCESS == code) {
    code = parseTableOptions(pCxt, pStmt);
  }

  return code;
}

X
Xiaoyu Wang 已提交
906 907 908 909 910 911
static void setUserAuthInfo(SParseContext* pCxt, SName* pTbName, SUserAuthInfo* pInfo) {
  snprintf(pInfo->user, sizeof(pInfo->user), "%s", pCxt->pUser);
  memcpy(&pInfo->tbName, pTbName, sizeof(SName));
  pInfo->type = AUTH_TYPE_WRITE;
}

X
Xiaoyu Wang 已提交
912
static int32_t checkAuth(SParseContext* pCxt, SName* pTbName, bool* pMissCache, SNode** pTagCond) {
X
Xiaoyu Wang 已提交
913 914 915 916 917
  int32_t       code = TSDB_CODE_SUCCESS;
  SUserAuthInfo authInfo = {0};
  setUserAuthInfo(pCxt, pTbName, &authInfo);
  SUserAuthRes authRes = {0};
  bool         exists = true;
X
Xiaoyu Wang 已提交
918
  if (pCxt->async) {
D
dapan1121 已提交
919
    code = catalogChkAuthFromCache(pCxt->pCatalog, &authInfo, &authRes, &exists);
X
Xiaoyu Wang 已提交
920
  } else {
X
Xiaoyu Wang 已提交
921 922 923 924
    SRequestConnInfo conn = {.pTrans = pCxt->pTransporter,
                             .requestId = pCxt->requestId,
                             .requestObjRefId = pCxt->requestRid,
                             .mgmtEps = pCxt->mgmtEpSet};
D
dapan1121 已提交
925
    code = catalogChkAuth(pCxt->pCatalog, &conn, &authInfo, &authRes);
X
Xiaoyu Wang 已提交
926
  }
X
Xiaoyu Wang 已提交
927 928 929
  if (TSDB_CODE_SUCCESS == code) {
    if (!exists) {
      *pMissCache = true;
X
Xiaoyu Wang 已提交
930
    } else if (!authRes.pass) {
X
Xiaoyu Wang 已提交
931
      code = TSDB_CODE_PAR_PERMISSION_DENIED;
X
Xiaoyu Wang 已提交
932 933
    } else if (NULL != authRes.pCond) {
      *pTagCond = authRes.pCond;
X
Xiaoyu Wang 已提交
934
    }
X
Xiaoyu Wang 已提交
935 936 937 938
  }
  return code;
}

X
Xiaoyu Wang 已提交
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
static int32_t checkAuthForTable(SParseContext* pCxt, SName* pTbName, bool* pMissCache, bool* pNeedTableTagVal) {
  SNode*  pTagCond = NULL;
  int32_t code = checkAuth(pCxt, pTbName, pMissCache, &pTagCond);
  if (TSDB_CODE_SUCCESS == code) {
    *pNeedTableTagVal = ((*pMissCache) || (NULL != pTagCond));
    *pMissCache = (NULL != pTagCond);
  }
  nodesDestroyNode(pTagCond);
  return code;
}

static int32_t checkAuthForStable(SParseContext* pCxt, SName* pTbName, bool* pMissCache, SNode** pTagCond) {
  return checkAuth(pCxt, pTbName, pMissCache, pTagCond);
}

X
Xiaoyu Wang 已提交
954 955
static int32_t getTableMeta(SInsertParseContext* pCxt, SName* pTbName, bool isStb, STableMeta** pTableMeta,
                            bool* pMissCache) {
X
Xiaoyu Wang 已提交
956 957
  SParseContext* pComCxt = pCxt->pComCxt;
  int32_t        code = TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
958 959
  if (pComCxt->async) {
    if (isStb) {
X
Xiaoyu Wang 已提交
960
      code = catalogGetCachedSTableMeta(pComCxt->pCatalog, pTbName, pTableMeta);
X
Xiaoyu Wang 已提交
961
    } else {
X
Xiaoyu Wang 已提交
962
      code = catalogGetCachedTableMeta(pComCxt->pCatalog, pTbName, pTableMeta);
X
Xiaoyu Wang 已提交
963 964
    }
  } else {
X
Xiaoyu Wang 已提交
965 966 967 968
    SRequestConnInfo conn = {.pTrans = pComCxt->pTransporter,
                             .requestId = pComCxt->requestId,
                             .requestObjRefId = pComCxt->requestRid,
                             .mgmtEps = pComCxt->mgmtEpSet};
X
Xiaoyu Wang 已提交
969 970 971 972
    if (isStb) {
      code = catalogGetSTableMeta(pComCxt->pCatalog, &conn, pTbName, pTableMeta);
    } else {
      code = catalogGetTableMeta(pComCxt->pCatalog, &conn, pTbName, pTableMeta);
wmmhello's avatar
wmmhello 已提交
973
    }
X
Xiaoyu Wang 已提交
974 975 976 977 978 979
  }
  if (TSDB_CODE_SUCCESS == code) {
    if (NULL == *pTableMeta) {
      *pMissCache = true;
    } else if (isStb && TSDB_SUPER_TABLE != (*pTableMeta)->tableType) {
      code = buildInvalidOperationMsg(&pCxt->msg, "create table only from super table is allowed");
X
Xiaoyu Wang 已提交
980 981
    } else if (!isStb && TSDB_SUPER_TABLE == (*pTableMeta)->tableType) {
      code = buildInvalidOperationMsg(&pCxt->msg, "insert data into super table is not supported");
X
Xiaoyu Wang 已提交
982 983 984 985 986
    }
  }
  return code;
}

X
Xiaoyu Wang 已提交
987
static int32_t getTableVgroup(SParseContext* pCxt, SVnodeModifyOpStmt* pStmt, bool isStb, bool* pMissCache) {
X
Xiaoyu Wang 已提交
988 989 990
  int32_t     code = TSDB_CODE_SUCCESS;
  SVgroupInfo vg;
  bool        exists = true;
X
Xiaoyu Wang 已提交
991
  if (pCxt->async) {
X
Xiaoyu Wang 已提交
992
    code = catalogGetCachedTableHashVgroup(pCxt->pCatalog, &pStmt->targetTableName, &vg, &exists);
X
Xiaoyu Wang 已提交
993
  } else {
X
Xiaoyu Wang 已提交
994 995 996 997
    SRequestConnInfo conn = {.pTrans = pCxt->pTransporter,
                             .requestId = pCxt->requestId,
                             .requestObjRefId = pCxt->requestRid,
                             .mgmtEps = pCxt->mgmtEpSet};
X
Xiaoyu Wang 已提交
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    code = catalogGetTableHashVgroup(pCxt->pCatalog, &conn, &pStmt->targetTableName, &vg);
  }
  if (TSDB_CODE_SUCCESS == code) {
    if (exists) {
      if (isStb) {
        pStmt->pTableMeta->vgId = vg.vgId;
      }
      code = taosHashPut(pStmt->pVgroupsHashObj, (const char*)&vg.vgId, sizeof(vg.vgId), (char*)&vg, sizeof(vg));
    }
    *pMissCache = !exists;
  }
  return code;
}
1011

X
Xiaoyu Wang 已提交
1012
static int32_t getTableMetaAndVgroupImpl(SParseContext* pCxt, SVnodeModifyOpStmt* pStmt, bool* pMissCache) {
1013
  SVgroupInfo vg;
1014
  int32_t     code = catalogGetCachedTableVgMeta(pCxt->pCatalog, &pStmt->targetTableName, &vg, &pStmt->pTableMeta);
1015
  if (TSDB_CODE_SUCCESS == code) {
1016
    if (NULL != pStmt->pTableMeta) {
1017 1018
      code = taosHashPut(pStmt->pVgroupsHashObj, (const char*)&vg.vgId, sizeof(vg.vgId), (char*)&vg, sizeof(vg));
    }
1019
    *pMissCache = (NULL == pStmt->pTableMeta);
1020 1021 1022 1023
  }
  return code;
}

X
Xiaoyu Wang 已提交
1024
static int32_t getTableMetaAndVgroup(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, bool* pMissCache) {
1025 1026 1027
  SParseContext* pComCxt = pCxt->pComCxt;
  int32_t        code = TSDB_CODE_SUCCESS;
  if (pComCxt->async) {
D
dapan1121 已提交
1028
    code = getTableMetaAndVgroupImpl(pComCxt, pStmt, pMissCache);
1029 1030 1031 1032 1033 1034 1035 1036 1037
  } else {
    code = getTableMeta(pCxt, &pStmt->targetTableName, false, &pStmt->pTableMeta, pMissCache);
    if (TSDB_CODE_SUCCESS == code && !pCxt->missCache) {
      code = getTableVgroup(pCxt->pComCxt, pStmt, false, &pCxt->missCache);
    }
  }
  return code;
}

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
static int32_t collectUseTable(const SName* pName, SHashObj* pTable) {
  char fullName[TSDB_TABLE_FNAME_LEN];
  tNameExtractFullName(pName, fullName);
  return taosHashPut(pTable, fullName, strlen(fullName), pName, sizeof(SName));
}

static int32_t collectUseDatabase(const SName* pName, SHashObj* pDbs) {
  char dbFName[TSDB_DB_FNAME_LEN] = {0};
  tNameGetFullDbName(pName, dbFName);
  return taosHashPut(pDbs, dbFName, strlen(dbFName), dbFName, sizeof(dbFName));
}

X
Xiaoyu Wang 已提交
1050
static int32_t getTargetTableSchema(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
1051 1052 1053 1054 1055
  if (pCxt->forceUpdate) {
    pCxt->missCache = true;
    return TSDB_CODE_SUCCESS;
  }

X
Xiaoyu Wang 已提交
1056
  int32_t code = checkAuthForTable(pCxt->pComCxt, &pStmt->targetTableName, &pCxt->missCache, &pCxt->needTableTagVal);
X
Xiaoyu Wang 已提交
1057
  if (TSDB_CODE_SUCCESS == code && !pCxt->missCache) {
1058
    code = getTableMetaAndVgroup(pCxt, pStmt, &pCxt->missCache);
X
Xiaoyu Wang 已提交
1059
  }
1060
  if (TSDB_CODE_SUCCESS == code && !pCxt->pComCxt->async) {
1061
    code = collectUseDatabase(&pStmt->targetTableName, pStmt->pDbFNameHashObj);
1062 1063 1064
    if (TSDB_CODE_SUCCESS == code) {
      code = collectUseTable(&pStmt->targetTableName, pStmt->pTableNameHashObj);
    }
1065
  }
X
Xiaoyu Wang 已提交
1066 1067 1068
  return code;
}

X
Xiaoyu Wang 已提交
1069
static int32_t preParseUsingTableName(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, SToken* pTbName) {
X
Xiaoyu Wang 已提交
1070 1071 1072
  return insCreateSName(&pStmt->usingTableName, pTbName, pCxt->pComCxt->acctId, pCxt->pComCxt->db, &pCxt->msg);
}

X
Xiaoyu Wang 已提交
1073
static int32_t getUsingTableSchema(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
1074 1075 1076 1077 1078
  if (pCxt->forceUpdate) {
    pCxt->missCache = true;
    return TSDB_CODE_SUCCESS;
  }

X
Xiaoyu Wang 已提交
1079
  int32_t code = checkAuthForStable(pCxt->pComCxt, &pStmt->usingTableName, &pCxt->missCache, &pStmt->pTagCond);
X
Xiaoyu Wang 已提交
1080
  if (TSDB_CODE_SUCCESS == code && !pCxt->missCache) {
X
Xiaoyu Wang 已提交
1081 1082 1083 1084 1085
    code = getTableMeta(pCxt, &pStmt->usingTableName, true, &pStmt->pTableMeta, &pCxt->missCache);
  }
  if (TSDB_CODE_SUCCESS == code && !pCxt->missCache) {
    code = getTableVgroup(pCxt->pComCxt, pStmt, true, &pCxt->missCache);
  }
1086 1087 1088 1089 1090 1091
  if (TSDB_CODE_SUCCESS == code && !pCxt->pComCxt->async) {
    code = collectUseDatabase(&pStmt->usingTableName, pStmt->pDbFNameHashObj);
    if (TSDB_CODE_SUCCESS == code) {
      code = collectUseTable(&pStmt->usingTableName, pStmt->pTableNameHashObj);
    }
  }
X
Xiaoyu Wang 已提交
1092 1093 1094
  return code;
}

X
Xiaoyu Wang 已提交
1095
static int32_t parseUsingTableNameImpl(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
1096 1097 1098 1099 1100 1101
  SToken token;
  NEXT_TOKEN(pStmt->pSql, token);
  int32_t code = preParseUsingTableName(pCxt, pStmt, &token);
  if (TSDB_CODE_SUCCESS == code) {
    code = getUsingTableSchema(pCxt, pStmt);
  }
X
Xiaoyu Wang 已提交
1102
  if (TSDB_CODE_SUCCESS == code && !pCxt->missCache) {
X
Xiaoyu Wang 已提交
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
    code = storeTableMeta(pCxt, pStmt);
  }
  return code;
}

// input pStmt->pSql:
//   1(care). [USING stb_name [(tag1_name, ...)] TAGS (tag1_value, ...) [table_options]] ...
//   2. VALUES ... | FILE ...
// output pStmt->pSql:
//   1. [(tag1_name, ...)] TAGS (tag1_value, ...) [table_options]] ...
//   2. VALUES ... | FILE ...
X
Xiaoyu Wang 已提交
1114
static int32_t parseUsingTableName(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
1115 1116 1117 1118 1119 1120 1121
  SToken  token;
  int32_t index = 0;
  NEXT_TOKEN_KEEP_SQL(pStmt->pSql, token, index);
  if (TK_USING != token.type) {
    return getTargetTableSchema(pCxt, pStmt);
  }

X
Xiaoyu Wang 已提交
1122
  pStmt->usingTableProcessing = true;
X
Xiaoyu Wang 已提交
1123 1124
  // pStmt->pSql -> stb_name [(tag1_name, ...)
  pStmt->pSql += index;
X
Xiaoyu Wang 已提交
1125 1126
  int32_t code = parseDuplicateUsingClause(pCxt, pStmt, &pCxt->usingDuplicateTable);
  if (TSDB_CODE_SUCCESS == code && !pCxt->usingDuplicateTable) {
X
Xiaoyu Wang 已提交
1127 1128 1129 1130 1131
    return parseUsingTableNameImpl(pCxt, pStmt);
  }
  return code;
}

X
Xiaoyu Wang 已提交
1132
static int32_t preParseTargetTableName(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, SToken* pTbName) {
X
Xiaoyu Wang 已提交
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
  return insCreateSName(&pStmt->targetTableName, pTbName, pCxt->pComCxt->acctId, pCxt->pComCxt->db, &pCxt->msg);
}

// input pStmt->pSql:
//   1(care). [(field1_name, ...)] ...
//   2. [ USING ... ] ...
//   3. VALUES ... | FILE ...
// output pStmt->pSql:
//   1. [ USING ... ] ...
//   2. VALUES ... | FILE ...
X
Xiaoyu Wang 已提交
1143
static int32_t preParseBoundColumnsClause(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
1144 1145 1146 1147
  SToken  token;
  int32_t index = 0;
  NEXT_TOKEN_KEEP_SQL(pStmt->pSql, token, index);
  if (TK_NK_LP != token.type) {
1148 1149 1150
    return TSDB_CODE_SUCCESS;
  }

X
Xiaoyu Wang 已提交
1151 1152 1153 1154 1155 1156
  // pStmt->pSql -> field1_name, ...)
  pStmt->pSql += index;
  pStmt->pBoundCols = pStmt->pSql;
  return skipParentheses(pCxt, &pStmt->pSql);
}

X
Xiaoyu Wang 已提交
1157
static int32_t getTableDataCxt(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, STableDataCxt** pTableCxt) {
X
Xiaoyu Wang 已提交
1158
  if (pCxt->pComCxt->async) {
X
Xiaoyu Wang 已提交
1159 1160
    return insGetTableDataCxt(pStmt->pTableBlockHashObj, &pStmt->pTableMeta->uid, sizeof(pStmt->pTableMeta->uid),
                              pStmt->pTableMeta, &pStmt->pCreateTblReq, pTableCxt, false);
X
Xiaoyu Wang 已提交
1161
  }
X
Xiaoyu Wang 已提交
1162

X
Xiaoyu Wang 已提交
1163 1164
  char tbFName[TSDB_TABLE_FNAME_LEN];
  tNameExtractFullName(&pStmt->targetTableName, tbFName);
D
dapan1121 已提交
1165 1166 1167
  if (pStmt->usingTableProcessing) {
    pStmt->pTableMeta->uid = 0;
  }
X
Xiaoyu Wang 已提交
1168
  return insGetTableDataCxt(pStmt->pTableBlockHashObj, tbFName, strlen(tbFName), pStmt->pTableMeta,
D
dapan1121 已提交
1169
                            &pStmt->pCreateTblReq, pTableCxt, NULL != pCxt->pComCxt->pStmtCb);
X
Xiaoyu Wang 已提交
1170 1171
}

X
Xiaoyu Wang 已提交
1172
static int32_t parseBoundColumnsClause(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, STableDataCxt* pTableCxt) {
X
Xiaoyu Wang 已提交
1173 1174 1175 1176 1177 1178 1179 1180 1181
  SToken  token;
  int32_t index = 0;
  NEXT_TOKEN_KEEP_SQL(pStmt->pSql, token, index);
  if (TK_NK_LP == token.type) {
    pStmt->pSql += index;
    if (NULL != pStmt->pBoundCols) {
      return buildSyntaxErrMsg(&pCxt->msg, "keyword VALUES or FILE is expected", token.z);
    }
    // pStmt->pSql -> field1_name, ...)
X
Xiaoyu Wang 已提交
1182 1183
    return parseBoundColumns(pCxt, &pStmt->pSql, false, getTableColumnSchema(pStmt->pTableMeta),
                             &pTableCxt->boundColsInfo);
X
Xiaoyu Wang 已提交
1184 1185 1186
  }

  if (NULL != pStmt->pBoundCols) {
X
Xiaoyu Wang 已提交
1187 1188
    return parseBoundColumns(pCxt, &pStmt->pBoundCols, false, getTableColumnSchema(pStmt->pTableMeta),
                             &pTableCxt->boundColsInfo);
X
Xiaoyu Wang 已提交
1189 1190 1191 1192 1193
  }

  return TSDB_CODE_SUCCESS;
}

D
dapan1121 已提交
1194 1195 1196 1197 1198 1199
int32_t initTableColSubmitData(STableDataCxt* pTableCxt) {
  if (0 == (pTableCxt->pData->flags & SUBMIT_REQ_COLUMN_DATA_FORMAT)) {
    return TSDB_CODE_SUCCESS;
  }

  for (int32_t i = 0; i < pTableCxt->boundColsInfo.numOfBound; ++i) {
X
Xiaoyu Wang 已提交
1200
    SSchema*  pSchema = &pTableCxt->pMeta->schema[pTableCxt->boundColsInfo.pColIndex[i]];
D
dapan1121 已提交
1201 1202 1203 1204 1205 1206 1207 1208 1209 1210
    SColData* pCol = taosArrayReserve(pTableCxt->pData->aCol, 1);
    if (NULL == pCol) {
      return TSDB_CODE_OUT_OF_MEMORY;
    }
    tColDataInit(pCol, pSchema->colId, pSchema->type, 0);
  }

  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
1211 1212 1213 1214
// input pStmt->pSql:
//   1. [(tag1_name, ...)] ...
//   2. VALUES ... | FILE ...
// output pStmt->pSql: VALUES ... | FILE ...
X
Xiaoyu Wang 已提交
1215
static int32_t parseSchemaClauseBottom(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt,
X
Xiaoyu Wang 已提交
1216
                                       STableDataCxt** pTableCxt) {
X
Xiaoyu Wang 已提交
1217 1218
  int32_t code = parseUsingClauseBottom(pCxt, pStmt);
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
1219
    code = getTableDataCxt(pCxt, pStmt, pTableCxt);
X
Xiaoyu Wang 已提交
1220 1221
  }
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
1222
    code = parseBoundColumnsClause(pCxt, pStmt, *pTableCxt);
X
Xiaoyu Wang 已提交
1223
  }
D
dapan1121 已提交
1224 1225 1226
  if (TSDB_CODE_SUCCESS == code) {
    code = initTableColSubmitData(*pTableCxt);
  }
X
Xiaoyu Wang 已提交
1227 1228 1229 1230 1231 1232 1233
  return code;
}

// input pStmt->pSql: [(field1_name, ...)] [ USING ... ] VALUES ... | FILE ...
// output pStmt->pSql:
//   1. [(tag1_name, ...)] ...
//   2. VALUES ... | FILE ...
X
Xiaoyu Wang 已提交
1234
static int32_t parseSchemaClauseTop(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, SToken* pTbName) {
X
Xiaoyu Wang 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
  int32_t code = preParseTargetTableName(pCxt, pStmt, pTbName);
  if (TSDB_CODE_SUCCESS == code) {
    // option: [(field1_name, ...)]
    code = preParseBoundColumnsClause(pCxt, pStmt);
  }
  if (TSDB_CODE_SUCCESS == code) {
    // option: [USING stb_name]
    code = parseUsingTableName(pCxt, pStmt);
  }
  return code;
}

static int32_t parseValueTokenImpl(SInsertParseContext* pCxt, const char** pSql, SToken* pToken, SSchema* pSchema,
X
Xiaoyu Wang 已提交
1248
                                   int16_t timePrec, SColVal* pVal) {
wmmhello's avatar
wmmhello 已提交
1249 1250 1251 1252
  switch (pSchema->type) {
    case TSDB_DATA_TYPE_BOOL: {
      if ((pToken->type == TK_NK_BOOL || pToken->type == TK_NK_STRING) && (pToken->n != 0)) {
        if (strncmp(pToken->z, "true", pToken->n) == 0) {
X
Xiaoyu Wang 已提交
1253
          pVal->value.val = TRUE_VALUE;
wmmhello's avatar
wmmhello 已提交
1254
        } else if (strncmp(pToken->z, "false", pToken->n) == 0) {
X
Xiaoyu Wang 已提交
1255
          pVal->value.val = FALSE_VALUE;
wmmhello's avatar
wmmhello 已提交
1256
        } else {
X
Xiaoyu Wang 已提交
1257
          return buildSyntaxErrMsg(&pCxt->msg, "invalid bool data", pToken->z);
wmmhello's avatar
wmmhello 已提交
1258 1259
        }
      } else if (pToken->type == TK_NK_INTEGER) {
X
Xiaoyu Wang 已提交
1260
        pVal->value.val = ((taosStr2Int64(pToken->z, NULL, 10) == 0) ? FALSE_VALUE : TRUE_VALUE);
wmmhello's avatar
wmmhello 已提交
1261
      } else if (pToken->type == TK_NK_FLOAT) {
X
Xiaoyu Wang 已提交
1262
        pVal->value.val = ((taosStr2Double(pToken->z, NULL) == 0) ? FALSE_VALUE : TRUE_VALUE);
wmmhello's avatar
wmmhello 已提交
1263
      } else {
X
Xiaoyu Wang 已提交
1264
        return buildSyntaxErrMsg(&pCxt->msg, "invalid bool data", pToken->z);
D
dapan1121 已提交
1265
      }
X
Xiaoyu Wang 已提交
1266
      break;
wmmhello's avatar
wmmhello 已提交
1267 1268
    }
    case TSDB_DATA_TYPE_TINYINT: {
X
Xiaoyu Wang 已提交
1269
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &pVal->value.val)) {
X
Xiaoyu Wang 已提交
1270
        return buildSyntaxErrMsg(&pCxt->msg, "invalid tinyint data", pToken->z);
X
Xiaoyu Wang 已提交
1271
      } else if (!IS_VALID_TINYINT(pVal->value.val)) {
X
Xiaoyu Wang 已提交
1272
        return buildSyntaxErrMsg(&pCxt->msg, "tinyint data overflow", pToken->z);
D
dapan1121 已提交
1273
      }
X
Xiaoyu Wang 已提交
1274
      break;
1275
    }
wmmhello's avatar
wmmhello 已提交
1276
    case TSDB_DATA_TYPE_UTINYINT: {
X
Xiaoyu Wang 已提交
1277
      if (TSDB_CODE_SUCCESS != toUInteger(pToken->z, pToken->n, 10, &pVal->value.val)) {
X
Xiaoyu Wang 已提交
1278
        return buildSyntaxErrMsg(&pCxt->msg, "invalid unsigned tinyint data", pToken->z);
X
Xiaoyu Wang 已提交
1279
      } else if (pVal->value.val > UINT8_MAX) {
X
Xiaoyu Wang 已提交
1280
        return buildSyntaxErrMsg(&pCxt->msg, "unsigned tinyint data overflow", pToken->z);
wmmhello's avatar
wmmhello 已提交
1281
      }
X
Xiaoyu Wang 已提交
1282
      break;
wmmhello's avatar
wmmhello 已提交
1283 1284
    }
    case TSDB_DATA_TYPE_SMALLINT: {
X
Xiaoyu Wang 已提交
1285
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &pVal->value.val)) {
X
Xiaoyu Wang 已提交
1286
        return buildSyntaxErrMsg(&pCxt->msg, "invalid smallint data", pToken->z);
X
Xiaoyu Wang 已提交
1287
      } else if (!IS_VALID_SMALLINT(pVal->value.val)) {
X
Xiaoyu Wang 已提交
1288
        return buildSyntaxErrMsg(&pCxt->msg, "smallint data overflow", pToken->z);
wmmhello's avatar
wmmhello 已提交
1289
      }
X
Xiaoyu Wang 已提交
1290
      break;
wmmhello's avatar
wmmhello 已提交
1291 1292
    }
    case TSDB_DATA_TYPE_USMALLINT: {
X
Xiaoyu Wang 已提交
1293
      if (TSDB_CODE_SUCCESS != toUInteger(pToken->z, pToken->n, 10, &pVal->value.val)) {
X
Xiaoyu Wang 已提交
1294
        return buildSyntaxErrMsg(&pCxt->msg, "invalid unsigned smallint data", pToken->z);
X
Xiaoyu Wang 已提交
1295
      } else if (pVal->value.val > UINT16_MAX) {
X
Xiaoyu Wang 已提交
1296
        return buildSyntaxErrMsg(&pCxt->msg, "unsigned smallint data overflow", pToken->z);
wmmhello's avatar
wmmhello 已提交
1297
      }
X
Xiaoyu Wang 已提交
1298
      break;
wmmhello's avatar
wmmhello 已提交
1299 1300
    }
    case TSDB_DATA_TYPE_INT: {
X
Xiaoyu Wang 已提交
1301
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &pVal->value.val)) {
X
Xiaoyu Wang 已提交
1302
        return buildSyntaxErrMsg(&pCxt->msg, "invalid int data", pToken->z);
X
Xiaoyu Wang 已提交
1303
      } else if (!IS_VALID_INT(pVal->value.val)) {
X
Xiaoyu Wang 已提交
1304
        return buildSyntaxErrMsg(&pCxt->msg, "int data overflow", pToken->z);
wmmhello's avatar
wmmhello 已提交
1305
      }
X
Xiaoyu Wang 已提交
1306
      break;
wmmhello's avatar
wmmhello 已提交
1307 1308
    }
    case TSDB_DATA_TYPE_UINT: {
X
Xiaoyu Wang 已提交
1309
      if (TSDB_CODE_SUCCESS != toUInteger(pToken->z, pToken->n, 10, &pVal->value.val)) {
X
Xiaoyu Wang 已提交
1310
        return buildSyntaxErrMsg(&pCxt->msg, "invalid unsigned int data", pToken->z);
X
Xiaoyu Wang 已提交
1311
      } else if (pVal->value.val > UINT32_MAX) {
X
Xiaoyu Wang 已提交
1312
        return buildSyntaxErrMsg(&pCxt->msg, "unsigned int data overflow", pToken->z);
wmmhello's avatar
wmmhello 已提交
1313
      }
X
Xiaoyu Wang 已提交
1314
      break;
wmmhello's avatar
wmmhello 已提交
1315 1316
    }
    case TSDB_DATA_TYPE_BIGINT: {
X
Xiaoyu Wang 已提交
1317
      if (TSDB_CODE_SUCCESS != toInteger(pToken->z, pToken->n, 10, &pVal->value.val)) {
X
Xiaoyu Wang 已提交
1318
        return buildSyntaxErrMsg(&pCxt->msg, "invalid bigint data", pToken->z);
wmmhello's avatar
wmmhello 已提交
1319
      }
X
Xiaoyu Wang 已提交
1320
      break;
wmmhello's avatar
wmmhello 已提交
1321 1322
    }
    case TSDB_DATA_TYPE_UBIGINT: {
X
Xiaoyu Wang 已提交
1323
      if (TSDB_CODE_SUCCESS != toUInteger(pToken->z, pToken->n, 10, &pVal->value.val)) {
X
Xiaoyu Wang 已提交
1324
        return buildSyntaxErrMsg(&pCxt->msg, "invalid unsigned bigint data", pToken->z);
wmmhello's avatar
wmmhello 已提交
1325
      }
X
Xiaoyu Wang 已提交
1326
      break;
wmmhello's avatar
wmmhello 已提交
1327 1328
    }
    case TSDB_DATA_TYPE_FLOAT: {
X
Xiaoyu Wang 已提交
1329
      char*  endptr = NULL;
wmmhello's avatar
wmmhello 已提交
1330 1331
      double dv;
      if (TK_NK_ILLEGAL == toDouble(pToken, &dv, &endptr)) {
X
Xiaoyu Wang 已提交
1332
        return buildSyntaxErrMsg(&pCxt->msg, "illegal float data", pToken->z);
wmmhello's avatar
wmmhello 已提交
1333 1334 1335
      }
      if (((dv == HUGE_VAL || dv == -HUGE_VAL) && errno == ERANGE) || dv > FLT_MAX || dv < -FLT_MAX || isinf(dv) ||
          isnan(dv)) {
X
Xiaoyu Wang 已提交
1336
        return buildSyntaxErrMsg(&pCxt->msg, "illegal float data", pToken->z);
wmmhello's avatar
wmmhello 已提交
1337
      }
X
Xiaoyu Wang 已提交
1338 1339
      float f = dv;
      memcpy(&pVal->value.val, &f, sizeof(f));
X
Xiaoyu Wang 已提交
1340
      break;
wmmhello's avatar
wmmhello 已提交
1341 1342
    }
    case TSDB_DATA_TYPE_DOUBLE: {
X
Xiaoyu Wang 已提交
1343
      char*  endptr = NULL;
wmmhello's avatar
wmmhello 已提交
1344 1345
      double dv;
      if (TK_NK_ILLEGAL == toDouble(pToken, &dv, &endptr)) {
X
Xiaoyu Wang 已提交
1346
        return buildSyntaxErrMsg(&pCxt->msg, "illegal double data", pToken->z);
wmmhello's avatar
wmmhello 已提交
1347 1348
      }
      if (((dv == HUGE_VAL || dv == -HUGE_VAL) && errno == ERANGE) || isinf(dv) || isnan(dv)) {
X
Xiaoyu Wang 已提交
1349
        return buildSyntaxErrMsg(&pCxt->msg, "illegal double data", pToken->z);
wmmhello's avatar
wmmhello 已提交
1350
      }
X
Xiaoyu Wang 已提交
1351 1352
      pVal->value.val = *(int64_t*)&dv;
      break;
wmmhello's avatar
wmmhello 已提交
1353 1354 1355 1356
    }
    case TSDB_DATA_TYPE_BINARY: {
      // Too long values will raise the invalid sql error message
      if (pToken->n + VARSTR_HEADER_SIZE > pSchema->bytes) {
X
Xiaoyu Wang 已提交
1357
        return generateSyntaxErrMsg(&pCxt->msg, TSDB_CODE_PAR_VALUE_TOO_LONG, pSchema->name);
D
stmt  
dapan1121 已提交
1358
      }
X
Xiaoyu Wang 已提交
1359 1360 1361 1362 1363
      pVal->value.pData = taosMemoryMalloc(pToken->n);
      if (NULL == pVal->value.pData) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      memcpy(pVal->value.pData, pToken->z, pToken->n);
X
Xiaoyu Wang 已提交
1364 1365
      pVal->value.nData = pToken->n;
      break;
X
Xiaoyu Wang 已提交
1366
    }
X
Xiaoyu Wang 已提交
1367
    case TSDB_DATA_TYPE_NCHAR: {
X
Xiaoyu Wang 已提交
1368 1369 1370 1371 1372 1373 1374
      // if the converted output len is over than pColumnModel->bytes, return error: 'Argument list too long'
      int32_t len = 0;
      char*   pUcs4 = taosMemoryCalloc(1, pSchema->bytes - VARSTR_HEADER_SIZE);
      if (NULL == pUcs4) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      if (!taosMbsToUcs4(pToken->z, pToken->n, (TdUcs4*)pUcs4, pSchema->bytes - VARSTR_HEADER_SIZE, &len)) {
1375
        taosMemoryFree(pUcs4);
X
Xiaoyu Wang 已提交
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385
        if (errno == E2BIG) {
          return generateSyntaxErrMsg(&pCxt->msg, TSDB_CODE_PAR_VALUE_TOO_LONG, pSchema->name);
        }
        char buf[512] = {0};
        snprintf(buf, tListLen(buf), "%s", strerror(errno));
        return buildSyntaxErrMsg(&pCxt->msg, buf, pToken->z);
      }
      pVal->value.pData = pUcs4;
      pVal->value.nData = len;
      break;
1386
    }
X
Xiaoyu Wang 已提交
1387 1388 1389
    case TSDB_DATA_TYPE_JSON: {
      if (pToken->n > (TSDB_MAX_JSON_TAG_LEN - VARSTR_HEADER_SIZE) / TSDB_NCHAR_SIZE) {
        return buildSyntaxErrMsg(&pCxt->msg, "json string too long than 4095", pToken->z);
1390
      }
X
Xiaoyu Wang 已提交
1391 1392 1393 1394 1395
      pVal->value.pData = taosMemoryMalloc(pToken->n);
      if (NULL == pVal->value.pData) {
        return TSDB_CODE_OUT_OF_MEMORY;
      }
      memcpy(pVal->value.pData, pToken->z, pToken->n);
X
Xiaoyu Wang 已提交
1396 1397
      pVal->value.nData = pToken->n;
      break;
1398
    }
D
Dingle Zhang 已提交
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
    case TSDB_DATA_TYPE_GEOMETRY: {
      int32_t code = TSDB_CODE_FAILED;
      unsigned char *output = NULL;
      size_t size = 0;

      code = parseGeometry(pToken, &output, &size);
      if (code != TSDB_CODE_SUCCESS) {
        code = buildSyntaxErrMsg(&pCxt->msg, getThreadLocalGeosCtx()->errMsg, pToken->z);
      }
      // Too long values will raise the invalid sql error message
1409
      else if (size + VARSTR_HEADER_SIZE > pSchema->bytes) {
D
Dingle Zhang 已提交
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
        code = generateSyntaxErrMsg(&pCxt->msg, TSDB_CODE_PAR_VALUE_TOO_LONG, pSchema->name);
      }
      else {
        pVal->value.pData = taosMemoryMalloc(size);
        if (NULL == pVal->value.pData) {
          code = TSDB_CODE_OUT_OF_MEMORY;
        }
        else {
          memcpy(pVal->value.pData, output, size);
          pVal->value.nData = size;
        }
      }

      geosFreeBuffer(output);
      if (code != TSDB_CODE_SUCCESS) {
        return code;
      }

      break;
    }
X
Xiaoyu Wang 已提交
1430
    case TSDB_DATA_TYPE_TIMESTAMP: {
X
Xiaoyu Wang 已提交
1431
      if (parseTime(pSql, pToken, timePrec, &pVal->value.val, &pCxt->msg) != TSDB_CODE_SUCCESS) {
X
Xiaoyu Wang 已提交
1432 1433
        return buildSyntaxErrMsg(&pCxt->msg, "invalid timestamp", pToken->z);
      }
X
Xiaoyu Wang 已提交
1434
      break;
X
Xiaoyu Wang 已提交
1435
    }
X
Xiaoyu Wang 已提交
1436 1437
    default:
      return TSDB_CODE_FAILED;
X
Xiaoyu Wang 已提交
1438
  }
1439

X
Xiaoyu Wang 已提交
1440
  pVal->flag = CV_FLAG_VALUE;
X
Xiaoyu Wang 已提交
1441
  return TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
1442
}
D
dapan 已提交
1443

X
Xiaoyu Wang 已提交
1444
static int32_t parseValueToken(SInsertParseContext* pCxt, const char** pSql, SToken* pToken, SSchema* pSchema,
X
Xiaoyu Wang 已提交
1445
                               int16_t timePrec, SColVal* pVal) {
X
Xiaoyu Wang 已提交
1446 1447 1448 1449 1450
  int32_t code = checkAndTrimValue(pToken, pCxt->tmpTokenBuf, &pCxt->msg);
  if (TSDB_CODE_SUCCESS == code && isNullValue(pSchema->type, pToken)) {
    if (TSDB_DATA_TYPE_TIMESTAMP == pSchema->type && PRIMARYKEY_TIMESTAMP_COL_ID == pSchema->colId) {
      return buildSyntaxErrMsg(&pCxt->msg, "primary timestamp should not be null", pToken->z);
    }
X
Xiaoyu Wang 已提交
1451 1452
    pVal->flag = CV_FLAG_NULL;
    return TSDB_CODE_SUCCESS;
1453 1454
  }

X
Xiaoyu Wang 已提交
1455 1456
  if (TSDB_CODE_SUCCESS == code && IS_NUMERIC_TYPE(pSchema->type) && pToken->n == 0) {
    return buildSyntaxErrMsg(&pCxt->msg, "invalid numeric data", pToken->z);
1457 1458
  }

X
Xiaoyu Wang 已提交
1459
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
1460
    code = parseValueTokenImpl(pCxt, pSql, pToken, pSchema, timePrec, pVal);
X
Xiaoyu Wang 已提交
1461
  }
1462

X
Xiaoyu Wang 已提交
1463
  return code;
1464 1465
}

X
Xiaoyu Wang 已提交
1466 1467 1468 1469
static void clearColValArray(SArray* pCols) {
  int32_t num = taosArrayGetSize(pCols);
  for (int32_t i = 0; i < num; ++i) {
    SColVal* pCol = taosArrayGet(pCols, i);
X
Xiaoyu Wang 已提交
1470
    if (IS_VAR_DATA_TYPE(pCol->type)) {
X
Xiaoyu Wang 已提交
1471 1472 1473 1474 1475
      taosMemoryFreeClear(pCol->value.pData);
    }
  }
}

X
Xiaoyu Wang 已提交
1476
static int parseOneRow(SInsertParseContext* pCxt, const char** pSql, STableDataCxt* pTableCxt, bool* pGotRow,
X
Xiaoyu Wang 已提交
1477
                       SToken* pToken) {
X
Xiaoyu Wang 已提交
1478 1479 1480 1481 1482
  SBoundColInfo* pCols = &pTableCxt->boundColsInfo;
  bool           isParseBindParam = false;
  SSchema*       pSchemas = getTableColumnSchema(pTableCxt->pMeta);

  int32_t code = TSDB_CODE_SUCCESS;
1483
  // 1. set the parsed value from sql string
X
Xiaoyu Wang 已提交
1484
  for (int i = 0; i < pCols->numOfBound && TSDB_CODE_SUCCESS == code; ++i) {
X
Xiaoyu Wang 已提交
1485 1486 1487 1488 1489
    const char* pOrigSql = *pSql;
    bool        ignoreComma = false;
    NEXT_TOKEN_WITH_PREV_EXT(*pSql, *pToken, &ignoreComma);
    if (ignoreComma) {
      code = buildSyntaxErrMsg(&pCxt->msg, "invalid data or symbol", pOrigSql);
X
Xiaoyu Wang 已提交
1490
      break;
X
Xiaoyu Wang 已提交
1491
    }
D
stmt  
dapan1121 已提交
1492

X
Xiaoyu Wang 已提交
1493 1494
    SSchema* pSchema = &pSchemas[pCols->pColIndex[i]];
    SColVal* pVal = taosArrayGet(pTableCxt->pValues, pCols->pColIndex[i]);
D
stmt  
dapan1121 已提交
1495

X
Xiaoyu Wang 已提交
1496
    if (pToken->type == TK_NK_QUESTION) {
D
stmt  
dapan1121 已提交
1497
      isParseBindParam = true;
X
Xiaoyu Wang 已提交
1498 1499
      if (NULL == pCxt->pComCxt->pStmtCb) {
        code = buildSyntaxErrMsg(&pCxt->msg, "? only used in stmt", pToken->z);
X
Xiaoyu Wang 已提交
1500 1501 1502 1503 1504 1505
        break;
      }
    } else {
      if (TK_NK_RP == pToken->type) {
        code = generateSyntaxErrMsg(&pCxt->msg, TSDB_CODE_PAR_INVALID_COLUMNS_NUM);
        break;
D
stmt  
dapan1121 已提交
1506
      }
D
dapan1121 已提交
1507

X
Xiaoyu Wang 已提交
1508 1509 1510 1511
      if (isParseBindParam) {
        code = buildInvalidOperationMsg(&pCxt->msg, "no mix usage for ? and values");
        break;
      }
X
Xiaoyu Wang 已提交
1512

X
Xiaoyu Wang 已提交
1513 1514 1515
      if (TSDB_CODE_SUCCESS == code) {
        code = parseValueToken(pCxt, pSql, pToken, pSchema, getTableInfo(pTableCxt->pMeta).precision, pVal);
      }
X
Xiaoyu Wang 已提交
1516
    }
1517

X
Xiaoyu Wang 已提交
1518 1519 1520 1521
    if (TSDB_CODE_SUCCESS == code && i < pCols->numOfBound - 1) {
      NEXT_VALID_TOKEN(*pSql, *pToken);
      if (TK_NK_COMMA != pToken->type) {
        code = buildSyntaxErrMsg(&pCxt->msg, ", expected", pToken->z);
X
Xiaoyu Wang 已提交
1522 1523
      }
    }
1524 1525
  }

D
dapan1121 已提交
1526
  if (TSDB_CODE_SUCCESS == code && !isParseBindParam) {
X
Xiaoyu Wang 已提交
1527
    SRow** pRow = taosArrayReserve(pTableCxt->pData->aRowP, 1);
X
Xiaoyu Wang 已提交
1528
    code = tRowBuild(pTableCxt->pValues, pTableCxt->pSchema, pRow);
X
Xiaoyu Wang 已提交
1529 1530 1531
    if (TSDB_CODE_SUCCESS == code) {
      insCheckTableDataOrder(pTableCxt, TD_ROW_KEY(*pRow));
    }
X
Xiaoyu Wang 已提交
1532
  }
1533

X
Xiaoyu Wang 已提交
1534 1535
  if (TSDB_CODE_SUCCESS == code && !isParseBindParam) {
    *pGotRow = true;
1536 1537
  }

X
Xiaoyu Wang 已提交
1538 1539
  clearColValArray(pTableCxt->pValues);

X
Xiaoyu Wang 已提交
1540
  return code;
1541 1542 1543
}

// pSql -> (field1_value, ...) [(field1_value2, ...) ...]
X
Xiaoyu Wang 已提交
1544
static int32_t parseValues(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, STableDataCxt* pTableCxt,
X
Xiaoyu Wang 已提交
1545 1546
                           int32_t* pNumOfRows, SToken* pToken) {
  int32_t code = TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
1547 1548 1549

  (*pNumOfRows) = 0;
  while (TSDB_CODE_SUCCESS == code) {
1550
    int32_t index = 0;
X
Xiaoyu Wang 已提交
1551 1552
    NEXT_TOKEN_KEEP_SQL(pStmt->pSql, *pToken, index);
    if (TK_NK_LP != pToken->type) {
1553 1554
      break;
    }
X
Xiaoyu Wang 已提交
1555
    pStmt->pSql += index;
1556

D
stmt  
dapan1121 已提交
1557
    bool gotRow = false;
X
Xiaoyu Wang 已提交
1558
    if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
1559
      code = parseOneRow(pCxt, &pStmt->pSql, pTableCxt, &gotRow, pToken);
D
stmt  
dapan1121 已提交
1560
    }
1561

X
Xiaoyu Wang 已提交
1562 1563 1564 1565 1566 1567 1568
    if (TSDB_CODE_SUCCESS == code) {
      NEXT_VALID_TOKEN(pStmt->pSql, *pToken);
      if (TK_NK_COMMA == pToken->type) {
        code = generateSyntaxErrMsg(&pCxt->msg, TSDB_CODE_PAR_INVALID_COLUMNS_NUM);
      } else if (TK_NK_RP != pToken->type) {
        code = buildSyntaxErrMsg(&pCxt->msg, ") expected", pToken->z);
      }
1569 1570
    }

X
Xiaoyu Wang 已提交
1571 1572
    if (TSDB_CODE_SUCCESS == code && gotRow) {
      (*pNumOfRows)++;
D
stmt  
dapan1121 已提交
1573
    }
1574 1575
  }

X
Xiaoyu Wang 已提交
1576 1577 1578
  if (TSDB_CODE_SUCCESS == code && 0 == (*pNumOfRows) &&
      (!TSDB_QUERY_HAS_TYPE(pStmt->insertType, TSDB_QUERY_TYPE_STMT_INSERT))) {
    code = buildSyntaxErrMsg(&pCxt->msg, "no any data points", NULL);
1579
  }
X
Xiaoyu Wang 已提交
1580
  return code;
1581 1582
}

X
Xiaoyu Wang 已提交
1583
// VALUES (field1_value, ...) [(field1_value2, ...) ...]
X
Xiaoyu Wang 已提交
1584
static int32_t parseValuesClause(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, STableDataCxt* pTableCxt,
X
Xiaoyu Wang 已提交
1585
                                 SToken* pToken) {
1586
  int32_t numOfRows = 0;
X
Xiaoyu Wang 已提交
1587
  int32_t code = parseValues(pCxt, pStmt, pTableCxt, &numOfRows, pToken);
X
Xiaoyu Wang 已提交
1588 1589 1590 1591 1592 1593
  if (TSDB_CODE_SUCCESS == code) {
    pStmt->totalRowsNum += numOfRows;
    pStmt->totalTbNum += 1;
    TSDB_QUERY_SET_TYPE(pStmt->insertType, TSDB_QUERY_TYPE_INSERT);
  }
  return code;
1594 1595
}

X
Xiaoyu Wang 已提交
1596
static int32_t parseCsvFile(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, STableDataCxt* pTableCxt,
X
Xiaoyu Wang 已提交
1597 1598
                            int32_t* pNumOfRows) {
  int32_t code = TSDB_CODE_SUCCESS;
X
Xiaoyu Wang 已提交
1599
  (*pNumOfRows) = 0;
X
Xiaoyu Wang 已提交
1600 1601
  char*   pLine = NULL;
  int64_t readLen = 0;
D
dapan1121 已提交
1602
  bool    firstLine = (pStmt->fileProcessing == false);
X
Xiaoyu Wang 已提交
1603
  pStmt->fileProcessing = false;
X
Xiaoyu Wang 已提交
1604
  while (TSDB_CODE_SUCCESS == code && (readLen = taosGetLineFile(pStmt->fp, &pLine)) != -1) {
X
Xiaoyu Wang 已提交
1605 1606 1607 1608 1609
    if (('\r' == pLine[readLen - 1]) || ('\n' == pLine[readLen - 1])) {
      pLine[--readLen] = '\0';
    }

    if (readLen == 0) {
D
dapan1121 已提交
1610
      firstLine = false;
X
Xiaoyu Wang 已提交
1611 1612 1613
      continue;
    }

X
Xiaoyu Wang 已提交
1614 1615 1616 1617
    bool gotRow = false;
    if (TSDB_CODE_SUCCESS == code) {
      SToken token;
      strtolower(pLine, pLine);
X
Xiaoyu Wang 已提交
1618
      const char* pRow = pLine;
1619

H
Haojun Liao 已提交
1620
      code = parseOneRow(pCxt, (const char**)&pRow, pTableCxt, &gotRow, &token);
D
dapan1121 已提交
1621 1622 1623 1624 1625
      if (code && firstLine) {
        firstLine = false;
        code = 0;
        continue;
      }
X
Xiaoyu Wang 已提交
1626
    }
X
Xiaoyu Wang 已提交
1627 1628 1629

    if (TSDB_CODE_SUCCESS == code && gotRow) {
      (*pNumOfRows)++;
X
Xiaoyu Wang 已提交
1630
    }
1631

1632
    if (TSDB_CODE_SUCCESS == code && (*pNumOfRows) > tsMaxInsertBatchRows) {
X
Xiaoyu Wang 已提交
1633
      pStmt->fileProcessing = true;
1634 1635
      break;
    }
D
dapan1121 已提交
1636 1637

    firstLine = false;
X
Xiaoyu Wang 已提交
1638
  }
X
Xiaoyu Wang 已提交
1639
  taosMemoryFree(pLine);
X
Xiaoyu Wang 已提交
1640

1641 1642
  parserDebug("0x%" PRIx64 " %d rows have been parsed", pCxt->pComCxt->requestId, *pNumOfRows);

X
Xiaoyu Wang 已提交
1643
  if (TSDB_CODE_SUCCESS == code && 0 == (*pNumOfRows) &&
X
Xiaoyu Wang 已提交
1644
      (!TSDB_QUERY_HAS_TYPE(pStmt->insertType, TSDB_QUERY_TYPE_STMT_INSERT)) && !pStmt->fileProcessing) {
X
Xiaoyu Wang 已提交
1645
    code = buildSyntaxErrMsg(&pCxt->msg, "no any data points", NULL);
X
Xiaoyu Wang 已提交
1646
  }
X
Xiaoyu Wang 已提交
1647
  return code;
X
Xiaoyu Wang 已提交
1648 1649
}

X
Xiaoyu Wang 已提交
1650
static int32_t parseDataFromFileImpl(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, STableDataCxt* pTableCxt) {
X
Xiaoyu Wang 已提交
1651
  int32_t numOfRows = 0;
X
Xiaoyu Wang 已提交
1652
  int32_t code = parseCsvFile(pCxt, pStmt, pTableCxt, &numOfRows);
X
Xiaoyu Wang 已提交
1653 1654 1655 1656
  if (TSDB_CODE_SUCCESS == code) {
    pStmt->totalRowsNum += numOfRows;
    pStmt->totalTbNum += 1;
    TSDB_QUERY_SET_TYPE(pStmt->insertType, TSDB_QUERY_TYPE_FILE_INSERT);
X
Xiaoyu Wang 已提交
1657
    if (!pStmt->fileProcessing) {
X
Xiaoyu Wang 已提交
1658 1659 1660 1661
      taosCloseFile(&pStmt->fp);
    } else {
      parserDebug("0x%" PRIx64 " insert from csv. File is too large, do it in batches.", pCxt->pComCxt->requestId);
    }
1662
  }
X
Xiaoyu Wang 已提交
1663
  return code;
X
Xiaoyu Wang 已提交
1664 1665
}

X
Xiaoyu Wang 已提交
1666
static int32_t parseDataFromFile(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, SToken* pFilePath,
X
Xiaoyu Wang 已提交
1667
                                 STableDataCxt* pTableCxt) {
1668
  char filePathStr[TSDB_FILENAME_LEN] = {0};
X
Xiaoyu Wang 已提交
1669 1670
  if (TK_NK_STRING == pFilePath->type) {
    trimString(pFilePath->z, pFilePath->n, filePathStr, sizeof(filePathStr));
1671
  } else {
X
Xiaoyu Wang 已提交
1672
    strncpy(filePathStr, pFilePath->z, pFilePath->n);
1673
  }
X
Xiaoyu Wang 已提交
1674 1675
  pStmt->fp = taosOpenFile(filePathStr, TD_FILE_READ | TD_FILE_STREAM);
  if (NULL == pStmt->fp) {
1676 1677 1678
    return TAOS_SYSTEM_ERROR(errno);
  }

X
Xiaoyu Wang 已提交
1679
  return parseDataFromFileImpl(pCxt, pStmt, pTableCxt);
1680 1681
}

X
Xiaoyu Wang 已提交
1682
static int32_t parseFileClause(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, STableDataCxt* pTableCxt,
X
Xiaoyu Wang 已提交
1683
                               SToken* pToken) {
1684 1685 1686 1687
  if (tsUseAdapter) {
    return buildInvalidOperationMsg(&pCxt->msg, "proxy mode does not support csv loading");
  }

X
Xiaoyu Wang 已提交
1688 1689 1690
  NEXT_TOKEN(pStmt->pSql, *pToken);
  if (0 == pToken->n || (TK_NK_STRING != pToken->type && TK_NK_ID != pToken->type)) {
    return buildSyntaxErrMsg(&pCxt->msg, "file path is required following keyword FILE", pToken->z);
1691
  }
X
Xiaoyu Wang 已提交
1692
  return parseDataFromFile(pCxt, pStmt, pToken, pTableCxt);
X
Xiaoyu Wang 已提交
1693 1694
}

X
Xiaoyu Wang 已提交
1695
// VALUES (field1_value, ...) [(field1_value2, ...) ...] | FILE csv_file_path
X
Xiaoyu Wang 已提交
1696
static int32_t parseDataClause(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, STableDataCxt* pTableCxt) {
X
Xiaoyu Wang 已提交
1697 1698 1699 1700
  SToken token;
  NEXT_TOKEN(pStmt->pSql, token);
  switch (token.type) {
    case TK_VALUES:
X
Xiaoyu Wang 已提交
1701
      return parseValuesClause(pCxt, pStmt, pTableCxt, &token);
X
Xiaoyu Wang 已提交
1702
    case TK_FILE:
X
Xiaoyu Wang 已提交
1703
      return parseFileClause(pCxt, pStmt, pTableCxt, &token);
X
Xiaoyu Wang 已提交
1704 1705 1706 1707
    default:
      break;
  }
  return buildSyntaxErrMsg(&pCxt->msg, "keyword VALUES or FILE is expected", token.z);
X
Xiaoyu Wang 已提交
1708 1709
}

X
Xiaoyu Wang 已提交
1710 1711 1712
// input pStmt->pSql:
//   1. [(tag1_name, ...)] ...
//   2. VALUES ... | FILE ...
X
Xiaoyu Wang 已提交
1713
static int32_t parseInsertTableClauseBottom(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
1714 1715
  STableDataCxt* pTableCxt = NULL;
  int32_t        code = parseSchemaClauseBottom(pCxt, pStmt, &pTableCxt);
X
Xiaoyu Wang 已提交
1716
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
1717
    code = parseDataClause(pCxt, pStmt, pTableCxt);
X
Xiaoyu Wang 已提交
1718 1719 1720 1721
  }
  return code;
}

X
Xiaoyu Wang 已提交
1722
static void resetEnvPreTable(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
1723
  insDestroyBoundColInfo(&pCxt->tags);
X
Xiaoyu Wang 已提交
1724
  taosMemoryFreeClear(pStmt->pTableMeta);
X
Xiaoyu Wang 已提交
1725 1726
  nodesDestroyNode(pStmt->pTagCond);
  taosArrayDestroy(pStmt->pTableTag);
X
Xiaoyu Wang 已提交
1727 1728
  tdDestroySVCreateTbReq(pStmt->pCreateTblReq);
  taosMemoryFreeClear(pStmt->pCreateTblReq);
X
Xiaoyu Wang 已提交
1729 1730
  pCxt->missCache = false;
  pCxt->usingDuplicateTable = false;
X
Xiaoyu Wang 已提交
1731
  pStmt->pBoundCols = NULL;
X
Xiaoyu Wang 已提交
1732 1733
  pStmt->usingTableProcessing = false;
  pStmt->fileProcessing = false;
1734
  pStmt->usingTableName.type = 0;
X
Xiaoyu Wang 已提交
1735 1736
}

X
Xiaoyu Wang 已提交
1737
// input pStmt->pSql: [(field1_name, ...)] [ USING ... ] VALUES ... | FILE ...
X
Xiaoyu Wang 已提交
1738
static int32_t parseInsertTableClause(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, SToken* pTbName) {
X
Xiaoyu Wang 已提交
1739
  resetEnvPreTable(pCxt, pStmt);
X
Xiaoyu Wang 已提交
1740 1741 1742 1743 1744 1745
  int32_t code = parseSchemaClauseTop(pCxt, pStmt, pTbName);
  if (TSDB_CODE_SUCCESS == code && !pCxt->missCache) {
    code = parseInsertTableClauseBottom(pCxt, pStmt);
  }
  return code;
}
X
Xiaoyu Wang 已提交
1746

X
Xiaoyu Wang 已提交
1747
static int32_t checkTableClauseFirstToken(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, SToken* pTbName,
X
Xiaoyu Wang 已提交
1748 1749 1750 1751 1752
                                          bool* pHasData) {
  // no data in the sql string anymore.
  if (0 == pTbName->n) {
    if (0 != pTbName->type && '\0' != pStmt->pSql[0]) {
      return buildSyntaxErrMsg(&pCxt->msg, "invalid charactor in SQL", pTbName->z);
1753 1754
    }

X
Xiaoyu Wang 已提交
1755 1756
    if (0 == pStmt->totalRowsNum && (!TSDB_QUERY_HAS_TYPE(pStmt->insertType, TSDB_QUERY_TYPE_STMT_INSERT))) {
      return buildInvalidOperationMsg(&pCxt->msg, "no data in sql");
D
stmt  
dapan1121 已提交
1757 1758
    }

X
Xiaoyu Wang 已提交
1759 1760 1761
    *pHasData = false;
    return TSDB_CODE_SUCCESS;
  }
X
Xiaoyu Wang 已提交
1762

X
Xiaoyu Wang 已提交
1763 1764 1765
  if (TSDB_QUERY_HAS_TYPE(pStmt->insertType, TSDB_QUERY_TYPE_STMT_INSERT) && pStmt->totalTbNum > 0) {
    return buildInvalidOperationMsg(&pCxt->msg, "single table allowed in one stmt");
  }
1766

X
Xiaoyu Wang 已提交
1767 1768 1769
  if (TK_NK_QUESTION == pTbName->type) {
    if (NULL == pCxt->pComCxt->pStmtCb) {
      return buildSyntaxErrMsg(&pCxt->msg, "? only used in stmt", pTbName->z);
X
Xiaoyu Wang 已提交
1770
    }
X
Xiaoyu Wang 已提交
1771

X
Xiaoyu Wang 已提交
1772 1773 1774 1775 1776 1777 1778
    char*   tbName = NULL;
    int32_t code = (*pCxt->pComCxt->pStmtCb->getTbNameFn)(pCxt->pComCxt->pStmtCb->pStmt, &tbName);
    if (TSDB_CODE_SUCCESS == code) {
      pTbName->z = tbName;
      pTbName->n = strlen(tbName);
    } else {
      return code;
1779
    }
X
Xiaoyu Wang 已提交
1780
  }
1781

1782
  if (TK_NK_ID != pTbName->type && TK_NK_STRING != pTbName->type && TK_NK_QUESTION != pTbName->type) {
1783 1784 1785
    return buildSyntaxErrMsg(&pCxt->msg, "table_name is expected", pTbName->z);
  }

X
Xiaoyu Wang 已提交
1786 1787 1788
  *pHasData = true;
  return TSDB_CODE_SUCCESS;
}
1789

X
Xiaoyu Wang 已提交
1790
static int32_t setStmtInfo(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
1791
  SBoundColInfo* tags = taosMemoryMalloc(sizeof(pCxt->tags));
X
Xiaoyu Wang 已提交
1792
  if (NULL == tags) {
S
Shengliang Guan 已提交
1793
    return TSDB_CODE_OUT_OF_MEMORY;
X
Xiaoyu Wang 已提交
1794 1795
  }
  memcpy(tags, &pCxt->tags, sizeof(pCxt->tags));
1796

X
Xiaoyu Wang 已提交
1797
  SStmtCallback* pStmtCb = pCxt->pComCxt->pStmtCb;
X
Xiaoyu Wang 已提交
1798 1799 1800
  int32_t        code = (*pStmtCb->setInfoFn)(pStmtCb->pStmt, pStmt->pTableMeta, tags, &pStmt->targetTableName,
                                       pStmt->usingTableProcessing, pStmt->pVgroupsHashObj, pStmt->pTableBlockHashObj,
                                       pStmt->usingTableName.tname);
1801

X
Xiaoyu Wang 已提交
1802 1803 1804 1805 1806
  memset(&pCxt->tags, 0, sizeof(pCxt->tags));
  pStmt->pVgroupsHashObj = NULL;
  pStmt->pTableBlockHashObj = NULL;
  return code;
}
1807

X
Xiaoyu Wang 已提交
1808
static int32_t parseInsertBodyBottom(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
1809 1810 1811
  if (TSDB_QUERY_HAS_TYPE(pStmt->insertType, TSDB_QUERY_TYPE_STMT_INSERT)) {
    return setStmtInfo(pCxt, pStmt);
  }
D
stmt  
dapan1121 已提交
1812

X
Xiaoyu Wang 已提交
1813
  // merge according to vgId
X
Xiaoyu Wang 已提交
1814
  int32_t code = insMergeTableDataCxt(pStmt->pTableBlockHashObj, &pStmt->pVgDataBlocks);
X
Xiaoyu Wang 已提交
1815
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
1816
    code = insBuildVgDataBlocks(pStmt->pVgroupsHashObj, pStmt->pVgDataBlocks, &pStmt->pDataBlocks);
X
Xiaoyu Wang 已提交
1817
  }
X
Xiaoyu Wang 已提交
1818

X
Xiaoyu Wang 已提交
1819 1820
  return code;
}
1821

X
Xiaoyu Wang 已提交
1822 1823 1824 1825 1826
// tb_name
//     [USING stb_name [(tag1_name, ...)] TAGS (tag1_value, ...)]
//     [(field1_name, ...)]
//     VALUES (field1_value, ...) [(field1_value2, ...) ...] | FILE csv_file_path
// [...];
X
Xiaoyu Wang 已提交
1827
static int32_t parseInsertBody(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
1828 1829 1830 1831
  SToken  token;
  int32_t code = TSDB_CODE_SUCCESS;
  bool    hasData = true;
  // for each table
X
Xiaoyu Wang 已提交
1832
  while (TSDB_CODE_SUCCESS == code && hasData && !pCxt->missCache && !pStmt->fileProcessing) {
X
Xiaoyu Wang 已提交
1833 1834 1835 1836 1837
    // pStmt->pSql -> tb_name ...
    NEXT_TOKEN(pStmt->pSql, token);
    code = checkTableClauseFirstToken(pCxt, pStmt, &token, &hasData);
    if (TSDB_CODE_SUCCESS == code && hasData) {
      code = parseInsertTableClause(pCxt, pStmt, &token);
1838 1839
    }
  }
X
Xiaoyu Wang 已提交
1840

X
Xiaoyu Wang 已提交
1841 1842 1843 1844 1845
  if (TSDB_CODE_SUCCESS == code && !pCxt->missCache) {
    code = parseInsertBodyBottom(pCxt, pStmt);
  }
  return code;
}
D
stmt  
dapan1121 已提交
1846

X
Xiaoyu Wang 已提交
1847
static void destroySubTableHashElem(void* p) { taosMemoryFree(*(STableMeta**)p); }
X
Xiaoyu Wang 已提交
1848

X
Xiaoyu Wang 已提交
1849
static int32_t createVnodeModifOpStmt(SInsertParseContext* pCxt, bool reentry, SNode** pOutput) {
X
Xiaoyu Wang 已提交
1850
  SVnodeModifyOpStmt* pStmt = (SVnodeModifyOpStmt*)nodesMakeNode(QUERY_NODE_VNODE_MODIFY_STMT);
X
Xiaoyu Wang 已提交
1851 1852
  if (NULL == pStmt) {
    return TSDB_CODE_OUT_OF_MEMORY;
D
stmt  
dapan1121 已提交
1853
  }
X
Xiaoyu Wang 已提交
1854

X
Xiaoyu Wang 已提交
1855
  if (pCxt->pComCxt->pStmtCb) {
X
Xiaoyu Wang 已提交
1856
    TSDB_QUERY_SET_TYPE(pStmt->insertType, TSDB_QUERY_TYPE_STMT_INSERT);
1857
  }
X
Xiaoyu Wang 已提交
1858
  pStmt->pSql = pCxt->pComCxt->pSql;
X
Xiaoyu Wang 已提交
1859 1860
  pStmt->freeHashFunc = insDestroyTableDataCxtHashMap;
  pStmt->freeArrayFunc = insDestroyVgroupDataCxtList;
X
Xiaoyu Wang 已提交
1861

X
Xiaoyu Wang 已提交
1862 1863 1864 1865 1866
  if (!reentry) {
    pStmt->pVgroupsHashObj = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_NO_LOCK);
    pStmt->pTableBlockHashObj =
        taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BIGINT), true, HASH_NO_LOCK);
  }
X
Xiaoyu Wang 已提交
1867 1868 1869
  pStmt->pSubTableHashObj = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_VARCHAR), true, HASH_NO_LOCK);
  pStmt->pTableNameHashObj = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_VARCHAR), true, HASH_NO_LOCK);
  pStmt->pDbFNameHashObj = taosHashInit(64, taosGetDefaultHashFunction(TSDB_DATA_TYPE_VARCHAR), true, HASH_NO_LOCK);
X
Xiaoyu Wang 已提交
1870 1871
  if ((!reentry && (NULL == pStmt->pVgroupsHashObj || NULL == pStmt->pTableBlockHashObj)) ||
      NULL == pStmt->pSubTableHashObj || NULL == pStmt->pTableNameHashObj || NULL == pStmt->pDbFNameHashObj) {
X
Xiaoyu Wang 已提交
1872 1873
    nodesDestroyNode((SNode*)pStmt);
    return TSDB_CODE_OUT_OF_MEMORY;
1874
  }
X
Xiaoyu Wang 已提交
1875 1876 1877 1878 1879

  taosHashSetFreeFp(pStmt->pSubTableHashObj, destroySubTableHashElem);

  *pOutput = (SNode*)pStmt;
  return TSDB_CODE_SUCCESS;
1880 1881
}

X
Xiaoyu Wang 已提交
1882
static int32_t createInsertQuery(SInsertParseContext* pCxt, SQuery** pOutput) {
X
Xiaoyu Wang 已提交
1883 1884 1885
  SQuery* pQuery = (SQuery*)nodesMakeNode(QUERY_NODE_QUERY);
  if (NULL == pQuery) {
    return TSDB_CODE_OUT_OF_MEMORY;
D
stmt  
dapan1121 已提交
1886
  }
X
Xiaoyu Wang 已提交
1887

X
Xiaoyu Wang 已提交
1888 1889 1890
  pQuery->execMode = QUERY_EXEC_MODE_SCHEDULE;
  pQuery->haveResultSet = false;
  pQuery->msgType = TDMT_VND_SUBMIT;
1891

X
Xiaoyu Wang 已提交
1892
  int32_t code = createVnodeModifOpStmt(pCxt, false, &pQuery->pRoot);
X
Xiaoyu Wang 已提交
1893 1894 1895 1896
  if (TSDB_CODE_SUCCESS == code) {
    *pOutput = pQuery;
  } else {
    nodesDestroyNode((SNode*)pQuery);
D
stmt  
dapan1121 已提交
1897
  }
X
Xiaoyu Wang 已提交
1898 1899
  return code;
}
D
stmt  
dapan1121 已提交
1900

X
Xiaoyu Wang 已提交
1901
static int32_t checkAuthFromMetaData(const SArray* pUsers, SNode** pTagCond) {
X
Xiaoyu Wang 已提交
1902 1903
  if (1 != taosArrayGetSize(pUsers)) {
    return TSDB_CODE_FAILED;
1904
  }
1905

X
Xiaoyu Wang 已提交
1906 1907
  SMetaRes* pRes = taosArrayGet(pUsers, 0);
  if (TSDB_CODE_SUCCESS == pRes->code) {
X
Xiaoyu Wang 已提交
1908 1909 1910 1911 1912
    SUserAuthRes* pAuth = pRes->pRes;
    if (NULL != pAuth->pCond) {
      *pTagCond = nodesCloneNode(pAuth->pCond);
    }
    return pAuth->pass ? TSDB_CODE_SUCCESS : TSDB_CODE_PAR_PERMISSION_DENIED;
X
Xiaoyu Wang 已提交
1913 1914 1915
  }
  return pRes->code;
}
X
Xiaoyu Wang 已提交
1916

X
Xiaoyu Wang 已提交
1917 1918 1919 1920
static int32_t getTableMetaFromMetaData(const SArray* pTables, STableMeta** pMeta) {
  if (1 != taosArrayGetSize(pTables)) {
    return TSDB_CODE_FAILED;
  }
X
Xiaoyu Wang 已提交
1921 1922

  taosMemoryFreeClear(*pMeta);
X
Xiaoyu Wang 已提交
1923 1924 1925 1926
  SMetaRes* pRes = taosArrayGet(pTables, 0);
  if (TSDB_CODE_SUCCESS == pRes->code) {
    *pMeta = tableMetaDup((const STableMeta*)pRes->pRes);
    if (NULL == *pMeta) {
D
dapan1121 已提交
1927 1928 1929
      return TSDB_CODE_OUT_OF_MEMORY;
    }
  }
X
Xiaoyu Wang 已提交
1930 1931
  return pRes->code;
}
1932

X
Xiaoyu Wang 已提交
1933
static int32_t getTableVgroupFromMetaData(const SArray* pTables, SVnodeModifyOpStmt* pStmt, bool isStb) {
X
Xiaoyu Wang 已提交
1934 1935
  if (1 != taosArrayGetSize(pTables)) {
    return TSDB_CODE_FAILED;
D
dapan1121 已提交
1936 1937
  }

X
Xiaoyu Wang 已提交
1938 1939 1940
  SMetaRes* pRes = taosArrayGet(pTables, 0);
  if (TSDB_CODE_SUCCESS != pRes->code) {
    return pRes->code;
1941
  }
1942

X
Xiaoyu Wang 已提交
1943 1944 1945 1946 1947 1948 1949
  SVgroupInfo* pVg = pRes->pRes;
  if (isStb) {
    pStmt->pTableMeta->vgId = pVg->vgId;
  }
  return taosHashPut(pStmt->pVgroupsHashObj, (const char*)&pVg->vgId, sizeof(pVg->vgId), (char*)pVg,
                     sizeof(SVgroupInfo));
}
D
dapan1121 已提交
1950

X
Xiaoyu Wang 已提交
1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
static int32_t buildTagNameFromMeta(STableMeta* pMeta, SArray** pTagName) {
  *pTagName = taosArrayInit(pMeta->tableInfo.numOfTags, TSDB_COL_NAME_LEN);
  if (NULL == *pTagName) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
  SSchema* pSchema = getTableTagSchema(pMeta);
  for (int32_t i = 0; i < pMeta->tableInfo.numOfTags; ++i) {
    taosArrayPush(*pTagName, pSchema[i].name);
  }
  return TSDB_CODE_SUCCESS;
}

static int32_t checkSubtablePrivilegeForTable(const SArray* pTables, SVnodeModifyOpStmt* pStmt) {
  if (1 != taosArrayGetSize(pTables)) {
    return TSDB_CODE_FAILED;
  }

  SMetaRes* pRes = taosArrayGet(pTables, 0);
  if (TSDB_CODE_SUCCESS != pRes->code) {
    return pRes->code;
  }

  SArray* pTagName = NULL;
  int32_t code = buildTagNameFromMeta(pStmt->pTableMeta, &pTagName);
  if (TSDB_CODE_SUCCESS == code) {
    code = checkSubtablePrivilege((SArray*)pRes->pRes, pTagName, &pStmt->pTagCond);
  }
  taosArrayDestroy(pTagName);
  return code;
}

X
Xiaoyu Wang 已提交
1982
static int32_t getTableSchemaFromMetaData(SInsertParseContext* pCxt, const SMetaData* pMetaData,
X
Xiaoyu Wang 已提交
1983
                                          SVnodeModifyOpStmt* pStmt, bool isStb) {
X
Xiaoyu Wang 已提交
1984
  int32_t code = checkAuthFromMetaData(pMetaData->pUser, &pStmt->pTagCond);
X
Xiaoyu Wang 已提交
1985 1986
  if (TSDB_CODE_SUCCESS == code) {
    code = getTableMetaFromMetaData(pMetaData->pTableMeta, &pStmt->pTableMeta);
X
Xiaoyu Wang 已提交
1987
  }
X
Xiaoyu Wang 已提交
1988 1989 1990
  if (TSDB_CODE_SUCCESS == code && !isStb && TSDB_SUPER_TABLE == pStmt->pTableMeta->tableType) {
    code = buildInvalidOperationMsg(&pCxt->msg, "insert data into super table is not supported");
  }
1991 1992 1993
  if (TSDB_CODE_SUCCESS == code && isStb) {
    code = storeTableMeta(pCxt, pStmt);
  }
X
Xiaoyu Wang 已提交
1994 1995
  if (TSDB_CODE_SUCCESS == code) {
    code = getTableVgroupFromMetaData(pMetaData->pTableHash, pStmt, isStb);
1996
  }
X
Xiaoyu Wang 已提交
1997 1998 1999
  if (TSDB_CODE_SUCCESS == code && !isStb && NULL != pStmt->pTagCond) {
    code = checkSubtablePrivilegeForTable(pMetaData->pTableTag, pStmt);
  }
X
Xiaoyu Wang 已提交
2000
  return code;
2001
}
D
stmt  
dapan1121 已提交
2002

X
Xiaoyu Wang 已提交
2003 2004 2005 2006 2007 2008
static void destoryTablesReq(void* p) {
  STablesReq* pRes = (STablesReq*)p;
  taosArrayDestroy(pRes->pTables);
}

static void clearCatalogReq(SCatalogReq* pCatalogReq) {
X
Xiaoyu Wang 已提交
2009 2010 2011 2012
  if (NULL == pCatalogReq) {
    return;
  }

X
Xiaoyu Wang 已提交
2013 2014 2015 2016 2017 2018
  taosArrayDestroyEx(pCatalogReq->pTableMeta, destoryTablesReq);
  pCatalogReq->pTableMeta = NULL;
  taosArrayDestroyEx(pCatalogReq->pTableHash, destoryTablesReq);
  pCatalogReq->pTableHash = NULL;
  taosArrayDestroy(pCatalogReq->pUser);
  pCatalogReq->pUser = NULL;
X
Xiaoyu Wang 已提交
2019 2020
  taosArrayDestroy(pCatalogReq->pTableTag);
  pCatalogReq->pTableTag = NULL;
X
Xiaoyu Wang 已提交
2021 2022
}

X
Xiaoyu Wang 已提交
2023
static int32_t setVnodeModifOpStmt(SInsertParseContext* pCxt, SCatalogReq* pCatalogReq, const SMetaData* pMetaData,
X
Xiaoyu Wang 已提交
2024
                                   SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
2025 2026
  clearCatalogReq(pCatalogReq);

X
Xiaoyu Wang 已提交
2027
  if (pStmt->usingTableProcessing) {
X
Xiaoyu Wang 已提交
2028
    return getTableSchemaFromMetaData(pCxt, pMetaData, pStmt, true);
X
Xiaoyu Wang 已提交
2029
  }
X
Xiaoyu Wang 已提交
2030
  return getTableSchemaFromMetaData(pCxt, pMetaData, pStmt, false);
X
Xiaoyu Wang 已提交
2031 2032
}

X
Xiaoyu Wang 已提交
2033
static int32_t resetVnodeModifOpStmt(SInsertParseContext* pCxt, SQuery* pQuery) {
X
Xiaoyu Wang 已提交
2034 2035 2036 2037
  nodesDestroyNode(pQuery->pRoot);

  int32_t code = createVnodeModifOpStmt(pCxt, true, &pQuery->pRoot);
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
2038
    SVnodeModifyOpStmt* pStmt = (SVnodeModifyOpStmt*)pQuery->pRoot;
X
Xiaoyu Wang 已提交
2039

X
Xiaoyu Wang 已提交
2040 2041
    (*pCxt->pComCxt->pStmtCb->getExecInfoFn)(pCxt->pComCxt->pStmtCb->pStmt, &pStmt->pVgroupsHashObj,
                                             &pStmt->pTableBlockHashObj);
X
Xiaoyu Wang 已提交
2042 2043 2044 2045 2046 2047
    if (NULL == pStmt->pVgroupsHashObj) {
      pStmt->pVgroupsHashObj = taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_INT), true, HASH_NO_LOCK);
    }
    if (NULL == pStmt->pTableBlockHashObj) {
      pStmt->pTableBlockHashObj =
          taosHashInit(128, taosGetDefaultHashFunction(TSDB_DATA_TYPE_BINARY), true, HASH_NO_LOCK);
2048
    }
X
Xiaoyu Wang 已提交
2049 2050 2051
    if (NULL == pStmt->pVgroupsHashObj || NULL == pStmt->pTableBlockHashObj) {
      code = TSDB_CODE_OUT_OF_MEMORY;
    }
2052
  }
X
Xiaoyu Wang 已提交
2053

X
Xiaoyu Wang 已提交
2054
  return code;
2055 2056
}

X
Xiaoyu Wang 已提交
2057
static int32_t initInsertQuery(SInsertParseContext* pCxt, SCatalogReq* pCatalogReq, const SMetaData* pMetaData,
X
Xiaoyu Wang 已提交
2058
                               SQuery** pQuery) {
X
Xiaoyu Wang 已提交
2059 2060 2061
  if (NULL == *pQuery) {
    return createInsertQuery(pCxt, pQuery);
  }
X
Xiaoyu Wang 已提交
2062

X
Xiaoyu Wang 已提交
2063
  if (NULL != pCxt->pComCxt->pStmtCb) {
X
Xiaoyu Wang 已提交
2064 2065 2066
    return resetVnodeModifOpStmt(pCxt, *pQuery);
  }

X
Xiaoyu Wang 已提交
2067
  SVnodeModifyOpStmt* pStmt = (SVnodeModifyOpStmt*)(*pQuery)->pRoot;
X
Xiaoyu Wang 已提交
2068 2069 2070

  if (!pStmt->fileProcessing) {
    return setVnodeModifOpStmt(pCxt, pCatalogReq, pMetaData, pStmt);
X
Xiaoyu Wang 已提交
2071 2072 2073
  }

  return TSDB_CODE_SUCCESS;
2074 2075
}

X
Xiaoyu Wang 已提交
2076
static int32_t setRefreshMate(SQuery* pQuery) {
X
Xiaoyu Wang 已提交
2077
  SVnodeModifyOpStmt* pStmt = (SVnodeModifyOpStmt*)pQuery->pRoot;
2078 2079 2080 2081 2082 2083 2084 2085 2086

  if (taosHashGetSize(pStmt->pTableNameHashObj) > 0) {
    taosArrayDestroy(pQuery->pTableList);
    pQuery->pTableList = taosArrayInit(taosHashGetSize(pStmt->pTableNameHashObj), sizeof(SName));
    SName* pTable = taosHashIterate(pStmt->pTableNameHashObj, NULL);
    while (NULL != pTable) {
      taosArrayPush(pQuery->pTableList, pTable);
      pTable = taosHashIterate(pStmt->pTableNameHashObj, pTable);
    }
2087 2088
  }

2089 2090 2091 2092 2093 2094 2095 2096
  if (taosHashGetSize(pStmt->pDbFNameHashObj) > 0) {
    taosArrayDestroy(pQuery->pDbList);
    pQuery->pDbList = taosArrayInit(taosHashGetSize(pStmt->pDbFNameHashObj), TSDB_DB_FNAME_LEN);
    char* pDb = taosHashIterate(pStmt->pDbFNameHashObj, NULL);
    while (NULL != pDb) {
      taosArrayPush(pQuery->pDbList, pDb);
      pDb = taosHashIterate(pStmt->pDbFNameHashObj, pDb);
    }
2097 2098 2099 2100 2101
  }

  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
2102 2103 2104 2105 2106 2107
// INSERT INTO
//   tb_name
//       [USING stb_name [(tag1_name, ...)] TAGS (tag1_value, ...) [table_options]]
//       [(field1_name, ...)]
//       VALUES (field1_value, ...) [(field1_value2, ...) ...] | FILE csv_file_path
//   [...];
X
Xiaoyu Wang 已提交
2108
static int32_t parseInsertSqlFromStart(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
2109 2110 2111 2112 2113
  int32_t code = skipInsertInto(&pStmt->pSql, &pCxt->msg);
  if (TSDB_CODE_SUCCESS == code) {
    code = parseInsertBody(pCxt, pStmt);
  }
  return code;
2114 2115
}

X
Xiaoyu Wang 已提交
2116
static int32_t parseInsertSqlFromCsv(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
2117 2118
  STableDataCxt* pTableCxt = NULL;
  int32_t        code = getTableDataCxt(pCxt, pStmt, &pTableCxt);
X
Xiaoyu Wang 已提交
2119
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
2120
    code = parseDataFromFileImpl(pCxt, pStmt, pTableCxt);
2121 2122
  }

X
Xiaoyu Wang 已提交
2123 2124 2125 2126 2127 2128 2129 2130 2131
  if (TSDB_CODE_SUCCESS == code) {
    if (pStmt->fileProcessing) {
      code = parseInsertBodyBottom(pCxt, pStmt);
    } else {
      code = parseInsertBody(pCxt, pStmt);
    }
  }

  return code;
X
Xiaoyu Wang 已提交
2132 2133
}

X
Xiaoyu Wang 已提交
2134
static int32_t parseInsertSqlFromTable(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
2135 2136 2137 2138 2139 2140
  int32_t code = parseInsertTableClauseBottom(pCxt, pStmt);
  if (TSDB_CODE_SUCCESS == code) {
    code = parseInsertBody(pCxt, pStmt);
  }
  return code;
}
2141

X
Xiaoyu Wang 已提交
2142
static int32_t parseInsertSqlImpl(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt) {
X
Xiaoyu Wang 已提交
2143 2144 2145
  if (pStmt->pSql == pCxt->pComCxt->pSql || NULL != pCxt->pComCxt->pStmtCb) {
    return parseInsertSqlFromStart(pCxt, pStmt);
  }
2146

X
Xiaoyu Wang 已提交
2147 2148 2149
  if (pStmt->fileProcessing) {
    return parseInsertSqlFromCsv(pCxt, pStmt);
  }
2150

X
Xiaoyu Wang 已提交
2151 2152
  return parseInsertSqlFromTable(pCxt, pStmt);
}
2153

X
Xiaoyu Wang 已提交
2154 2155 2156 2157 2158
static int32_t buildInsertTableReq(SName* pName, SArray** pTables) {
  *pTables = taosArrayInit(1, sizeof(SName));
  if (NULL == *pTables) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
2159

X
Xiaoyu Wang 已提交
2160 2161 2162
  taosArrayPush(*pTables, pName);
  return TSDB_CODE_SUCCESS;
}
2163

X
Xiaoyu Wang 已提交
2164 2165 2166 2167 2168
static int32_t buildInsertDbReq(SName* pName, SArray** pDbs) {
  if (NULL == *pDbs) {
    *pDbs = taosArrayInit(1, sizeof(STablesReq));
    if (NULL == *pDbs) {
      return TSDB_CODE_OUT_OF_MEMORY;
2169
    }
X
Xiaoyu Wang 已提交
2170
  }
2171

X
Xiaoyu Wang 已提交
2172 2173 2174 2175
  STablesReq req = {0};
  tNameGetFullDbName(pName, req.dbFName);
  buildInsertTableReq(pName, &req.pTables);
  taosArrayPush(*pDbs, &req);
2176

X
Xiaoyu Wang 已提交
2177 2178
  return TSDB_CODE_SUCCESS;
}
2179

X
Xiaoyu Wang 已提交
2180 2181 2182 2183 2184
static int32_t buildInsertUserAuthReq(const char* pUser, SName* pName, SArray** pUserAuth) {
  *pUserAuth = taosArrayInit(1, sizeof(SUserAuthInfo));
  if (NULL == *pUserAuth) {
    return TSDB_CODE_OUT_OF_MEMORY;
  }
X
Xiaoyu Wang 已提交
2185

X
Xiaoyu Wang 已提交
2186 2187
  SUserAuthInfo userAuth = {.type = AUTH_TYPE_WRITE};
  snprintf(userAuth.user, sizeof(userAuth.user), "%s", pUser);
X
Xiaoyu Wang 已提交
2188
  memcpy(&userAuth.tbName, pName, sizeof(SName));
X
Xiaoyu Wang 已提交
2189
  taosArrayPush(*pUserAuth, &userAuth);
2190

X
Xiaoyu Wang 已提交
2191 2192 2193
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
2194 2195
static int32_t buildInsertTableTagReq(SName* pName, SArray** pTables) { return buildInsertTableReq(pName, pTables); }

X
Xiaoyu Wang 已提交
2196
static int32_t buildInsertCatalogReq(SInsertParseContext* pCxt, SVnodeModifyOpStmt* pStmt, SCatalogReq* pCatalogReq) {
X
Xiaoyu Wang 已提交
2197 2198 2199 2200 2201 2202
  int32_t code = buildInsertUserAuthReq(
      pCxt->pComCxt->pUser, (0 == pStmt->usingTableName.type ? &pStmt->targetTableName : &pStmt->usingTableName),
      &pCatalogReq->pUser);
  if (TSDB_CODE_SUCCESS == code && pCxt->needTableTagVal) {
    code = buildInsertTableTagReq(&pStmt->targetTableName, &pCatalogReq->pTableTag);
  }
X
Xiaoyu Wang 已提交
2203 2204 2205 2206 2207
  if (TSDB_CODE_SUCCESS == code) {
    if (0 == pStmt->usingTableName.type) {
      code = buildInsertDbReq(&pStmt->targetTableName, &pCatalogReq->pTableMeta);
    } else {
      code = buildInsertDbReq(&pStmt->usingTableName, &pCatalogReq->pTableMeta);
2208
    }
X
Xiaoyu Wang 已提交
2209 2210 2211 2212 2213 2214
  }
  if (TSDB_CODE_SUCCESS == code) {
    code = buildInsertDbReq(&pStmt->targetTableName, &pCatalogReq->pTableHash);
  }
  return code;
}
2215

X
Xiaoyu Wang 已提交
2216
static int32_t setNextStageInfo(SInsertParseContext* pCxt, SQuery* pQuery, SCatalogReq* pCatalogReq) {
X
Xiaoyu Wang 已提交
2217
  SVnodeModifyOpStmt* pStmt = (SVnodeModifyOpStmt*)pQuery->pRoot;
X
Xiaoyu Wang 已提交
2218
  if (pCxt->missCache) {
2219 2220
    parserDebug("0x%" PRIx64 " %d rows of %d tables have been inserted before cache miss", pCxt->pComCxt->requestId,
                pStmt->totalRowsNum, pStmt->totalTbNum);
X
Xiaoyu Wang 已提交
2221

X
Xiaoyu Wang 已提交
2222
    pQuery->execStage = QUERY_EXEC_STAGE_PARSE;
2223
    return buildInsertCatalogReq(pCxt, pStmt, pCatalogReq);
2224 2225
  }

2226 2227
  parserDebug("0x%" PRIx64 " %d rows of %d tables have been inserted", pCxt->pComCxt->requestId, pStmt->totalRowsNum,
              pStmt->totalTbNum);
X
Xiaoyu Wang 已提交
2228

X
Xiaoyu Wang 已提交
2229
  pQuery->execStage = QUERY_EXEC_STAGE_SCHEDULE;
2230 2231 2232
  return TSDB_CODE_SUCCESS;
}

X
Xiaoyu Wang 已提交
2233
int32_t parseInsertSql(SParseContext* pCxt, SQuery** pQuery, SCatalogReq* pCatalogReq, const SMetaData* pMetaData) {
X
Xiaoyu Wang 已提交
2234 2235 2236 2237 2238
  SInsertParseContext context = {.pComCxt = pCxt,
                                 .msg = {.buf = pCxt->pMsg, .len = pCxt->msgLen},
                                 .missCache = false,
                                 .usingDuplicateTable = false,
                                 .forceUpdate = (NULL != pCatalogReq ? pCatalogReq->forceUpdate : false)};
X
Xiaoyu Wang 已提交
2239

X
Xiaoyu Wang 已提交
2240
  int32_t code = initInsertQuery(&context, pCatalogReq, pMetaData, pQuery);
2241
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
2242
    code = parseInsertSqlImpl(&context, (SVnodeModifyOpStmt*)(*pQuery)->pRoot);
2243 2244
  }
  if (TSDB_CODE_SUCCESS == code) {
X
Xiaoyu Wang 已提交
2245 2246 2247 2248 2249
    code = setNextStageInfo(&context, *pQuery, pCatalogReq);
  }
  if ((TSDB_CODE_SUCCESS == code || NEED_CLIENT_HANDLE_ERROR(code)) &&
      QUERY_EXEC_STAGE_SCHEDULE == (*pQuery)->execStage) {
    code = setRefreshMate(*pQuery);
2250
  }
X
Xiaoyu Wang 已提交
2251
  insDestroyBoundColInfo(&context.tags);
2252 2253
  return code;
}