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

taosdata / TDengine / #4879

11 Dec 2025 02:43AM UTC coverage: 64.544% (-0.03%) from 64.569%
#4879

push

travis-ci

guanshengliang
feat(TS-7270): internal dependence

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

3883 existing lines in 125 files now uncovered.

163565 of 253417 relevant lines covered (64.54%)

105600506.39 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) {
19,225,901✔
71
  for (char c = *cmd++; c != 0; c = *cmd++) {
19,277,497✔
72
    if (c != ' ' && c != '\t' && c != ';') {
14,082,258✔
73
      return false;
14,030,662✔
74
    }
75
  }
76
  return true;
5,195,239✔
77
}
78

79
int32_t shellRunSingleCommand(char *command) {
12,236,940✔
80
  shellCmdkilled = false;
12,236,940✔
81

82
  if (shellIsEmptyCommand(command)) {
12,236,940✔
83
    return 0;
5,195,239✔
84
  }
85

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

90
  if (shellRegexMatch(command, "^[\t ]*clear[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
7,041,128✔
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,041,128✔
103
                      REG_EXTENDED | REG_ICASE)) {
104
    strtok(command, " \t");
568✔
105
    strtok(NULL, " \t");
568✔
106
    char *p = strtok(NULL, " \t");
568✔
107
    if (strncasecmp(p, "default", 7) == 0) {
568✔
108
      shell.args.displayWidth = SHELL_DEFAULT_MAX_BINARY_DISPLAY_WIDTH;
×
109
    } else {
110
      int32_t displayWidth = atoi(p);
568✔
111
      displayWidth = TRANGE(displayWidth, 1, 10 * 1024);
568✔
112
      shell.args.displayWidth = displayWidth;
568✔
113
    }
114
    return 0;
568✔
115
  }
116

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

136
void shellRecordCommandToHistory(char *command) {
803,085✔
137
  if (strncasecmp(command, "create user ", 12) == 0 || strncasecmp(command, "alter user ", 11) == 0) {
803,085✔
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;
803,085✔
145
  if (pHistory->hstart == pHistory->hend ||
803,085✔
146
      pHistory->hist[(pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE] == NULL ||
568✔
147
      strcmp(command, pHistory->hist[(pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE]) != 0) {
568✔
148
    if (pHistory->hist[pHistory->hend] != NULL) {
803,085✔
149
      taosMemoryFreeClear(pHistory->hist[pHistory->hend]);
×
150
    }
151
    pHistory->hist[pHistory->hend] = taosStrdup(command);
803,085✔
152

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

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

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

173
  if (recordHistory) shellRecordCommandToHistory(command);
6,988,389✔
174

175
  char quote = 0, *cmd = command;
6,988,389✔
176
  for (char c = *command++; c != 0; c = *command++) {
632,256,449✔
177
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
625,268,633✔
178
      command++;
3,404✔
179
      continue;
3,404✔
180
    }
181

182
    if (quote == c) {
625,265,229✔
183
      quote = 0;
2,565,857✔
184
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
622,699,372✔
185
      quote = c;
2,565,857✔
186
    } else if (c == ';' && quote == 0) {
620,133,515✔
187
      c = *command;
5,249,124✔
188
      *command = 0;
5,249,124✔
189
      if (shellRunSingleCommand(cmd) < 0) {
5,249,124✔
190
        return -1;
573✔
191
      }
192
      *command = c;
5,248,551✔
193
      cmd = command;
5,248,551✔
194
    }
195
  }
196
  return shellRunSingleCommand(cmd);
6,987,816✔
197
}
198

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

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

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

214
  p = (char *)pstr + len - 3;
7,032,397✔
215
  if (strcmp(p, "\\G;") == 0) {
7,032,397✔
216
    return p;
55,884✔
217
  }
218

219
  return NULL;
6,976,513✔
220
}
221

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

229
  if ((sptr = strstr(command, ">>")) != NULL) {
7,039,992✔
230
    fname = sptr + 2;
633,146✔
231
    while (*fname == ' ') fname++;
1,265,150✔
232
    *sptr = '\0';
633,146✔
233

234
    cptr = strstr(fname, ";");
633,146✔
235
    if (cptr != NULL) {
633,146✔
236
      *cptr = '\0';
507✔
237
    }
238
  }
239

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

245
  st = taosGetTimestampUs();
7,039,992✔
246

247
  TAOS_RES *pSql = taos_query(shell.conn, command);
7,039,992✔
248
  if (taos_errno(pSql)) {
7,039,992✔
249
    shellPrintError(pSql, st);
2,016,980✔
250
    return;
2,016,980✔
251
  }
252

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

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

259
    taos_free_result(pSql);
11,224✔
260

261
    return;
11,224✔
262
  }
263

264
  // pre string
265
  char *pre = "Query OK";
5,011,788✔
266
  if (shellRegexMatch(command, "^\\s*delete\\s*from\\s*.*", REG_EXTENDED | REG_ICASE)) {
5,011,788✔
267
    pre = "Delete OK";
285✔
268
  } else if (shellRegexMatch(command, "^\\s*insert\\s*into\\s*.*", REG_EXTENDED | REG_ICASE)) {
5,011,503✔
269
    pre = "Insert OK";
9,633✔
270
  } else if (shellRegexMatch(command, "^\\s*create\\s*.*", REG_EXTENDED | REG_ICASE)) {
5,001,870✔
271
    pre = "Create OK";
11,211✔
272
  } else if (shellRegexMatch(command, "^\\s*drop\\s*.*", REG_EXTENDED | REG_ICASE)) {
4,990,659✔
273
    pre = "Drop OK";
15,050✔
274
  }
275

276
  TAOS_FIELD *pFields = taos_fetch_fields(pSql);
5,011,788✔
277
  if (pFields != NULL) {  // select and show kinds of commands
5,011,788✔
278
    int32_t error_no = 0;
3,693,274✔
279

280
    int64_t numOfRows = shellDumpResult(pSql, fname, &error_no, printMode, command);
3,693,274✔
281
    if (numOfRows < 0) return;
3,693,274✔
282

283
    et = taosGetTimestampUs();
3,693,274✔
284
    if (error_no == 0) {
3,693,274✔
285
      printf("Query OK, %" PRId64 " row(s) in set (%.6fs)\r\n", numOfRows, (et - st) / 1E6);
3,693,274✔
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);
3,693,274✔
291
  } else {
292
    int64_t num_rows_affacted = taos_affected_rows64(pSql);
1,318,514✔
293
    taos_free_result(pSql);
1,318,514✔
294
    et = taosGetTimestampUs();
1,318,514✔
295
    printf("%s, %" PRId64 " row(s) affected (%.6fs)\r\n", pre, num_rows_affacted, (et - st) / 1E6);
1,318,514✔
296

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

301
  printf("\r\n");
5,011,788✔
302
}
303

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

310
  time_t  tt;
175,559,940✔
311
  int32_t ms = 0;
175,653,756✔
312
  if (precision == TSDB_TIME_PRECISION_NANO) {
175,653,756✔
313
    tt = (time_t)(val / 1000000000);
5,680✔
314
    ms = val % 1000000000;
5,680✔
315
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
175,648,076✔
316
    tt = (time_t)(val / 1000000);
5,680✔
317
    ms = val % 1000000;
5,680✔
318
  } else {
319
    tt = (time_t)(val / 1000);
175,642,396✔
320
    ms = val % 1000;
175,642,396✔
321
  }
322

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

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

340
  if (precision == TSDB_TIME_PRECISION_NANO) {
175,653,756✔
341
    sprintf(buf + pos, ".%09d", ms);
5,680✔
342
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
175,648,076✔
343
    sprintf(buf + pos, ".%06d", ms);
5,680✔
344
  } else {
345
    sprintf(buf + pos, ".%03d", ms);
175,642,396✔
346
  }
347

348
  return buf;
175,653,756✔
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,007,733,781✔
361
  if (val == NULL) {
1,007,733,781✔
362
    taosFprintfFile(pFile, "NULL");
5,898,353✔
363
    return;
5,898,353✔
364
  }
365

366
  char    quotationStr[2] = {'"', 0};
1,001,835,428✔
367
  int32_t width;
368

369
  int n = 0;
1,001,835,428✔
370
#define LENGTH 64
371
  char buf[LENGTH] = {0};
1,001,835,428✔
372
  switch (field->type) {
1,001,835,428✔
373
    case TSDB_DATA_TYPE_BOOL:
302,606,717✔
374
      taosFprintfFile(pFile, "%d", ((((int32_t)(*((char *)val))) == 1) ? 1 : 0));
302,606,717✔
375
      break;
302,606,717✔
376
    case TSDB_DATA_TYPE_TINYINT:
19,719,989✔
377
      taosFprintfFile(pFile, "%d", *((int8_t *)val));
19,719,989✔
378
      break;
19,719,989✔
379
    case TSDB_DATA_TYPE_UTINYINT:
2,306,587✔
380
      taosFprintfFile(pFile, "%u", *((uint8_t *)val));
2,306,587✔
381
      break;
2,306,587✔
382
    case TSDB_DATA_TYPE_SMALLINT:
780,717✔
383
      taosFprintfFile(pFile, "%d", *((int16_t *)val));
780,717✔
384
      break;
780,717✔
385
    case TSDB_DATA_TYPE_USMALLINT:
1,559,061✔
386
      taosFprintfFile(pFile, "%u", *((uint16_t *)val));
1,559,061✔
387
      break;
1,559,061✔
388
    case TSDB_DATA_TYPE_INT:
46,395,792✔
389
      taosFprintfFile(pFile, "%d", *((int32_t *)val));
46,395,792✔
390
      break;
46,395,792✔
391
    case TSDB_DATA_TYPE_UINT:
1,520,960✔
392
      taosFprintfFile(pFile, "%u", *((uint32_t *)val));
1,520,960✔
393
      break;
1,520,960✔
394
    case TSDB_DATA_TYPE_BIGINT:
104,149,165✔
395
      taosFprintfFile(pFile, "%" PRId64, *((int64_t *)val));
104,149,165✔
396
      break;
104,149,165✔
397
    case TSDB_DATA_TYPE_UBIGINT:
780,717✔
398
      taosFprintfFile(pFile, "%" PRIu64, *((uint64_t *)val));
780,717✔
399
      break;
780,717✔
400
    case TSDB_DATA_TYPE_FLOAT:
19,728,763✔
401
      width = SHELL_FLOAT_WIDTH;
19,728,763✔
402
      if (tsEnableScience) {
19,728,763✔
403
        taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
×
404
      } else {
405
        n = tsnprintf(buf, LENGTH, "%*.7f", width, GET_FLOAT_VAL(val));
19,728,763✔
406
        if (n > SHELL_FLOAT_WIDTH) {
19,728,763✔
407
          taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
540,592✔
408
        } else {
409
          taosFprintfFile(pFile, "%s", buf);
19,188,171✔
410
        }
411
      }
412
      break;
19,728,763✔
413
    case TSDB_DATA_TYPE_DOUBLE:
141,119,564✔
414
      width = SHELL_DOUBLE_WIDTH;
141,119,564✔
415
      if (tsEnableScience) {
141,119,564✔
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));
141,119,564✔
420
        if (n > SHELL_DOUBLE_WIDTH) {
141,119,564✔
421
          taosFprintfFile(pFile, "%*.15e", width, GET_DOUBLE_VAL(val));
108,874,617✔
422
        } else {
423
          taosFprintfFile(pFile, "%s", buf);
32,244,947✔
424
        }
425
      }
426
      break;
141,119,564✔
427
    case TSDB_DATA_TYPE_BINARY:
83,403,110✔
428
    case TSDB_DATA_TYPE_NCHAR:
429
    case TSDB_DATA_TYPE_JSON: {
430
      int32_t bufIndex = 0;
83,403,110✔
431
      char   *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
83,403,110✔
432
      if (tmp == NULL) break;
83,403,110✔
433
      for (int32_t i = 0; i < length; i++) {
1,134,880,052✔
434
        tmp[bufIndex] = val[i];
1,051,476,942✔
435
        bufIndex++;
1,051,476,942✔
436
        if (val[i] == '\"') {
1,051,476,942✔
437
          tmp[bufIndex] = val[i];
×
438
          bufIndex++;
×
439
        }
440
      }
441
      tmp[bufIndex] = 0;
83,403,110✔
442

443
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
83,403,110✔
444
      taosMemoryFree(tmp);
83,403,110✔
445
    } break;
83,403,110✔
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:
58,443,344✔
465
      shellFormatTimestamp(buf, sizeof(buf), *(int64_t *)val, precision);
58,443,344✔
466
      taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
58,443,344✔
467
      break;
58,443,344✔
468
    case TSDB_DATA_TYPE_DECIMAL64:
219,320,942✔
469
    case TSDB_DATA_TYPE_DECIMAL:
470
      taosFprintfFile(pFile, "%s", val);
219,320,942✔
471
      break;
219,320,942✔
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) {
612,093✔
490
  char fullname[PATH_MAX] = {0};
612,093✔
491
  if (taosExpandDir(fname, fullname, PATH_MAX) != 0) {
612,093✔
492
    tstrncpy(fullname, fname, PATH_MAX);
×
493
  }
494

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

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

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

510
  for (int32_t col = 0; col < num_fields; col++) {
1,451,829✔
511
    if (col > 0) {
839,736✔
512
      taosFprintfFile(pFile, ",");
227,643✔
513
    }
514
    taosFprintfFile(pFile, "%s", fields[col].name);
839,736✔
515
  }
516
  taosFprintfFile(pFile, "\r\n");
612,093✔
517

518
  int64_t numOfRows = 0;
612,093✔
519
  do {
520
    int32_t *length = taos_fetch_lengths(tres);
642,657,753✔
521
    for (int32_t i = 0; i < num_fields; i++) {
1,650,391,534✔
522
      if (i > 0) {
1,007,733,781✔
523
        taosFprintfFile(pFile, ",");
365,076,028✔
524
      }
525
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
1,007,733,781✔
526
    }
527
    taosFprintfFile(pFile, "\r\n");
642,657,753✔
528

529
    numOfRows++;
642,657,753✔
530
    row = taos_fetch_row(tres);
642,657,753✔
531
  } while (row != NULL);
642,657,753✔
532

533
  taosCloseFile(&pFile);
612,093✔
534

535
  return numOfRows;
612,093✔
536
}
537

538
void shellPrintNChar(const char *str, int32_t length, int32_t width) {
77,826,326✔
539
  TdWchar tail[3];
77,741,801✔
540
  int32_t pos = 0, cols = 0, totalCols = 0, tailLen = 0;
77,826,326✔
541

542
  while (pos < length) {
1,224,495,821✔
543
    TdWchar wc;
1,146,809,062✔
544
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
1,147,247,038✔
545
    if (bytes <= 0) {
1,147,247,038✔
546
      break;
24,476✔
547
    }
548

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

560
    if (w <= 0) {
1,147,222,562✔
561
      continue;
5,760✔
562
    }
563

564
    if (width <= 0) {
1,147,216,802✔
565
      printf("%lc", wc);
63,735,928✔
566
      continue;
63,735,928✔
567
    }
568

569
    totalCols += w;
1,083,480,874✔
570
    if (totalCols > width) {
1,083,480,874✔
571
      break;
553,067✔
572
    }
573
    if (totalCols <= (width - 3)) {
1,082,927,807✔
574
      printf("%lc", wc);
1,081,207,678✔
575
      cols += w;
1,081,207,678✔
576
    } else {
577
      tail[tailLen] = wc;
1,720,129✔
578
      tailLen++;
1,720,129✔
579
    }
580
  }
581

582
  if (totalCols > width) {
77,826,326✔
583
    // width could be 1 or 2, so printf("...") cannot be used
584
    for (int32_t i = 0; i < 3; i++) {
2,212,268✔
585
      if (cols >= width) {
1,659,201✔
586
        break;
×
587
      }
588
      putchar('.');
1,659,201✔
589
      ++cols;
1,659,201✔
590
    }
591
  } else {
592
    for (int32_t i = 0; i < tailLen; i++) {
77,339,326✔
593
      printf("%lc", tail[i]);
66,067✔
594
    }
595
    cols = totalCols;
77,273,259✔
596
  }
597

598
  for (; cols < width; cols++) {
1,060,058,837✔
599
    putchar(' ');
982,232,511✔
600
  }
601
}
77,826,326✔
602

603
void shellPrintString(const char *str, int32_t width) {
257,464,367✔
604
  int32_t len = strlen(str);
257,464,367✔
605

606
  if (width == 0) {
257,464,367✔
607
    printf("%s", str);
×
608
  } else if (len > width) {
257,464,367✔
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, "");
257,464,367✔
616
  }
617
}
257,464,367✔
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) {
787,130,409✔
646
  if (val == NULL) {
787,130,409✔
647
    shellPrintString(TSDB_DATA_NULL_STR, width);
211,542,933✔
648
    return;
211,542,933✔
649
  }
650

651
  int n = 0;
575,587,476✔
652
#define LENGTH 64
653
  char buf[LENGTH] = {0};
575,587,476✔
654
  switch (field->type) {
575,587,476✔
655
    case TSDB_DATA_TYPE_BOOL:
45,921,434✔
656
      shellPrintString(((((int32_t)(*((char *)val))) == TSDB_FALSE) ? "false" : "true"), width);
45,921,434✔
657
      break;
45,921,434✔
658
    case TSDB_DATA_TYPE_TINYINT:
17,193,844✔
659
      printf("%*d", width, *((int8_t *)val));
17,193,844✔
660
      break;
17,193,844✔
661
    case TSDB_DATA_TYPE_UTINYINT:
26,778,326✔
662
      printf("%*u", width, *((uint8_t *)val));
26,778,326✔
663
      break;
26,778,326✔
664
    case TSDB_DATA_TYPE_SMALLINT:
12,109,666✔
665
      printf("%*d", width, *((int16_t *)val));
12,109,666✔
666
      break;
12,109,666✔
667
    case TSDB_DATA_TYPE_USMALLINT:
33,564,337✔
668
      printf("%*u", width, *((uint16_t *)val));
33,564,337✔
669
      break;
33,564,337✔
670
    case TSDB_DATA_TYPE_INT:
29,843,899✔
671
      printf("%*d", width, *((int32_t *)val));
29,843,899✔
672
      break;
29,843,899✔
673
    case TSDB_DATA_TYPE_UINT:
24,921,161✔
674
      printf("%*u", width, *((uint32_t *)val));
24,921,161✔
675
      break;
24,921,161✔
676
    case TSDB_DATA_TYPE_BIGINT:
86,327,673✔
677
      printf("%*" PRId64, width, taosGetInt64Aligned((int64_t *)val));
86,327,673✔
678
      break;
86,327,673✔
679
    case TSDB_DATA_TYPE_UBIGINT:
33,888,571✔
680
      printf("%*" PRIu64, width, taosGetUInt64Aligned((uint64_t *)val));
33,888,571✔
681
      break;
33,888,571✔
682
    case TSDB_DATA_TYPE_FLOAT:
13,561,157✔
683
      width = width >= LENGTH ? LENGTH - 1 : width;
13,561,157✔
684
      if (tsEnableScience) {
13,561,157✔
685
        printf("%*.7e", width, taosGetFloatAligned((float *)val));
×
686
      } else {
687
        snprintf(buf, LENGTH, "%*.*g", width, FLT_DIG, taosGetFloatAligned((float *)val));
13,561,157✔
688
        printf("%s", buf);
13,561,157✔
689
      }
690
      break;
13,561,157✔
691
    case TSDB_DATA_TYPE_DOUBLE:
56,440,095✔
692
      width = width >= LENGTH ? LENGTH - 1 : width;
56,440,095✔
693
      if (tsEnableScience) {
56,440,095✔
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));
56,440,095✔
698
        printf("%*s", width, buf);
56,440,095✔
699
      }
700
      break;
56,440,095✔
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:
77,826,326✔
712
    case TSDB_DATA_TYPE_NCHAR:
713
    case TSDB_DATA_TYPE_JSON:
714
      shellPrintNChar(val, length, width);
77,826,326✔
715
      break;
77,826,326✔
716
    case TSDB_DATA_TYPE_GEOMETRY:
×
717
      shellPrintGeometry(val, length, width);
×
718
      break;
×
719
    case TSDB_DATA_TYPE_TIMESTAMP:
117,210,412✔
720
      shellFormatTimestamp(buf, sizeof(buf), taosGetInt64Aligned((int64_t *)val), precision);
117,210,412✔
721
      printf("%s", buf);
117,210,412✔
722
      break;
117,210,412✔
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:
575✔
736
    case TSDB_DATA_TYPE_DECIMAL64:
737
      printf("%*s", width, val);
575✔
738
    default:
575✔
739
      break;
575✔
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,081,181✔
779
  dump_info->sql = sql;
3,081,181✔
780
  dump_info->vertical = vertical;
3,081,181✔
781
  tsem_init(&dump_info->sem, 0, 0);
3,081,181✔
782
  dump_info->numOfAllRows = 0;
3,081,181✔
783

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

788
  dump_info->resShowMaxNum = UINT64_MAX;
3,081,181✔
789

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

794
  if (vertical) {
3,081,181✔
795
    dump_info->maxColNameLen = 0;
63,479✔
796
    for (int32_t col = 0; col < dump_info->numFields; col++) {
139,674✔
797
      int32_t len = (int32_t)strlen(dump_info->fields[col].name);
76,195✔
798
      if (len > dump_info->maxColNameLen) {
76,195✔
799
        dump_info->maxColNameLen = len;
67,413✔
800
      }
801
    }
802
  } else {
803
    for (int32_t col = 0; col < dump_info->numFields; col++) {
12,226,001✔
804
      dump_info->width[col] = shellCalcColWidth(dump_info->fields + col, dump_info->precision);
9,208,299✔
805
    }
806
  }
807
}
3,081,181✔
808

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

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

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

822
    int32_t *length = taos_fetch_lengths(tres);
1,117,236✔
823

824
    for (int32_t i = 0; i < dump_info->numFields; i++) {
2,278,007✔
825
      TAOS_FIELD *field = dump_info->fields + i;
1,160,771✔
826

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

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

835
    numOfPintRows++;
1,117,236✔
836
    numOfPrintRowsThisOne++;
1,117,236✔
837

838
    if (numOfPintRows == dump_info->resShowMaxNum) {
1,117,236✔
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,117,236✔
850
      return;
63,479✔
851
    }
852

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

858
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
9,208,299✔
859
  int32_t width = (int32_t)strlen(field->name);
9,208,299✔
860

861
  switch (field->type) {
9,208,299✔
862
    case TSDB_DATA_TYPE_NULL:
×
863
      return TMAX(4, width);  // null
×
864
    case TSDB_DATA_TYPE_BOOL:
448,310✔
865
      return TMAX(5, width);  // 'false'
448,310✔
866

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

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

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

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

883
    case TSDB_DATA_TYPE_FLOAT:
378,930✔
884
      return TMAX(SHELL_FLOAT_WIDTH, width);
378,930✔
885

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

889
    case TSDB_DATA_TYPE_BINARY:
1,342,918✔
890
    case TSDB_DATA_TYPE_GEOMETRY:
891
      if (field->bytes > shell.args.displayWidth) {
1,342,918✔
892
        return TMAX(shell.args.displayWidth, width);
689,012✔
893
      } else {
894
        return TMAX(field->bytes + 2, width);
653,906✔
895
      }
896
    case TSDB_DATA_TYPE_VARBINARY: {
3,458✔
897
      int32_t bytes = field->bytes * 2 + 2;
3,458✔
898
      if (bytes > shell.args.displayWidth) {
3,458✔
899
        return TMAX(shell.args.displayWidth, width);
×
900
      } else {
901
        return TMAX(bytes + 2, width);
3,458✔
902
      }
903
    }
904
    case TSDB_DATA_TYPE_NCHAR:
666,229✔
905
    case TSDB_DATA_TYPE_JSON: {
906
      uint16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
666,229✔
907
      if (bytes > shell.args.displayWidth) {
666,229✔
908
        return TMAX(shell.args.displayWidth, width);
666,229✔
909
      } else {
910
        return TMAX(bytes + 2, width);
×
911
      }
912
    }
913

914
    case TSDB_DATA_TYPE_TIMESTAMP:
1,211,160✔
915
      if (shell.args.is_raw_time) {
1,211,160✔
916
        return TMAX(14, width);
864✔
917
      }
918
      if (precision == TSDB_TIME_PRECISION_NANO) {
1,210,296✔
919
        return TMAX(29, width);
568✔
920
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
1,209,728✔
921
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
568✔
922
      } else {
923
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
1,209,160✔
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:
288✔
936
      return TMAX(width, 20);
288✔
937
    case TSDB_DATA_TYPE_DECIMAL:
287✔
938
      return TMAX(width, 40);
287✔
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) {
2,831,094✔
947
  int32_t rowWidth = 0;
2,831,094✔
948
  for (int32_t col = 0; col < num_fields; col++) {
10,645,872✔
949
    TAOS_FIELD *field = fields + col;
7,814,778✔
950
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
7,814,778✔
951
    int32_t     left = padding / 2;
7,814,778✔
952
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
7,814,778✔
953
    rowWidth += width[col] + 3;
7,814,778✔
954
  }
955

956
  putchar('\r');
2,831,094✔
957
  putchar('\n');
2,831,094✔
958
  for (int32_t i = 0; i < rowWidth; i++) {
203,884,313✔
959
    putchar('=');
201,053,219✔
960
  }
961
  putchar('\r');
2,831,094✔
962
  putchar('\n');
2,831,094✔
963
}
2,831,094✔
964

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

972
  int64_t numOfPintRows = dump_info->numOfAllRows;
2,856,925✔
973
  int     numOfPrintRowsThisOne = 0;
2,856,925✔
974
  if (numOfPintRows == 0) {
2,856,925✔
975
    shellPrintHeader(dump_info->fields, dump_info->width, dump_info->numFields);
2,831,094✔
976
  }
977

978
  while (row != NULL) {
122,901,645✔
979
    int32_t *length = taos_fetch_lengths(tres);
122,901,645✔
980
    for (int32_t i = 0; i < dump_info->numFields; i++) {
908,871,283✔
981
      putchar(' ');
785,969,638✔
982
      shellPrintField((const char *)row[i], dump_info->fields + i, dump_info->width[i], length[i],
785,969,638✔
983
                      dump_info->precision);
984
      putchar(' ');
785,969,638✔
985
      putchar('|');
785,969,638✔
986
    }
987
    putchar('\r');
122,901,645✔
988
    putchar('\n');
122,901,645✔
989

990
    numOfPintRows++;
122,901,645✔
991
    numOfPrintRowsThisOne++;
122,901,645✔
992

993
    if (numOfPintRows == dump_info->resShowMaxNum) {
122,901,645✔
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) {
122,901,645✔
1009
      return;
2,856,925✔
1010
    }
1011

1012
    row = taos_fetch_row(tres);
120,044,720✔
1013
  }
1014
  return;
×
1015
}
1016

1017
void shellDumpResultCallback(void *param, TAOS_RES *tres, int num_of_rows) {
6,001,585✔
1018
  tsDumpInfo *dump_info = (tsDumpInfo *)param;
6,001,585✔
1019
  if (num_of_rows > 0) {
6,001,585✔
1020
    dump_info->numOfRows = num_of_rows;
2,920,404✔
1021
    if (dump_info->numOfAllRows < dump_info->resShowMaxNum) {
2,920,404✔
1022
      if (dump_info->vertical) {
2,920,404✔
1023
        shellVerticalPrintResult(tres, dump_info);
63,479✔
1024
      } else {
1025
        shellHorizontalPrintResult(tres, dump_info);
2,856,925✔
1026
      }
1027
    }
1028
    dump_info->numOfAllRows += num_of_rows;
2,920,404✔
1029
    if (!shellCmdkilled) {
2,920,404✔
1030
      taos_fetch_rows_a(tres, shellDumpResultCallback, param);
2,920,404✔
1031
    } else {
1032
      tsem_post(&dump_info->sem);
×
1033
    }
1034
  } else {
1035
    if (num_of_rows < 0) {
3,081,181✔
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,081,181✔
1039
  }
1040
}
6,000,435✔
1041

1042
int64_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
3,693,274✔
1043
  int64_t num_of_rows = 0;
3,693,274✔
1044
  if (fname != NULL) {
3,693,274✔
1045
    num_of_rows = shellDumpResultToFile(fname, tres);
612,093✔
1046
  } else {
1047
    tsDumpInfo dump_info;
3,066,758✔
1048
    if (!shellCmdkilled) {
3,081,181✔
1049
      init_dump_info(&dump_info, tres, sql, vertical);
3,081,181✔
1050
      taos_fetch_rows_a(tres, shellDumpResultCallback, &dump_info);
3,081,181✔
1051
      tsem_wait(&dump_info.sem);
3,081,181✔
1052
      num_of_rows = dump_info.numOfAllRows;
3,081,181✔
1053
    }
1054
  }
1055

1056
  *error_no = shellCmdkilled ? TSDB_CODE_TSC_QUERY_KILLED : taos_errno(tres);
3,693,274✔
1057
  return num_of_rows;
3,693,274✔
1058
}
1059

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

1065
  char   *line = taosMemoryMalloc(tsMaxSQLLength + 1);
775,849✔
1066
  int32_t read_size = 0;
775,849✔
1067
  while ((read_size = taosGetsFile(pFile, tsMaxSQLLength, line)) > 0) {
163,078,440✔
1068
    line[read_size - 1] = '\0';
162,302,591✔
1069
    taosMemoryFree(pHistory->hist[pHistory->hend]);
162,302,591✔
1070
    pHistory->hist[pHistory->hend] = taosStrdup(line);
162,302,591✔
1071

1072
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
162,302,591✔
1073

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

1079
  taosMemoryFreeClear(line);
775,849✔
1080
  taosCloseFile(&pFile);
775,849✔
1081
  int64_t file_size;
746,143✔
1082
  if (taosStatFile(pHistory->file, &file_size, NULL, NULL) == 0 && file_size > SHELL_MAX_COMMAND_SIZE) {
775,849✔
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;
775,849✔
1100
}
1101

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

1108
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
1,605,602✔
1109
    if (pHistory->hist[i] != NULL) {
803,085✔
1110
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
803,085✔
1111
      taosMemoryFree(pHistory->hist[i]);
803,085✔
1112
      pHistory->hist[i] = NULL;
803,085✔
1113
    }
1114
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
803,085✔
1115
  }
1116
  taosCloseFile(&pFile);
802,517✔
1117
}
1118

1119
void shellCleanupHistory() {
803,089✔
1120
  SShellHistory *pHistory = &shell.history;
803,089✔
1121
  for (int32_t i = 0; i < SHELL_MAX_HISTORY_SIZE; ++i) {
803,892,089✔
1122
    if (pHistory->hist[i] != NULL) {
803,089,000✔
1123
      taosMemoryFree(pHistory->hist[i]);
162,302,591✔
1124
      pHistory->hist[i] = NULL;
162,302,591✔
1125
    }
1126
  }
1127
}
803,089✔
1128

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

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

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

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

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

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

1161
  char *line = taosMemoryMalloc(tsMaxSQLLength + 1);
49,811✔
1162
  while ((read_len = taosGetsFile(pFile, tsMaxSQLLength, line)) > 0) {
6,414,218✔
1163
    if (cmd_len + read_len >= tsMaxSQLLength) {
6,364,407✔
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,364,407✔
1171

1172
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
6,364,407✔
1173
      continue;
119,976✔
1174
    }
1175

1176
    if (line[read_len - 1] == '\\') {
6,244,431✔
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,244,431✔
1184
      line[read_len - 1] = ' ';
×
1185
    }
1186

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

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

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

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

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

1210
  int32_t code = taos_errno(tres);
730✔
1211
  if (code != TSDB_CODE_SUCCESS) {
730✔
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);
730✔
1221
  if (num_fields == 0) {
730✔
1222
    fprintf(stderr, "\r\nInvalid grant information.\r\n");
×
1223
    exit(0);
×
1224
  } else {
1225
    if (tres == NULL) {
730✔
1226
      fprintf(stderr, "\r\nGrant information is null.\r\n");
×
1227
      exit(0);
×
1228
    }
1229

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

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

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

1246
    if (strcmp(serverVersion, "community") == 0) {
730✔
1247
      verType = TSDB_VERSION_OSS;
×
1248
    } else if (strcmp(expiretime, "unlimited") == 0) {
730✔
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;
730✔
1253
      sprintf(buf, "Server is %s %s. License will expire at %s.\r\n", serverVersion, sinfo, expiretime);
730✔
1254
    }
1255

1256
    taos_free_result(tres);
730✔
1257
  }
1258

1259
  fprintf(stdout, "\r\n");
730✔
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;
730✔
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,314✔
1274
#endif
1275

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

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

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

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

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

1300
  return NULL;
730✔
1301
}
1302

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

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

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

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

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

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

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

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

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

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

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

1361
    if (pArgs->port_inputted) {
808,049✔
1362
      port = pArgs->port;
2,005✔
1363
    } else {
1364
      port = defaultPort(pArgs->connMode, pArgs->dsn);
806,044✔
1365
    }
1366

1367
    sprintf(show, "host:%s port:%d ", host, port);
808,049✔
1368

1369
    // connect normal
1370
    if (pArgs->auth) {
808,049✔
1371
      taos = taos_connect_auth(host, user, pArgs->auth, pArgs->database, port);
836✔
1372
    } else {
1373
      taos = taos_connect(host, user, pwd, pArgs->database, port);
807,213✔
1374
    }
1375
  }
1376

1377
  return taos;
814,870✔
1378
}
1379

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

1387
  SShellArgs *pArgs = &shell.args;
814,870✔
1388
  shell.conn = createConnect(pArgs);
814,870✔
1389

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

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

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

1407
  if (runOnce) {
803,089✔
1408
    if (pArgs->commands != NULL) {
802,359✔
1409
      printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
743,800✔
1410
      char *cmd = taosStrdup(pArgs->commands);
743,800✔
1411
      shellRunCommand(cmd, true);
743,800✔
1412
      taosMemoryFree(cmd);
743,800✔
1413
    }
1414

1415
    if (pArgs->file[0] != 0) {
802,359✔
1416
      shellSourceFile(pArgs->file);
58,559✔
1417
    }
1418

1419
    taos_close(shell.conn);
802,359✔
1420

1421
    shellWriteHistory();
802,359✔
1422
    shellCleanupHistory();
802,359✔
1423
    return 0;
802,359✔
1424
  }
1425

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

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

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

1438
  char    buf[512] = {0};
730✔
1439
  int32_t verType = shellGetGrantInfo(buf);
730✔
1440
#ifndef WINDOWS
1441
  printfIntroduction(verType);
730✔
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) {
730✔
1449
    printf("%s\n", buf);
730✔
1450
  }
1451

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

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

1466
  taosThreadJoin(spid, NULL);
730✔
1467

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

1472
  TAOS_RETURN(code);
730✔
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