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

taosdata / TDengine / #3615

18 Feb 2025 07:41AM UTC coverage: 62.953% (+1.6%) from 61.4%
#3615

push

travis-ci

web-flow
Merge pull request #29812 from taosdata/doc/analysis

doc: update tdgpt doc.

146885 of 299602 branches covered (49.03%)

Branch coverage included in aggregate %.

230802 of 300346 relevant lines covered (76.85%)

17263824.17 hits per line

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

65.73
/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 int32_t 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) {
9,477✔
70
  for (char c = *cmd++; c != 0; c = *cmd++) {
9,479✔
71
    if (c != ' ' && c != '\t' && c != ';') {
8,686!
72
      return false;
8,684✔
73
    }
74
  }
75
  return true;
793✔
76
}
77

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

81
  if (shellIsEmptyCommand(command)) {
5,135✔
82
    return 0;
793✔
83
  }
84

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

89
  if (shellRegexMatch(command, "^[\t ]*clear[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
4,342!
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;]*$",
4,342!
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)) {
4,342✔
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) {
4,341!
129
    shellRunSingleCommandWebsocketImp(command);
×
130
  } else {
131
#endif
132
    shellRunSingleCommandImp(command);
4,341✔
133
#ifdef WEBSOCKET
134
  }
135
#endif
136
  return 0;
4,341✔
137
}
138

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

147
  SShellHistory *pHistory = &shell.history;
897✔
148
  if (pHistory->hstart == pHistory->hend ||
897✔
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) {
897!
152
      taosMemoryFreeClear(pHistory->hist[pHistory->hend]);
897!
153
    }
154
    pHistory->hist[pHistory->hend] = taosStrdup(command);
897!
155

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

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

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

176
  if (recordHistory) shellRecordCommandToHistory(command);
4,342✔
177

178
  char quote = 0, *cmd = command;
4,342✔
179
  for (char c = *command++; c != 0; c = *command++) {
316,161✔
180
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
311,819!
181
      command++;
4✔
182
      continue;
4✔
183
    }
184

185
    if (quote == c) {
311,815✔
186
      quote = 0;
3,746✔
187
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
308,069!
188
      quote = c;
3,746✔
189
    } else if (c == ';' && quote == 0) {
304,323✔
190
      c = *command;
793✔
191
      *command = 0;
793✔
192
      if (shellRunSingleCommand(cmd) < 0) {
793!
193
        return -1;
×
194
      }
195
      *command = c;
793✔
196
      cmd = command;
793✔
197
    }
198
  }
199
  return shellRunSingleCommand(cmd);
4,342✔
200
}
201

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

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

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

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

222
  return NULL;
4,288✔
223
}
224

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

232
  if ((sptr = strstr(command, ">>")) != NULL) {
4,341✔
233
    fname = sptr + 2;
26✔
234
    while (*fname == ' ') fname++;
52✔
235
    *sptr = '\0';
26✔
236

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

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

248
  st = taosGetTimestampUs();
4,341✔
249

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

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

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

263
    taos_free_result(pSql);
1✔
264

265
    return;
1✔
266
  }
267

268
  // pre string
269
  char *pre = "Query OK";
4,328✔
270
  if (shellRegexMatch(command, "^\\s*delete\\s*from\\s*.*", REG_EXTENDED | REG_ICASE)) {
4,328!
271
    pre = "Delete OK";
×
272
  } else if (shellRegexMatch(command, "^\\s*insert\\s*into\\s*.*", REG_EXTENDED | REG_ICASE)) {
4,328!
273
    pre = "Insert OK";
×
274
  } else if (shellRegexMatch(command, "^\\s*create\\s*.*", REG_EXTENDED | REG_ICASE)) {
4,328✔
275
    pre = "Create OK";
56✔
276
  } else if (shellRegexMatch(command, "^\\s*drop\\s*.*", REG_EXTENDED | REG_ICASE)) {
4,272!
277
    pre = "Drop OK";
×
278
  }
279

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

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

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

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

306
  printf("\r\n");
4,328✔
307
}
308

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

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

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

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

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

353
  return buf;
448,641✔
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) {
2,128,155✔
366
  if (val == NULL) {
2,128,155✔
367
    taosFprintfFile(pFile, "NULL");
11,362✔
368
    return;
11,362✔
369
  }
370

371
  char    quotationStr[2] = {'"', 0};
2,116,793✔
372
  int32_t width;
373

374
  int n = 0;
2,116,793✔
375
#define LENGTH 64
376
  char buf[LENGTH] = {0};
2,116,793✔
377
  switch (field->type) {
2,116,793!
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:
399,578✔
394
      taosFprintfFile(pFile, "%d", *((int32_t *)val));
399,578✔
395
      break;
399,578✔
396
    case TSDB_DATA_TYPE_UINT:
×
397
      taosFprintfFile(pFile, "%u", *((uint32_t *)val));
×
398
      break;
×
399
    case TSDB_DATA_TYPE_BIGINT:
295,858✔
400
      taosFprintfFile(pFile, "%" PRId64, *((int64_t *)val));
295,858✔
401
      break;
295,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:
399,874✔
419
      width = SHELL_DOUBLE_WIDTH;
399,874✔
420
      if (tsEnableScience) {
399,874!
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));
399,874✔
425
        if (n > SHELL_DOUBLE_WIDTH) {
399,874✔
426
          taosFprintfFile(pFile, "%*.15e", width, GET_DOUBLE_VAL(val));
70,645✔
427
        } else {
428
          taosFprintfFile(pFile, "%s", buf);
329,229✔
429
        }
430
      }
431
      break;
399,874✔
432
    case TSDB_DATA_TYPE_BINARY:
580,004✔
433
    case TSDB_DATA_TYPE_NCHAR:
434
    case TSDB_DATA_TYPE_JSON: {
435
      int32_t bufIndex = 0;
580,004✔
436
      char   *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
580,004!
437
      if (tmp == NULL) break;
580,004!
438
      for (int32_t i = 0; i < length; i++) {
5,713,584✔
439
        tmp[bufIndex] = val[i];
5,133,580✔
440
        bufIndex++;
5,133,580✔
441
        if (val[i] == '\"') {
5,133,580!
442
          tmp[bufIndex] = val[i];
×
443
          bufIndex++;
×
444
        }
445
      }
446
      tmp[bufIndex] = 0;
580,004✔
447

448
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
580,004✔
449
      taosMemoryFree(tmp);
580,004!
450
    } break;
580,004✔
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:
441,479✔
470
      shellFormatTimestamp(buf, sizeof(buf), *(int64_t *)val, precision);
441,479✔
471
      taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
441,479✔
472
      break;
441,479✔
473
    default:
×
474
      break;
×
475
  }
476
}
477

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

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

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

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

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

507
  int64_t numOfRows = 0;
26✔
508
  do {
509
    int32_t *length = taos_fetch_lengths(tres);
311,479✔
510
    for (int32_t i = 0; i < num_fields; i++) {
2,439,634✔
511
      if (i > 0) {
2,128,155✔
512
        taosFprintfFile(pFile, ",");
1,816,676✔
513
      }
514
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
2,128,155✔
515
    }
516
    taosFprintfFile(pFile, "\r\n");
311,479✔
517

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

522
  taosCloseFile(&pFile);
26✔
523

524
  return numOfRows;
26✔
525
}
526

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

531
  while (pos < length) {
149,242✔
532
    TdWchar wc;
533
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
141,167✔
534
    if (bytes <= 0) {
141,167✔
535
      break;
48✔
536
    }
537

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

549
    if (w <= 0) {
141,157!
550
      continue;
88,907✔
551
    }
552

553
    if (width <= 0) {
141,157✔
554
      printf("%lc", wc);
88,907✔
555
      continue;
88,907✔
556
    }
557

558
    totalCols += w;
52,250✔
559
    if (totalCols > width) {
52,250✔
560
      break;
38✔
561
    }
562
    if (totalCols <= (width - 3)) {
52,212✔
563
      printf("%lc", wc);
51,991✔
564
      cols += w;
51,991✔
565
    } else {
566
      tail[tailLen] = wc;
221✔
567
      tailLen++;
221✔
568
    }
569
  }
570

571
  if (totalCols > width) {
8,123✔
572
    // width could be 1 or 2, so printf("...") cannot be used
573
    for (int32_t i = 0; i < 3; i++) {
152✔
574
      if (cols >= width) {
114!
575
        break;
×
576
      }
577
      putchar('.');
114✔
578
      ++cols;
114✔
579
    }
580
  } else {
581
    for (int32_t i = 0; i < tailLen; i++) {
8,210✔
582
      printf("%lc", tail[i]);
125✔
583
    }
584
    cols = totalCols;
8,085✔
585
  }
586

587
  for (; cols < width; cols++) {
151,472✔
588
    putchar(' ');
143,349✔
589
  }
590
}
8,123✔
591

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

595
  if (width == 0) {
3,608!
596
    printf("%s", str);
×
597
  } else if (len > width) {
3,608!
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, "");
3,608✔
605
  }
606
}
3,608✔
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) {
33,850✔
635
  if (val == NULL) {
33,850✔
636
    shellPrintString(TSDB_DATA_NULL_STR, width);
1,166✔
637
    return;
1,166✔
638
  }
639

640
  int n = 0;
32,684✔
641
#define LENGTH 64
642
  char buf[LENGTH] = {0};
32,684✔
643
  switch (field->type) {
32,684!
644
    case TSDB_DATA_TYPE_BOOL:
2,442✔
645
      shellPrintString(((((int32_t)(*((char *)val))) == TSDB_FALSE) ? "false" : "true"), width);
2,442✔
646
      break;
2,442✔
647
    case TSDB_DATA_TYPE_TINYINT:
26✔
648
      printf("%*d", width, *((int8_t *)val));
26✔
649
      break;
26✔
650
    case TSDB_DATA_TYPE_UTINYINT:
226✔
651
      printf("%*u", width, *((uint8_t *)val));
226✔
652
      break;
226✔
653
    case TSDB_DATA_TYPE_SMALLINT:
1,624✔
654
      printf("%*d", width, *((int16_t *)val));
1,624✔
655
      break;
1,624✔
656
    case TSDB_DATA_TYPE_USMALLINT:
8✔
657
      printf("%*u", width, *((uint16_t *)val));
8✔
658
      break;
8✔
659
    case TSDB_DATA_TYPE_INT:
4,002✔
660
      printf("%*d", width, *((int32_t *)val));
4,002✔
661
      break;
4,002✔
662
    case TSDB_DATA_TYPE_UINT:
8✔
663
      printf("%*u", width, *((uint32_t *)val));
8✔
664
      break;
8✔
665
    case TSDB_DATA_TYPE_BIGINT:
6,032✔
666
      printf("%*" PRId64, width, *((int64_t *)val));
6,032✔
667
      break;
6,032✔
668
    case TSDB_DATA_TYPE_UBIGINT:
43✔
669
      printf("%*" PRIu64, width, *((uint64_t *)val));
43✔
670
      break;
43✔
671
    case TSDB_DATA_TYPE_FLOAT:
742✔
672
      if (tsEnableScience) {
742!
673
        printf("%*.7e", width, GET_FLOAT_VAL(val));
×
674
      } else {
675
        n = snprintf(buf, LENGTH, "%*.*g", width, FLT_DIG, GET_FLOAT_VAL(val));
742✔
676
        if (n > SHELL_FLOAT_WIDTH) {
742✔
677
          printf("%*.7e", width, GET_FLOAT_VAL(val));
72✔
678
        } else {
679
          printf("%s", buf);
670✔
680
        }
681
      }
682
      break;
742✔
683
    case TSDB_DATA_TYPE_DOUBLE:
2,246✔
684
      if (tsEnableScience) {
2,246!
685
        snprintf(buf, LENGTH, "%*.15e", width, GET_DOUBLE_VAL(val));
×
686
        printf("%s", buf);
×
687
      } else {
688
        n = snprintf(buf, LENGTH, "%*.*g", width, DBL_DIG, GET_DOUBLE_VAL(val));
2,246✔
689
        if (n > SHELL_DOUBLE_WIDTH) {
2,246✔
690
          printf("%*.15e", width, GET_DOUBLE_VAL(val));
154✔
691
        } else {
692
          printf("%*s", width, buf);
2,092✔
693
        }
694
      }
695
      break;
2,246✔
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:
8,123✔
707
    case TSDB_DATA_TYPE_NCHAR:
708
    case TSDB_DATA_TYPE_JSON:
709
      shellPrintNChar(val, length, width);
8,123✔
710
      break;
8,123✔
711
    case TSDB_DATA_TYPE_GEOMETRY:
×
712
      shellPrintGeometry(val, length, width);
×
713
      break;
×
714
    case TSDB_DATA_TYPE_TIMESTAMP:
7,162✔
715
      shellFormatTimestamp(buf, sizeof(buf), *(int64_t *)val, precision);
7,162✔
716
      printf("%s", buf);
7,162✔
717
      break;
7,162✔
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
  // desc
734
  if (taosStrCaseStr(sql, "desc ") != NULL) {
×
735
    return true;
×
736
  }
737
  // show
738
  if (taosStrCaseStr(sql, "show ") != NULL) {
×
739
    return true;
×
740
  }
741
  // explain
742
  if (taosStrCaseStr(sql, "explain ") != NULL) {
×
743
    return true;
×
744
  }
745

746
  return false;
×
747
}
748

749
bool shellIsShowQuery(const char *sql) {
×
750
  // todo refactor
751
  if (taosStrCaseStr(sql, "show ") != NULL) {
×
752
    return true;
×
753
  }
754

755
  return false;
×
756
}
757

758
void init_dump_info(tsDumpInfo *dump_info, TAOS_RES *tres, const char *sql, bool vertical) {
4,228✔
759
  dump_info->sql = sql;
4,228✔
760
  dump_info->vertical = vertical;
4,228✔
761
  tsem_init(&dump_info->sem, 0, 0);
4,228✔
762
  dump_info->numOfAllRows = 0;
4,228✔
763

764
  dump_info->numFields = taos_num_fields(tres);
4,228✔
765
  dump_info->fields = taos_fetch_fields(tres);
4,228✔
766
  dump_info->precision = taos_result_precision(tres);
4,228✔
767

768
  dump_info->resShowMaxNum = UINT64_MAX;
4,228✔
769

770
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsShowWhole(dump_info->sql)) {
4,228!
771
    dump_info->resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
×
772
  }
773

774
  if (vertical) {
4,228✔
775
    dump_info->maxColNameLen = 0;
53✔
776
    for (int32_t col = 0; col < dump_info->numFields; col++) {
106✔
777
      int32_t len = (int32_t)strlen(dump_info->fields[col].name);
53✔
778
      if (len > dump_info->maxColNameLen) {
53!
779
        dump_info->maxColNameLen = len;
53✔
780
      }
781
    }
782
  } else {
783
    for (int32_t col = 0; col < dump_info->numFields; col++) {
10,550✔
784
      dump_info->width[col] = shellCalcColWidth(dump_info->fields + col, dump_info->precision);
6,375✔
785
    }
786
  }
787
}
4,228✔
788

789
void shellVerticalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
53✔
790
  TAOS_ROW row = taos_fetch_row(tres);
53✔
791
  if (row == NULL) {
53!
792
    printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
793
    return;
×
794
  }
795

796
  int64_t numOfPintRows = dump_info->numOfAllRows;
53✔
797
  int     numOfPrintRowsThisOne = 0;
53✔
798

799
  while (row != NULL) {
1,521!
800
    printf("*************************** %" PRId64 ".row ***************************\r\n", numOfPintRows + 1);
1,521✔
801

802
    int32_t *length = taos_fetch_lengths(tres);
1,521✔
803

804
    for (int32_t i = 0; i < dump_info->numFields; i++) {
3,042✔
805
      TAOS_FIELD *field = dump_info->fields + i;
1,521✔
806

807
      int32_t padding = (int32_t)(dump_info->maxColNameLen - strlen(field->name));
1,521✔
808
      printf("%*.s%s: ", padding, " ", field->name);
1,521✔
809

810
      shellPrintField((const char *)row[i], field, 0, length[i], dump_info->precision);
1,521✔
811
      putchar('\r');
1,521✔
812
      putchar('\n');
1,521✔
813
    }
814

815
    numOfPintRows++;
1,521✔
816
    numOfPrintRowsThisOne++;
1,521✔
817

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

829
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
1,521✔
830
      return;
53✔
831
    }
832

833
    row = taos_fetch_row(tres);
1,468✔
834
  }
835
  return;
×
836
}
837

838
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
6,375✔
839
  int32_t width = (int32_t)strlen(field->name);
6,375✔
840

841
  switch (field->type) {
6,375!
842
    case TSDB_DATA_TYPE_NULL:
×
843
      return TMAX(4, width);  // null
×
844
    case TSDB_DATA_TYPE_BOOL:
196✔
845
      return TMAX(5, width);  // 'false'
196✔
846

847
    case TSDB_DATA_TYPE_TINYINT:
110✔
848
    case TSDB_DATA_TYPE_UTINYINT:
849
      return TMAX(4, width);  // '-127'
110✔
850

851
    case TSDB_DATA_TYPE_SMALLINT:
232✔
852
    case TSDB_DATA_TYPE_USMALLINT:
853
      return TMAX(6, width);  // '-32767'
232✔
854

855
    case TSDB_DATA_TYPE_INT:
440✔
856
    case TSDB_DATA_TYPE_UINT:
857
      return TMAX(11, width);  // '-2147483648'
440✔
858

859
    case TSDB_DATA_TYPE_BIGINT:
1,609✔
860
    case TSDB_DATA_TYPE_UBIGINT:
861
      return TMAX(21, width);  // '-9223372036854775807'
1,609✔
862

863
    case TSDB_DATA_TYPE_FLOAT:
88✔
864
      return TMAX(SHELL_FLOAT_WIDTH, width);
88✔
865

866
    case TSDB_DATA_TYPE_DOUBLE:
924✔
867
      return TMAX(SHELL_DOUBLE_WIDTH, width);
924✔
868

869
    case TSDB_DATA_TYPE_BINARY:
1,360✔
870
    case TSDB_DATA_TYPE_GEOMETRY:
871
      if (field->bytes > shell.args.displayWidth) {
1,360✔
872
        return TMAX(shell.args.displayWidth, width);
678✔
873
      } else {
874
        return TMAX(field->bytes + 2, width);
682✔
875
      }
876
    case TSDB_DATA_TYPE_VARBINARY: {
×
877
      int32_t bytes = field->bytes * 2 + 2;
×
878
      if (bytes > shell.args.displayWidth) {
×
879
        return TMAX(shell.args.displayWidth, width);
×
880
      } else {
881
        return TMAX(bytes + 2, width);
×
882
      }
883
    }
884
    case TSDB_DATA_TYPE_NCHAR:
306✔
885
    case TSDB_DATA_TYPE_JSON: {
886
      uint16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
306✔
887
      if (bytes > shell.args.displayWidth) {
306!
888
        return TMAX(shell.args.displayWidth, width);
306✔
889
      } else {
890
        return TMAX(bytes + 2, width);
×
891
      }
892
    }
893

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

906
    default:
×
907
      ASSERT(false);
×
908
  }
909

910
  return 0;
×
911
}
912

913
void shellPrintHeader(TAOS_FIELD *fields, int32_t *width, int32_t num_fields) {
4,105✔
914
  int32_t rowWidth = 0;
4,105✔
915
  for (int32_t col = 0; col < num_fields; col++) {
10,240✔
916
    TAOS_FIELD *field = fields + col;
6,135✔
917
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
6,135✔
918
    int32_t     left = padding / 2;
6,135✔
919
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
6,135✔
920
    rowWidth += width[col] + 3;
6,135✔
921
  }
922

923
  putchar('\r');
4,105✔
924
  putchar('\n');
4,105✔
925
  for (int32_t i = 0; i < rowWidth; i++) {
178,226✔
926
    putchar('=');
174,121✔
927
  }
928
  putchar('\r');
4,105✔
929
  putchar('\n');
4,105✔
930
}
4,105✔
931

932
void shellHorizontalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
4,105✔
933
  TAOS_ROW row = taos_fetch_row(tres);
4,105✔
934
  if (row == NULL) {
4,105!
935
    printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
936
    return;
×
937
  }
938

939
  int64_t numOfPintRows = dump_info->numOfAllRows;
4,105✔
940
  int     numOfPrintRowsThisOne = 0;
4,105✔
941
  if (numOfPintRows == 0) {
4,105!
942
    shellPrintHeader(dump_info->fields, dump_info->width, dump_info->numFields);
4,105✔
943
  }
944

945
  while (row != NULL) {
17,582!
946
    int32_t *length = taos_fetch_lengths(tres);
17,582✔
947
    for (int32_t i = 0; i < dump_info->numFields; i++) {
49,911✔
948
      putchar(' ');
32,329✔
949
      shellPrintField((const char *)row[i], dump_info->fields + i, dump_info->width[i], length[i],
32,329✔
950
                      dump_info->precision);
951
      putchar(' ');
32,329✔
952
      putchar('|');
32,329✔
953
    }
954
    putchar('\r');
17,582✔
955
    putchar('\n');
17,582✔
956

957
    numOfPintRows++;
17,582✔
958
    numOfPrintRowsThisOne++;
17,582✔
959

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

975
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
17,582✔
976
      return;
4,105✔
977
    }
978

979
    row = taos_fetch_row(tres);
13,477✔
980
  }
981
  return;
×
982
}
983

984
void shellDumpResultCallback(void *param, TAOS_RES *tres, int num_of_rows) {
8,386✔
985
  tsDumpInfo *dump_info = (tsDumpInfo *)param;
8,386✔
986
  if (num_of_rows > 0) {
8,386✔
987
    dump_info->numOfRows = num_of_rows;
4,158✔
988
    if (dump_info->numOfAllRows < dump_info->resShowMaxNum) {
4,158!
989
      if (dump_info->vertical) {
4,158✔
990
        shellVerticalPrintResult(tres, dump_info);
53✔
991
      } else {
992
        shellHorizontalPrintResult(tres, dump_info);
4,105✔
993
      }
994
    }
995
    dump_info->numOfAllRows += num_of_rows;
4,158✔
996
    if (!shellCmdkilled) {
4,158!
997
      taos_fetch_rows_a(tres, shellDumpResultCallback, param);
4,158✔
998
    } else {
999
      tsem_post(&dump_info->sem);
×
1000
    }
1001
  } else {
1002
    if (num_of_rows < 0) {
4,228!
1003
      printf("\033[31masync retrieve failed, code: %d\033[0m\n", num_of_rows);
×
1004
    }
1005
    tsem_post(&dump_info->sem);
4,228✔
1006
  }
1007
}
8,386✔
1008

1009
int64_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
4,254✔
1010
  int64_t num_of_rows = 0;
4,254✔
1011
  if (fname != NULL) {
4,254✔
1012
    num_of_rows = shellDumpResultToFile(fname, tres);
26✔
1013
  } else {
1014
    tsDumpInfo dump_info;
1015
    if (!shellCmdkilled) {
4,228!
1016
      init_dump_info(&dump_info, tres, sql, vertical);
4,228✔
1017
      taos_fetch_rows_a(tres, shellDumpResultCallback, &dump_info);
4,228✔
1018
      tsem_wait(&dump_info.sem);
4,228✔
1019
      num_of_rows = dump_info.numOfAllRows;
4,228✔
1020
    }
1021
  }
1022

1023
  *error_no = shellCmdkilled ? TSDB_CODE_TSC_QUERY_KILLED : taos_errno(tres);
4,254!
1024
  return num_of_rows;
4,254✔
1025
}
1026

1027
void shellReadHistory() {
896✔
1028
  SShellHistory *pHistory = &shell.history;
896✔
1029
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
896✔
1030
  if (pFile == NULL) return;
896!
1031

1032
  char   *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
896!
1033
  int32_t read_size = 0;
896✔
1034
  while ((read_size = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) > 0) {
7,722,023✔
1035
    line[read_size - 1] = '\0';
7,721,127✔
1036
    taosMemoryFree(pHistory->hist[pHistory->hend]);
7,721,127!
1037
    pHistory->hist[pHistory->hend] = taosStrdup(line);
7,721,127!
1038

1039
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
7,721,127✔
1040

1041
    if (pHistory->hend == pHistory->hstart) {
7,721,127✔
1042
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
6,826,023✔
1043
    }
1044
  }
1045

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

1062
    /* coverity[+retval] */
1063
    taosFsyncFile(pFile);
×
1064
    taosCloseFile(&pFile);
×
1065
  }
1066
  pHistory->hstart = pHistory->hend;
896✔
1067
}
1068

1069
void shellWriteHistory() {
896✔
1070
  SShellHistory *pHistory = &shell.history;
896✔
1071
  if (pHistory->hend == pHistory->hstart) return;
896!
1072
  TdFilePtr pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
896✔
1073
  if (pFile == NULL) return;
896!
1074

1075
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
1,793✔
1076
    if (pHistory->hist[i] != NULL) {
897!
1077
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
897✔
1078
      taosMemoryFree(pHistory->hist[i]);
897!
1079
      pHistory->hist[i] = NULL;
897✔
1080
    }
1081
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
897✔
1082
  }
1083
  taosCloseFile(&pFile);
896✔
1084
}
1085

1086
void shellCleanupHistory() {
896✔
1087
  SShellHistory *pHistory = &shell.history;
896✔
1088
  for (int32_t i = 0; i < SHELL_MAX_HISTORY_SIZE; ++i) {
896,896✔
1089
    if (pHistory->hist[i] != NULL) {
896,000✔
1090
      taosMemoryFree(pHistory->hist[i]);
895,103!
1091
      pHistory->hist[i] = NULL;
895,103✔
1092
    }
1093
  }
1094
}
896✔
1095

1096
void shellPrintError(TAOS_RES *tres, int64_t st) {
12✔
1097
  int64_t et = taosGetTimestampUs();
12✔
1098
  fprintf(stderr, "\r\nDB error: %s[0x%08X] (%.6fs)\r\n", taos_errstr(tres), taos_errno(tres), (et - st) / 1E6);
12✔
1099
  taos_free_result(tres);
12✔
1100
}
12✔
1101

1102
bool shellIsCommentLine(char *line) {
4,160✔
1103
  if (line == NULL) return true;
4,160!
1104
  return shellRegexMatch(line, "^\\s*#.*", REG_EXTENDED);
4,160✔
1105
}
1106

1107
void shellSourceFile(const char *file) {
715✔
1108
  int32_t read_len = 0;
715✔
1109
  char   *cmd = taosMemoryCalloc(1, TSDB_MAX_ALLOWED_SQL_LEN + 1);
715!
1110
  size_t  cmd_len = 0;
715✔
1111
  char    fullname[PATH_MAX] = {0};
715✔
1112
  char    sourceFileCommand[PATH_MAX + 8] = {0};
715✔
1113

1114
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
715!
1115
    tstrncpy(fullname, file, PATH_MAX);
×
1116
  }
1117

1118
  sprintf(sourceFileCommand, "source %s;", fullname);
715✔
1119
  shellRecordCommandToHistory(sourceFileCommand);
715✔
1120

1121
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
715✔
1122
  if (pFile == NULL) {
715✔
1123
    fprintf(stderr, "failed to open file %s\r\n", fullname);
27✔
1124
    taosMemoryFree(cmd);
27!
1125
    return;
27✔
1126
  }
1127

1128
  char *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
688!
1129
  while ((read_len = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) > 0) {
4,900✔
1130
    if (cmd_len + read_len >= TSDB_MAX_ALLOWED_SQL_LEN) {
4,212!
1131
      printf("read command line too long over 1M, ignore this line. cmd_len = %d read_len=%d \n", (int32_t)cmd_len,
×
1132
             read_len);
1133
      cmd_len = 0;
×
1134
      memset(line, 0, TSDB_MAX_ALLOWED_SQL_LEN + 1);
×
1135
      continue;
×
1136
    }
1137
    line[--read_len] = '\0';
4,212✔
1138

1139
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
4,212!
1140
      continue;
52✔
1141
    }
1142

1143
    if (line[read_len - 1] == '\\') {
4,160!
1144
      line[read_len - 1] = ' ';
×
1145
      memcpy(cmd + cmd_len, line, read_len);
×
1146
      cmd_len += read_len;
×
1147
      continue;
×
1148
    }
1149

1150
    if (line[read_len - 1] == '\r') {
4,160!
1151
      line[read_len - 1] = ' ';
×
1152
    }
1153

1154
    memcpy(cmd + cmd_len, line, read_len);
4,160✔
1155
    printf("%s%s\r\n", shell.info.promptHeader, cmd);
4,160✔
1156
    shellRunCommand(cmd, false);
4,160✔
1157
    memset(cmd, 0, TSDB_MAX_ALLOWED_SQL_LEN);
4,160✔
1158
    cmd_len = 0;
4,160✔
1159
  }
1160

1161
  taosMemoryFree(cmd);
688!
1162
  taosMemoryFreeClear(line);
688!
1163
  taosCloseFile(&pFile);
688✔
1164
}
1165

1166
int32_t shellGetGrantInfo(char *buf) {
5✔
1167
  int32_t verType = TSDB_VERSION_UNKNOWN;
5✔
1168
  char    sinfo[256] = {0};
5✔
1169
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
5✔
1170
  strtok(sinfo, "\r\n");
5✔
1171

1172
  char sql[] = "show grants";
5✔
1173

1174
  TAOS_RES *tres = taos_query(shell.conn, sql);
5✔
1175

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

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

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

1206
    tstrncpy(serverVersion, row[0], 64);
5✔
1207
    memcpy(expiretime, row[1], fields[1].bytes);
5✔
1208
    memcpy(expired, row[2], fields[2].bytes);
5✔
1209

1210
    if (strcmp(serverVersion, "community") == 0) {
5!
1211
      verType = TSDB_VERSION_OSS;
×
1212
    } else if (strcmp(expiretime, "unlimited") == 0) {
5!
1213
      verType = TSDB_VERSION_ENTERPRISE;
×
1214
      sprintf(buf, "Server is %s, %s and will never expire.\r\n", serverVersion, sinfo);
×
1215
    } else {
1216
      verType = TSDB_VERSION_ENTERPRISE;
5✔
1217
      sprintf(buf, "Server is %s, %s and will expire at %s.\r\n", serverVersion, sinfo, expiretime);
5✔
1218
    }
1219

1220
    taos_free_result(tres);
5✔
1221
  }
1222

1223
  fprintf(stdout, "\r\n");
5✔
1224
  return verType;
5✔
1225
}
1226

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

1236
void shellCleanup(void *arg) { taosResetTerminalMode(); }
5✔
1237

1238
void *shellCancelHandler(void *arg) {
5✔
1239
  setThreadName("shellCancelHandler");
5✔
1240
  while (1) {
1241
    if (shell.exit == true) {
15✔
1242
      break;
5✔
1243
    }
1244

1245
    if (tsem_wait(&shell.cancelSem) != 0) {
10!
1246
      taosMsleep(10);
×
1247
      continue;
×
1248
    }
1249

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

1267
  return NULL;
5✔
1268
}
1269

1270
#pragma GCC diagnostic push
1271
#pragma GCC diagnostic ignored "-Wstringop-overflow"
1272

1273
void *shellThreadLoop(void *arg) {
5✔
1274
  setThreadName("shellThreadLoop");
5✔
1275
  taosGetOldTerminalMode();
5✔
1276
  taosThreadCleanupPush(shellCleanup, NULL);
5!
1277

1278
  do {
1279
    char *command = taosMemoryMalloc(SHELL_MAX_COMMAND_SIZE);
5!
1280
    if (command == NULL) {
5!
1281
      printf("failed to malloc command\r\n");
×
1282
      break;
×
1283
    }
1284

1285
    do {
1286
      memset(command, 0, SHELL_MAX_COMMAND_SIZE);
10✔
1287
      taosSetTerminalMode();
10✔
1288

1289
      if (shellReadCommand(command) != 0) {
10✔
1290
        break;
5✔
1291
      }
1292

1293
      taosResetTerminalMode();
5✔
1294
    } while (shellRunCommand(command, true) == 0);
5!
1295

1296
    taosMemoryFreeClear(command);
5!
1297
    shellWriteHistory();
5✔
1298
    shellExit();
5✔
1299
  } while (0);
1300

1301
  taosThreadCleanupPop(1);
5✔
1302
  return NULL;
5✔
1303
}
1304
#pragma GCC diagnostic pop
1305

1306
int32_t shellExecute() {
976✔
1307
  printf(shell.info.clientVersion, shell.info.cusName, taos_get_client_info(), shell.info.cusName);
976✔
1308
  fflush(stdout);
976✔
1309

1310
  SShellArgs *pArgs = &shell.args;
976✔
1311
#ifdef WEBSOCKET
1312
  if (shell.args.restful || shell.args.cloud) {
976!
1313
    if (shell_conn_ws_server(1)) {
60!
1314
      printf("failed to connect to server, reason: %s[0x%08X]\n%s", ws_errstr(NULL), ws_errno(NULL), ERROR_CODE_DETAIL);
60✔
1315
      fflush(stdout);
60✔
1316
      return -1;
60✔
1317
    }
1318
  } else {
1319
#endif
1320
    if (shell.args.auth == NULL) {
916✔
1321
      shell.conn = taos_connect(pArgs->host, pArgs->user, pArgs->password, pArgs->database, pArgs->port);
913✔
1322
    } else {
1323
      shell.conn = taos_connect_auth(pArgs->host, pArgs->user, pArgs->auth, pArgs->database, pArgs->port);
3✔
1324
    }
1325

1326
    if (shell.conn == NULL) {
916✔
1327
      printf("failed to connect to server, reason: %s[0x%08X]\n%s", taos_errstr(NULL), taos_errno(NULL), ERROR_CODE_DETAIL);
20✔
1328
      fflush(stdout);
20✔
1329
      return -1;
20✔
1330
    }
1331
#ifdef WEBSOCKET
1332
  }
1333
#endif
1334

1335
  bool runOnce = pArgs->commands != NULL || pArgs->file[0] != 0;
896✔
1336
  shellSetConn(shell.conn, runOnce);
896✔
1337
  shellReadHistory();
896✔
1338

1339
  if (shell.args.is_bi_mode) {
896✔
1340
    // need set bi mode
1341
    printf("Set BI mode is true.\n");
1✔
1342
#ifndef WEBSOCKET
1343
    taos_set_conn_mode(shell.conn, TAOS_CONN_MODE_BI, 1);
1344
#endif
1345
  }
1346

1347
  if (runOnce) {
896✔
1348
    if (pArgs->commands != NULL) {
891✔
1349
      printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
177✔
1350
      char *cmd = taosStrdup(pArgs->commands);
177!
1351
      shellRunCommand(cmd, true);
177✔
1352
      taosMemoryFree(cmd);
177!
1353
    }
1354

1355
    if (pArgs->file[0] != 0) {
891✔
1356
      shellSourceFile(pArgs->file);
714✔
1357
    }
1358
#ifdef WEBSOCKET
1359
    if (shell.args.restful || shell.args.cloud) {
891!
1360
      ws_close(shell.ws_conn);
×
1361
    } else {
1362
#endif
1363
      taos_close(shell.conn);
891✔
1364
#ifdef WEBSOCKET
1365
    }
1366
#endif
1367

1368
    shellWriteHistory();
891✔
1369
    shellCleanupHistory();
891✔
1370
    return 0;
891✔
1371
  }
1372

1373
  if (tsem_init(&shell.cancelSem, 0, 0) != 0) {
5!
1374
    printf("failed to create cancel semaphore\r\n");
×
1375
    return -1;
×
1376
  }
1377

1378
  TdThread spid = {0};
5✔
1379
  taosThreadCreate(&spid, NULL, shellCancelHandler, NULL);
5✔
1380

1381
  taosSetSignal(SIGTERM, shellQueryInterruptHandler);
5✔
1382
  taosSetSignal(SIGHUP, shellQueryInterruptHandler);
5✔
1383
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
5✔
1384

1385
#ifdef WEBSOCKET
1386
  if (!shell.args.restful && !shell.args.cloud) {
5!
1387
#endif
1388
    char    buf[512] = {0};
5✔
1389
    int32_t verType = shellGetGrantInfo(buf);
5✔
1390
#ifndef WINDOWS
1391
    printfIntroduction(verType);
5✔
1392
#else
1393
#ifndef WEBSOCKET
1394
  if (verType == TSDB_VERSION_OSS) {
1395
    showAD(false);
1396
  }
1397
#endif
1398
#endif
1399
    // printf version
1400
    if (verType == TSDB_VERSION_ENTERPRISE || verType == TSDB_VERSION_CLOUD) {
5!
1401
      printf("%s\n", buf);
5✔
1402
    }
1403

1404
#ifdef WEBSOCKET
1405
  }
1406
#endif
1407
  while (1) {
1408
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
5✔
1409
    taosThreadJoin(shell.pid, NULL);
5✔
1410
    taosThreadClear(&shell.pid);
5✔
1411
    if (shell.exit) {
5!
1412
      tsem_post(&shell.cancelSem);
5✔
1413
      break;
5✔
1414
    }
1415
  }
1416
#ifndef WEBSOCKET
1417
  // commnuity
1418
  if (verType == TSDB_VERSION_OSS) {
1419
    showAD(true);
1420
  }
1421
#endif
1422

1423
  taosThreadJoin(spid, NULL);
5✔
1424

1425
  shellCleanupHistory();
5✔
1426
  taos_kill_query(shell.conn);
5✔
1427
  taos_close(shell.conn);
5✔
1428

1429
  return 0;
5✔
1430
}
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