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

taosdata / TDengine / #5138

05 Nov 2026 03:32AM UTC coverage: 73.942% (-0.3%) from 74.268%
#5138

push

travis-ci

jbjia
fix: capture coverage once from per-thread gcda

Per-case lcov walked the shared build tree and kept each case busy for minutes. Pass GCOV_PREFIX into the test container so each thread writes its own counters, then merge and capture after the suite.

373256 of 504798 relevant lines covered (73.94%)

4305711.12 hits per line

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

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

18
#define ALLOW_FORBID_FUNC
19
#define _BSD_SOURCE
20
#define _GNU_SOURCE
21
#define _XOPEN_SOURCE
22
#define _DEFAULT_SOURCE
23
#include "../../inc/pub.h"
24
#include "geosWrapper.h"
25
#include "shellAuto.h"
26
#include "shellInt.h"
27
#include <errno.h>
28
#ifndef WINDOWS
29
#include <sys/stat.h>
30
#endif
31

32
SShellObj shell = {0};
33

34
typedef struct {
35
  const char *sql;
36
  bool        vertical;
37
  tsem_t      sem;
38
  int64_t     numOfRows;  // the num of this batch
39
  int64_t     numOfAllRows;
40

41
  int32_t     numFields;
42
  TAOS_FIELD *fields;
43
  int32_t     precision;
44
  timezone_t  tz;
45

46
  int32_t maxColNameLen;            // for vertical print
47
  int32_t width[TSDB_MAX_COLUMNS];  // for horizontal print
48

49
  uint64_t resShowMaxNum;
50
} tsDumpInfo;
51

52
static bool    shellIsEmptyCommand(const char *cmd);
53
static int32_t shellRunSingleCommand(char *command);
54
static void    shellRecordCommandToHistory(char *command);
55
static int32_t shellRunCommand(char *command, bool recordHistory);
56
static void    shellRunSingleCommandImp(char *command);
57
static char   *shellFormatTimestamp(char *buf, int32_t bufSize, int64_t val, int32_t precision, timezone_t tz);
58
static int64_t shellDumpResultToFile(const char *fname, TAOS_RES *tres);
59
static void    shellPrintNChar(const char *str, int32_t length, int32_t width);
60
static void    shellPrintGeometry(const unsigned char *str, int32_t length, int32_t width);
61
static void    shellVerticalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info);
62
static void    shellHorizontalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info);
63
static int64_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql);
64
static void    shellReadHistory();
65
static void    shellWriteHistory();
66
static TdFilePtr shellOpenHistoryFile(const char *path, int32_t tdFileOptions);
67
static void    shellPrintError(TAOS_RES *tres, int64_t st);
68
static bool    shellIsCommentLine(char *line);
69
static void    shellSourceFile(const char *file);
70
static int32_t shellGetGrantInfo(char *buf, int32_t bufSize);
71

72
static void  shellCleanup(void *arg);
73
static void *shellCancelHandler(void *arg);
74
static void *shellThreadLoop(void *arg);
75
static bool  shellHasBinaryNonPrintable(const char *val, int32_t length);
76
static void  shellHexEncode(char *dst, const char *val, int32_t length);
77
static char *shellAllocHexString(const char *val, int32_t length);
78
static void  shellPrintHex(const char *val, int32_t length, int32_t width);
79
void shellPrintString(const char *str, int32_t width);
80

81
bool shellCmdkilled = false;
82

83
bool shellIsEmptyCommand(const char *cmd) {
1,087,991 ✔
84
  for (char c = *cmd++; c != 0; c = *cmd++) {
1,088,014 ✔
85
    if (c != ' ' && c != '\t' && c != ';') {
728,240 ✔
86
      return false;
313,337 ✔
87
    }
88
  }
89
  return true;
152,524 ✔
90
}
91

