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

taosdata / TDengine / #4720

08 Sep 2025 08:43AM UTC coverage: 58.139% (-0.6%) from 58.762%
#4720

push

travis-ci

web-flow
Merge pull request #32881 from taosdata/enh/add-new-windows-ci

fix(ci): update workflow reference to use new Windows CI YAML

133181 of 292179 branches covered (45.58%)

Branch coverage included in aggregate %.

201691 of 283811 relevant lines covered (71.07%)

5442780.71 hits per line

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

69.95
/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) {
42,295✔
71
  for (char c = *cmd++; c != 0; c = *cmd++) {
43,526✔
72
    if (c != ' ' && c != '\t' && c != ';') {
33,001!
73
      return false;
31,770✔
74
    }
75
  }
76
  return true;
10,525✔
77
}
78

79
int32_t shellRunSingleCommand(char *command) {
27,021✔
80
  shellCmdkilled = false;
27,021✔
81

82
  if (shellIsEmptyCommand(command)) {
27,021✔
83
    return 0;
10,525✔
84
  }
85

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

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

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

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

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

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

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

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

173
  if (recordHistory) shellRecordCommandToHistory(command);
15,272✔
174

175
  char quote = 0, *cmd = command;
15,272✔
176
  for (char c = *command++; c != 0; c = *command++) {
1,432,536✔
177
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
1,417,266!
178
      command++;
4✔
179
      continue;
4✔
180
    }
181

182
    if (quote == c) {
1,417,262✔
183
      quote = 0;
10,738✔
184
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
1,406,524✔
185
      quote = c;
10,738✔
186
    } else if (c == ';' && quote == 0) {
1,395,786✔
187
      c = *command;
11,751✔
188
      *command = 0;
11,751✔
189
      if (shellRunSingleCommand(cmd) < 0) {
11,751✔
190
        return -1;
2✔
191
      }
192
      *command = c;
11,749✔
193
      cmd = command;
11,749✔
194
    }
195
  }
196
  return shellRunSingleCommand(cmd);
15,270✔
197
}
198

199
char *strendG(const char *pstr) {
16,490✔
200
  if (pstr == NULL) {
16,490!
201
    return NULL;
×
202
  }
203

204
  size_t len = strlen(pstr);
16,490✔
205
  if (len < 4) {
16,490!
206
    return NULL;
×
207
  }
208

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

214
  p = (char *)pstr + len - 3;
16,482✔
215
  if (strcmp(p, "\\G;") == 0) {
16,482✔
216
    return p;
63✔
217
  }
218

219
  return NULL;
16,419✔
220
}
221

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

229
  if ((sptr = strstr(command, ">>")) != NULL) {
16,490✔
230
    fname = sptr + 2;
47✔
231
    while (*fname == ' ') fname++;
90✔
232
    *sptr = '\0';
47✔
233

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

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

245
  st = taosGetTimestampUs();
16,490✔
246

247
  TAOS_RES *pSql = taos_query(shell.conn, command);
16,490✔
248
  if (taos_errno(pSql)) {
16,490✔
249
    shellPrintError(pSql, st);
2,877✔
250
    return;
2,877✔
251
  }
252

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

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

259
    taos_free_result(pSql);
43✔
260

261
    return;
43✔
262
  }
263

264
  // pre string
265
  char *pre = "Query OK";
13,570✔
266
  if (shellRegexMatch(command, "^\\s*delete\\s*from\\s*.*", REG_EXTENDED | REG_ICASE)) {
13,570✔
267
    pre = "Delete OK";
1✔
268
  } else if (shellRegexMatch(command, "^\\s*insert\\s*into\\s*.*", REG_EXTENDED | REG_ICASE)) {
13,569✔
269
    pre = "Insert OK";
49✔
270
  } else if (shellRegexMatch(command, "^\\s*create\\s*.*", REG_EXTENDED | REG_ICASE)) {
13,520✔
271
    pre = "Create OK";
59✔
272
  } else if (shellRegexMatch(command, "^\\s*drop\\s*.*", REG_EXTENDED | REG_ICASE)) {
13,461✔
273
    pre = "Drop OK";
8✔
274
  }
275

276
  TAOS_FIELD *pFields = taos_fetch_fields(pSql);
13,570✔
277
  if (pFields != NULL) {  // select and show kinds of commands
13,570✔
278
    int32_t error_no = 0;
10,334✔
279

280
    int64_t numOfRows = shellDumpResult(pSql, fname, &error_no, printMode, command);
10,334✔
281
    if (numOfRows < 0) return;
10,334!
282

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

297
    // call auto tab
298
    callbackAutoTab(command, NULL, false);
3,236✔
299
  }
300

301
  printf("\r\n");
13,570✔
302
}
303

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

310
  time_t  tt;
311
  int32_t ms = 0;
659,334✔
312
  if (precision == TSDB_TIME_PRECISION_NANO) {
659,334✔
313
    tt = (time_t)(val / 1000000000);
20✔
314
    ms = val % 1000000000;
20✔
315
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
659,314✔
316
    tt = (time_t)(val / 1000000);
20✔
317
    ms = val % 1000000;
20✔
318
  } else {
319
    tt = (time_t)(val / 1000);
659,294✔
320
    ms = val % 1000;
659,294✔
321
  }
322

323
  if (tt <= 0 && ms < 0) {
659,334!
324
    tt--;
×
325
    if (precision == TSDB_TIME_PRECISION_NANO) {
×
326
      ms += 1000000000;
×
327
    } else if (precision == TSDB_TIME_PRECISION_MICRO) {
×
328
      ms += 1000000;
×
329
    } else {
330
      ms += 1000;
×
331
    }
332
  }
333

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

340
  if (precision == TSDB_TIME_PRECISION_NANO) {
659,334✔
341
    sprintf(buf + pos, ".%09d", ms);
20✔
342
  } else if (precision == TSDB_TIME_PRECISION_MICRO) {
659,314✔
343
    sprintf(buf + pos, ".%06d", ms);
20✔
344
  } else {
345
    sprintf(buf + pos, ".%03d", ms);
659,294✔
346
  }
347

348
  return buf;
659,334✔
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) {
2,186,025✔
361
  if (val == NULL) {
2,186,025✔
362
    taosFprintfFile(pFile, "NULL");
12,766✔
363
    return;
12,766✔
364
  }
365

366
  char    quotationStr[2] = {'"', 0};
2,173,259✔
367
  int32_t width;
368

369
  int n = 0;
2,173,259✔
370
#define LENGTH 64
371
  char buf[LENGTH] = {0};
2,173,259✔
372
  switch (field->type) {
2,173,259!
373
    case TSDB_DATA_TYPE_BOOL:
×
374
      taosFprintfFile(pFile, "%d", ((((int32_t)(*((char *)val))) == 1) ? 1 : 0));
×
375
      break;
×
376
    case TSDB_DATA_TYPE_TINYINT:
×
377
      taosFprintfFile(pFile, "%d", *((int8_t *)val));
×
378
      break;
×
379
    case TSDB_DATA_TYPE_UTINYINT:
×
380
      taosFprintfFile(pFile, "%u", *((uint8_t *)val));
×
381
      break;
×
382
    case TSDB_DATA_TYPE_SMALLINT:
×
383
      taosFprintfFile(pFile, "%d", *((int16_t *)val));
×
384
      break;
×
385
    case TSDB_DATA_TYPE_USMALLINT:
×
386
      taosFprintfFile(pFile, "%u", *((uint16_t *)val));
×
387
      break;
×
388
    case TSDB_DATA_TYPE_INT:
420,848✔
389
      taosFprintfFile(pFile, "%d", *((int32_t *)val));
420,848✔
390
      break;
420,848✔
391
    case TSDB_DATA_TYPE_UINT:
×
392
      taosFprintfFile(pFile, "%u", *((uint32_t *)val));
×
393
      break;
×
394
    case TSDB_DATA_TYPE_BIGINT:
295,858✔
395
      taosFprintfFile(pFile, "%" PRId64, *((int64_t *)val));
295,858✔
396
      break;
295,858✔
397
    case TSDB_DATA_TYPE_UBIGINT:
×
398
      taosFprintfFile(pFile, "%" PRIu64, *((uint64_t *)val));
×
399
      break;
×
400
    case TSDB_DATA_TYPE_FLOAT:
20✔
401
      width = SHELL_FLOAT_WIDTH;
20✔
402
      if (tsEnableScience) {
20!
403
        taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
×
404
      } else {
405
        n = tsnprintf(buf, LENGTH, "%*.7f", width, GET_FLOAT_VAL(val));
20✔
406
        if (n > SHELL_FLOAT_WIDTH) {
20!
407
          taosFprintfFile(pFile, "%*.7e", width, GET_FLOAT_VAL(val));
×
408
        } else {
409
          taosFprintfFile(pFile, "%s", buf);
20✔
410
        }
411
      }
412
      break;
20✔
413
    case TSDB_DATA_TYPE_DOUBLE:
399,874✔
414
      width = SHELL_DOUBLE_WIDTH;
399,874✔
415
      if (tsEnableScience) {
399,874!
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));
399,874✔
420
        if (n > SHELL_DOUBLE_WIDTH) {
399,874✔
421
          taosFprintfFile(pFile, "%*.15e", width, GET_DOUBLE_VAL(val));
70,645✔
422
        } else {
423
          taosFprintfFile(pFile, "%s", buf);
329,229✔
424
        }
425
      }
426
      break;
399,874✔
427
    case TSDB_DATA_TYPE_BINARY:
603,212✔
428
    case TSDB_DATA_TYPE_NCHAR:
429
    case TSDB_DATA_TYPE_JSON: {
430
      int32_t bufIndex = 0;
603,212✔
431
      char   *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
603,212!
432
      if (tmp == NULL) break;
603,212!
433
      for (int32_t i = 0; i < length; i++) {
6,103,126✔
434
        tmp[bufIndex] = val[i];
5,499,914✔
435
        bufIndex++;
5,499,914✔
436
        if (val[i] == '\"') {
5,499,914!
437
          tmp[bufIndex] = val[i];
×
438
          bufIndex++;
×
439
        }
440
      }
441
      tmp[bufIndex] = 0;
603,212✔
442

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

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

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

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

510
  for (int32_t col = 0; col < num_fields; col++) {
236✔
511
    if (col > 0) {
189✔
512
      taosFprintfFile(pFile, ",");
142✔
513
    }
514
    taosFprintfFile(pFile, "%s", fields[col].name);
189✔
515
  }
516
  taosFprintfFile(pFile, "\r\n");
47✔
517

518
  int64_t numOfRows = 0;
47✔
519
  do {
520
    int32_t *length = taos_fetch_lengths(tres);
323,451✔
521
    for (int32_t i = 0; i < num_fields; i++) {
2,509,476✔
522
      if (i > 0) {
2,186,025✔
523
        taosFprintfFile(pFile, ",");
1,862,574✔
524
      }
525
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
2,186,025✔
526
    }
527
    taosFprintfFile(pFile, "\r\n");
323,451✔
528

529
    numOfRows++;
323,451✔
530
    row = taos_fetch_row(tres);
323,451✔
531
  } while (row != NULL);
323,451✔
532

533
  taosCloseFile(&pFile);
47✔
534

535
  return numOfRows;
47✔
536
}
537

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

542
  while (pos < length) {
2,992,547✔
543
    TdWchar wc;
544
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
2,807,430✔
545
    if (bytes <= 0) {
2,807,430✔
546
      break;
5,382✔
547
    }
548

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

560
    if (w <= 0) {
2,807,365✔
561
      continue;
90,859✔
562
    }
563

564
    if (width <= 0) {
2,807,347✔
565
      printf("%lc", wc);
90,841✔
566
      continue;
90,841✔
567
    }
568

569
    totalCols += w;
2,716,506✔
570
    if (totalCols > width) {
2,716,506✔
571
      break;
5,317✔
572
    }
573
    if (totalCols <= (width - 3)) {
2,711,189✔
574
      printf("%lc", wc);
2,692,905✔
575
      cols += w;
2,692,905✔
576
    } else {
577
      tail[tailLen] = wc;
18,284✔
578
      tailLen++;
18,284✔
579
    }
580
  }
581

582
  if (totalCols > width) {
190,499✔
583
    // width could be 1 or 2, so printf("...") cannot be used
584
    for (int32_t i = 0; i < 3; i++) {
21,268✔
585
      if (cols >= width) {
15,951!
586
        break;
×
587
      }
588
      putchar('.');
15,951✔
589
      ++cols;
15,951✔
590
    }
591
  } else {
592
    for (int32_t i = 0; i < tailLen; i++) {
187,533✔
593
      printf("%lc", tail[i]);
2,351✔
594
    }
595
    cols = totalCols;
185,182✔
596
  }
597

598
  for (; cols < width; cols++) {
2,524,166✔
599
    putchar(' ');
2,333,667✔
600
  }
601
}
190,499✔
602

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

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

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

625
  int32_t code = TSDB_CODE_FAILED;
×
626

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

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

640
  shellPrintString(outputWKT, width);
×
641

642
  geosFreeBuffer(outputWKT);
×
643
}
644

645
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision) {
1,651,858✔
646
  if (val == NULL) {
1,651,858✔
647
    shellPrintString(TSDB_DATA_NULL_STR, width);
717,318✔
648
    return;
717,318✔
649
  }
650

651
  int n = 0;
934,540✔
652
#define LENGTH 64
653
  char buf[LENGTH] = {0};
934,540✔
654
  switch (field->type) {
934,540!
655
    case TSDB_DATA_TYPE_BOOL:
51,165✔
656
      shellPrintString(((((int32_t)(*((char *)val))) == TSDB_FALSE) ? "false" : "true"), width);
51,165✔
657
      break;
51,165✔
658
    case TSDB_DATA_TYPE_TINYINT:
36,446✔
659
      printf("%*d", width, *((int8_t *)val));
36,446✔
660
      break;
36,446✔
661
    case TSDB_DATA_TYPE_UTINYINT:
57,081✔
662
      printf("%*u", width, *((uint8_t *)val));
57,081✔
663
      break;
57,081✔
664
    case TSDB_DATA_TYPE_SMALLINT:
28,985✔
665
      printf("%*d", width, *((int16_t *)val));
28,985✔
666
      break;
28,985✔
667
    case TSDB_DATA_TYPE_USMALLINT:
67,052✔
668
      printf("%*u", width, *((uint16_t *)val));
67,052✔
669
      break;
67,052✔
670
    case TSDB_DATA_TYPE_INT:
58,736✔
671
      printf("%*d", width, *((int32_t *)val));
58,736✔
672
      break;
58,736✔
673
    case TSDB_DATA_TYPE_UINT:
41,583✔
674
      printf("%*u", width, *((uint32_t *)val));
41,583✔
675
      break;
41,583✔
676
    case TSDB_DATA_TYPE_BIGINT:
81,889✔
677
      printf("%*" PRId64, width, taosGetInt64Aligned((int64_t *)val));
81,889✔
678
      break;
81,889✔
679
    case TSDB_DATA_TYPE_UBIGINT:
30,604✔
680
      printf("%*" PRIu64, width, taosGetUInt64Aligned((uint64_t *)val));
30,604✔
681
      break;
30,604✔
682
    case TSDB_DATA_TYPE_FLOAT:
39,264✔
683
      width = width >= LENGTH ? LENGTH - 1 : width;
39,264✔
684
      if (tsEnableScience) {
39,264!
685
        printf("%*.7e", width, taosGetFloatAligned((float *)val));
×
686
      } else {
687
        snprintf(buf, LENGTH, "%*.*g", width, FLT_DIG, taosGetFloatAligned((float *)val));
39,264✔
688
        printf("%s", buf);
39,264✔
689
      }
690
      break;
39,264✔
691
    case TSDB_DATA_TYPE_DOUBLE:
45,345✔
692
      width = width >= LENGTH ? LENGTH - 1 : width;
45,345✔
693
      if (tsEnableScience) {
45,345!
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));
45,345✔
698
        printf("%*s", width, buf);
45,345✔
699
      }
700
      break;
45,345✔
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:
190,499✔
712
    case TSDB_DATA_TYPE_NCHAR:
713
    case TSDB_DATA_TYPE_JSON:
714
      shellPrintNChar(val, length, width);
190,499✔
715
      break;
190,499✔
716
    case TSDB_DATA_TYPE_GEOMETRY:
×
717
      shellPrintGeometry(val, length, width);
×
718
      break;
×
719
    case TSDB_DATA_TYPE_TIMESTAMP:
205,889✔
720
      shellFormatTimestamp(buf, sizeof(buf), taosGetInt64Aligned((int64_t *)val), precision);
205,889✔
721
      printf("%s", buf);
205,889✔
722
      break;
205,889✔
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:
2✔
736
    case TSDB_DATA_TYPE_DECIMAL64:
737
      printf("%*s", width, val);
2✔
738
    default:
2✔
739
      break;
2✔
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) {
10,287✔
779
  dump_info->sql = sql;
10,287✔
780
  dump_info->vertical = vertical;
10,287✔
781
  tsem_init(&dump_info->sem, 0, 0);
10,287✔
782
  dump_info->numOfAllRows = 0;
10,287✔
783

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

788
  dump_info->resShowMaxNum = UINT64_MAX;
10,287✔
789

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

794
  if (vertical) {
10,287✔
795
    dump_info->maxColNameLen = 0;
71✔
796
    for (int32_t col = 0; col < dump_info->numFields; col++) {
177✔
797
      int32_t len = (int32_t)strlen(dump_info->fields[col].name);
106✔
798
      if (len > dump_info->maxColNameLen) {
106✔
799
        dump_info->maxColNameLen = len;
83✔
800
      }
801
    }
802
  } else {
803
    for (int32_t col = 0; col < dump_info->numFields; col++) {
34,233✔
804
      dump_info->width[col] = shellCalcColWidth(dump_info->fields + col, dump_info->precision);
24,017✔
805
    }
806
  }
807
}
10,287✔
808

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

816
  int64_t numOfPintRows = dump_info->numOfAllRows;
71✔
817
  int     numOfPrintRowsThisOne = 0;
71✔
818

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

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

824
    for (int32_t i = 0; i < dump_info->numFields; i++) {
3,285✔
825
      TAOS_FIELD *field = dump_info->fields + i;
1,710✔
826

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

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

835
    numOfPintRows++;
1,575✔
836
    numOfPrintRowsThisOne++;
1,575✔
837

838
    if (numOfPintRows == dump_info->resShowMaxNum) {
1,575!
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,575✔
850
      return;
71✔
851
    }
852

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

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

861
  switch (field->type) {
24,017!
862
    case TSDB_DATA_TYPE_NULL:
×
863
      return TMAX(4, width);  // null
×
864
    case TSDB_DATA_TYPE_BOOL:
573✔
865
      return TMAX(5, width);  // 'false'
573✔
866

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

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

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

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

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

886
    case TSDB_DATA_TYPE_DOUBLE:
2,126✔
887
      return TMAX(SHELL_DOUBLE_WIDTH, width);
2,126✔
888

889
    case TSDB_DATA_TYPE_BINARY:
4,510✔
890
    case TSDB_DATA_TYPE_GEOMETRY:
891
      if (field->bytes > shell.args.displayWidth) {
4,510✔
892
        return TMAX(shell.args.displayWidth, width);
2,384✔
893
      } else {
894
        return TMAX(field->bytes + 2, width);
2,126✔
895
      }
896
    case TSDB_DATA_TYPE_VARBINARY: {
8✔
897
      int32_t bytes = field->bytes * 2 + 2;
8✔
898
      if (bytes > shell.args.displayWidth) {
8!
899
        return TMAX(shell.args.displayWidth, width);
×
900
      } else {
901
        return TMAX(bytes + 2, width);
8✔
902
      }
903
    }
904
    case TSDB_DATA_TYPE_NCHAR:
951✔
905
    case TSDB_DATA_TYPE_JSON: {
906
      uint16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
951✔
907
      if (bytes > shell.args.displayWidth) {
951!
908
        return TMAX(shell.args.displayWidth, width);
951✔
909
      } else {
910
        return TMAX(bytes + 2, width);
×
911
      }
912
    }
913

914
    case TSDB_DATA_TYPE_TIMESTAMP:
4,989✔
915
      if (shell.args.is_raw_time) {
4,989✔
916
        return TMAX(14, width);
2✔
917
      }
918
      if (precision == TSDB_TIME_PRECISION_NANO) {
4,987✔
919
        return TMAX(29, width);
2✔
920
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
4,985✔
921
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
2✔
922
      } else {
923
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
4,983✔
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:
1✔
936
      return TMAX(width, 20);
1✔
937
    case TSDB_DATA_TYPE_DECIMAL:
1✔
938
      return TMAX(width, 40);
1✔
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) {
9,634✔
947
  int32_t rowWidth = 0;
9,634✔
948
  for (int32_t col = 0; col < num_fields; col++) {
30,884✔
949
    TAOS_FIELD *field = fields + col;
21,250✔
950
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
21,250✔
951
    int32_t     left = padding / 2;
21,250✔
952
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
21,250✔
953
    rowWidth += width[col] + 3;
21,250✔
954
  }
955

956
  putchar('\r');
9,634✔
957
  putchar('\n');
9,634✔
958
  for (int32_t i = 0; i < rowWidth; i++) {
549,429✔
959
    putchar('=');
539,795✔
960
  }
961
  putchar('\r');
9,634✔
962
  putchar('\n');
9,634✔
963
}
9,634✔
964

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

972
  int64_t numOfPintRows = dump_info->numOfAllRows;
10,555✔
973
  int     numOfPrintRowsThisOne = 0;
10,555✔
974
  if (numOfPintRows == 0) {
10,555✔
975
    shellPrintHeader(dump_info->fields, dump_info->width, dump_info->numFields);
9,634✔
976
  }
977

978
  while (row != NULL) {
261,254!
979
    int32_t *length = taos_fetch_lengths(tres);
261,254✔
980
    for (int32_t i = 0; i < dump_info->numFields; i++) {
1,911,402✔
981
      putchar(' ');
1,650,148✔
982
      shellPrintField((const char *)row[i], dump_info->fields + i, dump_info->width[i], length[i],
1,650,148✔
983
                      dump_info->precision);
984
      putchar(' ');
1,650,148✔
985
      putchar('|');
1,650,148✔
986
    }
987
    putchar('\r');
261,254✔
988
    putchar('\n');
261,254✔
989

990
    numOfPintRows++;
261,254✔
991
    numOfPrintRowsThisOne++;
261,254✔
992

993
    if (numOfPintRows == dump_info->resShowMaxNum) {
261,254!
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) {
261,254✔
1009
      return;
10,555✔
1010
    }
1011

1012
    row = taos_fetch_row(tres);
250,699✔
1013
  }
1014
  return;
×
1015
}
1016

1017
void shellDumpResultCallback(void *param, TAOS_RES *tres, int num_of_rows) {
20,913✔
1018
  tsDumpInfo *dump_info = (tsDumpInfo *)param;
20,913✔
1019
  if (num_of_rows > 0) {
20,913✔
1020
    dump_info->numOfRows = num_of_rows;
10,626✔
1021
    if (dump_info->numOfAllRows < dump_info->resShowMaxNum) {
10,626!
1022
      if (dump_info->vertical) {
10,626✔
1023
        shellVerticalPrintResult(tres, dump_info);
71✔
1024
      } else {
1025
        shellHorizontalPrintResult(tres, dump_info);
10,555✔
1026
      }
1027
    }
1028
    dump_info->numOfAllRows += num_of_rows;
10,626✔
1029
    if (!shellCmdkilled) {
10,626!
1030
      taos_fetch_rows_a(tres, shellDumpResultCallback, param);
10,626✔
1031
    } else {
1032
      tsem_post(&dump_info->sem);
×
1033
    }
1034
  } else {
1035
    if (num_of_rows < 0) {
10,287!
1036
      printf("\033[31masync retrieve failed, code: %d\033, %s[0m\n", num_of_rows, tstrerror(num_of_rows));
×
1037
    }
1038
    tsem_post(&dump_info->sem);
10,287✔
1039
  }
1040
}
20,913✔
1041

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

1056
  *error_no = shellCmdkilled ? TSDB_CODE_TSC_QUERY_KILLED : taos_errno(tres);
10,334!
1057
  return num_of_rows;
10,334✔
1058
}
1059

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

1065
  char   *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
1,668!
1066
  int32_t read_size = 0;
1,668✔
1067
  while ((read_size = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) > 0) {
13,598,623✔
1068
    line[read_size - 1] = '\0';
13,596,955✔
1069
    taosMemoryFree(pHistory->hist[pHistory->hend]);
13,596,955!
1070
    pHistory->hist[pHistory->hend] = taosStrdup(line);
13,596,955!
1071

1072
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
13,596,955✔
1073

1074
    if (pHistory->hend == pHistory->hstart) {
13,596,955✔
1075
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
11,930,623✔
1076
    }
1077
  }
1078

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

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

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

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

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

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

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

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

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

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

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

1161
  char *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
140!
1162
  while ((read_len = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) > 0) {
14,325✔
1163
    if (cmd_len + read_len >= TSDB_MAX_ALLOWED_SQL_LEN) {
14,185!
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, TSDB_MAX_ALLOWED_SQL_LEN + 1);
×
1168
      continue;
×
1169
    }
1170
    line[--read_len] = '\0';
14,185✔
1171

1172
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
14,185!
1173
      continue;
305✔
1174
    }
1175

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

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

1194
  taosMemoryFree(cmd);
140!
1195
  taosMemoryFreeClear(line);
140!
1196
  taosCloseFile(&pFile);
140✔
1197
}
1198

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

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

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

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

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

1240
    tstrncpy(serverVersion, row[0], 64);
5✔
1241
    memcpy(expiretime, row[1], fields[1].bytes);
5✔
1242
    memcpy(expired, row[2], fields[2].bytes);
5✔
1243
    
1244
    trimStr(serverVersion, "trial");
5✔
1245
    
1246
    if (strcmp(serverVersion, "community") == 0) {
5!
1247
      verType = TSDB_VERSION_OSS;
×
1248
    } else if (strcmp(expiretime, "unlimited") == 0) {
5!
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;
5✔
1253
      sprintf(buf, "Server is %s %s. License will expire at %s.\r\n", serverVersion, sinfo, expiretime);
5✔
1254
    }
1255

1256
    taos_free_result(tres);
5✔
1257
  }
1258

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

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

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

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

1290
    if (shell.conn) {
10✔
1291
      shellCmdkilled = true;
5✔
1292
      taos_kill_query(shell.conn);
5✔
1293
    }
1294

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

1300
  return NULL;
5✔
1301
}
1302

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

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

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

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

1322
      if (shellReadCommand(command) != 0) {
10✔
1323
        break;
5✔
1324
      }
1325

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

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

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

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

1348
  // set mode
1349
  if (pArgs->connMode != CONN_MODE_NATIVE && pArgs->dsn) {
1,690✔
1350
    dsnc = strToLowerCopy(pArgs->dsn);
19✔
1351
    if (dsnc == NULL) {
19!
1352
      return NULL;
2✔
1353
    }
1354

1355
    char *cport = NULL;
19✔
1356
    char  error[512] = "\0";
19✔
1357
    code = parseDsn(dsnc, &host, &cport, &user, &pwd, error);
19✔
1358
    if (code) {
19✔
1359
      printf("%s dsn=%s\n", error, dsnc);
2✔
1360
      free(dsnc);
2✔
1361
      return NULL;
2✔
1362
    }
1363

1364
    // default ws port
1365
    if (cport == NULL) {
17✔
1366
      if (user)
1!
1367
        port = DEFAULT_PORT_WS_CLOUD;
1✔
1368
      else
1369
        port = DEFAULT_PORT_WS_LOCAL;
×
1370
    } else {
1371
      port = atoi(cport);
16✔
1372
    }
1373

1374
    // websocket
1375
    memcpy(show, pArgs->dsn, 20);
17✔
1376
    memcpy(show + 20, "...", 3);
17✔
1377
    memcpy(show + 23, pArgs->dsn + strlen(pArgs->dsn) - 10, 10);
17✔
1378

1379
  } else {
1380
    host = (char *)pArgs->host;
1,671✔
1381
    user = (char *)pArgs->user;
1,671✔
1382
    pwd = pArgs->password;
1,671✔
1383

1384
    if (pArgs->port_inputted) {
1,671✔
1385
      port = pArgs->port;
9✔
1386
    } else {
1387
      port = defaultPort(pArgs->connMode, pArgs->dsn);
1,662✔
1388
    }
1389

1390
    sprintf(show, "host:%s port:%d ", host, port);
1,671✔
1391
  }
1392

1393
  // connect main
1394
  TAOS *taos = NULL;
1,688✔
1395
  if (pArgs->auth) {
1,688✔
1396
    taos = taos_connect_auth(host, user, pArgs->auth, pArgs->database, port);
3✔
1397
  } else {
1398
    taos = taos_connect(host, user, pwd, pArgs->database, port);
1,685✔
1399
  }
1400

1401
  // host user pointer in dsnc address
1402
  free(dsnc);
1,688✔
1403
  return taos;
1,688✔
1404
}
1405

1406
int32_t shellExecute(int argc, char *argv[]) {
1,690✔
1407
  int32_t code = 0;
1,690✔
1408
  printf(shell.info.clientVersion, shell.info.cusName,
3,380✔
1409
         workingMode(shell.args.connMode, shell.args.dsn) == CONN_MODE_NATIVE ? STR_NATIVE : STR_WEBSOCKET,
1,690✔
1410
         taos_get_client_info(), shell.info.cusName);
1411
  fflush(stdout);
1,690✔
1412

1413
  SShellArgs *pArgs = &shell.args;
1,690✔
1414
  shell.conn = createConnect(pArgs);
1,690✔
1415

1416
  if (shell.conn == NULL) {
1,690✔
1417
    printf("failed to connect to server, reason: %s [0x%08X]\n%s", taos_errstr(NULL), taos_errno(NULL),
22✔
1418
           ERROR_CODE_DETAIL);
1419
    fflush(stdout);
22✔
1420
    return -1;
22✔
1421
  }
1422

1423
  bool runOnce = pArgs->commands != NULL || pArgs->file[0] != 0;
1,668✔
1424
  shellSetConn(shell.conn, runOnce);
1,668✔
1425
  shellReadHistory();
1,668✔
1426

1427
  if (shell.args.is_bi_mode) {
1,668✔
1428
    // need set bi mode
1429
    printf("Set BI mode is true.\n");
6✔
1430
    taos_set_conn_mode(shell.conn, TAOS_CONN_MODE_BI, 1);
6✔
1431
  }
1432

1433
  if (runOnce) {
1,668✔
1434
    if (pArgs->commands != NULL) {
1,663✔
1435
      printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
1,389✔
1436
      char *cmd = taosStrdup(pArgs->commands);
1,389!
1437
      shellRunCommand(cmd, true);
1,389✔
1438
      taosMemoryFree(cmd);
1,389!
1439
    }
1440

1441
    if (pArgs->file[0] != 0) {
1,663✔
1442
      shellSourceFile(pArgs->file);
274✔
1443
    }
1444

1445
    taos_close(shell.conn);
1,663✔
1446

1447
    shellWriteHistory();
1,663✔
1448
    shellCleanupHistory();
1,663✔
1449
    return 0;
1,663✔
1450
  }
1451

1452
  if ((code = tsem_init(&shell.cancelSem, 0, 0)) != 0) {
5!
1453
    printf("failed to create cancel semaphore since %s\r\n", tstrerror(code));
×
1454
    return code;
×
1455
  }
1456

1457
  TdThread spid = {0};
5✔
1458
  taosThreadCreate(&spid, NULL, shellCancelHandler, NULL);
5✔
1459

1460
  taosSetSignal(SIGTERM, shellQueryInterruptHandler);
5✔
1461
  taosSetSignal(SIGHUP, shellQueryInterruptHandler);
5✔
1462
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
5✔
1463

1464
  char    buf[512] = {0};
5✔
1465
  int32_t verType = shellGetGrantInfo(buf);
5✔
1466
#ifndef WINDOWS
1467
  printfIntroduction(verType);
5✔
1468
#else
1469
  if (verType == TSDB_VERSION_OSS) {
1470
    showAD(false);
1471
  }
1472
#endif
1473
  // printf version
1474
  if (verType == TSDB_VERSION_ENTERPRISE || verType == TSDB_VERSION_CLOUD) {
5!
1475
    printf("%s\n", buf);
5✔
1476
  }
1477

1478
  while (1) {
1479
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
5✔
1480
    taosThreadJoin(shell.pid, NULL);
5✔
1481
    taosThreadClear(&shell.pid);
5✔
1482
    if (shell.exit) {
5!
1483
      tsem_post(&shell.cancelSem);
5✔
1484
      break;
5✔
1485
    }
1486
  }
1487

1488
  if (verType == TSDB_VERSION_OSS) {
5!
1489
    showAD(true);
×
1490
  }
1491

1492
  taosThreadJoin(spid, NULL);
5✔
1493

1494
  shellCleanupHistory();
5✔
1495
  taos_kill_query(shell.conn);
5✔
1496
  taos_close(shell.conn);
5✔
1497

1498
  TAOS_RETURN(code);
5✔
1499
}
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

© 2025 Coveralls, Inc