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

taosdata / TDengine / #4878

11 Dec 2025 02:43AM UTC coverage: 64.569% (-0.02%) from 64.586%
#4878

push

travis-ci

guanshengliang
feat(TS-7270): internal dependence

307 of 617 new or added lines in 24 files covered. (49.76%)

3821 existing lines in 123 files now uncovered.

163630 of 253417 relevant lines covered (64.57%)

107598827.89 hits per line

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

77.53
/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 "../../inc/pub.h"
22
#include "geosWrapper.h"
23
#include "shellAuto.h"
24
#include "shellInt.h"
25

26
SShellObj shell = {0};
27

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

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

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

42
  uint64_t resShowMaxNum;
43
} tsDumpInfo;
44

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

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

68
static bool shellCmdkilled = false;
69

70
bool shellIsEmptyCommand(const char *cmd) {
21,411,778✔
71
  for (char c = *cmd++; c != 0; c = *cmd++) {
21,462,893✔
72
    if (c != ' ' && c != '\t' && c != ';') {
15,799,793✔
73
      return false;
15,748,678✔
74
    }
75
  }
76
  return true;
5,663,100✔
77
}
78

79
int32_t shellRunSingleCommand(char *command) {
13,563,561✔
80
  shellCmdkilled = false;
13,563,561✔
81

82
  if (shellIsEmptyCommand(command)) {
13,563,561✔
83
    return 0;
5,663,100✔
84
  }
85

86
  if (shellRegexMatch(command, "^[ \t]*(quit|q|exit)[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
7,900,461✔
87
    return -1;
568✔
88
  }
89

90
  if (shellRegexMatch(command, "^[\t ]*clear[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
7,899,893✔
91
#pragma GCC diagnostic push
92
#pragma GCC diagnostic ignored "-Wunused-result"
93
#ifndef TD_ASTRA
94
    system("clear");
×
95
#else
96
    printf("\033[2J\033[H");
97
#endif
98
#pragma GCC diagnostic pop
99
    return 0;
×
100
  }
101

102
  if (shellRegexMatch(command, "^[\t ]*set[ \t]+max_binary_display_width[ \t]+(default|[1-9][0-9]*)[ \t;]*$",
7,899,893✔
103
                      REG_EXTENDED | REG_ICASE)) {
104
    strtok(command, " \t");
560✔
105
    strtok(NULL, " \t");
560✔
106
    char *p = strtok(NULL, " \t");
560✔
107
    if (strncasecmp(p, "default", 7) == 0) {
560✔
108
      shell.args.displayWidth = SHELL_DEFAULT_MAX_BINARY_DISPLAY_WIDTH;
×
109
    } else {
110
      int32_t displayWidth = atoi(p);
560✔
111
      displayWidth = TRANGE(displayWidth, 1, 10 * 1024);
560✔
112
      shell.args.displayWidth = displayWidth;
560✔
113
    }
114
    return 0;
560✔
115
  }
116

117
  if (shellRegexMatch(command, "^[ \t]*source[\t ]+[^ ]+[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
7,899,333✔
118
    /* If source file. */
119
    char *c_ptr = strtok(command, " ;");
560✔
120
    if (c_ptr == NULL) {
560✔
121
      shellRunSingleCommandImp(command);
×
122
      return 0;
×
123
    }
124
    c_ptr = strtok(NULL, " ;");
560✔
125
    if (c_ptr == NULL) {
560✔
126
      shellRunSingleCommandImp(command);
×
127
      return 0;
×
128
    }
129
    shellSourceFile(c_ptr);
560✔
130
    return 0;
560✔
131
  }
132
  shellRunSingleCommandImp(command);
7,898,773✔
133
  return 0;
7,898,773✔
134
}
135

136
void shellRecordCommandToHistory(char *command) {
1,196,750✔
137
  if (strncasecmp(command, "create user ", 12) == 0 || strncasecmp(command, "alter user ", 11) == 0) {
1,196,750✔
138
    if (taosStrCaseStr(command, " pass ")) {
×
139
      // have password command forbid record to history because security
140
      return;
×
141
    }
142
  }
143

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

153
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
1,196,750✔
154
    if (pHistory->hend == pHistory->hstart) {
1,196,750✔
155
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
×
156
    }
157
  }
158
}
159

160
int32_t shellRunCommand(char *command, bool recordHistory) {
7,848,217✔
161
  if (shellIsEmptyCommand(command)) {
7,848,217✔
162
    return 0;
×
163
  }
164

165
  // add help or help;
166
  if (strncasecmp(command, "help", 4) == 0) {
7,848,217✔
167
    if (command[4] == ';' || command[4] == ' ' || command[4] == 0) {
564✔
168
      showHelp();
564✔
169
      return 0;
564✔
170
    }
171
  }
172

173
  if (recordHistory) shellRecordCommandToHistory(command);
7,847,653✔
174

175
  char quote = 0, *cmd = command;
7,847,653✔
176
  for (char c = *command++; c != 0; c = *command++) {
748,501,679✔
177
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
740,654,594✔
178
      command++;
3,400✔
179
      continue;
3,400✔
180
    }
181

182
    if (quote == c) {
740,651,194✔
183
      quote = 0;
3,265,730✔
184
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
737,385,464✔
185
      quote = c;
3,265,730✔
186
    } else if (c == ';' && quote == 0) {
734,119,734✔
187
      c = *command;
5,716,476✔
188
      *command = 0;
5,716,476✔
189
      if (shellRunSingleCommand(cmd) < 0) {
5,716,476✔
190
        return -1;
568✔
191
      }
192
      *command = c;
5,715,908✔
193
      cmd = command;
5,715,908✔
194
    }
195
  }
196
  return shellRunSingleCommand(cmd);
7,847,085✔
197
}
198

199
char *strendG(const char *pstr) {
7,898,773✔
200
  if (pstr == NULL) {
7,898,773✔
201
    return NULL;
×
202
  }
203

204
  size_t len = strlen(pstr);
7,898,773✔
205
  if (len < 4) {
7,898,773✔
206
    return NULL;
×
207
  }
208

209
  char *p = (char *)pstr + len - 2;
7,898,773✔
210
  if (strcmp(p, "\\G") == 0) {
7,898,773✔
211
    return p;
7,604✔
212
  }
213

214
  p = (char *)pstr + len - 3;
7,891,169✔
215
  if (strcmp(p, "\\G;") == 0) {
7,891,169✔
216
    return p;
56,048✔
217
  }
218

219
  return NULL;
7,835,121✔
220
}
221

222
void shellRunSingleCommandImp(char *command) {
7,898,773✔
223
  int64_t st, et;
224
  char   *sptr = NULL;
7,898,773✔
225
  char   *cptr = NULL;
7,898,773✔
226
  char   *fname = NULL;
7,898,773✔
227
  bool    printMode = false;
7,898,773✔
228

229
  if ((sptr = strstr(command, ">>")) != NULL) {
7,898,773✔
230
    fname = sptr + 2;
1,024,826✔
231
    while (*fname == ' ') fname++;
2,048,520✔
232
    *sptr = '\0';
1,024,826✔
233

234
    cptr = strstr(fname, ";");
1,024,826✔
235
    if (cptr != NULL) {
1,024,826✔
236
      *cptr = '\0';
504✔
237
    }
238
  }
239

240
  if ((sptr = strendG(command)) != NULL) {
7,898,773✔
241
    *sptr = '\0';
63,652✔
242
    printMode = true;  // When output to a file, the switch does not work.
63,652✔
243
  }
244

245
  st = taosGetTimestampUs();
7,898,773✔
246

247
  TAOS_RES *pSql = taos_query(shell.conn, command);
7,898,773✔
248
  if (taos_errno(pSql)) {
7,898,773✔
249
    shellPrintError(pSql, st);
2,007,420✔
250
    return;
2,007,420✔
251
  }
252

253
  if (shellRegexMatch(command, "^\\s*use\\s+[a-zA-Z0-9_]+\\s*;\\s*$", REG_EXTENDED | REG_ICASE)) {
5,891,353✔
254
    printf("Database changed.\r\n\r\n");
11,179✔
255

256
    // call back auto tab module
257
    callbackAutoTab(command, pSql, true);
11,179✔
258

259
    taos_free_result(pSql);
11,179✔
260

261
    return;
11,179✔
262
  }
263

264
  // pre string
265
  char *pre = "Query OK";
5,880,174✔
266
  if (shellRegexMatch(command, "^\\s*delete\\s*from\\s*.*", REG_EXTENDED | REG_ICASE)) {
5,880,174✔
267
    pre = "Delete OK";
280✔
268
  } else if (shellRegexMatch(command, "^\\s*insert\\s*into\\s*.*", REG_EXTENDED | REG_ICASE)) {
5,879,894✔
269
    pre = "Insert OK";
9,509✔
270
  } else if (shellRegexMatch(command, "^\\s*create\\s*.*", REG_EXTENDED | REG_ICASE)) {
5,870,385✔
271
    pre = "Create OK";
11,146✔
272
  } else if (shellRegexMatch(command, "^\\s*drop\\s*.*", REG_EXTENDED | REG_ICASE)) {
5,859,239✔
273
    pre = "Drop OK";
14,698✔
274
  }
275

276
  TAOS_FIELD *pFields = taos_fetch_fields(pSql);
5,880,174✔
277
  if (pFields != NULL) {  // select and show kinds of commands
5,880,174✔
278
    int32_t error_no = 0;
4,566,387✔
279

280
    int64_t numOfRows = shellDumpResult(pSql, fname, &error_no, printMode, command);
4,566,387✔
281
    if (numOfRows < 0) return;
4,566,387✔
282

283
    et = taosGetTimestampUs();
4,566,387✔
284
    if (error_no == 0) {
4,566,387✔
285
      printf("Query OK, %" PRId64 " row(s) in set (%.6fs)\r\n", numOfRows, (et - st) / 1E6);
4,566,387✔
286
    } else {
287
      printf("Query interrupted (%s), %" PRId64 " row(s) in set (%.6fs)\r\n", tstrerror(error_no), numOfRows,
×
288
             (et - st) / 1E6);
×
289
    }
290
    taos_free_result(pSql);
4,566,387✔
291
  } else {
292
    int64_t num_rows_affacted = taos_affected_rows64(pSql);
1,313,787✔
293
    taos_free_result(pSql);
1,313,787✔
294
    et = taosGetTimestampUs();
1,313,787✔
295
    printf("%s, %" PRId64 " row(s) affected (%.6fs)\r\n", pre, num_rows_affacted, (et - st) / 1E6);
1,313,787✔
296

297
    // call auto tab
298
    callbackAutoTab(command, NULL, false);
1,313,787✔
299
  }
300

301
  printf("\r\n");
5,880,174✔
302
}
303

304
char *shellFormatTimestamp(char *buf, int32_t bufSize, int64_t val, int32_t precision) {
247,402,338✔
305
  if (shell.args.is_raw_time) {
247,402,338✔
306
    sprintf(buf, "%" PRId64, val);
×
307
    return buf;
×
308
  }
309

310
  time_t  tt;
247,308,654✔
311
  int32_t ms = 0;
247,402,338✔
312
  if (precision == TSDB_TIME_PRECISION_NANO) {
247,402,338✔
313
    tt = (time_t)(val / 1000000000);
5,600✔
314
    ms = val % 1000000000;
5,600✔
315
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
247,396,738✔
316
    tt = (time_t)(val / 1000000);
5,600✔
317
    ms = val % 1000000;
5,600✔
318
  } else {
319
    tt = (time_t)(val / 1000);
247,391,138✔
320
    ms = val % 1000;
247,391,138✔
321
  }
322

323
  if (tt <= 0 && ms < 0) {
247,402,338✔
324
    tt--;
11,165✔
325
    if (precision == TSDB_TIME_PRECISION_NANO) {
11,165✔
326
      ms += 1000000000;
×
327
    } else if (precision == TSDB_TIME_PRECISION_MICRO) {
11,165✔
328
      ms += 1000000;
×
329
    } else {
330
      ms += 1000;
11,165✔
331
    }
332
  }
333

334
  struct tm ptm = {0};
247,402,338✔
335
  if (taosLocalTime(&tt, &ptm, buf, bufSize, NULL) == NULL) {
247,402,338✔
336
    return buf;
×
337
  }
338
  size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
247,402,338✔
339

340
  if (precision == TSDB_TIME_PRECISION_NANO) {
247,402,338✔
341
    sprintf(buf + pos, ".%09d", ms);
5,600✔
342
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
247,396,738✔
343
    sprintf(buf + pos, ".%06d", ms);
5,600✔
344
  } else {
345
    sprintf(buf + pos, ".%03d", ms);
247,391,138✔
346
  }
347

348
  return buf;
247,402,338✔
349
}
350

351
char *shellDumpHexValue(char *buf, const char *val, int32_t length) {
×
352
  for (int32_t i = 0; i < length; i++) {
×
353
    sprintf(buf + (i * 2), "%02X", val[i]);
×
354
  }
355
  buf[length * 2] = 0;
×
356

357
  return buf;
×
358
}
359

360
void shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field, int32_t length, int32_t precision) {
1,580,758,657✔
361
  if (val == NULL) {
1,580,758,657✔
362
    taosFprintfFile(pFile, "NULL");
9,157,962✔
363
    return;
9,157,962✔
364
  }
365

366
  char    quotationStr[2] = {'"', 0};
1,571,600,695✔
367
  int32_t width;
368

369
  int n = 0;
1,571,600,695✔
370
#define LENGTH 64
371
  char buf[LENGTH] = {0};
1,571,600,695✔
372
  switch (field->type) {
1,571,600,695✔
373
    case TSDB_DATA_TYPE_BOOL:
588,559,048✔
374
      taosFprintfFile(pFile, "%d", ((((int32_t)(*((char *)val))) == 1) ? 1 : 0));
588,559,048✔
375
      break;
588,559,048✔
376
    case TSDB_DATA_TYPE_TINYINT:
36,863,637✔
377
      taosFprintfFile(pFile, "%d", *((int8_t *)val));
36,863,637✔
378
      break;
36,863,637✔
379
    case TSDB_DATA_TYPE_UTINYINT:
1,549,796✔
380
      taosFprintfFile(pFile, "%u", *((uint8_t *)val));
1,549,796✔
381
      break;
1,549,796✔
382
    case TSDB_DATA_TYPE_SMALLINT:
1,537,594✔
383
      taosFprintfFile(pFile, "%d", *((int16_t *)val));
1,537,594✔
384
      break;
1,537,594✔
385
    case TSDB_DATA_TYPE_USMALLINT:
2,327,122✔
386
      taosFprintfFile(pFile, "%u", *((uint16_t *)val));
2,327,122✔
387
      break;
2,327,122✔
388
    case TSDB_DATA_TYPE_INT:
45,777,514✔
389
      taosFprintfFile(pFile, "%d", *((int32_t *)val));
45,777,514✔
390
      break;
45,777,514✔
391
    case TSDB_DATA_TYPE_UINT:
1,550,360✔
392
      taosFprintfFile(pFile, "%u", *((uint32_t *)val));
1,550,360✔
393
      break;
1,550,360✔
394
    case TSDB_DATA_TYPE_BIGINT:
122,119,580✔
395
      taosFprintfFile(pFile, "%" PRId64, *((int64_t *)val));
122,119,580✔
396
      break;
122,119,580✔
397
    case TSDB_DATA_TYPE_UBIGINT:
1,540,006✔
398
      taosFprintfFile(pFile, "%" PRIu64, *((uint64_t *)val));
1,540,006✔
399
      break;
1,540,006✔
400
    case TSDB_DATA_TYPE_FLOAT:
35,322,378✔
401
      width = SHELL_FLOAT_WIDTH;
35,322,378✔
402
      if (tsEnableScience) {
35,322,378✔
403
        taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
×
404
      } else {
405
        n = tsnprintf(buf, LENGTH, "%*.7f", width, GET_FLOAT_VAL(val));
35,322,378✔
406
        if (n > SHELL_FLOAT_WIDTH) {
35,322,378✔
407
          taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
585,340✔
408
        } else {
409
          taosFprintfFile(pFile, "%s", buf);
34,737,038✔
410
        }
411
      }
412
      break;
35,322,378✔
413
    case TSDB_DATA_TYPE_DOUBLE:
211,739,291✔
414
      width = SHELL_DOUBLE_WIDTH;
211,739,291✔
415
      if (tsEnableScience) {
211,739,291✔
416
        snprintf(buf, LENGTH, "%*.15e", width, GET_DOUBLE_VAL(val));
×
417
        taosFprintfFile(pFile, "%s", buf);
×
418
      } else {
419
        n = tsnprintf(buf, LENGTH, "%*.15f", width, GET_DOUBLE_VAL(val));
211,739,291✔
420
        if (n > SHELL_DOUBLE_WIDTH) {
211,739,291✔
421
          taosFprintfFile(pFile, "%*.15e", width, GET_DOUBLE_VAL(val));
182,139,081✔
422
        } else {
423
          taosFprintfFile(pFile, "%s", buf);
29,600,210✔
424
        }
425
      }
426
      break;
211,739,291✔
427
    case TSDB_DATA_TYPE_BINARY:
99,167,652✔
428
    case TSDB_DATA_TYPE_NCHAR:
429
    case TSDB_DATA_TYPE_JSON: {
430
      int32_t bufIndex = 0;
99,167,652✔
431
      char   *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
99,167,652✔
432
      if (tmp == NULL) break;
99,167,652✔
433
      for (int32_t i = 0; i < length; i++) {
1,493,545,236✔
434
        tmp[bufIndex] = val[i];
1,394,377,584✔
435
        bufIndex++;
1,394,377,584✔
436
        if (val[i] == '\"') {
1,394,377,584✔
437
          tmp[bufIndex] = val[i];
×
438
          bufIndex++;
×
439
        }
440
      }
441
      tmp[bufIndex] = 0;
99,167,652✔
442

443
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
99,167,652✔
444
      taosMemoryFree(tmp);
99,167,652✔
445
    } break;
99,167,652✔
446
    case TSDB_DATA_TYPE_VARBINARY: {
×
447
      void    *tmp = NULL;
×
448
      uint32_t size = 0;
×
449
      if (taosAscii2Hex(val, length, &tmp, &size) < 0) {
×
450
        break;
×
451
      }
452
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
×
453
      taosMemoryFree(tmp);
×
454
      break;
×
455
    }
456
    case TSDB_DATA_TYPE_GEOMETRY: {
×
457
      char *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
×
458
      if (tmp == NULL) break;
×
459
      shellDumpHexValue(tmp, val, length);
×
460
      taosFprintfFile(pFile, "%s", buf);
×
461
      taosMemoryFree(tmp);
×
462
      break;
×
463
    }
464
    case TSDB_DATA_TYPE_TIMESTAMP:
74,795,528✔
465
      shellFormatTimestamp(buf, sizeof(buf), *(int64_t *)val, precision);
74,795,528✔
466
      taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
74,795,528✔
467
      break;
74,795,528✔
468
    case TSDB_DATA_TYPE_DECIMAL64:
348,751,189✔
469
    case TSDB_DATA_TYPE_DECIMAL:
470
      taosFprintfFile(pFile, "%s", val);
348,751,189✔
471
      break;
348,751,189✔
472
    case TSDB_DATA_TYPE_BLOB:
×
473
    case TSDB_DATA_TYPE_MEDIUMBLOB: {
474
      void    *tmp = NULL;
×
475
      uint32_t size = 0;
×
476
      if (taosAscii2Hex(val, length, &tmp, &size) < 0) {
×
477
        break;
×
478
      }
479
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
×
480
      taosMemoryFree(tmp);
×
481

482
      break;
×
483
    }
484
    default:
×
485
      break;
×
486
  }
487
}
488

489
int64_t shellDumpResultToFile(const char *fname, TAOS_RES *tres) {
1,003,307✔
490
  char fullname[PATH_MAX] = {0};
1,003,307✔
491
  if (taosExpandDir(fname, fullname, PATH_MAX) != 0) {
1,003,307✔
492
    tstrncpy(fullname, fname, PATH_MAX);
×
493
  }
494

495
  TAOS_ROW row = taos_fetch_row(tres);
1,003,307✔
496
  if (row == NULL) {
1,003,307✔
497
    return 0;
×
498
  }
499

500
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);
1,003,307✔
501
  if (pFile == NULL) {
1,003,307✔
502
    fprintf(stderr, "failed to open file: %s\r\n", fullname);
×
503
    return -1;
×
504
  }
505

506
  TAOS_FIELD *fields = taos_fetch_fields(tres);
1,003,307✔
507
  int32_t     num_fields = taos_num_fields(tres);
1,003,307✔
508
  int32_t     precision = taos_result_precision(tres);
1,003,307✔
509

510
  for (int32_t col = 0; col < num_fields; col++) {
2,412,715✔
511
    if (col > 0) {
1,409,408✔
512
      taosFprintfFile(pFile, ",");
406,101✔
513
    }
514
    taosFprintfFile(pFile, "%s", fields[col].name);
1,409,408✔
515
  }
516
  taosFprintfFile(pFile, "\r\n");
1,003,307✔
517

518
  int64_t numOfRows = 0;
1,003,307✔
519
  do {
520
    int32_t *length = taos_fetch_lengths(tres);
1,035,524,427✔
521
    for (int32_t i = 0; i < num_fields; i++) {
2,147,483,647✔
522
      if (i > 0) {
1,580,758,657✔
523
        taosFprintfFile(pFile, ",");
545,234,230✔
524
      }
525
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
1,580,758,657✔
526
    }
527
    taosFprintfFile(pFile, "\r\n");
1,035,524,427✔
528

529
    numOfRows++;
1,035,524,427✔
530
    row = taos_fetch_row(tres);
1,035,524,427✔
531
  } while (row != NULL);
1,035,524,427✔
532

533
  taosCloseFile(&pFile);
1,003,307✔
534

535
  return numOfRows;
1,003,307✔
536
}
537

538
void shellPrintNChar(const char *str, int32_t length, int32_t width) {
170,374,458✔
539
  TdWchar tail[3];
170,290,056✔
540
  int32_t pos = 0, cols = 0, totalCols = 0, tailLen = 0;
170,374,458✔
541

542
  while (pos < length) {
2,147,483,647✔
543
    TdWchar wc;
2,147,483,647✔
544
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
2,147,483,647✔
545
    if (bytes <= 0) {
2,147,483,647✔
546
      break;
42,793✔
547
    }
548

549
    if (pos + bytes > length) {
2,147,483,647✔
550
      break;
×
551
    }
552
    int w = 0;
2,147,483,647✔
553
    if (*(str + pos) == '\t' || *(str + pos) == '\n' || *(str + pos) == '\r') {
2,147,483,647✔
554
      w = bytes;
×
555
    } else {
556
      w = taosWcharWidth(wc);
2,147,483,647✔
557
    }
558
    pos += bytes;
2,147,483,647✔
559

560
    if (w <= 0) {
2,147,483,647✔
561
      continue;
11,250✔
562
    }
563

564
    if (width <= 0) {
2,147,483,647✔
565
      printf("%lc", wc);
63,948,614✔
566
      continue;
63,948,614✔
567
    }
568

569
    totalCols += w;
2,147,483,647✔
570
    if (totalCols > width) {
2,147,483,647✔
571
      break;
582,242✔
572
    }
573
    if (totalCols <= (width - 3)) {
2,147,483,647✔
574
      printf("%lc", wc);
2,147,483,647✔
575
      cols += w;
2,147,483,647✔
576
    } else {
577
      tail[tailLen] = wc;
1,843,037✔
578
      tailLen++;
1,843,037✔
579
    }
580
  }
581

582
  if (totalCols > width) {
170,374,458✔
583
    // width could be 1 or 2, so printf("...") cannot be used
584
    for (int32_t i = 0; i < 3; i++) {
2,328,968✔
585
      if (cols >= width) {
1,746,726✔
586
        break;
×
587
      }
588
      putchar('.');
1,746,726✔
589
      ++cols;
1,746,726✔
590
    }
591
  } else {
592
    for (int32_t i = 0; i < tailLen; i++) {
169,893,657✔
593
      printf("%lc", tail[i]);
101,441✔
594
    }
595
    cols = totalCols;
169,792,216✔
596
  }
597

598
  for (; cols < width; cols++) {
2,147,483,647✔
599
    putchar(' ');
2,147,483,647✔
600
  }
601
}
170,374,458✔
602

603
void shellPrintString(const char *str, int32_t width) {
639,210,015✔
604
  int32_t len = strlen(str);
639,210,015✔
605

606
  if (width == 0) {
639,210,015✔
607
    printf("%s", str);
×
608
  } else if (len > width) {
639,210,015✔
609
    if (width <= 3) {
×
610
      printf("%.*s.", width - 1, str);
×
611
    } else {
612
      printf("%.*s...", width - 3, str);
×
613
    }
614
  } else {
615
    printf("%s%*.s", str, width - len, "");
639,210,015✔
616
  }
617
}
639,210,015✔
618

619
void shellPrintGeometry(const unsigned char *val, int32_t length, int32_t width) {
×
620
  if (length == 0) {  // empty value
×
621
    shellPrintString("", width);
×
622
    return;
×
623
  }
624

625
  int32_t code = TSDB_CODE_FAILED;
×
626

627
  code = initCtxAsText();
×
628
  if (code != TSDB_CODE_SUCCESS) {
×
629
    shellPrintString(getGeosErrMsg(code), width);
×
630
    return;
×
631
  }
632

633
  char *outputWKT = NULL;
×
634
  code = doAsText(val, length, &outputWKT);
×
635
  if (code != TSDB_CODE_SUCCESS) {
×
636
    shellPrintString(getGeosErrMsg(code), width);  // should NOT happen
×
637
    return;
×
638
  }
639

640
  shellPrintString(outputWKT, width);
×
641

642
  geosFreeBuffer(outputWKT);
×
643
}
644

645
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision) {
1,473,160,057✔
646
  if (val == NULL) {
1,473,160,057✔
647
    shellPrintString(TSDB_DATA_NULL_STR, width);
578,326,984✔
648
    return;
578,326,984✔
649
  }
650

651
  int n = 0;
894,833,073✔
652
#define LENGTH 64
653
  char buf[LENGTH] = {0};
894,833,073✔
654
  switch (field->type) {
894,833,073✔
655
    case TSDB_DATA_TYPE_BOOL:
60,883,031✔
656
      shellPrintString(((((int32_t)(*((char *)val))) == TSDB_FALSE) ? "false" : "true"), width);
60,883,031✔
657
      break;
60,883,031✔
658
    case TSDB_DATA_TYPE_TINYINT:
29,702,390✔
659
      printf("%*d", width, *((int8_t *)val));
29,702,390✔
660
      break;
29,702,390✔
661
    case TSDB_DATA_TYPE_UTINYINT:
48,207,890✔
662
      printf("%*u", width, *((uint8_t *)val));
48,207,890✔
663
      break;
48,207,890✔
664
    case TSDB_DATA_TYPE_SMALLINT:
23,429,237✔
665
      printf("%*d", width, *((int16_t *)val));
23,429,237✔
666
      break;
23,429,237✔
667
    case TSDB_DATA_TYPE_USMALLINT:
53,216,425✔
668
      printf("%*u", width, *((uint16_t *)val));
53,216,425✔
669
      break;
53,216,425✔
670
    case TSDB_DATA_TYPE_INT:
57,682,070✔
671
      printf("%*d", width, *((int32_t *)val));
57,682,070✔
672
      break;
57,682,070✔
673
    case TSDB_DATA_TYPE_UINT:
38,534,043✔
674
      printf("%*u", width, *((uint32_t *)val));
38,534,043✔
675
      break;
38,534,043✔
676
    case TSDB_DATA_TYPE_BIGINT:
88,515,500✔
677
      printf("%*" PRId64, width, taosGetInt64Aligned((int64_t *)val));
88,515,500✔
678
      break;
88,515,500✔
679
    case TSDB_DATA_TYPE_UBIGINT:
40,532,530✔
680
      printf("%*" PRIu64, width, taosGetUInt64Aligned((uint64_t *)val));
40,532,530✔
681
      break;
40,532,530✔
682
    case TSDB_DATA_TYPE_FLOAT:
43,401,733✔
683
      width = width >= LENGTH ? LENGTH - 1 : width;
43,401,733✔
684
      if (tsEnableScience) {
43,401,733✔
685
        printf("%*.7e", width, taosGetFloatAligned((float *)val));
×
686
      } else {
687
        snprintf(buf, LENGTH, "%*.*g", width, FLT_DIG, taosGetFloatAligned((float *)val));
43,401,733✔
688
        printf("%s", buf);
43,401,733✔
689
      }
690
      break;
43,401,733✔
691
    case TSDB_DATA_TYPE_DOUBLE:
67,746,384✔
692
      width = width >= LENGTH ? LENGTH - 1 : width;
67,746,384✔
693
      if (tsEnableScience) {
67,746,384✔
694
        snprintf(buf, LENGTH, "%*.15e", width, taosGetDoubleAligned((double *)val));
×
695
        printf("%s", buf);
×
696
      } else {
697
        snprintf(buf, LENGTH, "%*.*g", width, DBL_DIG, taosGetDoubleAligned((double *)val));
67,746,384✔
698
        printf("%*s", width, buf);
67,746,384✔
699
      }
700
      break;
67,746,384✔
701
    case TSDB_DATA_TYPE_VARBINARY: {
×
702
      void    *data = NULL;
×
703
      uint32_t size = 0;
×
704
      if (taosAscii2Hex(val, length, &data, &size) < 0) {
×
705
        break;
×
706
      }
707
      shellPrintNChar(data, size, width);
×
708
      taosMemoryFree(data);
×
709
      break;
×
710
    }
711
    case TSDB_DATA_TYPE_BINARY:
170,374,458✔
712
    case TSDB_DATA_TYPE_NCHAR:
713
    case TSDB_DATA_TYPE_JSON:
714
      shellPrintNChar(val, length, width);
170,374,458✔
715
      break;
170,374,458✔
716
    case TSDB_DATA_TYPE_GEOMETRY:
×
717
      shellPrintGeometry(val, length, width);
×
718
      break;
×
719
    case TSDB_DATA_TYPE_TIMESTAMP:
172,606,810✔
720
      shellFormatTimestamp(buf, sizeof(buf), taosGetInt64Aligned((int64_t *)val), precision);
172,606,810✔
721
      printf("%s", buf);
172,606,810✔
722
      break;
172,606,810✔
723

724
    case TSDB_DATA_TYPE_BLOB:
×
725
    case TSDB_DATA_TYPE_MEDIUMBLOB: {
726
      void    *data = NULL;
×
727
      uint32_t size = 0;
×
728
      if (taosAscii2Hex(val, length, &data, &size) < 0) {
×
729
        break;
×
730
      }
731
      shellPrintNChar(data, size, width);
×
732
      taosMemoryFree(data);
×
733
      break;
×
734
    }
735
    case TSDB_DATA_TYPE_DECIMAL:
572✔
736
    case TSDB_DATA_TYPE_DECIMAL64:
737
      printf("%*s", width, val);
572✔
738
    default:
572✔
739
      break;
572✔
740
  }
741
}
742

743
// show whole result for this query return true, like limit or describe
744
bool shellIsShowWhole(const char *sql) {
×
745
  // limit
746
  if (taosStrCaseStr(sql, " limit ") != NULL) {
×
747
    return true;
×
748
  }
749
  // describe
750
  if (taosStrCaseStr(sql, "describe ") != NULL) {
×
751
    return true;
×
752
  }
753
  // desc
754
  if (taosStrCaseStr(sql, "desc ") != NULL) {
×
755
    return true;
×
756
  }
757
  // show
758
  if (taosStrCaseStr(sql, "show ") != NULL) {
×
759
    return true;
×
760
  }
761
  // explain
762
  if (taosStrCaseStr(sql, "explain ") != NULL) {
×
763
    return true;
×
764
  }
765

766
  return false;
×
767
}
768

769
bool shellIsShowQuery(const char *sql) {
×
770
  // todo refactor
771
  if (taosStrCaseStr(sql, "show ") != NULL) {
×
772
    return true;
×
773
  }
774

775
  return false;
×
776
}
777

778
void init_dump_info(tsDumpInfo *dump_info, TAOS_RES *tres, const char *sql, bool vertical) {
3,563,080✔
779
  dump_info->sql = sql;
3,563,080✔
780
  dump_info->vertical = vertical;
3,563,080✔
781
  tsem_init(&dump_info->sem, 0, 0);
3,563,080✔
782
  dump_info->numOfAllRows = 0;
3,563,080✔
783

784
  dump_info->numFields = taos_num_fields(tres);
3,563,080✔
785
  dump_info->fields = taos_fetch_fields(tres);
3,563,080✔
786
  dump_info->precision = taos_result_precision(tres);
3,563,080✔
787

788
  dump_info->resShowMaxNum = UINT64_MAX;
3,563,080✔
789

790
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsShowWhole(dump_info->sql)) {
3,563,080✔
791
    dump_info->resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
×
792
  }
793

794
  if (vertical) {
3,563,080✔
795
    dump_info->maxColNameLen = 0;
63,652✔
796
    for (int32_t col = 0; col < dump_info->numFields; col++) {
139,927✔
797
      int32_t len = (int32_t)strlen(dump_info->fields[col].name);
76,275✔
798
      if (len > dump_info->maxColNameLen) {
76,275✔
799
        dump_info->maxColNameLen = len;
67,554✔
800
      }
801
    }
802
  } else {
803
    for (int32_t col = 0; col < dump_info->numFields; col++) {
17,061,182✔
804
      dump_info->width[col] = shellCalcColWidth(dump_info->fields + col, dump_info->precision);
13,561,754✔
805
    }
806
  }
807
}
3,563,080✔
808

809
void shellVerticalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
63,652✔
810
  TAOS_ROW row = taos_fetch_row(tres);
63,652✔
811
  if (row == NULL) {
63,652✔
812
    printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
813
    return;
×
814
  }
815

816
  int64_t numOfPintRows = dump_info->numOfAllRows;
63,652✔
817
  int     numOfPrintRowsThisOne = 0;
63,652✔
818

819
  while (row != NULL) {
1,120,855✔
820
    printf("*************************** %" PRId64 ".row ***************************\r\n", numOfPintRows + 1);
1,120,855✔
821

822
    int32_t *length = taos_fetch_lengths(tres);
1,120,855✔
823

824
    for (int32_t i = 0; i < dump_info->numFields; i++) {
2,284,796✔
825
      TAOS_FIELD *field = dump_info->fields + i;
1,163,941✔
826

827
      int32_t padding = (int32_t)(dump_info->maxColNameLen - strlen(field->name));
1,163,941✔
828
      printf("%*.s%s: ", padding, " ", field->name);
1,163,941✔
829

830
      shellPrintField((const char *)row[i], field, 0, length[i], dump_info->precision);
1,163,941✔
831
      putchar('\r');
1,163,941✔
832
      putchar('\n');
1,163,941✔
833
    }
834

835
    numOfPintRows++;
1,120,855✔
836
    numOfPrintRowsThisOne++;
1,120,855✔
837

838
    if (numOfPintRows == dump_info->resShowMaxNum) {
1,120,855✔
839
      printf("\r\n");
×
840
      printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
×
841
      printf("         You can use the `LIMIT` clause to get fewer result to show.\r\n");
×
842
      printf("           Or use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
843
      printf("\r\n");
×
844
      printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
×
845
      printf("\r\n");
×
846
      return;
×
847
    }
848

849
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
1,120,855✔
850
      return;
63,652✔
851
    }
852

853
    row = taos_fetch_row(tres);
1,057,203✔
854
  }
855
  return;
×
856
}
857

858
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
13,561,754✔
859
  int32_t width = (int32_t)strlen(field->name);
13,561,754✔
860

861
  switch (field->type) {
13,561,754✔
862
    case TSDB_DATA_TYPE_NULL:
×
863
      return TMAX(4, width);  // null
×
864
    case TSDB_DATA_TYPE_BOOL:
822,981✔
865
      return TMAX(5, width);  // 'false'
822,981✔
866

867
    case TSDB_DATA_TYPE_TINYINT:
1,164,241✔
868
    case TSDB_DATA_TYPE_UTINYINT:
869
      return TMAX(4, width);  // '-127'
1,164,241✔
870

871
    case TSDB_DATA_TYPE_SMALLINT:
1,199,791✔
872
    case TSDB_DATA_TYPE_USMALLINT:
873
      return TMAX(6, width);  // '-32767'
1,199,791✔
874

875
    case TSDB_DATA_TYPE_INT:
1,527,268✔
876
    case TSDB_DATA_TYPE_UINT:
877
      return TMAX(11, width);  // '-2147483648'
1,527,268✔
878

879
    case TSDB_DATA_TYPE_BIGINT:
1,964,280✔
880
    case TSDB_DATA_TYPE_UBIGINT:
881
      return TMAX(21, width);  // '-9223372036854775807'
1,964,280✔
882

883
    case TSDB_DATA_TYPE_FLOAT:
795,445✔
884
      return TMAX(SHELL_FLOAT_WIDTH, width);
795,445✔
885

886
    case TSDB_DATA_TYPE_DOUBLE:
1,465,889✔
887
      return TMAX(SHELL_DOUBLE_WIDTH, width);
1,465,889✔
888

889
    case TSDB_DATA_TYPE_BINARY:
1,968,556✔
890
    case TSDB_DATA_TYPE_GEOMETRY:
891
      if (field->bytes > shell.args.displayWidth) {
1,968,556✔
892
        return TMAX(shell.args.displayWidth, width);
1,105,976✔
893
      } else {
894
        return TMAX(field->bytes + 2, width);
862,580✔
895
      }
896
    case TSDB_DATA_TYPE_VARBINARY: {
3,444✔
897
      int32_t bytes = field->bytes * 2 + 2;
3,444✔
898
      if (bytes > shell.args.displayWidth) {
3,444✔
899
        return TMAX(shell.args.displayWidth, width);
×
900
      } else {
901
        return TMAX(bytes + 2, width);
3,444✔
902
      }
903
    }
904
    case TSDB_DATA_TYPE_NCHAR:
1,280,040✔
905
    case TSDB_DATA_TYPE_JSON: {
906
      uint16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
1,280,040✔
907
      if (bytes > shell.args.displayWidth) {
1,280,040✔
908
        return TMAX(shell.args.displayWidth, width);
1,280,040✔
909
      } else {
910
        return TMAX(bytes + 2, width);
×
911
      }
912
    }
913

914
    case TSDB_DATA_TYPE_TIMESTAMP:
1,369,247✔
915
      if (shell.args.is_raw_time) {
1,369,247✔
916
        return TMAX(14, width);
861✔
917
      }
918
      if (precision == TSDB_TIME_PRECISION_NANO) {
1,368,386✔
919
        return TMAX(29, width);
560✔
920
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
1,367,826✔
921
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
560✔
922
      } else {
923
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
1,367,266✔
924
      }
925
    case TSDB_DATA_TYPE_BLOB:
×
926
    case TSDB_DATA_TYPE_MEDIUMBLOB: {
927
      int32_t bytes = TSDB_MAX_BLOB_LEN;
×
928
      if (bytes > shell.args.displayWidth) {
×
929
        return TMAX(shell.args.displayWidth, width);
×
930
      } else {
931
        return TMAX(bytes + 2, width);
×
932
      }
933
    } break;
934

935
    case TSDB_DATA_TYPE_DECIMAL64:
286✔
936
      return TMAX(width, 20);
286✔
937
    case TSDB_DATA_TYPE_DECIMAL:
286✔
938
      return TMAX(width, 40);
286✔
939
    default:
×
940
      ASSERT(false);
×
941
  }
942

943
  return 0;
×
944
}
945

946
void shellPrintHeader(TAOS_FIELD *fields, int32_t *width, int32_t num_fields) {
3,177,477✔
947
  int32_t rowWidth = 0;
3,177,477✔
948
  for (int32_t col = 0; col < num_fields; col++) {
14,264,795✔
949
    TAOS_FIELD *field = fields + col;
11,087,318✔
950
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
11,087,318✔
951
    int32_t     left = padding / 2;
11,087,318✔
952
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
11,087,318✔
953
    rowWidth += width[col] + 3;
11,087,318✔
954
  }
955

956
  putchar('\r');
3,177,477✔
957
  putchar('\n');
3,177,477✔
958
  for (int32_t i = 0; i < rowWidth; i++) {
276,866,270✔
959
    putchar('=');
273,688,793✔
960
  }
961
  putchar('\r');
3,177,477✔
962
  putchar('\n');
3,177,477✔
963
}
3,177,477✔
964

965
void shellHorizontalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
3,214,395✔
966
  TAOS_ROW row = taos_fetch_row(tres);
3,214,395✔
967
  if (row == NULL) {
3,214,395✔
968
    printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
969
    return;
×
970
  }
971

972
  int64_t numOfPintRows = dump_info->numOfAllRows;
3,214,395✔
973
  int     numOfPrintRowsThisOne = 0;
3,214,395✔
974
  if (numOfPintRows == 0) {
3,214,395✔
975
    shellPrintHeader(dump_info->fields, dump_info->width, dump_info->numFields);
3,177,477✔
976
  }
977

978
  while (row != NULL) {
189,113,686✔
979
    int32_t *length = taos_fetch_lengths(tres);
189,113,686✔
980
    for (int32_t i = 0; i < dump_info->numFields; i++) {
1,661,109,802✔
981
      putchar(' ');
1,471,996,116✔
982
      shellPrintField((const char *)row[i], dump_info->fields + i, dump_info->width[i], length[i],
1,471,996,116✔
983
                      dump_info->precision);
984
      putchar(' ');
1,471,996,116✔
985
      putchar('|');
1,471,996,116✔
986
    }
987
    putchar('\r');
189,113,686✔
988
    putchar('\n');
189,113,686✔
989

990
    numOfPintRows++;
189,113,686✔
991
    numOfPrintRowsThisOne++;
189,113,686✔
992

993
    if (numOfPintRows == dump_info->resShowMaxNum) {
189,113,686✔
994
      printf("\r\n");
×
995
      printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
×
996
      if (shellIsShowQuery(dump_info->sql)) {
×
997
        printf("         You can use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
998
      } else {
999
        printf("         You can use the `LIMIT` clause to get fewer result to show.\r\n");
×
1000
        printf("           Or use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
1001
      }
1002
      printf("\r\n");
×
1003
      printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
×
1004
      printf("\r\n");
×
1005
      return;
×
1006
    }
1007

1008
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
189,113,686✔
1009
      return;
3,214,395✔
1010
    }
1011

1012
    row = taos_fetch_row(tres);
185,899,291✔
1013
  }
1014
  return;
×
1015
}
1016

1017
void shellDumpResultCallback(void *param, TAOS_RES *tres, int num_of_rows) {
6,841,127✔
1018
  tsDumpInfo *dump_info = (tsDumpInfo *)param;
6,841,127✔
1019
  if (num_of_rows > 0) {
6,841,127✔
1020
    dump_info->numOfRows = num_of_rows;
3,278,047✔
1021
    if (dump_info->numOfAllRows < dump_info->resShowMaxNum) {
3,278,047✔
1022
      if (dump_info->vertical) {
3,278,047✔
1023
        shellVerticalPrintResult(tres, dump_info);
63,652✔
1024
      } else {
1025
        shellHorizontalPrintResult(tres, dump_info);
3,214,395✔
1026
      }
1027
    }
1028
    dump_info->numOfAllRows += num_of_rows;
3,278,047✔
1029
    if (!shellCmdkilled) {
3,278,047✔
1030
      taos_fetch_rows_a(tres, shellDumpResultCallback, param);
3,278,047✔
1031
    } else {
1032
      tsem_post(&dump_info->sem);
×
1033
    }
1034
  } else {
1035
    if (num_of_rows < 0) {
3,563,080✔
1036
      printf("\033[31masync retrieve failed, code: %d, %s\033[0m\n", num_of_rows, tstrerror(num_of_rows));
×
1037
    }
1038
    tsem_post(&dump_info->sem);
3,563,080✔
1039
  }
1040
}
6,840,852✔
1041

1042
int64_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
4,566,387✔
1043
  int64_t num_of_rows = 0;
4,566,387✔
1044
  if (fname != NULL) {
4,566,387✔
1045
    num_of_rows = shellDumpResultToFile(fname, tres);
1,003,307✔
1046
  } else {
1047
    tsDumpInfo dump_info;
3,548,697✔
1048
    if (!shellCmdkilled) {
3,563,080✔
1049
      init_dump_info(&dump_info, tres, sql, vertical);
3,563,080✔
1050
      taos_fetch_rows_a(tres, shellDumpResultCallback, &dump_info);
3,563,080✔
1051
      tsem_wait(&dump_info.sem);
3,563,080✔
1052
      num_of_rows = dump_info.numOfAllRows;
3,563,080✔
1053
    }
1054
  }
1055

1056
  *error_no = shellCmdkilled ? TSDB_CODE_TSC_QUERY_KILLED : taos_errno(tres);
4,566,387✔
1057
  return num_of_rows;
4,566,387✔
1058
}
1059

1060
void shellReadHistory() {
1,196,754✔
1061
  SShellHistory *pHistory = &shell.history;
1,196,754✔
1062
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
1,196,754✔
1063
  if (pFile == NULL) return;
1,196,754✔
1064

1065
  char   *line = taosMemoryMalloc(tsMaxSQLLength + 1);
1,168,939✔
1066
  int32_t read_size = 0;
1,168,939✔
1067
  while ((read_size = taosGetsFile(pFile, tsMaxSQLLength, line)) > 0) {
268,972,067✔
1068
    line[read_size - 1] = '\0';
267,803,128✔
1069
    taosMemoryFree(pHistory->hist[pHistory->hend]);
267,803,128✔
1070
    pHistory->hist[pHistory->hend] = taosStrdup(line);
267,803,128✔
1071

1072
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
267,803,128✔
1073

1074
    if (pHistory->hend == pHistory->hstart) {
267,803,128✔
1075
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
×
1076
    }
1077
  }
1078

1079
  taosMemoryFreeClear(line);
1,168,939✔
1080
  taosCloseFile(&pFile);
1,168,939✔
1081
  int64_t file_size;
1,139,482✔
1082
  if (taosStatFile(pHistory->file, &file_size, NULL, NULL) == 0 && file_size > SHELL_MAX_COMMAND_SIZE) {
1,168,939✔
1083
    TdFilePtr pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_TRUNC);
×
1084
    if (pFile == NULL) return;
×
1085
    int32_t endIndex = pHistory->hstart;
×
1086
    if (endIndex != 0) {
×
1087
      endIndex = pHistory->hend;
×
1088
    }
1089
    for (int32_t i = (pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE; i != endIndex;) {
×
1090
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
×
1091
      i = (i + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE;
×
1092
    }
1093
    taosFprintfFile(pFile, "%s\n", pHistory->hist[endIndex]);
×
1094

1095
    /* coverity[+retval] */
1096
    taosFsyncFile(pFile);
×
1097
    taosCloseFile(&pFile);
×
1098
  }
1099
  pHistory->hstart = pHistory->hend;
1,168,939✔
1100
}
1101

1102
void shellWriteHistory() {
1,196,754✔
1103
  SShellHistory *pHistory = &shell.history;
1,196,754✔
1104
  if (pHistory->hend == pHistory->hstart) return;
1,196,754✔
1105
  TdFilePtr pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
1,196,190✔
1106
  if (pFile == NULL) return;
1,196,190✔
1107

1108
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
2,392,940✔
1109
    if (pHistory->hist[i] != NULL) {
1,196,750✔
1110
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
1,196,750✔
1111
      taosMemoryFree(pHistory->hist[i]);
1,196,750✔
1112
      pHistory->hist[i] = NULL;
1,196,750✔
1113
    }
1114
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
1,196,750✔
1115
  }
1116
  taosCloseFile(&pFile);
1,196,190✔
1117
}
1118

1119
void shellCleanupHistory() {
1,196,754✔
1120
  SShellHistory *pHistory = &shell.history;
1,196,754✔
1121
  for (int32_t i = 0; i < SHELL_MAX_HISTORY_SIZE; ++i) {
1,197,950,754✔
1122
    if (pHistory->hist[i] != NULL) {
1,196,754,000✔
1123
      taosMemoryFree(pHistory->hist[i]);
267,803,128✔
1124
      pHistory->hist[i] = NULL;
267,803,128✔
1125
    }
1126
  }
1127
}
1,196,754✔
1128

1129
void shellPrintError(TAOS_RES *tres, int64_t st) {
2,007,420✔
1130
  int64_t et = taosGetTimestampUs();
2,007,420✔
1131
  fprintf(stderr, "\r\nDB error: %s [0x%08X] (%.6fs)\r\n", taos_errstr(tres), taos_errno(tres), (et - st) / 1E6);
2,007,420✔
1132
  taos_free_result(tres);
2,007,420✔
1133
}
2,007,420✔
1134

1135
bool shellIsCommentLine(char *line) {
6,713,098✔
1136
  if (line == NULL) return true;
6,713,098✔
1137
  return shellRegexMatch(line, "^\\s*#.*", REG_EXTENDED);
6,713,098✔
1138
}
1139

1140
void shellSourceFile(const char *file) {
62,195✔
1141
  int32_t read_len = 0;
62,195✔
1142
  char   *cmd = taosMemoryCalloc(1, tsMaxSQLLength + 1);
62,195✔
1143
  size_t  cmd_len = 0;
62,195✔
1144
  char    fullname[PATH_MAX] = {0};
62,195✔
1145
  char    sourceFileCommand[PATH_MAX + 8] = {0};
62,195✔
1146

1147
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
62,195✔
1148
    tstrncpy(fullname, file, PATH_MAX);
×
1149
  }
1150

1151
  sprintf(sourceFileCommand, "source %s;", fullname);
62,195✔
1152
  shellRecordCommandToHistory(sourceFileCommand);
62,195✔
1153

1154
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
62,195✔
1155
  if (pFile == NULL) {
62,195✔
1156
    fprintf(stderr, "failed to open file %s\r\n", fullname);
9,274✔
1157
    taosMemoryFree(cmd);
9,274✔
1158
    return;
9,274✔
1159
  }
1160

1161
  char *line = taosMemoryMalloc(tsMaxSQLLength + 1);
52,921✔
1162
  while ((read_len = taosGetsFile(pFile, tsMaxSQLLength, line)) > 0) {
6,908,803✔
1163
    if (cmd_len + read_len >= tsMaxSQLLength) {
6,855,882✔
1164
      printf("read command line too long over 1M, ignore this line. cmd_len = %d read_len=%d \n", (int32_t)cmd_len,
×
1165
             read_len);
1166
      cmd_len = 0;
×
1167
      memset(line, 0, tsMaxSQLLength + 1);
×
1168
      continue;
×
1169
    }
1170
    line[--read_len] = '\0';
6,855,882✔
1171

1172
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
6,855,882✔
1173
      continue;
142,784✔
1174
    }
1175

1176
    if (line[read_len - 1] == '\\') {
6,713,098✔
1177
      line[read_len - 1] = ' ';
×
1178
      memcpy(cmd + cmd_len, line, read_len);
×
1179
      cmd_len += read_len;
×
1180
      continue;
×
1181
    }
1182

1183
    if (line[read_len - 1] == '\r') {
6,713,098✔
1184
      line[read_len - 1] = ' ';
×
1185
    }
1186

1187
    memcpy(cmd + cmd_len, line, read_len);
6,713,098✔
1188
    printf("%s%s\r\n", shell.info.promptHeader, cmd);
6,713,098✔
1189
    shellRunCommand(cmd, false);
6,713,098✔
1190
    memset(cmd, 0, tsMaxSQLLength);
6,713,098✔
1191
    cmd_len = 0;
6,713,098✔
1192
  }
1193

1194
  taosMemoryFree(cmd);
52,921✔
1195
  taosMemoryFreeClear(line);
52,921✔
1196
  taosCloseFile(&pFile);
52,921✔
1197
}
1198

1199
int32_t shellGetGrantInfo(char *buf) {
739✔
1200
  int32_t verType = TSDB_VERSION_UNKNOWN;
739✔
1201
  char    sinfo[256] = {0};
739✔
1202
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
739✔
1203
  strtok(sinfo, "\r\n");
739✔
1204

1205
#ifndef TD_ASTRA
1206
  char sql[] = "show grants";
739✔
1207

1208
  TAOS_RES *tres = taos_query(shell.conn, sql);
739✔
1209

1210
  int32_t code = taos_errno(tres);
739✔
1211
  if (code != TSDB_CODE_SUCCESS) {
739✔
1212
    if (code != TSDB_CODE_OPS_NOT_SUPPORT && code != TSDB_CODE_MND_NO_RIGHTS &&
×
1213
        code != TSDB_CODE_PAR_PERMISSION_DENIED) {
1214
      fprintf(stderr, "Failed to check Server Edition, Reason:0x%04x:%s\r\n\r\n", code, taos_errstr(tres));
×
1215
    }
1216
    taos_free_result(tres);
×
1217
    return verType;
×
1218
  }
1219

1220
  int32_t num_fields = taos_field_count(tres);
739✔
1221
  if (num_fields == 0) {
739✔
1222
    fprintf(stderr, "\r\nInvalid grant information.\r\n");
×
1223
    exit(0);
×
1224
  } else {
1225
    if (tres == NULL) {
739✔
1226
      fprintf(stderr, "\r\nGrant information is null.\r\n");
×
1227
      exit(0);
×
1228
    }
1229

1230
    TAOS_FIELD *fields = taos_fetch_fields(tres);
739✔
1231
    TAOS_ROW    row = taos_fetch_row(tres);
739✔
1232
    if (row == NULL) {
739✔
1233
      fprintf(stderr, "\r\nFailed to get grant information from server. Abort.\r\n");
×
1234
      exit(0);
×
1235
    }
1236
    char serverVersion[64] = {0};
739✔
1237
    char expiretime[32] = {0};
739✔
1238
    char expired[32] = {0};
739✔
1239

1240
    tstrncpy(serverVersion, row[0], 64);
739✔
1241
    memcpy(expiretime, row[1], fields[1].bytes);
739✔
1242
    memcpy(expired, row[2], fields[2].bytes);
739✔
1243

1244
    trimStr(serverVersion, "trial");
739✔
1245

1246
    if (strcmp(serverVersion, "community") == 0) {
739✔
1247
      verType = TSDB_VERSION_OSS;
×
1248
    } else if (strcmp(expiretime, "unlimited") == 0) {
739✔
1249
      verType = TSDB_VERSION_ENTERPRISE;
×
1250
      sprintf(buf, "Server is %s %s. License will never expire.\r\n", serverVersion, sinfo);
×
1251
    } else {
1252
      verType = TSDB_VERSION_ENTERPRISE;
739✔
1253
      sprintf(buf, "Server is %s %s. License will expire at %s.\r\n", serverVersion, sinfo, expiretime);
739✔
1254
    }
1255

1256
    taos_free_result(tres);
739✔
1257
  }
1258

1259
  fprintf(stdout, "\r\n");
739✔
1260
#else
1261
  verType = TSDB_VERSION_ENTERPRISE;
1262
  sprintf(buf, "Server is %s %s. License will never expire.\r\n", TD_PRODUCT_NAME, sinfo);
1263
#endif
1264
  return verType;
739✔
1265
}
1266

1267
#ifdef WINDOWS
1268
BOOL shellQueryInterruptHandler(DWORD fdwCtrlType) {
1269
  tsem_post(&shell.cancelSem);
1270
  return TRUE;
1271
}
1272
#else
1273
void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }
1,478✔
1274
#endif
1275

1276
void shellCleanup(void *arg) { taosResetTerminalMode(); }
739✔
1277

1278
void *shellCancelHandler(void *arg) {
739✔
1279
  setThreadName("shellCancelHandler");
739✔
1280
  while (1) {
1281
    if (shell.exit == true) {
2,217✔
1282
      break;
739✔
1283
    }
1284

1285
    if (tsem_wait(&shell.cancelSem) != 0) {
1,478✔
1286
      taosMsleep(10);
×
1287
      continue;
×
1288
    }
1289

1290
    if (shell.conn) {
1,478✔
1291
      shellCmdkilled = true;
739✔
1292
      taos_kill_query(shell.conn);
739✔
1293
    }
1294

1295
#ifdef WINDOWS
1296
    printf("\n%s", shell.info.promptHeader);
1297
#endif
1298
  }
1299

1300
  return NULL;
739✔
1301
}
1302

1303
#pragma GCC diagnostic push
1304
#pragma GCC diagnostic ignored "-Wstringop-overflow"
1305

1306
void *shellThreadLoop(void *arg) {
739✔
1307
  setThreadName("shellThreadLoop");
739✔
1308
  taosGetOldTerminalMode();
739✔
1309
  taosThreadCleanupPush(shellCleanup, NULL);
739✔
1310

1311
  do {
1312
    char *command = taosMemoryMalloc(SHELL_MAX_COMMAND_SIZE);
739✔
1313
    if (command == NULL) {
739✔
1314
      printf("failed to malloc command\r\n");
×
1315
      break;
×
1316
    }
1317

1318
    do {
1319
      memset(command, 0, SHELL_MAX_COMMAND_SIZE);
1,478✔
1320
      taosSetTerminalMode();
1,478✔
1321

1322
      if (shellReadCommand(command) != 0) {
1,478✔
1323
        break;
739✔
1324
      }
1325

1326
      taosResetTerminalMode();
739✔
1327
    } while (shellRunCommand(command, true) == 0);
739✔
1328

1329
    taosMemoryFreeClear(command);
739✔
1330
    shellWriteHistory();
739✔
1331
    shellExit();
739✔
1332
  } while (0);
1333

1334
  taosThreadCleanupPop(1);
739✔
1335
  return NULL;
739✔
1336
}
1337
#pragma GCC diagnostic pop
1338

1339
TAOS *createConnect(SShellArgs *pArgs) {
1,208,313✔
1340
  char     show[256] = "\0";
1,208,313✔
1341
  char    *host = NULL;
1,208,313✔
1342
  uint16_t port = 0;
1,208,313✔
1343
  char    *user = NULL;
1,208,313✔
1344
  char    *pwd = NULL;
1,208,313✔
1345
  TAOS    *taos = NULL;
1,208,313✔
1346

1347
  // set mode
1348
  if (pArgs->connMode != CONN_MODE_NATIVE && pArgs->dsn) {
1,208,313✔
1349
    // websocket
1350
    memcpy(show, pArgs->dsn, 20);
6,768✔
1351
    memcpy(show + 20, "...", 3);
6,768✔
1352
    memcpy(show + 23, pArgs->dsn + strlen(pArgs->dsn) - 10, 10);
6,768✔
1353

1354
    // connect dsn
1355
    taos = taos_connect_with_dsn(pArgs->dsn);
6,768✔
1356
  } else {
1357
    host = (char *)pArgs->host;
1,201,545✔
1358
    user = (char *)pArgs->user;
1,201,545✔
1359
    pwd = pArgs->password;
1,201,545✔
1360

1361
    if (pArgs->port_inputted) {
1,201,545✔
1362
      port = pArgs->port;
2,006✔
1363
    } else {
1364
      port = defaultPort(pArgs->connMode, pArgs->dsn);
1,199,539✔
1365
    }
1366

1367
    sprintf(show, "host:%s port:%d ", host, port);
1,201,545✔
1368

1369
    // connect normal
1370
    if (pArgs->auth) {
1,201,545✔
1371
      taos = taos_connect_auth(host, user, pArgs->auth, pArgs->database, port);
828✔
1372
    } else {
1373
      taos = taos_connect(host, user, pwd, pArgs->database, port);
1,200,717✔
1374
    }
1375
  }
1376

1377
  return taos;
1,208,313✔
1378
}
1379

1380
int32_t shellExecute(int argc, char *argv[]) {
1,208,313✔
1381
  int32_t code = 0;
1,208,313✔
1382
  printf(shell.info.clientVersion, shell.info.cusName,
2,416,626✔
1383
         workingMode(shell.args.connMode, shell.args.dsn) == CONN_MODE_NATIVE ? STR_NATIVE : STR_WEBSOCKET,
1,208,313✔
1384
         taos_get_client_info(), shell.info.cusName);
1385
  fflush(stdout);
1,208,313✔
1386

1387
  SShellArgs *pArgs = &shell.args;
1,208,313✔
1388
  shell.conn = createConnect(pArgs);
1,208,313✔
1389

1390
  if (shell.conn == NULL) {
1,208,313✔
1391
    printf("failed to connect to server, reason: %s [0x%08X]\n%s", taos_errstr(NULL), taos_errno(NULL),
11,559✔
1392
           ERROR_CODE_DETAIL);
1393
    fflush(stdout);
11,559✔
1394
    return -1;
11,559✔
1395
  }
1396

1397
  bool runOnce = pArgs->commands != NULL || pArgs->file[0] != 0;
1,196,754✔
1398
  shellSetConn(shell.conn, runOnce);
1,196,754✔
1399
  shellReadHistory();
1,196,754✔
1400

1401
  if (shell.args.is_bi_mode) {
1,196,754✔
1402
    // need set bi mode
1403
    printf("Set BI mode is true.\n");
2,246✔
1404
    taos_set_conn_mode(shell.conn, TAOS_CONN_MODE_BI, 1);
2,246✔
1405
  }
1406

1407
  if (runOnce) {
1,196,754✔
1408
    if (pArgs->commands != NULL) {
1,196,015✔
1409
      printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
1,134,380✔
1410
      char *cmd = taosStrdup(pArgs->commands);
1,134,380✔
1411
      shellRunCommand(cmd, true);
1,134,380✔
1412
      taosMemoryFree(cmd);
1,134,380✔
1413
    }
1414

1415
    if (pArgs->file[0] != 0) {
1,196,015✔
1416
      shellSourceFile(pArgs->file);
61,635✔
1417
    }
1418

1419
    taos_close(shell.conn);
1,196,015✔
1420

1421
    shellWriteHistory();
1,196,015✔
1422
    shellCleanupHistory();
1,196,015✔
1423
    return 0;
1,196,015✔
1424
  }
1425

1426
  if ((code = tsem_init(&shell.cancelSem, 0, 0)) != 0) {
739✔
UNCOV
1427
    printf("failed to create cancel semaphore since %s\r\n", tstrerror(code));
×
UNCOV
1428
    return code;
×
1429
  }
1430

1431
  TdThread spid = {0};
739✔
1432
  taosThreadCreate(&spid, NULL, shellCancelHandler, NULL);
739✔
1433

1434
  taosSetSignal(SIGTERM, shellQueryInterruptHandler);
739✔
1435
  taosSetSignal(SIGHUP, shellQueryInterruptHandler);
739✔
1436
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
739✔
1437

1438
  char    buf[512] = {0};
739✔
1439
  int32_t verType = shellGetGrantInfo(buf);
739✔
1440
#ifndef WINDOWS
1441
  printfIntroduction(verType);
739✔
1442
#else
1443
  if (verType == TSDB_VERSION_OSS) {
1444
    showAD(false);
1445
  }
1446
#endif
1447
  // printf version
1448
  if (verType == TSDB_VERSION_ENTERPRISE || verType == TSDB_VERSION_CLOUD) {
739✔
1449
    printf("%s\n", buf);
739✔
1450
  }
1451

1452
  while (1) {
1453
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
739✔
1454
    taosThreadJoin(shell.pid, NULL);
739✔
1455
    taosThreadClear(&shell.pid);
739✔
1456
    if (shell.exit) {
739✔
1457
      tsem_post(&shell.cancelSem);
739✔
1458
      break;
739✔
1459
    }
1460
  }
1461

1462
  if (verType == TSDB_VERSION_OSS) {
739✔
UNCOV
1463
    showAD(true);
×
1464
  }
1465

1466
  taosThreadJoin(spid, NULL);
739✔
1467

1468
  shellCleanupHistory();
739✔
1469
  taos_kill_query(shell.conn);
739✔
1470
  taos_close(shell.conn);
739✔
1471

1472
  TAOS_RETURN(code);
739✔
1473
}
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