92
int32_t shellRunSingleCommand(char *command) {
724,196 ✔
93
  shellCmdkilled = false;
724,196 ✔
94

95
  if (shellIsEmptyCommand(command)) {
1,138,982 ✔
96
    return 0;
152,443 ✔
97
  }
98

99
  if (shellRegexMatch(command, "^[ \t]*(quit|q|exit)[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
364,507 ✔
100
    return -1;
6 ✔
101
  }
102

103
  if (shellRegexMatch(command, "^[\t ]*clear[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
364,501 ✔
104
#pragma GCC diagnostic push
105
#pragma GCC diagnostic ignored "-Wunused-result"
106
#ifndef TD_ASTRA
107
    (void)system("clear");
×
108
#else
109
    (void)printf("\033[2J\033[H");
110
#endif
111
#pragma GCC diagnostic pop
112
    return 0;
×
113
  }
114

115
  if (shellRegexMatch(command, "^[\t ]*set[ \t]+max_binary_display_width[ \t]+(default|[1-9][0-9]*)[ \t;]*$",
364,501 ✔
116
                      REG_EXTENDED | REG_ICASE)) {
117
    strtok(command, " \t");
26 ✔
118
    strtok(NULL, " \t");
26 ✔
119
    char *p = strtok(NULL, " \t");
26 ✔
120
    if (strncasecmp(p, "default", 7) == 0) {
26 ✔
121
      shell.args.displayWidth = SHELL_DEFAULT_MAX_BINARY_DISPLAY_WIDTH;
×
122
    } else {
123
      int32_t displayWidth = atoi(p);
26 ✔
124
      displayWidth = TRANGE(displayWidth, 1, 10 * 1024);
26 ✔
125
      shell.args.displayWidth = displayWidth;
26 ✔
126
    }
127
    return 0;
26 ✔
128
  }
129

130
  if (shellRegexMatch(command, "^[ \t]*subscribe[ \t;]", REG_EXTENDED | REG_ICASE) ||
728,934 ✔
131
      shellRegexMatch(command, "^[ \t]*subscribe$", REG_EXTENDED | REG_ICASE)) {
364,459 ✔
132
    shellSubscribe(command);
16 ✔
133
    return 0;
16 ✔
134
  }
135

136
  if (shellRegexMatch(command, "^[ \t]*source[\t ]+[^ ]+[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
364,459 ✔
137
    /* If source file. */
138
    char *c_ptr = strtok(command, " ;");
×
139
    if (c_ptr == NULL) {
×
140
      shellRunSingleCommandImp(command);
×
141
      return 0;
×
142
    }
143
    c_ptr = strtok(NULL, " ;");
×
144
    if (c_ptr == NULL) {
×
145
      shellRunSingleCommandImp(command);
×
146
      return 0;
×
147
    }
148
    shellSourceFile(c_ptr);
×
149
    return 0;
×
150
  }
151
  shellRunSingleCommandImp(command);
364,459 ✔
152
  return 0;
364,459 ✔
153
}
154

155
void shellRecordCommandToHistory(char *command) {
2,496 ✔
156
  if (shellStatementHoldsCredential(command)) {
2,496 ✔
157
    // have password command forbid record to history because security
158
    return;
×
159
  }
160

161
  SShellHistory *pHistory = &shell.history;
2,496 ✔
162
  if (pHistory->hstart == pHistory->hend ||
2,496 ✔
163
      pHistory->hist[(pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE] == NULL ||
568 ✔
164
      strcmp(command, pHistory->hist[(pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE]) != 0) {
568 ✔
165
    if (pHistory->hist[pHistory->hend] != NULL) {
2,417 ✔
166
      taosMemoryFreeClear(pHistory->hist[pHistory->hend]);
×
167
    }
168
    pHistory->hist[pHistory->hend] = taosStrdup(command);
2,417 ✔
169

170
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
2,417 ✔
171
    if (pHistory->hend == pHistory->hstart) {
2,417 ✔
172
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
×
173
    }
174
  }
175
}
176

177
int32_t shellRunCommand(char *command, bool recordHistory) {
362,996 ✔
178
  if (shellIsEmptyCommand(command)) {
570,298 ✔
179
    return 0;
×
180
  }
181

182
  // add help or help;
183
  if (strncasecmp(command, "help", 4) == 0) {
362,996 ✔
184
    if (command[4] == ';' || command[4] == ' ' || command[4] == 0) {
×
185
      showHelp();
×
186
      return 0;
×
187
    }
188
  }
189

190
  char quote = 0, *cmd = command;
155,694 ✔
191
  for (char c = *command++; c != 0; c = *command++) {
53,631,515 ✔
192
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
53,268,525 ✔
193
      command++;
2 ✔
194
      continue;
2 ✔
195
    }
196

197
    if (quote == c) {
53,268,523 ✔
198
      quote = 0;
59,116 ✔
199
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
53,204,030 ✔
200
      quote = c;
59,116 ✔
201
    } else if (c == ';' && quote == 0) {
53,139,537 ✔
202
      c = *command;
361,206 ✔
203
      *command = 0;
361,206 ✔
204
      // the credential filter has to see one statement at a time, a credential
205
      // statement hidden behind another statement must not reach the history file
206
      if (recordHistory) shellRecordCommandToHistory(cmd);
361,206 ✔
207
      if (shellRunSingleCommand(cmd) < 0) {
361,206 ✔
208
        return -1;
6 ✔
209
      }
210
      *command = c;
361,200 ✔
211
      cmd = command;
361,200 ✔
212
    }
213
  }
214

215
  // the last statement has already been recorded when the line ends with a ';'
216
  if (recordHistory && !shellIsEmptyCommand(cmd)) {
363,032 ✔
217
    shellRecordCommandToHistory(cmd);
714 ✔
218
  }
219
  return shellRunSingleCommand(cmd);
362,990 ✔
220
}
221

222
char *strendG(const char *pstr) {
364,459 ✔
223
  if (pstr == NULL) {
364,459 ✔
224
    return NULL;
×
225
  }
226

227
  size_t len = strlen(pstr);
364,459 ✔
228
  if (len < 4) {
364,459 ✔
229
    return NULL;
×
230
  }
231

232
  char *p = (char *)pstr + len - 2;
364,459 ✔
233
  if (strcmp(p, "\\G") == 0) {
364,459 ✔
234
    return p;
19 ✔
235
  }
236

237
  p = (char *)pstr + len - 3;
364,440 ✔
238
  if (strcmp(p, "\\G;") == 0) {
364,440 ✔
239
    return p;
426 ✔
240
  }
241

242
  return NULL;
156,507 ✔
243
}
244

245
void shellRunSingleCommandImp(char *command) {
364,459 ✔
246
  int64_t st, et;
207,539 ✔
247
  char   *sptr = NULL;
364,459 ✔
248
  char   *cptr = NULL;
364,459 ✔
249
  char   *fname = NULL;
364,459 ✔
250
  bool    printMode = false;
364,459 ✔
251

252
  if ((sptr = strstr(command, ">>")) != NULL) {
364,459 ✔
253
    fname = sptr + 2;
643 ✔
254
    while (*fname == ' ') fname++;
1,280 ✔
255
    *sptr = '\0';
643 ✔
256

257
    cptr = strstr(fname, ";");
643 ✔
258
    if (cptr != NULL) {
643 ✔
259
      *cptr = '\0';
3 ✔
260
    }
261
  }
262

263
  if ((sptr = strendG(command)) != NULL) {
364,459 ✔
264
    *sptr = '\0';
445 ✔
265
    printMode = true;  // When output to a file, the switch does not work.
445 ✔
266
  }
267

268
  st = taosGetTimestampUs();
364,459 ✔
269

270
  TAOS_RES *pSql = taos_query(shell.conn, command);
364,459 ✔
271
  if (taos_errno(pSql)) {
364,459 ✔
272
    shellPrintError(pSql, st);
178,447 ✔
273
    return;
178,447 ✔
274
  }
275

276
  if (shellRegexMatch(command, "^[[:space:]]*use[[:space:]]+[a-zA-Z0-9_]+[[:space:]]*;?[[:space:]]*$", REG_EXTENDED | REG_ICASE)) {
186,012 ✔
277
    (void)printf("Database changed.\r\n\r\n");
192 ✔
278

279
    // call back auto tab module
280
    callbackAutoTab(command, pSql, true);
192 ✔
281

282
    taos_free_result(pSql);
192 ✔
283

284
    return;
192 ✔
285
  }
286

287
  // pre string
288
  char *pre = "Query OK";
185,820 ✔
289
  if (shellRegexMatch(command, "^[[:space:]]*delete[[:space:]]+from[[:space:]]*.*", REG_EXTENDED | REG_ICASE)) {
185,820 ✔
290
    pre = "Delete OK";
×
291
  } else if (shellRegexMatch(command, "^[[:space:]]*insert[[:space:]]+into[[:space:]]*.*", REG_EXTENDED | REG_ICASE)) {
185,820 ✔
292
    pre = "Insert OK";
1,197 ✔
293
  } else if (shellRegexMatch(command, "^[[:space:]]*create[[:space:]]*.*", REG_EXTENDED | REG_ICASE)) {
184,579 ✔
294
    pre = "Create OK";
136 ✔
295
  } else if (shellRegexMatch(command, "^[[:space:]]*drop[[:space:]]*.*", REG_EXTENDED | REG_ICASE)) {
184,401 ✔
296
    pre = "Drop OK";
72 ✔
297
  }
298

299
  TAOS_FIELD *pFields = taos_fetch_fields(pSql);
185,820 ✔
300
  if (pFields != NULL) {  // select and show kinds of commands
185,820 ✔
301
    int32_t error_no = 0;
182,376 ✔
302

303
    int64_t numOfRows = shellDumpResult(pSql, fname, &error_no, printMode, command);
182,376 ✔
304
    if (numOfRows < 0) {
182,376 ✔
305
      taos_free_result(pSql);
×
306
      return;
×
307
    }
308

309
    et = taosGetTimestampUs();
182,376 ✔
310
    if (error_no == 0) {
182,376 ✔
311
      (void)printf("Query OK, %" PRId64 " row(s) in set (%.6fs)\r\n", numOfRows, (et - st) / 1E6);
182,376 ✔
312
    } else {
313
      (void)printf("Query interrupted (%s), %" PRId64 " row(s) in set (%.6fs)\r\n", tstrerror(error_no), numOfRows,
×
314
             (et - st) / 1E6);
×
315
    }
316
    taos_free_result(pSql);
182,376 ✔
317
  } else {
318
    int64_t num_rows_affacted = taos_affected_rows64(pSql);
3,444 ✔
319
    taos_free_result(pSql);
3,444 ✔
320
    et = taosGetTimestampUs();
3,444 ✔
321
    (void)printf("%s, %" PRId64 " row(s) affected (%.6fs)\r\n", pre, num_rows_affacted, (et - st) / 1E6);
3,444 ✔
322

323
    // call auto tab
324
    callbackAutoTab(command, NULL, false);
3,444 ✔
325
  }
326

327
  (void)printf("\r\n");
185,820 ✔
328
}
329

330
char *shellFormatTimestamp(char *buf, int32_t bufSize, int64_t val, int32_t precision, timezone_t tz) {
3,181,454 ✔
331
  if (shell.args.is_raw_time) {
3,181,454 ✔
332
    (void)sprintf(buf, "%" PRId64, val);
305 ✔
333
    return buf;
305 ✔
334
  }
335

336
  time_t  tt;
3,181,149 ✔
337
  int32_t ms = 0;
3,181,149 ✔
338
  if (precision == TSDB_TIME_PRECISION_NANO) {
3,181,149 ✔
339
    tt = (time_t)(val / 1000000000);
1,662,668 ✔
340
    ms = val % 1000000000;
1,662,668 ✔
341
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
1,518,481 ✔
342
    tt = (time_t)(val / 1000000);
×
343
    ms = val % 1000000;
×
344
  } else {
345
    tt = (time_t)(val / 1000);
1,518,481 ✔
346
    ms = val % 1000;
1,518,481 ✔
347
  }
348

349
  if (tt <= 0 && ms < 0) {
3,181,149 ✔
350
    tt--;
22 ✔
351
    if (precision == TSDB_TIME_PRECISION_NANO) {
22 ✔
352
      ms += 1000000000;
×
353
    } else if (precision == TSDB_TIME_PRECISION_MICRO) {
22 ✔
354
      ms += 1000000;
×
355
    } else {
356
      ms += 1000;
22 ✔
357
    }
358
  }
359

360
  struct tm ptm = {0};
3,181,149 ✔
361
  if (taosLocalTime(&tt, &ptm, buf, bufSize, tz) == NULL) {
3,181,149 ✔
362
    return buf;
×
363
  }
364
  size_t pos = strftime(buf, 35, "%Y-%m-%d %H:%M:%S", &ptm);
3,181,149 ✔
365

366
  if (precision == TSDB_TIME_PRECISION_NANO) {
3,181,149 ✔
367
    (void)sprintf(buf + pos, ".%09d", ms);
1,662,668 ✔
368
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
1,518,481 ✔
369
    (void)sprintf(buf + pos, ".%06d", ms);
×
370
  } else {
371
    (void)sprintf(buf + pos, ".%03d", ms);
1,518,481 ✔
372
  }
373

374
  return buf;
3,173,538 ✔
375
}
376

377
char *shellDumpHexValue(char *buf, const char *val, int32_t length) {
×
378
  for (int32_t i = 0; i < length; i++) {
×
379
    (void)sprintf(buf + (i * 2), "%02X", val[i]);
×
380
  }
381
  buf[length * 2] = 0;
×
382

383
  return buf;
×
384
}
385

386
void shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field,
2,850,134 ✔
387
                          int32_t length, int32_t precision, timezone_t tz) {
388
  if (val == NULL) {
2,850,134 ✔
389
    taosFprintfFile(pFile, "NULL");
22,523 ✔
390
    return;
22,523 ✔
391
  }
392

393
  char    quotationStr[2] = {'"', 0};
2,827,611 ✔
394
  int32_t width;
×
395

396
  int n = 0;
2,827,611 ✔
397
#define LENGTH 64
398
  char buf[LENGTH] = {0};
2,827,611 ✔
399
  switch (field->type) {
2,827,611 ✔
400
    case TSDB_DATA_TYPE_BOOL:
378,144 ✔
401
      taosFprintfFile(pFile, "%d", ((((int32_t)(*((char *)val))) == 1) ? 1 : 0));
378,144 ✔
402
      break;
378,144 ✔
403
    case TSDB_DATA_TYPE_TINYINT:
22,000 ✔
404
      taosFprintfFile(pFile, "%d", *((int8_t *)val));
22,000 ✔
405
      break;
22,000 ✔
406
    case TSDB_DATA_TYPE_UTINYINT:
×
407
      taosFprintfFile(pFile, "%u", *((uint8_t *)val));
×
408
      break;
×
409
    case TSDB_DATA_TYPE_SMALLINT:
×
410
      taosFprintfFile(pFile, "%d", *((int16_t *)val));
×
411
      break;
×
412
    case TSDB_DATA_TYPE_USMALLINT:
×
413
      taosFprintfFile(pFile, "%u", *((uint16_t *)val));
×
414
      break;
×
415
    case TSDB_DATA_TYPE_INT:
419,893 ✔
416
      taosFprintfFile(pFile, "%d", *((int32_t *)val));
419,893 ✔
417
      break;
419,893 ✔
418
    case TSDB_DATA_TYPE_UINT:
×
419
      taosFprintfFile(pFile, "%u", *((uint32_t *)val));
×
420
      break;
×
421
    case TSDB_DATA_TYPE_BIGINT:
317,858 ✔
422
      taosFprintfFile(pFile, "%" PRId64, *((int64_t *)val));
317,858 ✔
423
      break;
317,858 ✔
424
    case TSDB_DATA_TYPE_UBIGINT:
×
425
      taosFprintfFile(pFile, "%" PRIu64, *((uint64_t *)val));
×
426
      break;
×
427
    case TSDB_DATA_TYPE_FLOAT:
22,000 ✔
428
      width = SHELL_FLOAT_WIDTH;
22,000 ✔
429
      if (tsEnableScience) {
22,000 ✔
430
        taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
×
431
      } else {
432
        n = tsnprintf(buf, LENGTH, "%*.7f", width, GET_FLOAT_VAL(val));
22,000 ✔
433
        if (n > SHELL_FLOAT_WIDTH) {
22,000 ✔
434
          taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
×
435
        } else {
436
          taosFprintfFile(pFile, "%s", buf);
22,000 ✔
437
        }
438
      }
439
      break;
22,000 ✔
440
    case TSDB_DATA_TYPE_DOUBLE:
432,044 ✔
441
      width = SHELL_DOUBLE_WIDTH;
432,044 ✔
442
      if (tsEnableScience) {
432,044 ✔
443
        (void)snprintf(buf, LENGTH, "%*.15e", width, GET_DOUBLE_VAL(val));
×
444
        taosFprintfFile(pFile, "%s", buf);
×
445
      } else {
446
        n = tsnprintf(buf, LENGTH, "%*.15f", width, GET_DOUBLE_VAL(val));
432,044 ✔
447
        if (n > SHELL_DOUBLE_WIDTH) {
432,044 ✔
448
          taosFprintfFile(pFile, "%*.15e", width, GET_DOUBLE_VAL(val));
152,099 ✔
449
        } else {
450
          taosFprintfFile(pFile, "%s", buf);
279,945 ✔
451
        }
452
      }
453
      break;
432,044 ✔
454
    case TSDB_DATA_TYPE_BINARY:
382,812 ✔
455
      if (shell.args.is_binary_as_hex && shellHasBinaryNonPrintable(val, length)) {
382,812 ✔
456
        char *tmp = shellAllocHexString(val, length);
4 ✔
457
        if (tmp == NULL) break;
4 ✔
458
        taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
4 ✔
459
        taosMemoryFree(tmp);
4 ✔
460
        break;
4 ✔
461
      }
462
      /* falls through */ // printable binary handled as NCHAR/JSON
463
    case TSDB_DATA_TYPE_NCHAR:
464
    case TSDB_DATA_TYPE_JSON: {
465
      int32_t bufIndex = 0;
622,808 ✔
466
      char   *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
622,808 ✔
467
      if (tmp == NULL) break;
622,808 ✔
468
      for (int32_t i = 0; i < length; i++) {
6,556,425 ✔
469
        tmp[bufIndex] = val[i];
5,933,617 ✔
470
        bufIndex++;
5,933,617 ✔
471
        if (val[i] == '\"') {
5,933,617 ✔
472
          tmp[bufIndex] = val[i];
×
473
          bufIndex++;
×
474
        }
475
      }
476
      tmp[bufIndex] = 0;
622,808 ✔
477

478
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
622,808 ✔
479
      taosMemoryFree(tmp);
622,808 ✔
480
    } break;
622,808 ✔
481
    case TSDB_DATA_TYPE_VARBINARY: {
×
482
      void    *tmp = NULL;
×
483
      uint32_t size = 0;
×
484
      if (taosAscii2Hex(val, length, &tmp, &size) < 0) {
×
485
        break;
×
486
      }
487
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
×
488
      taosMemoryFree(tmp);
×
489
      break;
×
490
    }
491
    case TSDB_DATA_TYPE_GEOMETRY: {
×
492
      char *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
×
493
      if (tmp == NULL) break;
×
494
      shellDumpHexValue(tmp, val, length);
×
495
      taosFprintfFile(pFile, "%s", buf);
×
496
      taosMemoryFree(tmp);
×
497
      break;
×
498
    }
499
    case TSDB_DATA_TYPE_TIMESTAMP:
419,968 ✔
500
      shellFormatTimestamp(buf, sizeof(buf), *(int64_t *)val, precision, tz);
419,968 ✔
501
      taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
419,968 ✔
502
      break;
419,968 ✔
503
    case TSDB_DATA_TYPE_DECIMAL64:
192,892 ✔
504
    case TSDB_DATA_TYPE_DECIMAL:
505
      taosFprintfFile(pFile, "%s", val);
192,892 ✔
506
      break;
192,892 ✔
507
    case TSDB_DATA_TYPE_BLOB:
×
508
    case TSDB_DATA_TYPE_MEDIUMBLOB: {
509
      void    *tmp = NULL;
×
510
      uint32_t size = 0;
×
511
      if (taosAscii2Hex(val, length, &tmp, &size) < 0) {
×
512
        break;
×
513
      }
514
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
×
515
      taosMemoryFree(tmp);
×
516

517
      break;
×
518
    }
519
    default:
×
520
      break;
×
521
  }
522
}
523

524
int64_t shellDumpResultToFile(const char *fname, TAOS_RES *tres) {
635 ✔
525
  char fullname[PATH_MAX] = {0};
635 ✔
526
  if (taosExpandDir(fname, fullname, PATH_MAX) != 0) {
635 ✔
527
    tstrncpy(fullname, fname, PATH_MAX);
×
528
  }
529

530
  TAOS_ROW row = taos_fetch_row(tres);
635 ✔
531
  if (row == NULL) {
635 ✔
532
    return 0;
×
533
  }
534

535
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_TRUNC | TD_FILE_STREAM);
635 ✔
536
  if (pFile == NULL) {
635 ✔
537
    (void)fprintf(stderr, "failed to open file: %s\r\n", fullname);
×
538
    return -1;
×
539
  }
540

541
  TAOS_FIELD *fields = taos_fetch_fields(tres);
635 ✔
542
  int32_t     num_fields = taos_num_fields(tres);
635 ✔
543
  int32_t     precision = taos_result_precision(tres);
635 ✔
544
  timezone_t  tz = (timezone_t)taos_get_result_tz(tres);
635 ✔
545

546
  for (int32_t col = 0; col < num_fields; col++) {
1,629 ✔
547
    if (col > 0) {
994 ✔
548
      taosFprintfFile(pFile, ",");
359 ✔
549
    }
550
    taosFprintfFile(pFile, "%s", fields[col].name);
994 ✔
551
  }
552
  taosFprintfFile(pFile, "\r\n");
635 ✔
553

554
  int64_t numOfRows = 0;
635 ✔
555
  do {
×
556
    int32_t *length = taos_fetch_lengths(tres);
857,983 ✔
557
    for (int32_t i = 0; i < num_fields; i++) {
3,708,117 ✔
558
      if (i > 0) {
2,850,134 ✔
559
        taosFprintfFile(pFile, ",");
1,992,151 ✔
560
      }
561
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision, tz);
2,850,134 ✔
562
    }
563
    taosFprintfFile(pFile, "\r\n");
857,983 ✔
564

565
    numOfRows++;
857,983 ✔
566
    row = taos_fetch_row(tres);
857,983 ✔
567
  } while (row != NULL);
857,983 ✔
568

569
  taosCloseFile(&pFile);
635 ✔
570

571
  return numOfRows;
635 ✔
572
}
573

574
// Shared non-printable detection for binary-ish display decisions. allowWhitespace
575
// tolerates the whitespace chars that occur in display text (SHOW CREATE of virtual
576
// super tables embeds '\n' between clauses); any other control byte or invalid
577
// multibyte sequence still reports non-printable (callers route such values to hex).
578
static bool shellHasNonPrintableImpl(const char *val, int32_t length, bool allowWhitespace) {
30 ✔
579
  for (int32_t i = 0; i < length; i++) {
51 ✔
580
    unsigned char c = (unsigned char)val[i];
35 ✔
581

582
    if (c == 0x7F || (c < 0x20 && !(allowWhitespace && (c == '\n' || c == '\r' || c == '\t')))) {
35 ✔
583
      return true;
14 ✔
584
    }
585
  }
586

587
  int32_t pos = 0;
16 ✔
588
  while (pos < length) {
25 ✔
589
    TdWchar wc;
19 ✔
590
    int32_t remain = length - pos;
19 ✔
591
    int32_t bytes = taosMbToWchar(&wc, val + pos, TMIN(MB_CUR_MAX, remain));
19 ✔
592
    if (bytes <= 0) {
19 ✔
593
      return true;
10 ✔
594
    }
595

596
    if (wc == 0x7F || (wc >= 0x80 && wc <= 0x9F)) {
9 ✔
597
      return true;
×
598
    }
599

600
    // wcwidth() returns -1 for control chars, including the whitespace bytes that
601
    // allowWhitespace exempts — skip those here too, mirroring shellPrintNChar
602
    // (which special-cases '\t'/'\n'/'\r' before taking the width), or DDL text
603
    // embedding '\n' would still be routed to hex output.
604
    if (taosWcharWidth(wc) <= 0 && !(allowWhitespace && (wc == '\n' || wc == '\r' || wc == '\t'))) {
9 ✔
605
      return true;
×
606
    }
607

608
    pos += bytes;
9 ✔
609
  }
610

611
  return false;
6 ✔
612
}
613

614
static bool shellHasBinaryNonPrintable(const char *val, int32_t length) {
30 ✔
615
  return shellHasNonPrintableImpl(val, length, false);
30 ✔
616
}
617

618
// BLOB values may hold display text (e.g. the DDL of SHOW CREATE TABLE, which may
619
// embed '\n'): tolerate whitespace, everything else keeps the hex representation.
620
static bool shellBlobHasNonPrintable(const char *val, int32_t length) {
×
621
  return shellHasNonPrintableImpl(val, length, true);
×
622
}
623

624
static void shellHexEncode(char *dst, const char *val, int32_t length) {
24 ✔
625
  static const char hexMap[] = "0123456789ABCDEF";
×
626

627
  for (int32_t i = 0; i < length; i++) {
59 ✔
628
    unsigned char c = (unsigned char)val[i];
35 ✔
629
    dst[i * 2] = hexMap[c >> 4];
35 ✔
630
    dst[i * 2 + 1] = hexMap[c & 0x0F];
35 ✔
631
  }
632

633
  dst[length * 2] = 0;
24 ✔
634
}
24 ✔
635

636
static char *shellAllocHexString(const char *val, int32_t length) {
24 ✔
637
  int32_t hexLen = 2 + length * 2;
24 ✔
638
  char   *hexBuf = (char *)taosMemoryCalloc(1, hexLen + 1);
24 ✔
639
  if (hexBuf == NULL) {
24 ✔
640
    return NULL;
×
641
  }
642

643
  hexBuf[0] = '0';
24 ✔
644
  hexBuf[1] = 'x';
24 ✔
645
  shellHexEncode(hexBuf + 2, val, length);
24 ✔
646
  return hexBuf;
24 ✔
647
}
648

649
static void shellPrintHex(const char *val, int32_t length, int32_t width) {
20 ✔
650
  char *hexBuf = shellAllocHexString(val, length);
20 ✔
651
  if (hexBuf == NULL) return;
20 ✔
652

653
  shellPrintString(hexBuf, width > 0 ? width : 0);
20 ✔
654

655
  taosMemoryFree(hexBuf);
20 ✔
656
}
657

658
void shellPrintNChar(const char *str, int32_t length, int32_t width) {
1,910,532 ✔
659
  TdWchar tail[3];
1,910,532 ✔
660
  int32_t pos = 0, cols = 0, totalCols = 0, tailLen = 0;
1,910,532 ✔
661

662
  while (pos < length) {
27,318,605 ✔
663
    TdWchar wc;
25,413,278 ✔
664
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
25,413,278 ✔
665
    if (bytes <= 0) {
25,413,278 ✔
666
      break;
1,151 ✔
667
    }
668

669
    if (pos + bytes > length) {
25,412,127 ✔
670
      break;
×
671
    }
672
    int w = 0;
25,412,127 ✔
673
    if (*(str + pos) == '\t' || *(str + pos) == '\n' || *(str + pos) == '\r') {
25,412,127 ✔
674
      w = bytes;
×
675
    } else {
676
      w = taosWcharWidth(wc);
25,412,127 ✔
677
    }
678
    pos += bytes;
25,412,127 ✔
679

680
    if (w <= 0) {
25,412,127 ✔
681
      continue;
64,019 ✔
682
    }
683

684
    if (width <= 0) {
25,411,766 ✔
685
      (void)printf("%lc", wc);
659,988 ✔
686
      continue;
659,988 ✔
687
    }
688

689
    totalCols += w;
24,751,778 ✔
690
    if (totalCols > width) {
24,751,778 ✔
691
      break;
4,054 ✔
692
    }
693
    if (totalCols <= (width - 3)) {
24,747,724 ✔
694
      (void)printf("%lc", wc);
24,732,301 ✔
695
      cols += w;
24,732,301 ✔
696
    } else {
697
      tail[tailLen] = wc;
15,423 ✔
698
      tailLen++;
15,423 ✔
699
    }
700
  }
701

702
  if (totalCols > width) {
1,910,532 ✔
703
    // width could be 1 or 2, so printf("...") cannot be used
704
    for (int32_t i = 0; i < 3; i++) {
16,216 ✔
705
      if (cols >= width) {
12,162 ✔
706
        break;
×
707
      }
708
      putchar('.');
12,162 ✔
709
      ++cols;
12,162 ✔
710
    }
711
  } else {
712
    for (int32_t i = 0; i < tailLen; i++) {
1,909,748 ✔
713
      (void)printf("%lc", tail[i]);
3,270 ✔
714
    }
715
    cols = totalCols;
1,888,968 ✔
716
  }
717

718
  for (; cols < width; cols++) {
34,614,639 ✔
719
    putchar(' ');
32,704,107 ✔
720
  }
721
}
1,910,532 ✔
722

723
void shellPrintString(const char *str, int32_t width) {
5,312,172 ✔
724
  int32_t len = strlen(str);
5,312,172 ✔
725

726
  if (width == 0) {
5,312,172 ✔
727
    (void)printf("%s", str);
×
728
  } else if (len > width) {
5,312,172 ✔
729
    if (width <= 3) {
30 ✔
730
      (void)printf("%.*s.", width - 1, str);
30 ✔
731
    } else {
732
      (void)printf("%.*s...", width - 3, str);
×
733
    }
734
  } else {
735
    (void)printf("%s%*.s", str, width - len, "");
5,312,142 ✔
736
  }
737
}
5,312,172 ✔
738

739
void shellPrintGeometry(const unsigned char *val, int32_t length, int32_t width) {
×
740
  if (length == 0) {  // empty value
×
741
    shellPrintString("", width);
×
742
    return;
×
743
  }
744

745
  int32_t code = TSDB_CODE_FAILED;
×
746

747
  code = initCtxAsText();
×
748
  if (code != TSDB_CODE_SUCCESS) {
×
749
    shellPrintString(getGeosErrMsg(code), width);
×
750
    return;
×
751
  }
752

753
  char *outputWKT = NULL;
×
754
  code = doAsText(val, length, &outputWKT);
×
755
  if (code != TSDB_CODE_SUCCESS) {
×
756
    shellPrintString(getGeosErrMsg(code), width);  // should NOT happen
×
757
    return;
×
758
  }
759

760
  shellPrintString(outputWKT, width);
×
761

762
  geosFreeBuffer(outputWKT);
×
763
}
764

765
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width,
19,278,914 ✔
766
                     int32_t length, int32_t precision, timezone_t tz) {
767
  if (val == NULL) {
19,278,914 ✔
768
    shellPrintString(TSDB_DATA_NULL_STR, width);
4,323,503 ✔
769
    return;
4,323,503 ✔
770
  }
771

772
  int n = 0;
14,955,411 ✔
773
#define LENGTH 64
774
  char buf[LENGTH] = {0};
14,955,411 ✔
775
  switch (field->type) {
14,955,411 ✔
776
    case TSDB_DATA_TYPE_BOOL:
988,649 ✔
777
      shellPrintString(((((int32_t)(*((char *)val))) == TSDB_FALSE) ? "false" : "true"), width);
988,649 ✔
778
      break;
988,649 ✔
779
    case TSDB_DATA_TYPE_TINYINT:
262,858 ✔
780
      (void)printf("%*d", width, *((int8_t *)val));
262,858 ✔
781
      break;
262,858 ✔
782
    case TSDB_DATA_TYPE_UTINYINT:
502,053 ✔
783
      (void)printf("%*u", width, *((uint8_t *)val));
502,053 ✔
784
      break;
502,053 ✔
785
    case TSDB_DATA_TYPE_SMALLINT:
616,672 ✔
786
      (void)printf("%*d", width, *((int16_t *)val));
616,672 ✔
787
      break;
616,672 ✔
788
    case TSDB_DATA_TYPE_USMALLINT:
310,246 ✔
789
      (void)printf("%*u", width, *((uint16_t *)val));
310,246 ✔
790
      break;
310,246 ✔
791
    case TSDB_DATA_TYPE_INT:
923,505 ✔
792
      (void)printf("%*d", width, *((int32_t *)val));
923,505 ✔
793
      break;
923,505 ✔
794
    case TSDB_DATA_TYPE_UINT:
446,786 ✔
795
      (void)printf("%*u", width, *((uint32_t *)val));
446,786 ✔
796
      break;
446,786 ✔
797
    case TSDB_DATA_TYPE_BIGINT:
3,577,240 ✔
798
      (void)printf("%*" PRId64, width, taosGetInt64Aligned((int64_t *)val));
3,611,225 ✔
799
      break;
3,611,225 ✔
800
    case TSDB_DATA_TYPE_UBIGINT:
347,102 ✔
801
      (void)printf("%*" PRIu64, width, taosGetUInt64Aligned((uint64_t *)val));
347,174 ✔
802
      break;
347,174 ✔
803
    case TSDB_DATA_TYPE_FLOAT:
567,548 ✔
804
      width = width >= LENGTH ? LENGTH - 1 : width;
567,548 ✔
805
      if (tsEnableScience) {
567,548 ✔
806
        (void)printf("%*.7e", width, taosGetFloatAligned((float *)val));
×
807
      } else {
808
        (void)snprintf(buf, LENGTH, "%*.*g", width, FLT_DIG, taosGetFloatAligned((float *)val));
567,548 ✔
809
        (void)printf("%s", buf);
567,548 ✔
810
      }
811
      break;
563,383 ✔
812
    case TSDB_DATA_TYPE_DOUBLE:
1,656,492 ✔
813
      width = width >= LENGTH ? LENGTH - 1 : width;
1,656,492 ✔
814
      if (tsEnableScience) {
1,656,492 ✔
815
        (void)snprintf(buf, LENGTH, "%*.15e", width, taosGetDoubleAligned((double *)val));
×
816
        (void)printf("%s", buf);
×
817
      } else {
818
        (void)snprintf(buf, LENGTH, "%*.*g", width, DBL_DIG, taosGetDoubleAligned((double *)val));
1,656,492 ✔
819
        (void)printf("%*s", width, buf);
1,656,492 ✔
820
      }
821
      break;
1,630,341 ✔
822
    case TSDB_DATA_TYPE_VARBINARY: {
3 ✔
823
      void    *data = NULL;
3 ✔
824
      uint32_t size = 0;
3 ✔
825
      if (taosAscii2Hex(val, length, &data, &size) < 0) {
3 ✔
826
        break;
×
827
      }
828
      shellPrintNChar(data, size, width);
3 ✔
829
      taosMemoryFree(data);
3 ✔
830
      break;
3 ✔
831
    }
832
    case TSDB_DATA_TYPE_BINARY:
843,747 ✔
833
      if (shell.args.is_binary_as_hex && shellHasBinaryNonPrintable(val, length)) {
843,747 ✔
834
        shellPrintHex(val, length, width);
20 ✔
835
      } else {
836
        shellPrintNChar(val, length, width);
843,727 ✔
837
      }
838
      break;
833,963 ✔
839
    case TSDB_DATA_TYPE_NCHAR:
1,066,802 ✔
840
    case TSDB_DATA_TYPE_JSON:
841
      shellPrintNChar(val, length, width);
1,066,802 ✔
842
      break;
1,066,802 ✔
843
    case TSDB_DATA_TYPE_GEOMETRY:
×
844
      shellPrintGeometry(val, length, width);
×
845
      break;
×
846
    case TSDB_DATA_TYPE_TIMESTAMP:
2,753,875 ✔
847
      shellFormatTimestamp(buf, sizeof(buf),
2,761,486 ✔
848
                           taosGetInt64Aligned((int64_t *)val), precision, tz);
849
      (void)printf("%s", buf);
2,761,486 ✔
850
      break;
2,761,486 ✔
851

852
    case TSDB_DATA_TYPE_BLOB:
×
853
    case TSDB_DATA_TYPE_MEDIUMBLOB: {
854
      // Display text (e.g. the DDL of SHOW CREATE TABLE, which may embed '\n') is shown
855
      // as-is via the same shellPrintNChar path as VARCHAR/NCHAR, so embedded newlines
856
      // render exactly as they did when the DDL arrived as VARCHAR. Other binary content
857
      // keeps the pre-existing taosAscii2Hex ('\x'-prefixed) representation, consistent
858
      // with VARBINARY and the dump-to-file output. Unlike BINARY (where -H affects only
859
      // values containing non-printable bytes), -H forces hex even for display text, so
860
      // users keep the pre-BLOB-text always-hex view for byte-level inspection of
861
      // printable BLOBs.
862
      if (!shell.args.is_binary_as_hex && !shellBlobHasNonPrintable(val, length)) {
×
863
        shellPrintNChar(val, length, width);
×
864
        break;
×
865
      }
866
      void    *data = NULL;
×
867
      uint32_t size = 0;
×
868
      if (taosAscii2Hex(val, length, &data, &size) < 0) {
×
869
        break;
×
870
      }
871
      shellPrintNChar(data, size, width);
×
872
      taosMemoryFree(data);
×
873
      break;
×
874
    }
875
    case TSDB_DATA_TYPE_DECIMAL:
50,165 ✔
876
    case TSDB_DATA_TYPE_DECIMAL64:
877
      (void)printf("%*s", width, val);
50,165 ✔
878
    default:
50,043 ✔
879
      break;
50,043 ✔
880
  }
881
}
882

883
// show whole result for this query return true, like limit or describe
884
bool shellIsShowWhole(const char *sql) {
6 ✔
885
  // limit
886
  char * p = taosStrCaseStr(sql, " limit ");
6 ✔
887
  if (p != NULL) {
6 ✔
888
    // except subquery, like "select * from (select * from t limit 10) limit 3", only the last limit is valid
889
    char * p1 = taosStrCaseStr(p + 7, ")");
3 ✔
890
    if (p1 == NULL) {
3 ✔
891
      return true;
1 ✔
892
    }
893
    if (taosStrCaseStr(p1 + 1, " limit ")) {
2 ✔
894
      return true;
1 ✔
895
    }
896
  }
897
  // describe
898
  if (taosStrCaseStr(sql, "describe ") != NULL) {
4 ✔
899
    return true;
1 ✔
900
  }
901
  // desc
902
  if (taosStrCaseStr(sql, "desc ") != NULL) {
3 ✔
903
    return true;
1 ✔
904
  }
905
  // show
906
  if (taosStrCaseStr(sql, "show ") != NULL) {
2 ✔
907
    return true;
×
908
  }
909
  // explain
910
  if (taosStrCaseStr(sql, "explain ") != NULL) {
2 ✔
911
    return true;
1 ✔
912
  }
913

914
  return false;
1 ✔
915
}
916

917
bool shellIsShowQuery(const char *sql) {
1 ✔
918
  // todo refactor
919
  if (taosStrCaseStr(sql, "show ") != NULL) {
1 ✔
920
    return true;
×
921
  }
922

923
  return false;
1 ✔
924
}
925

926
void init_dump_info(tsDumpInfo *dump_info, TAOS_RES *tres, const char *sql, bool vertical) {
181,741 ✔
927
  dump_info->sql = sql;
181,741 ✔
928
  dump_info->vertical = vertical;
181,741 ✔
929
  tsem_init(&dump_info->sem, 0, 0);
181,741 ✔
930
  dump_info->numOfAllRows = 0;
181,741 ✔
931

932
  dump_info->numFields = taos_num_fields(tres);
181,741 ✔
933
  dump_info->fields = taos_fetch_fields(tres);
181,741 ✔
934
  dump_info->precision = taos_result_precision(tres);
181,741 ✔
935
  dump_info->tz = (timezone_t)taos_get_result_tz(tres);
181,741 ✔
936

937
  dump_info->resShowMaxNum = UINT64_MAX;
181,741 ✔
938

939
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsShowWhole(dump_info->sql)) {
181,741 ✔
940
    dump_info->resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
1 ✔
941
  }
942

943
  if (vertical) {
181,741 ✔
944
    dump_info->maxColNameLen = 0;
440 ✔
945
    for (int32_t col = 0; col < dump_info->numFields; col++) {
911 ✔
946
      int32_t len = (int32_t)strlen(dump_info->fields[col].name);
471 ✔
947
      if (len > dump_info->maxColNameLen) {
471 ✔
948
        dump_info->maxColNameLen = len;
459 ✔
949
      }
950
    }
951
  } else {
952
    for (int32_t col = 0; col < dump_info->numFields; col++) {
744,972 ✔
953
      dump_info->width[col] = shellCalcColWidth(dump_info->fields + col, dump_info->precision);
563,671 ✔
954
    }
955
    // set an appropriate width for token and totp_secret display
956
    if (shellRegexMatch(sql, "^[\t ]*create[ \t]+token[ \t]+.*", REG_EXTENDED | REG_ICASE)) {
181,301 ✔
957
      dump_info->width[0] = TMAX(dump_info->width[0], SHELL_SHOW_TOKEN_DISPLAY_WIDTH);
×
958
    } else if (shellRegexMatch(sql, "^[\t ]*create[ \t]+totp_secret[ \t]+.*", REG_EXTENDED | REG_ICASE)) {
181,301 ✔
959
      dump_info->width[0] = TMAX(dump_info->width[0], SHELL_SHOW_TOTP_SECRET_DISPLAY_WIDTH);
×
960
    }
961
  }
962
}
181,741 ✔
963

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

971
  int64_t numOfPintRows = dump_info->numOfAllRows;
436 ✔
972
  int     numOfPrintRowsThisOne = 0;
436 ✔
973

974
  while (row != NULL) {
10,101 ✔
975
    (void)printf("*************************** %" PRId64 ".row ***************************\r\n", numOfPintRows + 1);
10,101 ✔
976

977
    int32_t *length = taos_fetch_lengths(tres);
10,101 ✔
978

979
    for (int32_t i = 0; i < dump_info->numFields; i++) {
20,923 ✔
980
      TAOS_FIELD *field = dump_info->fields + i;
10,822 ✔
981

982
      // as in shellPrintHeader(), the column name is server supplied
983
      char    name[sizeof(field->name)] = {0};
10,822 ✔
984
      tstrncpy(name, field->name, sizeof(name));
10,822 ✔
985
      shellStripControlChars(name);
10,822 ✔
986

987
      int32_t padding = (int32_t)(dump_info->maxColNameLen - strlen(name));
10,822 ✔
988
      (void)printf("%*.s%s: ", padding, " ", name);
10,822 ✔
989

990
      shellPrintField((const char *)row[i], field, 0, length[i], dump_info->precision, dump_info->tz);
10,822 ✔
991
      putchar('\r');
10,822 ✔
992
      putchar('\n');
10,822 ✔
993
    }
994

995
    numOfPintRows++;
10,101 ✔
996
    numOfPrintRowsThisOne++;
10,101 ✔
997

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

1009
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
10,101 ✔
1010
      return;
404 ✔
1011
    }
1012

1013
    row = taos_fetch_row(tres);
9,665 ✔
1014
  }
1015
  return;
×
1016
}
1017

1018
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
563,718 ✔
1019
  int32_t width = (int32_t)strlen(field->name);
563,718 ✔
1020

1021
  switch (field->type) {
563,718 ✔
1022
    case TSDB_DATA_TYPE_NULL:
×
1023
      return TMAX(4, width);  // null
×
1024
    case TSDB_DATA_TYPE_BOOL:
64,159 ✔
1025
      return TMAX(5, width);  // 'false'
64,159 ✔
1026

1027
    case TSDB_DATA_TYPE_TINYINT:
24,664 ✔
1028
    case TSDB_DATA_TYPE_UTINYINT:
1029
      return TMAX(4, width);  // '-127'
24,664 ✔
1030

1031
    case TSDB_DATA_TYPE_SMALLINT:
32,917 ✔
1032
    case TSDB_DATA_TYPE_USMALLINT:
1033
      return TMAX(6, width);  // '-32767'
32,917 ✔
1034

1035
    case TSDB_DATA_TYPE_INT:
73,131 ✔
1036
    case TSDB_DATA_TYPE_UINT:
1037
      return TMAX(11, width);  // '-2147483648'
73,131 ✔
1038

1039
    case TSDB_DATA_TYPE_BIGINT:
106,810 ✔
1040
    case TSDB_DATA_TYPE_UBIGINT:
1041
      return TMAX(21, width);  // '-9223372036854775807'
106,810 ✔
1042

1043
    case TSDB_DATA_TYPE_FLOAT:
20,907 ✔
1044
      return TMAX(SHELL_FLOAT_WIDTH, width);
20,907 ✔
1045

1046
    case TSDB_DATA_TYPE_DOUBLE:
78,687 ✔
1047
      return TMAX(SHELL_DOUBLE_WIDTH, width);
78,687 ✔
1048

1049
    case TSDB_DATA_TYPE_BINARY:
41,252 ✔
1050
    case TSDB_DATA_TYPE_GEOMETRY:
1051
      if (field->bytes > shell.args.displayWidth) {
41,252 ✔
1052
        return TMAX(shell.args.displayWidth, width);
26,236 ✔
1053
      } else {
1054
        return TMAX(field->bytes + 2, width);
15,016 ✔
1055
      }
1056
    case TSDB_DATA_TYPE_VARBINARY: {
6 ✔
1057
      int32_t bytes = field->bytes * 2 + 2;
6 ✔
1058
      if (bytes > shell.args.displayWidth) {
6 ✔
1059
        return TMAX(shell.args.displayWidth, width);
2 ✔
1060
      } else {
1061
        return TMAX(bytes + 2, width);
4 ✔
1062
      }
1063
    }
1064
    case TSDB_DATA_TYPE_NCHAR:
41,335 ✔
1065
    case TSDB_DATA_TYPE_JSON: {
1066
      uint16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
41,335 ✔
1067
      if (bytes > shell.args.displayWidth) {
41,335 ✔
1068
        return TMAX(shell.args.displayWidth, width);
41,332 ✔
1069
      } else {
1070
        return TMAX(bytes + 2, width);
3 ✔
1071
      }
1072
    }
1073

1074
    case TSDB_DATA_TYPE_TIMESTAMP:
78,291 ✔
1075
      if (shell.args.is_raw_time) {
78,291 ✔
1076
        return TMAX(14, width);
4 ✔
1077
      }
1078
      if (precision == TSDB_TIME_PRECISION_NANO) {
78,287 ✔
1079
        return TMAX(29, width);
24,162 ✔
1080
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
54,125 ✔
1081
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
×
1082
      } else {
1083
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
54,125 ✔
1084
      }
1085
    case TSDB_DATA_TYPE_BLOB:
×
1086
    case TSDB_DATA_TYPE_MEDIUMBLOB: {
1087
      int32_t bytes = TSDB_MAX_BLOB_LEN;
×
1088
      if (bytes > shell.args.displayWidth) {
×
1089
        return TMAX(shell.args.displayWidth, width);
×
1090
      } else {
1091
        return TMAX(bytes + 2, width);
×
1092
      }
1093
    } break;
×
1094

1095
    case TSDB_DATA_TYPE_DECIMAL64:
3 ✔
1096
      return TMAX(width, 20);
3 ✔
1097
    case TSDB_DATA_TYPE_DECIMAL:
1,556 ✔
1098
      return TMAX(width, 40);
1,556 ✔
1099
    default:
×
1100
      ASSERT(false);
×
1101
  }
1102

1103
  return 0;
×
1104
}
1105

1106
void shellPrintHeader(TAOS_FIELD *fields, int32_t *width, int32_t num_fields) {
130,021 ✔
1107
  int32_t rowWidth = 0;
130,021 ✔
1108
  for (int32_t col = 0; col < num_fields; col++) {
590,902 ✔
1109
    TAOS_FIELD *field = fields + col;
460,881 ✔
1110
    // the column name is copied verbatim from the server schema, so control
1111
    // characters must be stripped before it reaches the terminal
1112
    char    name[sizeof(field->name)] = {0};
460,881 ✔
1113
    tstrncpy(name, field->name, sizeof(name));
460,881 ✔
1114
    shellStripControlChars(name);
460,881 ✔
1115

1116
    int32_t     padding = (int32_t)(width[col] - strlen(name));
460,881 ✔
1117
    int32_t     left = padding / 2;
460,881 ✔
1118
    (void)printf(" %*.s%s%*.s |", left, " ", name, padding - left, " ");
460,881 ✔
1119
    rowWidth += width[col] + 3;
460,881 ✔
1120
  }
1121

1122
  putchar('\r');
130,021 ✔
1123
  putchar('\n');
130,021 ✔
1124
  for (int32_t i = 0; i < rowWidth; i++) {
13,379,087 ✔
1125
    putchar('=');
13,249,066 ✔
1126
  }
1127
  putchar('\r');
130,021 ✔
1128
  putchar('\n');
130,021 ✔
1129
}
130,021 ✔
1130

1131
void shellHorizontalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
131,901 ✔
1132
  TAOS_ROW row = taos_fetch_row(tres);
131,901 ✔
1133
  if (row == NULL) {
131,901 ✔
1134
    (void)printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
1135
    return;
×
1136
  }
1137

1138
  int64_t numOfPintRows = dump_info->numOfAllRows;
131,901 ✔
1139
  int     numOfPrintRowsThisOne = 0;
131,901 ✔
1140
  if (numOfPintRows == 0) {
131,901 ✔
1141
    shellPrintHeader(dump_info->fields, dump_info->width, dump_info->numFields);
130,009 ✔
1142
  }
1143

1144
  while (row != NULL) {
2,488,463 ✔
1145
    int32_t *length = taos_fetch_lengths(tres);
2,488,463 ✔
1146
    for (int32_t i = 0; i < dump_info->numFields; i++) {
21,756,371 ✔
1147
      putchar(' ');
19,267,908 ✔
1148
      shellPrintField((const char *)row[i], dump_info->fields + i, dump_info->width[i], length[i],
19,267,908 ✔
1149
                      dump_info->precision, dump_info->tz);
1150
      putchar(' ');
19,267,908 ✔
1151
      putchar('|');
19,267,908 ✔
1152
    }
1153
    putchar('\r');
2,488,463 ✔
1154
    putchar('\n');
2,488,463 ✔
1155

1156
    numOfPintRows++;
2,488,463 ✔
1157
    numOfPrintRowsThisOne++;
2,488,463 ✔
1158

1159
    if (numOfPintRows == dump_info->resShowMaxNum) {
2,488,463 ✔
1160
      (void)printf("\r\n");
1 ✔
1161
      (void)printf(" Notice: The result shows only the first %d rows.\r\n", SHELL_DEFAULT_RES_SHOW_NUM);
1 ✔
1162
      if (shellIsShowQuery(dump_info->sql)) {
1 ✔
1163
        (void)printf("         You can use '>>' to redirect the whole set of the result to a specified file.\r\n");
×
1164
      } else {
1165
        (void)printf("         You can use the `LIMIT` clause to get fewer result to show.\r\n");
1 ✔
1166
        (void)printf("           Or use '>>' to redirect the whole set of the result to a specified file.\r\n");
1 ✔
1167
      }
1168
      (void)printf("\r\n");
1 ✔
1169
      (void)printf("         You can use Ctrl+C to stop the underway fetching.\r\n");
1 ✔
1170
      (void)printf("\r\n");
1 ✔
1171
      return;
1 ✔
1172
    }
1173

1174
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
2,488,462 ✔
1175
      return;
99,768 ✔
1176
    }
1177

1178
    row = taos_fetch_row(tres);
2,356,562 ✔
1179
  }
1180
  return;
×
1181
}
1182

1183
void shellDumpResultCallback(void *param, TAOS_RES *tres, int num_of_rows) {
314,078 ✔
1184
  tsDumpInfo *dump_info = (tsDumpInfo *)param;
314,078 ✔
1185
  if (num_of_rows > 0) {
314,078 ✔
1186
    dump_info->numOfRows = num_of_rows;
132,337 ✔
1187
    if (dump_info->numOfAllRows < dump_info->resShowMaxNum) {
132,337 ✔
1188
      if (dump_info->vertical) {
132,337 ✔
1189
        shellVerticalPrintResult(tres, dump_info);
436 ✔
1190
      } else {
1191
        shellHorizontalPrintResult(tres, dump_info);
131,901 ✔
1192
      }
1193
    }
1194
    dump_info->numOfAllRows += num_of_rows;
132,337 ✔
1195
    if (!shellCmdkilled) {
132,337 ✔
1196
      taos_fetch_rows_a(tres, shellDumpResultCallback, param);
132,337 ✔
1197
    } else {
1198
      tsem_post(&dump_info->sem);
×
1199
    }
1200
  } else {
1201
    if (num_of_rows < 0 && num_of_rows != (int32_t)(TSDB_CODE_TSC_QUERY_KILLED)) {
181,741 ✔
1202
      uError("async retrieve failed, code: 0x%08X, %s", (uint32_t)num_of_rows, tstrerror(num_of_rows));
×
1203
    }
1204
    tsem_post(&dump_info->sem);
181,741 ✔
1205
  }
1206
}
314,078 ✔
1207

1208
int64_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
182,376 ✔
1209
  int64_t num_of_rows = 0;
182,376 ✔
1210
  if (fname != NULL) {
182,376 ✔
1211
    num_of_rows = shellDumpResultToFile(fname, tres);
635 ✔
1212
  } else {
1213
    tsDumpInfo dump_info;
181,741 ✔
1214
    if (!shellCmdkilled) {
181,741 ✔
1215
      init_dump_info(&dump_info, tres, sql, vertical);
181,741 ✔
1216
      taos_fetch_rows_a(tres, shellDumpResultCallback, &dump_info);
181,741 ✔
1217
      tsem_wait(&dump_info.sem);
181,741 ✔
1218
      num_of_rows = dump_info.numOfAllRows;
181,741 ✔
1219
    }
1220
  }
1221

1222
  *error_no = shellCmdkilled ? TSDB_CODE_TSC_QUERY_KILLED : taos_errno(tres);
182,376 ✔
1223
  return num_of_rows;
182,376 ✔
1224
}
1225

1226
/*
1227
 * The history file holds every command line typed by the operator, so it is
1228
 * created with owner only permissions (fopen would otherwise apply the process
1229
 * umask, 0644 on most systems) and a file left behind with looser permissions by
1230
 * an older version of the shell is tightened as well.
1231
 */
1232
static TdFilePtr shellOpenHistoryFile(const char *path, int32_t tdFileOptions) {
3,856 ✔
1233
  int32_t   oldUmask = taosUmaskFile(0077);
3,856 ✔
1234
  TdFilePtr pFile = taosOpenFile(path, tdFileOptions);
3,856 ✔
1235
  taosUmaskFile(oldUmask);
3,856 ✔
1236

1237
#ifndef WINDOWS
1238
  if (pFile != NULL && chmod(path, S_IRUSR | S_IWUSR) != 0) {
3,856 ✔
1239
    uWarn("failed to change mode of history file %s to 0600, errno:%d", path, errno);
×
1240
  }
1241
#endif
1242

1243
  return pFile;
3,856 ✔
1244
}
1245

1246
void shellReadHistory() {
1,928 ✔
1247
  SShellHistory *pHistory = &shell.history;
1,928 ✔
1248
  TdFilePtr      pFile = shellOpenHistoryFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
1,928 ✔
1249
  if (pFile == NULL) return;
1,928 ✔
1250

1251
  char   *line = taosMemoryMalloc(tsMaxSQLLength + 1);
1,623 ✔
1252
  int32_t read_size = 0;
1,623 ✔
1253
  while ((read_size = taosGetsFile(pFile, tsMaxSQLLength, line)) > 0) {
191,073 ✔
1254
    line[read_size - 1] = '\0';
189,386 ✔
1255
    taosMemoryFree(pHistory->hist[pHistory->hend]);
189,386 ✔
1256
    pHistory->hist[pHistory->hend] = taosStrdup(line);
189,386 ✔
1257

1258
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
189,386 ✔
1259

1260
    if (pHistory->hend == pHistory->hstart) {
189,386 ✔
1261
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
×
1262
    }
1263
  }
1264

1265
  taosMemoryFreeClear(line);
1,623 ✔
1266
  taosCloseFile(&pFile);
1,623 ✔
1267
  int64_t file_size;
1,623 ✔
1268
  if (taosStatFile(pHistory->file, &file_size, NULL, NULL) == 0 && file_size > SHELL_MAX_COMMAND_SIZE) {
1,623 ✔
1269
    TdFilePtr pFile = shellOpenHistoryFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_TRUNC);
×
1270
    if (pFile == NULL) return;
×
1271
    int32_t endIndex = pHistory->hstart;
×
1272
    if (endIndex != 0) {
×
1273
      endIndex = pHistory->hend;
×
1274
    }
1275
    for (int32_t i = (pHistory->hend + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE; i != endIndex;) {
×
1276
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
×
1277
      i = (i + SHELL_MAX_HISTORY_SIZE - 1) % SHELL_MAX_HISTORY_SIZE;
×
1278
    }
1279
    taosFprintfFile(pFile, "%s\n", pHistory->hist[endIndex]);
×
1280

1281
    /* coverity[+retval] */
1282
    taosFsyncFile(pFile);
×
1283
    taosCloseFile(&pFile);
×
1284
  }
1285
  pHistory->hstart = pHistory->hend;
1,623 ✔
1286
}
1287

1288
void shellWriteHistory() {
1,928 ✔
1289
  SShellHistory *pHistory = &shell.history;
1,928 ✔
1290
  if (pHistory->hend == pHistory->hstart) return;
1,928 ✔
1291
  TdFilePtr pFile = shellOpenHistoryFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
1,928 ✔
1292
  if (pFile == NULL) return;
1,928 ✔
1293

1294
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
4,345 ✔
1295
    if (pHistory->hist[i] != NULL) {
2,417 ✔
1296
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
2,417 ✔
1297
      taosMemoryFree(pHistory->hist[i]);
2,417 ✔
1298
      pHistory->hist[i] = NULL;
2,417 ✔
1299
    }
1300
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
2,417 ✔
1301
  }
1302
  taosCloseFile(&pFile);
1,928 ✔
1303
}
1304

1305
void shellCleanupHistory() {
1,928 ✔
1306
  SShellHistory *pHistory = &shell.history;
1,928 ✔
1307
  for (int32_t i = 0; i < SHELL_MAX_HISTORY_SIZE; ++i) {
1,929,928 ✔
1308
    if (pHistory->hist[i] != NULL) {
1,928,000 ✔
1309
      taosMemoryFree(pHistory->hist[i]);
189,386 ✔
1310
      pHistory->hist[i] = NULL;
189,386 ✔
1311
    }
1312
  }
1313
}
1,928 ✔
1314

1315
void shellPrintError(TAOS_RES *tres, int64_t st) {
178,447 ✔
1316
  int code = taos_errno(tres);
178,447 ✔
1317
  int64_t et = taosGetTimestampUs();
178,447 ✔
1318

1319
  // the error text may originate from the server response, strip control
1320
  // characters so that it cannot carry terminal escape sequences
1321
  char errInfo[1024] = {0};
178,447 ✔
1322
  tstrncpy(errInfo, taos_errstr(tres), sizeof(errInfo));
178,447 ✔
1323
  shellStripControlChars(errInfo);
178,447 ✔
1324

1325
  (void)printf("\r\nDB error: %s [0x%08X] (%.6fs)\r\n", errInfo, code, (et - st) / 1E6);
178,447 ✔
1326
  taos_free_result(tres);
178,447 ✔
1327

1328
  // tip
1329
  if (code == TSDB_CODE_MND_USER_PASSWORD_EXPIRED) {
178,447 ✔
1330
    (void)fprintf(stdout, "******************** TIPS ********************\n");
×
1331
    (void)fprintf(stdout, "Please reset your password using the `ALTER USER <user_name> PASS 'new_password'` command.\n");
×
1332
    (void)fprintf(stdout, "**********************************************\n");
×
1333
  }
1334
}
178,447 ✔
1335

1336
bool shellIsCommentLine(char *line) {
363,639 ✔
1337
  if (line == NULL) return true;
363,639 ✔
1338
  return shellRegexMatch(line, "^[[:space:]]*#.*", REG_EXTENDED);
363,639 ✔
1339
}
1340

1341
void shellSourceFile(const char *file) {
1,129 ✔
1342
  int32_t read_len = 0;
1,129 ✔
1343
  char   *cmd = taosMemoryCalloc(1, tsMaxSQLLength + 1);
1,129 ✔
1344
  size_t  cmd_len = 0;
1,129 ✔
1345
  char    fullname[PATH_MAX] = {0};
1,129 ✔
1346
  char    sourceFileCommand[PATH_MAX + 8] = {0};
1,129 ✔
1347

1348
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
1,129 ✔
1349
    tstrncpy(fullname, file, PATH_MAX);
×
1350
  }
1351

1352
  (void)sprintf(sourceFileCommand, "source %s;", fullname);
1,129 ✔
1353
  shellRecordCommandToHistory(sourceFileCommand);
1,129 ✔
1354

1355
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
1,129 ✔
1356
  if (pFile == NULL) {
1,129 ✔
1357
    (void)fprintf(stderr, "failed to open file %s\r\n", fullname);
40 ✔
1358
    taosMemoryFree(cmd);
40 ✔
1359
    return;
40 ✔
1360
  }
1361

1362
  char *line = taosMemoryMalloc(tsMaxSQLLength + 1);
1,089 ✔
1363
  while ((read_len = taosGetsFile(pFile, tsMaxSQLLength, line)) > 0) {
373,488 ✔
1364
    if (cmd_len + read_len >= tsMaxSQLLength) {
372,399 ✔
1365
      (void)printf("read command line too long over 1M, ignore this line. cmd_len = %d read_len=%d \n", (int32_t)cmd_len,
×
1366
             read_len);
1367
      cmd_len = 0;
×
1368
      memset(line, 0, tsMaxSQLLength + 1);
×
1369
      continue;
×
1370
    }
1371
    line[--read_len] = '\0';
372,399 ✔
1372

1373
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
579,659 ✔
1374
      continue;
9,614 ✔
1375
    }
1376

1377
    if (line[read_len - 1] == '\\') {
362,785 ✔
1378
      line[read_len - 1] = ' ';
594 ✔
1379
      memcpy(cmd + cmd_len, line, read_len);
594 ✔
1380
      cmd_len += read_len;
594 ✔
1381
      continue;
594 ✔
1382
    }
1383

1384
    if (line[read_len - 1] == '\r') {
362,191 ✔
1385
      line[--read_len] = '\0';
226 ✔
1386
    }
1387

1388
    memcpy(cmd + cmd_len, line, read_len);
362,191 ✔
1389
    (void)printf("%s%s\r\n", shell.info.promptHeader, cmd);
362,191 ✔
1390
    shellRunCommand(cmd, false);
362,191 ✔
1391
    memset(cmd, 0, tsMaxSQLLength);
362,191 ✔
1392
    cmd_len = 0;
362,191 ✔
1393
  }
1394

1395
  taosMemoryFree(cmd);
1,089 ✔
1396
  taosMemoryFreeClear(line);
1,089 ✔
1397
  taosCloseFile(&pFile);
1,089 ✔
1398
}
1399

1400
/*
1401
 * Copy one result cell into a fixed size buffer. Both the cell length and the
1402
 * declared column width come from the server and are bounded only by
1403
 * TSDB_MAX_BINARY_LEN, so the copy length has to be clamped to the destination
1404
 * here; the buffer is always NUL terminated and a NULL cell yields an empty
1405
 * string instead of dereferencing a NULL pointer.
1406
 */
1407
static void shellCopyResultCell(char *dst, int32_t dstSize, const char *src, int32_t srcLen) {
27 ✔
1408
  dst[0] = 0;
27 ✔
1409

1410
  if (src == NULL || srcLen <= 0) {
27 ✔
1411
    return;
×
1412
  }
1413

1414
  int32_t copyLen = TMIN(srcLen, dstSize - 1);
27 ✔
1415
  memcpy(dst, src, copyLen);
27 ✔
1416
  dst[copyLen] = 0;
27 ✔
1417
}
1418

1419
int32_t shellGetGrantInfo(char *buf, int32_t bufSize) {
9 ✔
1420
  int32_t verType = TSDB_VERSION_UNKNOWN;
9 ✔
1421
  char    sinfo[256] = {0};
9 ✔
1422
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
9 ✔
1423
  strtok(sinfo, "\r\n");
9 ✔
1424
  shellStripControlChars(sinfo);
9 ✔
1425

1426
#ifndef TD_ASTRA
1427
  char sql[] = "show grants";
9 ✔
1428

1429
  TAOS_RES *tres = taos_query(shell.conn, sql);
9 ✔
1430

1431
  int32_t code = taos_errno(tres);
9 ✔
1432
  if (code != TSDB_CODE_SUCCESS) {
9 ✔
1433
    if (code != TSDB_CODE_OPS_NOT_SUPPORT && code != TSDB_CODE_MND_NO_RIGHTS &&
×
1434
        code != TSDB_CODE_PAR_PERMISSION_DENIED) {
1435
      (void)fprintf(stderr, "Failed to check Server Edition, Reason:0x%04x:%s\r\n\r\n", code, taos_errstr(tres));
×
1436
    }
1437
    taos_free_result(tres);
×
1438
    return verType;
×
1439
  }
1440

1441
  if (tres == NULL) {
9 ✔
1442
    (void)fprintf(stderr, "\r\nGrant information is null.\r\n");
×
1443
    exit(0);
×
1444
  }
1445

1446
  // the reply is indexed up to the third column below, so fewer columns than the
1447
  // ins_grants result must not be accepted
1448
  int32_t num_fields = taos_field_count(tres);
9 ✔
1449
  if (num_fields < SHELL_GRANT_FIELD_CNT) {
9 ✔
1450
    (void)fprintf(stderr, "\r\nInvalid grant information.\r\n");
×
1451
    exit(0);
×
1452
  }
1453

1454
  {
1455
    TAOS_ROW row = taos_fetch_row(tres);
9 ✔
1456
    if (row == NULL) {
9 ✔
1457
      (void)fprintf(stderr, "\r\nFailed to get grant information from server. Abort.\r\n");
×
1458
      exit(0);
×
1459
    }
1460

1461
    int32_t  cellLength[SHELL_GRANT_FIELD_CNT] = {0};
9 ✔
1462
    int32_t *lengths = taos_fetch_lengths(tres);
9 ✔
1463
    if (lengths != NULL) {
9 ✔
1464
      memcpy(cellLength, lengths, sizeof(cellLength));
9 ✔
1465
    }
1466

1467
    char serverVersion[SHELL_GRANT_VERSION_LEN] = {0};
9 ✔
1468
    char expiretime[SHELL_GRANT_EXPIRE_LEN] = {0};
9 ✔
1469
    char expired[SHELL_GRANT_EXPIRE_LEN] = {0};
9 ✔
1470

1471
    shellCopyResultCell(serverVersion, sizeof(serverVersion), row[0], cellLength[0]);
9 ✔
1472
    shellCopyResultCell(expiretime, sizeof(expiretime), row[1], cellLength[1]);
9 ✔
1473
    shellCopyResultCell(expired, sizeof(expired), row[2], cellLength[2]);
9 ✔
1474

1475
    trimStr(serverVersion, "trial");
9 ✔
1476

1477
    if (strcmp(serverVersion, "community") == 0) {
9 ✔
1478
      verType = TSDB_VERSION_OSS;
×
1479
    } else if (strcmp(expiretime, "unlimited") == 0) {
9 ✔
1480
      verType = TSDB_VERSION_ENTERPRISE;
×
1481
      (void)snprintf(buf, bufSize, "Server is %s %s. License will never expire.\r\n", serverVersion, sinfo);
×
1482
    } else {
1483
      verType = TSDB_VERSION_ENTERPRISE;
9 ✔
1484
      (void)snprintf(buf, bufSize, "Server is %s %s. License will expire at %s.\r\n", serverVersion, sinfo, expiretime);
9 ✔
1485
    }
1486

1487
    taos_free_result(tres);
9 ✔
1488
  }
1489

1490
  (void)fprintf(stdout, "\r\n");
9 ✔
1491
#else
1492
  verType = TSDB_VERSION_ENTERPRISE;
1493
  (void)snprintf(buf, bufSize, "Server is %s %s. License will never expire.\r\n", TD_PRODUCT_NAME, sinfo);
1494
#endif
1495
  return verType;
9 ✔
1496
}
1497

1498
#ifdef WINDOWS
1499
BOOL shellQueryInterruptHandler(DWORD fdwCtrlType) {
1500
  tsem_post(&shell.cancelSem);
1501
  return TRUE;
1502
}
1503
#else
1504
void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }
4 ✔
1505
#endif
1506

1507
void shellCleanup(void *arg) { taosResetTerminalMode(); }
9 ✔
1508

1509
void *shellCancelHandler(void *arg) {
9 ✔
1510
  setThreadName("shellCancelHandler");
9 ✔
1511
  while (1) {
×
1512
    if (shell.exit == true) {
21 ✔
1513
      break;
9 ✔
1514
    }
1515

1516
    if (tsem_wait(&shell.cancelSem) != 0) {
12 ✔
1517
      taosMsleep(10);
×
1518
      continue;
×
1519
    }
1520

1521
    if (shell.conn) {
12 ✔
1522
      shellCmdkilled = true;
3 ✔
1523
      taos_kill_query(shell.conn);
3 ✔
1524
    }
1525

1526
#ifdef WINDOWS
1527
    (void)printf("\n%s", shell.info.promptHeader);
1528
#endif
1529
  }
1530

1531
  return NULL;
9 ✔
1532
}
1533

1534
#pragma GCC diagnostic push
1535
#pragma GCC diagnostic ignored "-Wstringop-overflow"
1536

1537
void *shellThreadLoop(void *arg) {
9 ✔
1538
  setThreadName("shellThreadLoop");
9 ✔
1539
  taosGetOldTerminalMode();
9 ✔
1540
  taosThreadCleanupPush(shellCleanup, NULL);
9 ✔
1541

1542
  do {
×
1543
    char *command = taosMemoryMalloc(SHELL_MAX_COMMAND_SIZE);
9 ✔
1544
    if (command == NULL) {
9 ✔
1545
      (void)printf("failed to malloc command\r\n");
×
1546
      break;
×
1547
    }
1548

1549
    do {
×
1550
      memset(command, 0, SHELL_MAX_COMMAND_SIZE);
18 ✔
1551
      taosSetTerminalMode();
18 ✔
1552

1553
      if (shellReadCommand(command) != 0) {
18 ✔
1554
        break;
3 ✔
1555
      }
1556

1557
      taosResetTerminalMode();
15 ✔
1558
    } while (shellRunCommand(command, true) == 0);
15 ✔
1559

1560
    taosMemoryFreeClear(command);
9 ✔
1561
    shellWriteHistory();
9 ✔
1562
    shellExit();
9 ✔
1563
  } while (0);
1564

1565
  taosThreadCleanupPop(1);
9 ✔
1566
  return NULL;
9 ✔
1567
}
1568

1569
bool inputTotpCode(char *totpCode) {
13 ✔
1570
  bool ret = true;
13 ✔
1571
  (void)printf("Please enter your TOTP code:");
13 ✔
1572
  if (scanf("%255s", totpCode) != 1) {
13 ✔
1573
    (void)fprintf(stderr, "TOTP code reading error\n");
1 ✔
1574
    ret = false;
1 ✔
1575
  }
1576
  if (EOF == getchar()) {
13 ✔
1577
    // tip
1578
    (void)fprintf(stdout, "getchar() return EOF\r\n");
1 ✔
1579
  }
1580
  return ret;
13 ✔
1581
}
1582

1583
#pragma GCC diagnostic pop
1584

1585
TAOS *createConnect(SShellArgs *pArgs) {
1,981 ✔
1586
  char     show[256] = "\0";
1,981 ✔
1587
  char    *host = NULL;
1,981 ✔
1588
  uint16_t port = 0;
1,981 ✔
1589
  char    *user = NULL;
1,981 ✔
1590
  char    *pwd = NULL;
1,981 ✔
1591
  TAOS    *taos = NULL;
1,981 ✔
1592

1593
  // set mode
1594
  if (pArgs->connMode != CONN_MODE_NATIVE && pArgs->dsn) {
1,981 ✔
1595
    // websocket
1596
    memcpy(show, pArgs->dsn, 20);
×
1597
    memcpy(show + 20, "...", 3);
×
1598
    memcpy(show + 23, pArgs->dsn + strlen(pArgs->dsn) - 10, 10);
×
1599

1600
    // connect dsn
1601
    taos = taos_connect_with_dsn(pArgs->dsn);
×
1602
  } else {
1603
    host = (char *)pArgs->host;
1,981 ✔
1604
    user = (char *)pArgs->user;
1,981 ✔
1605
    pwd = pArgs->password;
1,981 ✔
1606

1607
    if (pArgs->port_inputted) {
1,981 ✔
1608
      port = pArgs->port;
29 ✔
1609
    } else {
1610
      port = defaultPort(pArgs->connMode, pArgs->dsn);
1,952 ✔
1611
    }
1612

1613
    (void)sprintf(show, "host:%s port:%d ", host, port);
1,981 ✔
1614

1615
    // connect normal
1616
    if (pArgs->auth) {
1,981 ✔
1617
      taos = taos_connect_auth(host, user, pArgs->auth, pArgs->database, port);
2 ✔
1618
    } else {
1619
#ifdef TD_ENTERPRISE
1620
      if (strlen(pArgs->token) > 0) {
1,979 ✔
1621
        // token
1622
        (void)printf("Connect with token ...");
29 ✔
1623
        taos = taos_connect_token(host, pArgs->token, pArgs->database, port);
29 ✔
1624
        if (taos != NULL) {
29 ✔
1625
          (void)printf("... [ OK ]\n");
12 ✔
1626
          return taos;
12 ✔
1627
        }
1628
        (void)printf("... [ FAILED ]\n");
17 ✔
1629
        return NULL;
17 ✔
1630
      }
1631
#endif
1632
      taos = taos_connect(host, user, pwd, pArgs->database, port);
1,950 ✔
1633
    }
1634

1635
    if (taos == NULL) {
1,952 ✔
1636
      // failed
1637
      int code = taos_errno(NULL);
44 ✔
1638
      if (code == TSDB_CODE_MND_WRONG_TOTP_CODE) {
44 ✔
1639
         // totp
1640
        char totpCode[TSDB_USER_PASSWORD_LONGLEN];
13 ✔
1641
        memset(totpCode, 0, sizeof(totpCode));
13 ✔
1642
        if (inputTotpCode(totpCode)) {
13 ✔
1643
          (void)printf("Connect with TOTP code:%s ...", totpCode);
12 ✔
1644
          taos = taos_connect_totp(host, user, pwd, totpCode, pArgs->database, port);
12 ✔
1645
          if (taos != NULL) {
12 ✔
1646
            (void)printf("... [ OK ]\n");
8 ✔
1647
            return taos;
8 ✔
1648
          }
1649
          (void)printf("... [ FAILED ]\n");
4 ✔
1650
          return NULL;
4 ✔
1651
        }
1652
      }
1653
      // token
1654
    }
1655
  }
1656

1657
  return taos;
1,821 ✔
1658
}
1659

1660
int32_t shellExecute(int argc, char *argv[]) {
1,981 ✔
1661
  int32_t code = 0;
1,981 ✔
1662
  (void)printf(shell.info.clientVersion, shell.info.cusName,
3,962 ✔
1663
         workingMode(shell.args.connMode, shell.args.dsn) == CONN_MODE_NATIVE ? STR_NATIVE : STR_WEBSOCKET,
1,981 ✔
1664
         taos_get_client_info(), shell.info.cusName);
1665
  fflush(stdout);
1,981 ✔
1666

1667
  SShellArgs *pArgs = &shell.args;
1,981 ✔
1668
  shell.conn = createConnect(pArgs);
1,981 ✔
1669

1670
  if (shell.conn == NULL) {
1,981 ✔
1671
    (void)printf("failed to connect to server, reason: %s [0x%08X]\n%s", taos_errstr(NULL), taos_errno(NULL),
53 ✔
1672
           ERROR_CODE_DETAIL);
1673
    fflush(stdout);
53 ✔
1674
    return -1;
53 ✔
1675
  }
1676

1677
  (void)taos_options_connection(shell.conn, TSDB_OPTION_CONNECTION_USER_APP, "taos");
1,928 ✔
1678

1679
  bool runOnce = pArgs->commands != NULL || pArgs->file[0] != 0;
1,928 ✔
1680
  shellSetConn(shell.conn, runOnce);
1,928 ✔
1681
  shellReadHistory();
1,928 ✔
1682

1683
  if (shell.args.is_bi_mode) {
1,928 ✔
1684
    // need set bi mode
1685
    (void)printf("Set BI mode is true.\n");
2 ✔
1686
    taos_set_conn_mode(shell.conn, TAOS_CONN_MODE_BI, 1);
2 ✔
1687
  }
1688

1689
  if (runOnce) {
1,928 ✔
1690
    if (pArgs->commands != NULL) {
1,919 ✔
1691
      (void)printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
790 ✔
1692
      char *cmd = taosStrdup(pArgs->commands);
790 ✔
1693
      shellRunCommand(cmd, true);
790 ✔
1694
      taosMemoryFree(cmd);
790 ✔
1695
    }
1696

1697
    if (pArgs->file[0] != 0) {
1,919 ✔
1698
      shellSourceFile(pArgs->file);
1,129 ✔
1699
    }
1700

1701
    taos_close(shell.conn);
1,919 ✔
1702

1703
    shellWriteHistory();
1,919 ✔
1704
    shellCleanupHistory();
1,919 ✔
1705
    // Push the result out while this process is still in control of it: a
1706
    // sanitizer runtime that is preloaded into the client ends the process with
1707
    // _exit() and would otherwise discard whatever is still buffered here.
1708
    fflush(stdout);
1,919 ✔
1709
    return 0;
1,919 ✔
1710
  }
1711

1712
  if ((code = tsem_init(&shell.cancelSem, 0, 0)) != 0) {
9 ✔
1713
    (void)printf("failed to create cancel semaphore since %s\r\n", tstrerror(code));
×
1714
    return code;
×
1715
  }
1716

1717
  TdThread spid = {0};
9 ✔
1718
  taosThreadCreate(&spid, NULL, shellCancelHandler, NULL);
9 ✔
1719

1720
  taosSetSignal(SIGTERM, shellQueryInterruptHandler);
9 ✔
1721
  taosSetSignal(SIGHUP, shellQueryInterruptHandler);
9 ✔
1722
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
9 ✔
1723

1724
  char    buf[512] = {0};
9 ✔
1725
  int32_t verType = shellGetGrantInfo(buf, sizeof(buf));
9 ✔
1726
#ifndef WINDOWS
1727
  printfIntroduction(verType);
9 ✔
1728
#else
1729
  if (verType == TSDB_VERSION_OSS) {
1730
    showAD(false);
1731
  }
1732
#endif
1733
  // printf version
1734
  if (verType == TSDB_VERSION_ENTERPRISE || verType == TSDB_VERSION_CLOUD) {
9 ✔
1735
    (void)printf("%s\n", buf);
9 ✔
1736
  }
1737

1738
  while (1) {
×
1739
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
9 ✔
1740
    taosThreadJoin(shell.pid, NULL);
9 ✔
1741
    taosThreadClear(&shell.pid);
9 ✔
1742
    if (shell.exit) {
9 ✔
1743
      tsem_post(&shell.cancelSem);
9 ✔
1744
      break;
9 ✔
1745
    }
1746
  }
1747

1748
  if (verType == TSDB_VERSION_OSS) {
9 ✔
1749
    showAD(true);
×
1750
  }
1751

1752
  taosThreadJoin(spid, NULL);
9 ✔
1753

1754
  shellCleanupHistory();
9 ✔
1755
  taos_kill_query(shell.conn);
9 ✔
1756
  taos_close(shell.conn);
9 ✔
1757

1758
  TAOS_RETURN(code);
9 ✔
1759
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc