• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

taosdata / TDengine / #3533

20 Nov 2024 07:11AM UTC coverage: 58.848% (-1.9%) from 60.78%
#3533

push

travis-ci

web-flow
Merge pull request #28823 from taosdata/fix/3.0/TD-32587

fix:[TD-32587]fix stmt segmentation fault

115578 of 252434 branches covered (45.79%)

Branch coverage included in aggregate %.

1 of 4 new or added lines in 1 file covered. (25.0%)

8038 existing lines in 233 files now uncovered.

194926 of 275199 relevant lines covered (70.83%)

1494459.59 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

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

16
#define ALLOW_FORBID_FUNC
17
#define _BSD_SOURCE
18
#define _GNU_SOURCE
19
#define _XOPEN_SOURCE
20
#define _DEFAULT_SOURCE
21
#include "geosWrapper.h"
22
#include "shellAuto.h"
23
#include "shellInt.h"
24

25
SShellObj shell = {0};
26

27
typedef struct {
28
  const char *sql;
29
  bool        vertical;
30
  tsem_t      sem;
31
  int64_t     numOfRows;  // the num of this batch
32
  int64_t     numOfAllRows;
33

34
  int32_t     numFields;
35
  TAOS_FIELD *fields;
36
  int32_t     precision;
37

38
  int32_t maxColNameLen;            // for vertical print
39
  int32_t width[TSDB_MAX_COLUMNS];  // for horizontal print
40

41
  uint64_t resShowMaxNum;
42
} tsDumpInfo;
43

44
static bool    shellIsEmptyCommand(const char *cmd);
45
static int32_t shellRunSingleCommand(char *command);
46
static void    shellRecordCommandToHistory(char *command);
47
static int32_t shellRunCommand(char *command, bool recordHistory);
48
static void    shellRunSingleCommandImp(char *command);
49
static char   *shellFormatTimestamp(char *buf, int32_t bufSize, int64_t val, int32_t precision);
50
static int64_t shellDumpResultToFile(const char *fname, TAOS_RES *tres);
51
static void    shellPrintNChar(const char *str, int32_t length, int32_t width);
52
static void    shellPrintGeometry(const unsigned char *str, int32_t length, int32_t width);
53
static void    shellVerticalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info);
54
static void    shellHorizontalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info);
55
static int64_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql);
56
static void    shellReadHistory();
57
static void    shellWriteHistory();
58
static void    shellPrintError(TAOS_RES *tres, int64_t st);
59
static bool    shellIsCommentLine(char *line);
60
static void    shellSourceFile(const char *file);
61
static bool    shellGetGrantInfo(char* buf);
62

63
static void  shellCleanup(void *arg);
64
static void *shellCancelHandler(void *arg);
65
static void *shellThreadLoop(void *arg);
66

67
static bool shellCmdkilled = false;
68

69
bool shellIsEmptyCommand(const char *cmd) {
34,714✔
70
  for (char c = *cmd++; c != 0; c = *cmd++) {
43,990✔
71
    if (c != ' ' && c != '\t' && c != ';') {
27,806!
72
      return false;
18,530✔
73
    }
74
  }
75
  return true;
16,184✔
76
}
77

78
int32_t shellRunSingleCommand(char *command) {
25,477✔
79
  shellCmdkilled = false;
25,477✔
80

81
  if (shellIsEmptyCommand(command)) {
25,477✔
82
    return 0;
16,184✔
83
  }
84

85
  if (shellRegexMatch(command, "^[ \t]*(quit|q|exit)[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
9,293!
86
    return -1;
×
87
  }
88

89
  if (shellRegexMatch(command, "^[\t ]*clear[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
9,293!
90
#pragma GCC diagnostic push
91
#pragma GCC diagnostic ignored "-Wunused-result"
92
    system("clear");
×
93
#pragma GCC diagnostic pop
94
    return 0;
×
95
  }
96

97
  if (shellRegexMatch(command, "^[\t ]*set[ \t]+max_binary_display_width[ \t]+(default|[1-9][0-9]*)[ \t;]*$",
9,293!
98
                      REG_EXTENDED | REG_ICASE)) {
99
    strtok(command, " \t");
×
100
    strtok(NULL, " \t");
×
101
    char *p = strtok(NULL, " \t");
×
102
    if (strncasecmp(p, "default", 7) == 0) {
×
103
      shell.args.displayWidth = SHELL_DEFAULT_MAX_BINARY_DISPLAY_WIDTH;
×
104
    } else {
105
      int32_t displayWidth = atoi(p);
×
106
      displayWidth = TRANGE(displayWidth, 1, 10 * 1024);
×
107
      shell.args.displayWidth = displayWidth;
×
108
    }
109
    return 0;
×
110
  }
111

112
  if (shellRegexMatch(command, "^[ \t]*source[\t ]+[^ ]+[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
9,293✔
113
    /* If source file. */
114
    char *c_ptr = strtok(command, " ;");
1✔
115
    if (c_ptr == NULL) {
1!
116
      shellRunSingleCommandImp(command);
×
117
      return 0;
×
118
    }
119
    c_ptr = strtok(NULL, " ;");
1✔
120
    if (c_ptr == NULL) {
1!
121
      shellRunSingleCommandImp(command);
×
122
      return 0;
×
123
    }
124
    shellSourceFile(c_ptr);
1✔
125
    return 0;
1✔
126
  }
127
#ifdef WEBSOCKET
128
  if (shell.args.restful || shell.args.cloud) {
129
    shellRunSingleCommandWebsocketImp(command);
130
  } else {
131
#endif
132
    shellRunSingleCommandImp(command);
9,292✔
133
#ifdef WEBSOCKET
134
  }
135
#endif
136
  return 0;
9,292✔
137
}
138

139
void shellRecordCommandToHistory(char *command) {
147✔
140
  if (strncasecmp(command, "create user ", 12) == 0 || strncasecmp(command, "alter user ", 11) == 0) {
147!
141
    if (taosStrCaseStr(command, " pass ")) {
4!
142
      // have password command forbid record to history because security
143
      return;
×
144
    }
145
  }
146

147
  SShellHistory *pHistory = &shell.history;
147✔
148
  if (pHistory->hstart == pHistory->hend ||
147✔
149
      pHistory->hist[(pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE] == NULL ||
1!
150
      strcmp(command, pHistory->hist[(pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE]) != 0) {
1!
151
    if (pHistory->hist[pHistory->hend] != NULL) {
147!
152
      taosMemoryFreeClear(pHistory->hist[pHistory->hend]);
147!
153
    }
154
    pHistory->hist[pHistory->hend] = taosStrdup(command);
147✔
155

156
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
147✔
157
    if (pHistory->hend == pHistory->hstart) {
147!
158
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
×
159
    }
160
  }
161
}
162

163
int32_t shellRunCommand(char *command, bool recordHistory) {
9,237✔
164
  if (shellIsEmptyCommand(command)) {
9,237!
165
    return 0;
×
166
  }
167

168
  // add help or help;
169
  if (strncasecmp(command, "help", 4) == 0) {
9,237!
170
    if (command[4] == ';' || command[4] == ' ' || command[4] == 0) {
×
171
      showHelp();
×
172
      return 0;
×
173
    }
174
  }
175

176
  if (recordHistory) shellRecordCommandToHistory(command);
9,237✔
177

178
  char quote = 0, *cmd = command;
9,237✔
179
  for (char c = *command++; c != 0; c = *command++) {
6,488,313✔
180
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
6,479,076!
UNCOV
181
      command++;
×
UNCOV
182
      continue;
×
183
    }
184

185
    if (quote == c) {
6,479,076✔
186
      quote = 0;
40,653✔
187
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
6,438,423✔
188
      quote = c;
40,653✔
189
    } else if (c == ';' && quote == 0) {
6,397,770✔
190
      c = *command;
16,240✔
191
      *command = 0;
16,240✔
192
      if (shellRunSingleCommand(cmd) < 0) {
16,240!
193
        return -1;
×
194
      }
195
      *command = c;
16,240✔
196
      cmd = command;
16,240✔
197
    }
198
  }
199
  return shellRunSingleCommand(cmd);
9,237✔
200
}
201

202
char *strendG(const char *pstr) {
9,292✔
203
  if (pstr == NULL) {
9,292!
204
    return NULL;
×
205
  }
206

207
  size_t len = strlen(pstr);
9,292✔
208
  if (len < 4) {
9,292!
209
    return NULL;
×
210
  }
211

212
  char *p = (char *)pstr + len - 2;
9,292✔
213
  if (strcmp(p, "\\G") == 0) {
9,292✔
214
    return p;
4✔
215
  }
216

217
  p = (char *)pstr + len - 3;
9,288✔
218
  if (strcmp(p, "\\G;") == 0) {
9,288✔
219
    return p;
55✔
220
  }
221

222
  return NULL;
9,233✔
223
}
224

225
void shellRunSingleCommandImp(char *command) {
9,292✔
226
  int64_t st, et;
227
  char   *sptr = NULL;
9,292✔
228
  char   *cptr = NULL;
9,292✔
229
  char   *fname = NULL;
9,292✔
230
  bool    printMode = false;
9,292✔
231

232
  if ((sptr = strstr(command, ">>")) != NULL) {
9,292✔
233
    fname = sptr + 2;
35✔
234
    while (*fname == ' ') fname++;
58✔
235
    *sptr = '\0';
35✔
236

237
    cptr = strstr(fname, ";");
35✔
238
    if (cptr != NULL) {
35✔
239
      *cptr = '\0';
12✔
240
    }
241
  }
242

243
  if ((sptr = strendG(command)) != NULL) {
9,292✔
244
    *sptr = '\0';
59✔
245
    printMode = true;  // When output to a file, the switch does not work.
59✔
246
  }
247

248
  st = taosGetTimestampUs();
9,292✔
249

250
  TAOS_RES *pSql = taos_query(shell.conn, command);
9,292✔
251
  if (taos_errno(pSql)) {
9,292✔
252
    shellPrintError(pSql, st);
165✔
253
    return;
165✔
254
  }
255

256
  if (shellRegexMatch(command, "^\\s*use\\s+[a-zA-Z0-9_]+\\s*;\\s*$", REG_EXTENDED | REG_ICASE)) {
9,127✔
257
    fprintf(stdout, "Database changed.\r\n\r\n");
19✔
258
    fflush(stdout);
19✔
259

260
    // call back auto tab module
261
    callbackAutoTab(command, pSql, true);
19✔
262

263
    taos_free_result(pSql);
19✔
264

265
    return;
19✔
266
  }
267

268
  // pre string
269
  char *pre = "Query OK";
9,108✔
270
  if (shellRegexMatch(command, "^\\s*delete\\s*from\\s*.*", REG_EXTENDED | REG_ICASE)) {
9,108✔
271
    pre = "Delete OK";
10✔
272
  } else if (shellRegexMatch(command, "^\\s*insert\\s*into\\s*.*", REG_EXTENDED | REG_ICASE)) {
9,098✔
273
    pre = "Insert OK";
2,432✔
274
  } else if (shellRegexMatch(command, "^\\s*create\\s*.*", REG_EXTENDED | REG_ICASE)) {
6,666✔
275
    pre = "Create OK";
186✔
276
  } else if (shellRegexMatch(command, "^\\s*drop\\s*.*", REG_EXTENDED | REG_ICASE)) {
6,480✔
277
    pre = "Drop OK";
12✔
278
  }
279

280
  TAOS_FIELD *pFields = taos_fetch_fields(pSql);
9,108✔
281
  if (pFields != NULL) {  // select and show kinds of commands
9,108✔
282
    int32_t error_no = 0;
4,856✔
283

284
    int64_t numOfRows = shellDumpResult(pSql, fname, &error_no, printMode, command);
4,856✔
285
    if (numOfRows < 0) return;
4,856!
286

287
    et = taosGetTimestampUs();
4,856✔
288
    if (error_no == 0) {
4,856✔
289
      printf("Query OK, %" PRId64 " row(s) in set (%.6fs)\r\n", numOfRows, (et - st) / 1E6);
4,853✔
290
    } else {
291
      terrno = error_no;
3✔
292
      printf("Query interrupted (%s), %" PRId64 " row(s) in set (%.6fs)\r\n", taos_errstr(NULL), numOfRows,
3✔
293
             (et - st) / 1E6);
3✔
294
    }
295
    taos_free_result(pSql);
4,856✔
296
  } else {
297
    int64_t num_rows_affacted = taos_affected_rows64(pSql);
4,252✔
298
    taos_free_result(pSql);
4,252✔
299
    et = taosGetTimestampUs();
4,252✔
300
    printf("%s, %" PRId64 " row(s) affected (%.6fs)\r\n", pre, num_rows_affacted, (et - st) / 1E6);
4,252✔
301

302
    // call auto tab
303
    callbackAutoTab(command, NULL, false);
4,252✔
304
  }
305

306
  printf("\r\n");
9,108✔
307
}
308

309
char *shellFormatTimestamp(char *buf, int32_t bufSize, int64_t val, int32_t precision) {
354,226✔
310
  if (shell.args.is_raw_time) {
354,226!
311
    sprintf(buf, "%" PRId64, val);
×
312
    return buf;
×
313
  }
314

315
  time_t  tt;
316
  int32_t ms = 0;
354,226✔
317
  if (precision == TSDB_TIME_PRECISION_NANO) {
354,226!
318
    tt = (time_t)(val / 1000000000);
×
319
    ms = val % 1000000000;
×
320
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
354,226!
321
    tt = (time_t)(val / 1000000);
×
322
    ms = val % 1000000;
×
323
  } else {
324
    tt = (time_t)(val / 1000);
354,226✔
325
    ms = val % 1000;
354,226✔
326
  }
327

328
  if (tt <= 0 && ms < 0) {
354,226✔
329
    tt--;
100✔
330
    if (precision == TSDB_TIME_PRECISION_NANO) {
100!
331
      ms += 1000000000;
×
332
    } else if (precision == TSDB_TIME_PRECISION_MICRO) {
100!
333
      ms += 1000000;
×
334
    } else {
335
      ms += 1000;
100✔
336
    }
337
  }
338

339
  struct tm ptm = {0};
354,226✔
340
  if (taosLocalTime(&tt, &ptm, buf, bufSize) == NULL) {
354,226!
341
    return buf;
×
342
  }
343
  size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
354,226✔
344

345
  if (precision == TSDB_TIME_PRECISION_NANO) {
354,226!
346
    sprintf(buf + pos, ".%09d", ms);
×
347
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
354,226!
348
    sprintf(buf + pos, ".%06d", ms);
×
349
  } else {
350
    sprintf(buf + pos, ".%03d", ms);
354,226✔
351
  }
352

353
  return buf;
354,226✔
354
}
355

356
char *shellDumpHexValue(char *buf, const char *val, int32_t length) {
×
357
  for (int32_t i = 0; i < length; i++) {
×
358
    sprintf(buf + (i * 2), "%02X", val[i]);
×
359
  }
360
  buf[length * 2] = 0;
×
361

362
  return buf;
×
363
}
364

365
void shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field, int32_t length, int32_t precision) {
1,486,898✔
366
  if (val == NULL) {
1,486,898✔
367
    taosFprintfFile(pFile, "NULL");
1,405✔
368
    return;
1,405✔
369
  }
370

371
  char    quotationStr[2] = {'"', 0};
1,485,493✔
372
  int32_t width;
373

374
  int n = 0;
1,485,493✔
375
#define LENGTH 64
376
  char buf[LENGTH] = {0};
1,485,493✔
377
  switch (field->type) {
1,485,493!
378
    case TSDB_DATA_TYPE_BOOL:
×
379
      taosFprintfFile(pFile, "%d", ((((int32_t)(*((char *)val))) == 1) ? 1 : 0));
×
380
      break;
×
381
    case TSDB_DATA_TYPE_TINYINT:
×
382
      taosFprintfFile(pFile, "%d", *((int8_t *)val));
×
383
      break;
×
384
    case TSDB_DATA_TYPE_UTINYINT:
×
385
      taosFprintfFile(pFile, "%u", *((uint8_t *)val));
×
386
      break;
×
387
    case TSDB_DATA_TYPE_SMALLINT:
×
388
      taosFprintfFile(pFile, "%d", *((int16_t *)val));
×
389
      break;
×
390
    case TSDB_DATA_TYPE_USMALLINT:
×
391
      taosFprintfFile(pFile, "%u", *((uint16_t *)val));
×
392
      break;
×
393
    case TSDB_DATA_TYPE_INT:
291,835✔
394
      taosFprintfFile(pFile, "%d", *((int32_t *)val));
291,835✔
395
      break;
291,835✔
396
    case TSDB_DATA_TYPE_UINT:
×
397
      taosFprintfFile(pFile, "%u", *((uint32_t *)val));
×
398
      break;
×
399
    case TSDB_DATA_TYPE_BIGINT:
220,858✔
400
      taosFprintfFile(pFile, "%" PRId64, *((int64_t *)val));
220,858✔
401
      break;
220,858✔
402
    case TSDB_DATA_TYPE_UBIGINT:
×
403
      taosFprintfFile(pFile, "%" PRIu64, *((uint64_t *)val));
×
404
      break;
×
405
    case TSDB_DATA_TYPE_FLOAT:
×
406
      width = SHELL_FLOAT_WIDTH;
×
407
      if (tsEnableScience) {
×
408
        taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
×
409
      } else {
410
        n = tsnprintf(buf, LENGTH, "%*.7f", width, GET_FLOAT_VAL(val));
×
411
        if (n > SHELL_FLOAT_WIDTH) {
×
412
          taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
×
413
        } else {
414
          taosFprintfFile(pFile, "%s", buf);
×
415
        }
416
      }
417
      break;
×
418
    case TSDB_DATA_TYPE_DOUBLE:
224,517✔
419
      width = SHELL_DOUBLE_WIDTH;
224,517✔
420
      if (tsEnableScience) {
224,517!
421
        snprintf(buf, LENGTH, "%*.15e", width, GET_DOUBLE_VAL(val));
×
422
        taosFprintfFile(pFile, "%s", buf);
×
423
      } else {
424
        n = tsnprintf(buf, LENGTH, "%*.15f", width, GET_DOUBLE_VAL(val));
224,517✔
425
        if (n > SHELL_DOUBLE_WIDTH) {
224,517✔
426
          taosFprintfFile(pFile, "%*.15e", width, GET_DOUBLE_VAL(val));
1,286✔
427
        } else {
428
          taosFprintfFile(pFile, "%s", buf);
223,231✔
429
        }
430
      }
431
      break;
224,517✔
432
    case TSDB_DATA_TYPE_BINARY:
473,209✔
433
    case TSDB_DATA_TYPE_NCHAR:
434
    case TSDB_DATA_TYPE_JSON: {
435
      int32_t bufIndex = 0;
473,209✔
436
      char   *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
473,209✔
437
      if (tmp == NULL) break;
473,209!
438
      for (int32_t i = 0; i < length; i++) {
4,517,323✔
439
        tmp[bufIndex] = val[i];
4,044,114✔
440
        bufIndex++;
4,044,114✔
441
        if (val[i] == '\"') {
4,044,114!
442
          tmp[bufIndex] = val[i];
×
443
          bufIndex++;
×
444
        }
445
      }
446
      tmp[bufIndex] = 0;
473,209✔
447

448
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
473,209✔
449
      taosMemoryFree(tmp);
473,209✔
450
    } break;
473,209✔
451
    case TSDB_DATA_TYPE_VARBINARY: {
×
452
      void    *tmp = NULL;
×
453
      uint32_t size = 0;
×
454
      if (taosAscii2Hex(val, length, &tmp, &size) < 0) {
×
455
        break;
×
456
      }
457
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
×
458
      taosMemoryFree(tmp);
×
459
      break;
×
460
    }
461
    case TSDB_DATA_TYPE_GEOMETRY: {
×
462
      char *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
×
463
      if (tmp == NULL) break;
×
464
      shellDumpHexValue(tmp, val, length);
×
465
      taosFprintfFile(pFile, "%s", buf);
×
466
      taosMemoryFree(tmp);
×
467
      break;
×
468
    }
469
    case TSDB_DATA_TYPE_TIMESTAMP:
275,074✔
470
      shellFormatTimestamp(buf, sizeof(buf), *(int64_t *)val, precision);
275,074✔
471
      taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
275,074✔
472
      break;
275,074✔
473
    default:
×
474
      break;
×
475
  }
476
}
477

478
int64_t shellDumpResultToFile(const char *fname, TAOS_RES *tres) {
31✔
479
  char fullname[PATH_MAX] = {0};
31✔
480
  if (taosExpandDir(fname, fullname, PATH_MAX) != 0) {
31!
481
    tstrncpy(fullname, fname, PATH_MAX);
×
482
  }
483

484
  TAOS_ROW row = taos_fetch_row(tres);
31✔
485
  if (row == NULL) {
31!
486
    return 0;
×
487
  }
488

489
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);
31✔
490
  if (pFile == NULL) {
31!
491
    fprintf(stderr, "failed to open file: %s\r\n", fullname);
×
492
    return -1;
×
493
  }
494

495
  TAOS_FIELD *fields = taos_fetch_fields(tres);
31✔
496
  int32_t     num_fields = taos_num_fields(tres);
31✔
497
  int32_t     precision = taos_result_precision(tres);
31✔
498

499
  for (int32_t col = 0; col < num_fields; col++) {
159✔
500
    if (col > 0) {
128✔
501
      taosFprintfFile(pFile, ",");
97✔
502
    }
503
    taosFprintfFile(pFile, "%s", fields[col].name);
128✔
504
  }
505
  taosFprintfFile(pFile, "\r\n");
31✔
506

507
  int64_t numOfRows = 0;
31✔
508
  do {
509
    int32_t *length = taos_fetch_lengths(tres);
165,078✔
510
    for (int32_t i = 0; i < num_fields; i++) {
1,651,976✔
511
      if (i > 0) {
1,486,898✔
512
        taosFprintfFile(pFile, ",");
1,321,820✔
513
      }
514
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
1,486,898✔
515
    }
516
    taosFprintfFile(pFile, "\r\n");
165,078✔
517

518
    numOfRows++;
165,078✔
519
    row = taos_fetch_row(tres);
165,078✔
520
  } while (row != NULL);
165,078✔
521

522
  taosCloseFile(&pFile);
31✔
523

524
  return numOfRows;
31✔
525
}
526

527
void shellPrintNChar(const char *str, int32_t length, int32_t width) {
20,743✔
528
  TdWchar tail[3];
529
  int32_t pos = 0, cols = 0, totalCols = 0, tailLen = 0;
20,743✔
530

531
  while (pos < length) {
487,823✔
532
    TdWchar wc;
533
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
475,070✔
534
    if (bytes <= 0) {
475,070✔
535
      break;
7,990✔
536
    }
537

538
    if (pos + bytes > length) {
475,062!
539
      break;
×
540
    }
541
    int w = 0;
475,062✔
542
    if (*(str + pos) == '\t' || *(str + pos) == '\n' || *(str + pos) == '\r') {
475,062!
543
      w = bytes;
×
544
    } else {
545
      w = taosWcharWidth(wc);
475,062✔
546
    }
547
    pos += bytes;
475,062✔
548

549
    if (w <= 0) {
475,062!
550
      continue;
84,699✔
551
    }
552

553
    if (width <= 0) {
475,062✔
554
      printf("%lc", wc);
84,699✔
555
      continue;
84,699✔
556
    }
557

558
    totalCols += w;
390,363✔
559
    if (totalCols > width) {
390,363✔
560
      break;
7,982✔
561
    }
562
    if (totalCols <= (width - 3)) {
382,381✔
563
      printf("%lc", wc);
358,249✔
564
      cols += w;
358,249✔
565
    } else {
566
      tail[tailLen] = wc;
24,132✔
567
      tailLen++;
24,132✔
568
    }
569
  }
570

571
  if (totalCols > width) {
20,743✔
572
    // width could be 1 or 2, so printf("...") cannot be used
573
    for (int32_t i = 0; i < 3; i++) {
31,928✔
574
      if (cols >= width) {
23,946!
575
        break;
×
576
      }
577
      putchar('.');
23,946✔
578
      ++cols;
23,946✔
579
    }
580
  } else {
581
    for (int32_t i = 0; i < tailLen; i++) {
12,947✔
582
      printf("%lc", tail[i]);
186✔
583
    }
584
    cols = totalCols;
12,761✔
585
  }
586

587
  for (; cols < width; cols++) {
275,406✔
588
    putchar(' ');
254,663✔
589
  }
590
}
20,743✔
591

592
void shellPrintString(const char *str, int32_t width) {
18,295✔
593
  int32_t len = strlen(str);
18,295✔
594

595
  if (width == 0) {
18,295!
596
    printf("%s", str);
×
597
  } else if (len > width) {
18,295!
598
    if (width <= 3) {
×
599
      printf("%.*s.", width - 1, str);
×
600
    } else {
601
      printf("%.*s...", width - 3, str);
×
602
    }
603
  } else {
604
    printf("%s%*.s", str, width - len, "");
18,295✔
605
  }
606
}
18,295✔
607

608
void shellPrintGeometry(const unsigned char *val, int32_t length, int32_t width) {
×
609
  if (length == 0) {  // empty value
×
610
    shellPrintString("", width);
×
611
    return;
×
612
  }
613

614
  int32_t code = TSDB_CODE_FAILED;
×
615

616
  code = initCtxAsText();
×
617
  if (code != TSDB_CODE_SUCCESS) {
×
618
    shellPrintString(getGeosErrMsg(code), width);
×
619
    return;
×
620
  }
621

622
  char *outputWKT = NULL;
×
623
  code = doAsText(val, length, &outputWKT);
×
624
  if (code != TSDB_CODE_SUCCESS) {
×
625
    shellPrintString(getGeosErrMsg(code), width);  // should NOT happen
×
626
    return;
×
627
  }
628

629
  shellPrintString(outputWKT, width);
×
630

631
  geosFreeBuffer(outputWKT);
×
632
}
633

634
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision) {
212,560✔
635
  if (val == NULL) {
212,560✔
636
    shellPrintString(TSDB_DATA_NULL_STR, width);
15,771✔
637
    return;
15,771✔
638
  }
639

640
  int n = 0;
196,789✔
641
#define LENGTH 64
642
  char buf[LENGTH] = {0};
196,789✔
643
  switch (field->type) {
196,789!
644
    case TSDB_DATA_TYPE_BOOL:
2,524✔
645
      shellPrintString(((((int32_t)(*((char *)val))) == TSDB_FALSE) ? "false" : "true"), width);
2,524✔
646
      break;
2,524✔
647
    case TSDB_DATA_TYPE_TINYINT:
3,207✔
648
      printf("%*d", width, *((int8_t *)val));
3,207✔
649
      break;
3,207✔
UNCOV
650
    case TSDB_DATA_TYPE_UTINYINT:
×
UNCOV
651
      printf("%*u", width, *((uint8_t *)val));
×
UNCOV
652
      break;
×
653
    case TSDB_DATA_TYPE_SMALLINT:
6,211✔
654
      printf("%*d", width, *((int16_t *)val));
6,211✔
655
      break;
6,211✔
656
    case TSDB_DATA_TYPE_USMALLINT:
×
657
      printf("%*u", width, *((uint16_t *)val));
×
658
      break;
×
659
    case TSDB_DATA_TYPE_INT:
3,882✔
660
      printf("%*d", width, *((int32_t *)val));
3,882✔
661
      break;
3,882✔
662
    case TSDB_DATA_TYPE_UINT:
×
663
      printf("%*u", width, *((uint32_t *)val));
×
664
      break;
×
665
    case TSDB_DATA_TYPE_BIGINT:
12,862✔
666
      printf("%*" PRId64, width, *((int64_t *)val));
12,862✔
667
      break;
12,862✔
668
    case TSDB_DATA_TYPE_UBIGINT:
×
669
      printf("%*" PRIu64, width, *((uint64_t *)val));
×
670
      break;
×
671
    case TSDB_DATA_TYPE_FLOAT:
1,680✔
672
      if (tsEnableScience) {
1,680!
673
        printf("%*.7e", width, GET_FLOAT_VAL(val));
×
674
      } else {
675
        n = tsnprintf(buf, LENGTH, "%*.7f", width, GET_FLOAT_VAL(val));
1,680✔
676
        if (n > SHELL_FLOAT_WIDTH) {
1,680✔
677
          printf("%*.7e", width, GET_FLOAT_VAL(val));
229✔
678
        } else {
679
          printf("%s", buf);
1,451✔
680
        }
681
      }
682
      break;
1,680✔
683
    case TSDB_DATA_TYPE_DOUBLE:
66,528✔
684
      if (tsEnableScience) {
66,528!
685
        snprintf(buf, LENGTH, "%*.15e", width, GET_DOUBLE_VAL(val));
×
686
        printf("%s", buf);
×
687
      } else {
688
        n = tsnprintf(buf, LENGTH, "%*.15f", width, GET_DOUBLE_VAL(val));
66,528✔
689
        if (n > SHELL_DOUBLE_WIDTH) {
66,528✔
690
          printf("%*.15e", width, GET_DOUBLE_VAL(val));
7,773✔
691
        } else {
692
          printf("%*s", width, buf);
58,755✔
693
        }
694
      }
695
      break;
66,528✔
696
    case TSDB_DATA_TYPE_VARBINARY: {
×
697
      void    *data = NULL;
×
698
      uint32_t size = 0;
×
699
      if (taosAscii2Hex(val, length, &data, &size) < 0) {
×
700
        break;
×
701
      }
702
      shellPrintNChar(data, size, width);
×
703
      taosMemoryFree(data);
×
704
      break;
×
705
    }
706
    case TSDB_DATA_TYPE_BINARY:
20,743✔
707
    case TSDB_DATA_TYPE_NCHAR:
708
    case TSDB_DATA_TYPE_JSON:
709
      shellPrintNChar(val, length, width);
20,743✔
710
      break;
20,743✔
711
    case TSDB_DATA_TYPE_GEOMETRY:
×
712
      shellPrintGeometry(val, length, width);
×
713
      break;
×
714
    case TSDB_DATA_TYPE_TIMESTAMP:
79,152✔
715
      shellFormatTimestamp(buf, sizeof(buf), *(int64_t *)val, precision);
79,152✔
716
      printf("%s", buf);
79,152✔
717
      break;
79,152✔
718
    default:
×
719
      break;
×
720
  }
721
}
722

723
// show whole result for this query return true, like limit or describe
724
bool shellIsShowWhole(const char *sql) {
×
725
  // limit
726
  if (taosStrCaseStr(sql, " limit ") != NULL) {
×
727
    return true;
×
728
  }
729
  // describe
730
  if (taosStrCaseStr(sql, "describe ") != NULL) {
×
731
    return true;
×
732
  }
733
  // show
734
  if (taosStrCaseStr(sql, "show ") != NULL) {
×
735
    return true;
×
736
  }
737
  // explain
738
  if (taosStrCaseStr(sql, "explain ") != NULL) {
×
739
    return true;
×
740
  }
741

742
  return false;
×
743
}
744

745
bool shellIsShowQuery(const char *sql) {
×
746
  // todo refactor
747
  if (taosStrCaseStr(sql, "show ") != NULL) {
×
748
    return true;
×
749
  }
750

751
  return false;
×
752
}
753

754
void init_dump_info(tsDumpInfo *dump_info, TAOS_RES *tres, const char *sql, bool vertical) {
4,825✔
755
  dump_info->sql = sql;
4,825✔
756
  dump_info->vertical = vertical;
4,825✔
757
  tsem_init(&dump_info->sem, 0, 0);
4,825✔
758
  dump_info->numOfAllRows = 0;
4,825✔
759

760
  dump_info->numFields = taos_num_fields(tres);
4,825✔
761
  dump_info->fields = taos_fetch_fields(tres);
4,825✔
762
  dump_info->precision = taos_result_precision(tres);
4,825✔
763

764
  dump_info->resShowMaxNum = UINT64_MAX;
4,825✔
765

766
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsShowWhole(dump_info->sql)) {
4,825!
767
    dump_info->resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
×
768
  }
769

770
  if (vertical) {
4,825✔
771
    dump_info->maxColNameLen = 0;
59✔
772
    for (int32_t col = 0; col < dump_info->numFields; col++) {
120✔
773
      int32_t len = (int32_t)strlen(dump_info->fields[col].name);
61✔
774
      if (len > dump_info->maxColNameLen) {
61!
775
        dump_info->maxColNameLen = len;
61✔
776
      }
777
    }
778
  } else {
779
    for (int32_t col = 0; col < dump_info->numFields; col++) {
13,300✔
780
      dump_info->width[col] = shellCalcColWidth(dump_info->fields + col, dump_info->precision);
8,534✔
781
    }
782
  }
783
}
4,825✔
784

785
void shellVerticalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
59✔
786
  TAOS_ROW row = taos_fetch_row(tres);
59✔
787
  if (row == NULL) {
59!
788
    printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
789
    return;
×
790
  }
791

792
  int64_t numOfPintRows = dump_info->numOfAllRows;
59✔
793
  int     numOfPrintRowsThisOne = 0;
59✔
794

795
  while (row != NULL) {
1,473!
796
    printf("*************************** %" PRId64 ".row ***************************\r\n", numOfPintRows + 1);
1,473✔
797

798
    int32_t *length = taos_fetch_lengths(tres);
1,473✔
799

800
    for (int32_t i = 0; i < dump_info->numFields; i++) {
2,950✔
801
      TAOS_FIELD *field = dump_info->fields + i;
1,477✔
802

803
      int32_t padding = (int32_t)(dump_info->maxColNameLen - strlen(field->name));
1,477✔
804
      printf("%*.s%s: ", padding, " ", field->name);
1,477✔
805

806
      shellPrintField((const char *)row[i], field, 0, length[i], dump_info->precision);
1,477✔
807
      putchar('\r');
1,477✔
808
      putchar('\n');
1,477✔
809
    }
810

811
    numOfPintRows++;
1,473✔
812
    numOfPrintRowsThisOne++;
1,473✔
813

814
    if (numOfPintRows == dump_info->resShowMaxNum) {
1,473!
815
      printf("\r\n");
×
816
      printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
×
817
      printf("         You can use the `LIMIT` clause to get fewer result to show.\r\n");
×
818
      printf("           Or use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
819
      printf("\r\n");
×
820
      printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
×
821
      printf("\r\n");
×
822
      return;
×
823
    }
824

825
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
1,473✔
826
      return;
59✔
827
    }
828

829
    row = taos_fetch_row(tres);
1,414✔
830
  }
831
  return;
×
832
}
833

834
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
8,534✔
835
  int32_t width = (int32_t)strlen(field->name);
8,534✔
836

837
  switch (field->type) {
8,534!
838
    case TSDB_DATA_TYPE_NULL:
×
839
      return TMAX(4, width);  // null
×
840
    case TSDB_DATA_TYPE_BOOL:
70✔
841
      return TMAX(5, width);  // 'false'
70✔
842

843
    case TSDB_DATA_TYPE_TINYINT:
51✔
844
    case TSDB_DATA_TYPE_UTINYINT:
845
      return TMAX(4, width);  // '-127'
51✔
846

847
    case TSDB_DATA_TYPE_SMALLINT:
1,107✔
848
    case TSDB_DATA_TYPE_USMALLINT:
849
      return TMAX(6, width);  // '-32767'
1,107✔
850

851
    case TSDB_DATA_TYPE_INT:
337✔
852
    case TSDB_DATA_TYPE_UINT:
853
      return TMAX(11, width);  // '-2147483648'
337✔
854

855
    case TSDB_DATA_TYPE_BIGINT:
1,211✔
856
    case TSDB_DATA_TYPE_UBIGINT:
857
      return TMAX(21, width);  // '-9223372036854775807'
1,211✔
858

859
    case TSDB_DATA_TYPE_FLOAT:
48✔
860
      return TMAX(SHELL_FLOAT_WIDTH, width);
48✔
861

862
    case TSDB_DATA_TYPE_DOUBLE:
2,372✔
863
      return TMAX(SHELL_DOUBLE_WIDTH, width);
2,372✔
864

865
    case TSDB_DATA_TYPE_BINARY:
1,573✔
866
    case TSDB_DATA_TYPE_GEOMETRY:
867
      if (field->bytes > shell.args.displayWidth) {
1,573✔
868
        return TMAX(shell.args.displayWidth, width);
1,383✔
869
      } else {
870
        return TMAX(field->bytes + 2, width);
190✔
871
      }
872
    case TSDB_DATA_TYPE_VARBINARY: {
×
873
      int32_t bytes = field->bytes * 2 + 2;
×
874
      if (bytes > shell.args.displayWidth) {
×
875
        return TMAX(shell.args.displayWidth, width);
×
876
      } else {
877
        return TMAX(bytes + 2, width);
×
878
      }
879
    }
880
    case TSDB_DATA_TYPE_NCHAR:
126✔
881
    case TSDB_DATA_TYPE_JSON: {
882
      uint16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
126✔
883
      if (bytes > shell.args.displayWidth) {
126!
884
        return TMAX(shell.args.displayWidth, width);
126✔
885
      } else {
886
        return TMAX(bytes + 2, width);
×
887
      }
888
    }
889

890
    case TSDB_DATA_TYPE_TIMESTAMP:
1,639✔
891
      if (shell.args.is_raw_time) {
1,639!
892
        return TMAX(14, width);
×
893
      }
894
      if (precision == TSDB_TIME_PRECISION_NANO) {
1,639!
895
        return TMAX(29, width);
×
896
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
1,639!
897
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
×
898
      } else {
899
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
1,639✔
900
      }
901

902
    default:
×
903
      ASSERT(false);
×
904
  }
905

906
  return 0;
×
907
}
908

909
void shellPrintHeader(TAOS_FIELD *fields, int32_t *width, int32_t num_fields) {
4,514✔
910
  int32_t rowWidth = 0;
4,514✔
911
  for (int32_t col = 0; col < num_fields; col++) {
12,542✔
912
    TAOS_FIELD *field = fields + col;
8,028✔
913
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
8,028✔
914
    int32_t     left = padding / 2;
8,028✔
915
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
8,028✔
916
    rowWidth += width[col] + 3;
8,028✔
917
  }
918

919
  putchar('\r');
4,514✔
920
  putchar('\n');
4,514✔
921
  for (int32_t i = 0; i < rowWidth; i++) {
249,309✔
922
    putchar('=');
244,795✔
923
  }
924
  putchar('\r');
4,514✔
925
  putchar('\n');
4,514✔
926
}
4,514✔
927

928
void shellHorizontalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
4,721✔
929
  TAOS_ROW row = taos_fetch_row(tres);
4,721✔
930
  if (row == NULL) {
4,721!
931
    printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
932
    return;
×
933
  }
934

935
  int64_t numOfPintRows = dump_info->numOfAllRows;
4,721✔
936
  int     numOfPrintRowsThisOne = 0;
4,721✔
937
  if (numOfPintRows == 0) {
4,721✔
938
    shellPrintHeader(dump_info->fields, dump_info->width, dump_info->numFields);
4,514✔
939
  }
940

941
  while (row != NULL) {
134,063!
942
    int32_t *length = taos_fetch_lengths(tres);
134,063✔
943
    for (int32_t i = 0; i < dump_info->numFields; i++) {
345,146✔
944
      putchar(' ');
211,083✔
945
      shellPrintField((const char *)row[i], dump_info->fields + i, dump_info->width[i], length[i],
211,083✔
946
                      dump_info->precision);
947
      putchar(' ');
211,083✔
948
      putchar('|');
211,083✔
949
    }
950
    putchar('\r');
134,063✔
951
    putchar('\n');
134,063✔
952

953
    numOfPintRows++;
134,063✔
954
    numOfPrintRowsThisOne++;
134,063✔
955

956
    if (numOfPintRows == dump_info->resShowMaxNum) {
134,063!
957
      printf("\r\n");
×
958
      printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
×
959
      if (shellIsShowQuery(dump_info->sql)) {
×
960
        printf("         You can use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
961
      } else {
962
        printf("         You can use the `LIMIT` clause to get fewer result to show.\r\n");
×
963
        printf("           Or use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
964
      }
965
      printf("\r\n");
×
966
      printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
×
967
      printf("\r\n");
×
968
      return;
×
969
    }
970

971
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
134,063✔
972
      return;
4,721✔
973
    }
974

975
    row = taos_fetch_row(tres);
129,342✔
976
  }
977
  return;
×
978
}
979

980
void shellDumpResultCallback(void *param, TAOS_RES *tres, int num_of_rows) {
9,605✔
981
  tsDumpInfo *dump_info = (tsDumpInfo *)param;
9,605✔
982
  if (num_of_rows > 0) {
9,605✔
983
    dump_info->numOfRows = num_of_rows;
4,780✔
984
    if (dump_info->numOfAllRows < dump_info->resShowMaxNum) {
4,780!
985
      if (dump_info->vertical) {
4,780✔
986
        shellVerticalPrintResult(tres, dump_info);
59✔
987
      } else {
988
        shellHorizontalPrintResult(tres, dump_info);
4,721✔
989
      }
990
    }
991
    dump_info->numOfAllRows += num_of_rows;
4,780✔
992
    if (!shellCmdkilled) {
4,780!
993
      taos_fetch_rows_a(tres, shellDumpResultCallback, param);
4,780✔
994
    } else {
995
      tsem_post(&dump_info->sem);
×
996
    }
997
  } else {
998
    if (num_of_rows < 0) {
4,825!
999
      printf("\033[31masync retrieve failed, code: %d\033[0m\n", num_of_rows);
×
1000
    }
1001
    tsem_post(&dump_info->sem);
4,825✔
1002
  }
1003
}
9,605✔
1004

1005
int64_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
4,856✔
1006
  int64_t num_of_rows = 0;
4,856✔
1007
  if (fname != NULL) {
4,856✔
1008
    num_of_rows = shellDumpResultToFile(fname, tres);
31✔
1009
  } else {
1010
    tsDumpInfo dump_info;
1011
    if (!shellCmdkilled) {
4,825!
1012
      init_dump_info(&dump_info, tres, sql, vertical);
4,825✔
1013
      taos_fetch_rows_a(tres, shellDumpResultCallback, &dump_info);
4,825✔
1014
      tsem_wait(&dump_info.sem);
4,825✔
1015
      num_of_rows = dump_info.numOfAllRows;
4,825✔
1016
    }
1017
  }
1018

1019
  *error_no = shellCmdkilled ? TSDB_CODE_TSC_QUERY_KILLED : taos_errno(tres);
4,856!
1020
  return num_of_rows;
4,856✔
1021
}
1022

1023
void shellReadHistory() {
146✔
1024
  SShellHistory *pHistory = &shell.history;
146✔
1025
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
146✔
1026
  if (pFile == NULL) return;
146!
1027

1028
  char   *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
146✔
1029
  int32_t read_size = 0;
146✔
1030
  while ((read_size = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) > 0) {
1,116,107✔
1031
    line[read_size - 1] = '\0';
1,115,961✔
1032
    taosMemoryFree(pHistory->hist[pHistory->hend]);
1,115,961✔
1033
    pHistory->hist[pHistory->hend] = taosStrdup(line);
1,115,961✔
1034

1035
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
1,115,961✔
1036

1037
    if (pHistory->hend == pHistory->hstart) {
1,115,961✔
1038
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
970,107✔
1039
    }
1040
  }
1041

1042
  taosMemoryFreeClear(line);
146!
1043
  taosCloseFile(&pFile);
146✔
1044
  int64_t file_size;
1045
  if (taosStatFile(pHistory->file, &file_size, NULL, NULL) == 0 && file_size > SHELL_MAX_COMMAND_SIZE) {
146!
1046
    TdFilePtr pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_TRUNC);
×
1047
    if (pFile == NULL) return;
×
1048
    int32_t endIndex = pHistory->hstart;
×
1049
    if (endIndex != 0) {
×
1050
      endIndex = pHistory->hend;
×
1051
    }
1052
    for (int32_t i = (pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE; i != endIndex;) {
×
1053
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
×
1054
      i = (i + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE;
×
1055
    }
1056
    taosFprintfFile(pFile, "%s\n", pHistory->hist[endIndex]);
×
1057

1058
    /* coverity[+retval] */
1059
    taosFsyncFile(pFile);
×
1060
    taosCloseFile(&pFile);
×
1061
  }
1062
  pHistory->hstart = pHistory->hend;
146✔
1063
}
1064

1065
void shellWriteHistory() {
146✔
1066
  SShellHistory *pHistory = &shell.history;
146✔
1067
  if (pHistory->hend == pHistory->hstart) return;
146!
1068
  TdFilePtr pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
146✔
1069
  if (pFile == NULL) return;
146!
1070

1071
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
293✔
1072
    if (pHistory->hist[i] != NULL) {
147!
1073
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
147✔
1074
      taosMemoryFree(pHistory->hist[i]);
147✔
1075
      pHistory->hist[i] = NULL;
147✔
1076
    }
1077
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
147✔
1078
  }
1079
  taosCloseFile(&pFile);
146✔
1080
}
1081

1082
void shellCleanupHistory() {
146✔
1083
  SShellHistory *pHistory = &shell.history;
146✔
1084
  for (int32_t i = 0; i < SHELL_MAX_HISTORY_SIZE; ++i) {
146,146✔
1085
    if (pHistory->hist[i] != NULL) {
146,000✔
1086
      taosMemoryFree(pHistory->hist[i]);
145,853✔
1087
      pHistory->hist[i] = NULL;
145,853✔
1088
    }
1089
  }
1090
}
146✔
1091

1092
void shellPrintError(TAOS_RES *tres, int64_t st) {
165✔
1093
  int64_t et = taosGetTimestampUs();
165✔
1094
  fprintf(stderr, "\r\nDB error: %s (%.6fs)\r\n", taos_errstr(tres), (et - st) / 1E6);
165✔
1095
  taos_free_result(tres);
165✔
1096
}
165✔
1097

1098
bool shellIsCommentLine(char *line) {
9,108✔
1099
  if (line == NULL) return true;
9,108!
1100
  return shellRegexMatch(line, "^\\s*#.*", REG_EXTENDED);
9,108✔
1101
}
1102

1103
void shellSourceFile(const char *file) {
18✔
1104
  int32_t read_len = 0;
18✔
1105
  char   *cmd = taosMemoryCalloc(1, TSDB_MAX_ALLOWED_SQL_LEN + 1);
18✔
1106
  size_t  cmd_len = 0;
18✔
1107
  char    fullname[PATH_MAX] = {0};
18✔
1108
  char    sourceFileCommand[PATH_MAX + 8] = {0};
18✔
1109

1110
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
18!
1111
    tstrncpy(fullname, file, PATH_MAX);
×
1112
  }
1113

1114
  sprintf(sourceFileCommand, "source %s;", fullname);
18✔
1115
  shellRecordCommandToHistory(sourceFileCommand);
18✔
1116

1117
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
18✔
1118
  if (pFile == NULL) {
18!
UNCOV
1119
    fprintf(stderr, "failed to open file %s\r\n", fullname);
×
UNCOV
1120
    taosMemoryFree(cmd);
×
UNCOV
1121
    return;
×
1122
  }
1123

1124
  char *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
18✔
1125
  while ((read_len = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) > 0) {
9,211✔
1126
    if (cmd_len + read_len >= TSDB_MAX_ALLOWED_SQL_LEN) {
9,193!
1127
      printf("read command line too long over 1M, ignore this line. cmd_len = %d read_len=%d \n", (int32_t)cmd_len,
×
1128
             read_len);
1129
      cmd_len = 0;
×
1130
      memset(line, 0, TSDB_MAX_ALLOWED_SQL_LEN + 1);
×
1131
      continue;
×
1132
    }
1133
    line[--read_len] = '\0';
9,193✔
1134

1135
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
9,193!
1136
      continue;
85✔
1137
    }
1138

1139
    if (line[read_len - 1] == '\\') {
9,108!
1140
      line[read_len - 1] = ' ';
×
1141
      memcpy(cmd + cmd_len, line, read_len);
×
1142
      cmd_len += read_len;
×
1143
      continue;
×
1144
    }
1145

1146
    if (line[read_len - 1] == '\r') {
9,108!
1147
      line[read_len - 1] = ' ';
×
1148
    }
1149

1150
    memcpy(cmd + cmd_len, line, read_len);
9,108✔
1151
    printf("%s%s\r\n", shell.info.promptHeader, cmd);
9,108✔
1152
    shellRunCommand(cmd, false);
9,108✔
1153
    memset(cmd, 0, TSDB_MAX_ALLOWED_SQL_LEN);
9,108✔
1154
    cmd_len = 0;
9,108✔
1155
  }
1156

1157
  taosMemoryFree(cmd);
18✔
1158
  taosMemoryFreeClear(line);
18!
1159
  taosCloseFile(&pFile);
18✔
1160
}
1161

1162
bool shellGetGrantInfo(char *buf) {
5✔
1163
  bool community = true;
5✔
1164
  char sinfo[256] = {0};
5✔
1165
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
5✔
1166
  strtok(sinfo, "\r\n");
5✔
1167

1168
  char sql[] = "show grants";
5✔
1169

1170
  TAOS_RES *tres = taos_query(shell.conn, sql);
5✔
1171

1172
  int32_t code = taos_errno(tres);
5✔
1173
  if (code != TSDB_CODE_SUCCESS) {
5!
1174
    if (code != TSDB_CODE_OPS_NOT_SUPPORT && code != TSDB_CODE_MND_NO_RIGHTS &&
×
1175
        code != TSDB_CODE_PAR_PERMISSION_DENIED) {
1176
      fprintf(stderr, "Failed to check Server Edition, Reason:0x%04x:%s\r\n\r\n", code, taos_errstr(tres));
×
1177
    }
1178
    taos_free_result(tres);
×
1179
    return community;
×
1180
  }
1181

1182
  int32_t num_fields = taos_field_count(tres);
5✔
1183
  if (num_fields == 0) {
5!
1184
    fprintf(stderr, "\r\nInvalid grant information.\r\n");
×
1185
    exit(0);
×
1186
  } else {
1187
    if (tres == NULL) {
5!
1188
      fprintf(stderr, "\r\nGrant information is null.\r\n");
×
1189
      exit(0);
×
1190
    }
1191

1192
    TAOS_FIELD *fields = taos_fetch_fields(tres);
5✔
1193
    TAOS_ROW    row = taos_fetch_row(tres);
5✔
1194
    if (row == NULL) {
5!
1195
      fprintf(stderr, "\r\nFailed to get grant information from server. Abort.\r\n");
×
1196
      exit(0);
×
1197
    }
1198
    char serverVersion[64] = {0};
5✔
1199
    char expiretime[32] = {0};
5✔
1200
    char expired[32] = {0};
5✔
1201

1202
    tstrncpy(serverVersion, row[0], 64);
5✔
1203
    memcpy(expiretime, row[1], fields[1].bytes);
5✔
1204
    memcpy(expired, row[2], fields[2].bytes);
5✔
1205

1206
    if (strcmp(serverVersion, "community") == 0) {
5!
1207
      community = true;
×
1208
    } else if (strcmp(expiretime, "unlimited") == 0) {
5!
1209
      community = false;
×
1210
      sprintf(buf, "Server is %s, %s and will never expire.\r\n", serverVersion, sinfo);
×
1211
    } else {
1212
      community = false;
5✔
1213
      sprintf(buf, "Server is %s, %s and will expire at %s.\r\n", serverVersion, sinfo, expiretime);
5✔
1214
    }
1215

1216
    taos_free_result(tres);
5✔
1217
  }
1218

1219
  fprintf(stdout, "\r\n");
5✔
1220
  return community;
5✔
1221
}
1222

1223
#ifdef WINDOWS
1224
BOOL shellQueryInterruptHandler(DWORD fdwCtrlType) {
1225
  tsem_post(&shell.cancelSem);
1226
  return TRUE;
1227
}
1228
#else
1229
void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }
5✔
1230
#endif
1231

1232
void shellCleanup(void *arg) { taosResetTerminalMode(); }
5✔
1233

1234
void *shellCancelHandler(void *arg) {
5✔
1235
  setThreadName("shellCancelHandler");
5✔
1236
  while (1) {
1237
    if (shell.exit == true) {
15✔
1238
      break;
5✔
1239
    }
1240

1241
    if (tsem_wait(&shell.cancelSem) != 0) {
10!
1242
      taosMsleep(10);
×
1243
      continue;
×
1244
    }
1245

1246
#ifdef WEBSOCKET
1247
    if (shell.args.restful || shell.args.cloud) {
1248
      shell.stop_query = true;
1249
    } else {
1250
#endif
1251
      if (shell.conn) {
10✔
1252
        shellCmdkilled = true;
5✔
1253
        taos_kill_query(shell.conn);
5✔
1254
      }
1255
#ifdef WEBSOCKET
1256
    }
1257
#endif
1258
#ifdef WINDOWS
1259
    printf("\n%s", shell.info.promptHeader);
1260
#endif
1261
  }
1262

1263
  return NULL;
5✔
1264
}
1265

1266
void *shellThreadLoop(void *arg) {
5✔
1267
  setThreadName("shellThreadLoop");
5✔
1268
  taosGetOldTerminalMode();
5✔
1269
  taosThreadCleanupPush(shellCleanup, NULL);
5!
1270

1271
  do {
1272
    char *command = taosMemoryMalloc(SHELL_MAX_COMMAND_SIZE);
5✔
1273
    if (command == NULL) {
5!
1274
      printf("failed to malloc command\r\n");
×
1275
      break;
×
1276
    }
1277

1278
    do {
1279
      memset(command, 0, SHELL_MAX_COMMAND_SIZE);
10✔
1280
      taosSetTerminalMode();
10✔
1281

1282
      if (shellReadCommand(command) != 0) {
10✔
1283
        break;
5✔
1284
      }
1285

1286
      taosResetTerminalMode();
5✔
1287
    } while (shellRunCommand(command, true) == 0);
5!
1288

1289
    taosMemoryFreeClear(command);
5!
1290
    shellWriteHistory();
5✔
1291
    shellExit();
5✔
1292
  } while (0);
1293

1294
  taosThreadCleanupPop(1);
5✔
1295
  return NULL;
5✔
1296
}
1297

1298
int32_t shellExecute() {
157✔
1299
  printf(shell.info.clientVersion, shell.info.cusName, taos_get_client_info(), shell.info.cusName);
157✔
1300
  fflush(stdout);
157✔
1301

1302
  SShellArgs *pArgs = &shell.args;
157✔
1303
#ifdef WEBSOCKET
1304
  if (shell.args.restful || shell.args.cloud) {
1305
    if (shell_conn_ws_server(1)) {
1306
      return -1;
1307
    }
1308
  } else {
1309
#endif
1310
    if (shell.args.auth == NULL) {
157✔
1311
      shell.conn = taos_connect(pArgs->host, pArgs->user, pArgs->password, pArgs->database, pArgs->port);
155✔
1312
    } else {
1313
      shell.conn = taos_connect_auth(pArgs->host, pArgs->user, pArgs->auth, pArgs->database, pArgs->port);
2✔
1314
    }
1315

1316
    if (shell.conn == NULL) {
157✔
1317
      printf("failed to connect to server, reason: %s\n", taos_errstr(NULL));
11✔
1318
      fflush(stdout);
11✔
1319
      return -1;
11✔
1320
    }
1321
#ifdef WEBSOCKET
1322
  }
1323
#endif
1324

1325
  bool runOnce = pArgs->commands != NULL || pArgs->file[0] != 0;
146✔
1326
  shellSetConn(shell.conn, runOnce);
146✔
1327
  shellReadHistory();
146✔
1328

1329
  if (shell.args.is_bi_mode) {
146!
1330
    // need set bi mode
1331
    printf("Set BI mode is true.\n");
×
1332
#ifndef WEBSOCKET
1333
    taos_set_conn_mode(shell.conn, TAOS_CONN_MODE_BI, 1);
×
1334
#endif
1335
  }
1336

1337
  if (runOnce) {
146✔
1338
    if (pArgs->commands != NULL) {
141✔
1339
      printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
124✔
1340
      char *cmd = taosStrdup(pArgs->commands);
124✔
1341
      shellRunCommand(cmd, true);
124✔
1342
      taosMemoryFree(cmd);
124✔
1343
    }
1344

1345
    if (pArgs->file[0] != 0) {
141✔
1346
      shellSourceFile(pArgs->file);
17✔
1347
    }
1348
#ifdef WEBSOCKET
1349
    if (shell.args.restful || shell.args.cloud) {
1350
      ws_close(shell.ws_conn);
1351
    } else {
1352
#endif
1353
      taos_close(shell.conn);
141✔
1354
#ifdef WEBSOCKET
1355
    }
1356
#endif
1357

1358
    shellWriteHistory();
141✔
1359
    shellCleanupHistory();
141✔
1360
    return 0;
141✔
1361
  }
1362

1363
  if (tsem_init(&shell.cancelSem, 0, 0) != 0) {
5!
1364
    printf("failed to create cancel semaphore\r\n");
×
1365
    return -1;
×
1366
  }
1367

1368
  TdThread spid = {0};
5✔
1369
  taosThreadCreate(&spid, NULL, shellCancelHandler, NULL);
5✔
1370

1371
  taosSetSignal(SIGTERM, shellQueryInterruptHandler);
5✔
1372
  taosSetSignal(SIGHUP, shellQueryInterruptHandler);
5✔
1373
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
5✔
1374

1375
#ifdef WEBSOCKET
1376
  if (!shell.args.restful && !shell.args.cloud) {
1377
#endif
1378
    char *buf = taosMemoryMalloc(512);
5✔
1379
    bool  community = shellGetGrantInfo(buf);
5✔
1380
#ifndef WINDOWS
1381
    printfIntroduction(community);
5✔
1382
#else
1383
#ifndef WEBSOCKET
1384
  if (community) {
1385
    showAD(false);
1386
  }
1387
#endif
1388
#endif
1389
    // printf version
1390
    if (!community) {
5!
1391
      printf("%s\n", buf);
5✔
1392
    }
1393
    taosMemoryFree(buf);
5✔
1394

1395
#ifdef WEBSOCKET
1396
  }
1397
#endif
1398
  while (1) {
1399
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
5✔
1400
    taosThreadJoin(shell.pid, NULL);
5✔
1401
    taosThreadClear(&shell.pid);
5✔
1402
    if (shell.exit) {
5!
1403
      tsem_post(&shell.cancelSem);
5✔
1404
      break;
5✔
1405
    }
1406
  }
1407
#ifndef WEBSOCKET
1408
  // commnuity
1409
  if (community) {
5!
1410
    showAD(true);
×
1411
  }
1412
#endif
1413

1414
  taosThreadJoin(spid, NULL);
5✔
1415

1416
  shellCleanupHistory();
5✔
1417
  taos_kill_query(shell.conn);
5✔
1418
  taos_close(shell.conn);
5✔
1419

1420
  return 0;
5✔
1421
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc