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

taosdata / TDengine / #3534

21 Nov 2024 07:36AM UTC coverage: 60.825% (+2.0%) from 58.848%
#3534

push

travis-ci

web-flow
Merge pull request #28810 from taosdata/ehn/add-sync-heartbeat-sent-time-to-log

ehn:add-sync-heartbeat-sent-time-to-log

120023 of 252376 branches covered (47.56%)

Branch coverage included in aggregate %.

43 of 47 new or added lines in 3 files covered. (91.49%)

2254 existing lines in 162 files now uncovered.

200876 of 275203 relevant lines covered (72.99%)

16110754.39 hits per line

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

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

16
#define ALLOW_FORBID_FUNC
17
#define _BSD_SOURCE
18
#define _GNU_SOURCE
19
#define _XOPEN_SOURCE
20
#define _DEFAULT_SOURCE
21
#include "geosWrapper.h"
22
#include "shellAuto.h"
23
#include "shellInt.h"
24

25
SShellObj shell = {0};
26

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

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

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

41
  uint64_t resShowMaxNum;
42
} tsDumpInfo;
43

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

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

67
static bool shellCmdkilled = false;
68

69
bool shellIsEmptyCommand(const char *cmd) {
801,835✔
70
  for (char c = *cmd++; c != 0; c = *cmd++) {
984,268✔
71
    if (c != ' ' && c != '\t' && c != ';') {
602,611!
72
      return false;
420,178✔
73
    }
74
  }
75
  return true;
381,657✔
76
}
77

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

81
  if (shellIsEmptyCommand(command)) {
592,354✔
82
    return 0;
381,657✔
83
  }
84

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

89
  if (shellRegexMatch(command, "^[\t ]*clear[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
210,697!
90
#pragma GCC diagnostic push
91
#pragma GCC diagnostic ignored "-Wunused-result"
92
    system("clear");
×
93
#pragma GCC diagnostic pop
94
    return 0;
×
95
  }
96

97
  if (shellRegexMatch(command, "^[\t ]*set[ \t]+max_binary_display_width[ \t]+(default|[1-9][0-9]*)[ \t;]*$",
210,697!
98
                      REG_EXTENDED | REG_ICASE)) {
99
    strtok(command, " \t");
×
100
    strtok(NULL, " \t");
×
101
    char *p = strtok(NULL, " \t");
×
102
    if (strncasecmp(p, "default", 7) == 0) {
×
103
      shell.args.displayWidth = SHELL_DEFAULT_MAX_BINARY_DISPLAY_WIDTH;
×
104
    } else {
105
      int32_t displayWidth = atoi(p);
×
106
      displayWidth = TRANGE(displayWidth, 1, 10 * 1024);
×
107
      shell.args.displayWidth = displayWidth;
×
108
    }
109
    return 0;
×
110
  }
111

112
  if (shellRegexMatch(command, "^[ \t]*source[\t ]+[^ ]+[ \t;]*$", REG_EXTENDED | REG_ICASE)) {
210,697✔
113
    /* If source file. */
114
    char *c_ptr = strtok(command, " ;");
1✔
115
    if (c_ptr == NULL) {
1!
116
      shellRunSingleCommandImp(command);
×
117
      return 0;
×
118
    }
119
    c_ptr = strtok(NULL, " ;");
1✔
120
    if (c_ptr == NULL) {
1!
121
      shellRunSingleCommandImp(command);
×
122
      return 0;
×
123
    }
124
    shellSourceFile(c_ptr);
1✔
125
    return 0;
1✔
126
  }
127
#ifdef WEBSOCKET
128
  if (shell.args.restful || shell.args.cloud) {
129
    shellRunSingleCommandWebsocketImp(command);
130
  } else {
131
#endif
132
    shellRunSingleCommandImp(command);
210,696✔
133
#ifdef WEBSOCKET
134
  }
135
#endif
136
  return 0;
210,696✔
137
}
138

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

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

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

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

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

176
  if (recordHistory) shellRecordCommandToHistory(command);
209,481✔
177

178
  char quote = 0, *cmd = command;
209,481✔
179
  for (char c = *command++; c != 0; c = *command++) {
156,921,577✔
180
    if (c == '\\' && (*command == '\'' || *command == '"' || *command == '`')) {
156,712,096!
181
      command++;
2✔
182
      continue;
2✔
183
    }
184

185
    if (quote == c) {
156,712,094✔
186
      quote = 0;
2,186,840✔
187
    } else if (quote == 0 && (c == '\'' || c == '"' || c == '`')) {
154,525,254✔
188
      quote = c;
2,186,840✔
189
    } else if (c == ';' && quote == 0) {
152,338,414✔
190
      c = *command;
382,873✔
191
      *command = 0;
382,873✔
192
      if (shellRunSingleCommand(cmd) < 0) {
382,873!
193
        return -1;
×
194
      }
195
      *command = c;
382,873✔
196
      cmd = command;
382,873✔
197
    }
198
  }
199
  return shellRunSingleCommand(cmd);
209,481✔
200
}
201

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

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

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

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

222
  return NULL;
210,637✔
223
}
224

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

232
  if ((sptr = strstr(command, ">>")) != NULL) {
210,696✔
233
    fname = sptr + 2;
43✔
234
    while (*fname == ' ') fname++;
74✔
235
    *sptr = '\0';
43✔
236

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

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

248
  st = taosGetTimestampUs();
210,696✔
249

250
  TAOS_RES *pSql = taos_query(shell.conn, command);
210,696✔
251
  if (taos_errno(pSql)) {
210,696✔
252
    shellPrintError(pSql, st);
2,846✔
253
    return;
2,846✔
254
  }
255

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

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

263
    taos_free_result(pSql);
170✔
264

265
    return;
170✔
266
  }
267

268
  // pre string
269
  char *pre = "Query OK";
207,680✔
270
  if (shellRegexMatch(command, "^\\s*delete\\s*from\\s*.*", REG_EXTENDED | REG_ICASE)) {
207,680✔
271
    pre = "Delete OK";
25✔
272
  } else if (shellRegexMatch(command, "^\\s*insert\\s*into\\s*.*", REG_EXTENDED | REG_ICASE)) {
207,655✔
273
    pre = "Insert OK";
117,975✔
274
  } else if (shellRegexMatch(command, "^\\s*create\\s*.*", REG_EXTENDED | REG_ICASE)) {
89,680✔
275
    pre = "Create OK";
4,131✔
276
  } else if (shellRegexMatch(command, "^\\s*drop\\s*.*", REG_EXTENDED | REG_ICASE)) {
85,549✔
277
    pre = "Drop OK";
152✔
278
  }
279

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

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

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

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

306
  printf("\r\n");
207,680✔
307
}
308

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

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

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

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

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

353
  return buf;
4,069,604✔
354
}
355

356
char *shellDumpHexValue(char *buf, const char *val, int32_t length) {
×
357
  for (int32_t i = 0; i < length; i++) {
×
358
    sprintf(buf + (i * 2), "%02X", val[i]);
×
359
  }
360
  buf[length * 2] = 0;
×
361

362
  return buf;
×
363
}
364

365
void shellDumpFieldToFile(TdFilePtr pFile, const char *val, TAOS_FIELD *field, int32_t length, int32_t precision) {
2,185,983✔
366
  if (val == NULL) {
2,185,983✔
367
    taosFprintfFile(pFile, "NULL");
12,766✔
368
    return;
12,766✔
369
  }
370

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

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

448
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
603,212✔
449
      taosMemoryFree(tmp);
603,212✔
450
    } break;
603,212✔
451
    case TSDB_DATA_TYPE_VARBINARY: {
×
452
      void    *tmp = NULL;
×
453
      uint32_t size = 0;
×
454
      if (taosAscii2Hex(val, length, &tmp, &size) < 0) {
×
455
        break;
×
456
      }
457
      taosFprintfFile(pFile, "%s%s%s", quotationStr, tmp, quotationStr);
×
458
      taosMemoryFree(tmp);
×
459
      break;
×
460
    }
461
    case TSDB_DATA_TYPE_GEOMETRY: {
×
462
      char *tmp = (char *)taosMemoryCalloc(length * 2 + 1, 1);
×
463
      if (tmp == NULL) break;
×
464
      shellDumpHexValue(tmp, val, length);
×
465
      taosFprintfFile(pFile, "%s", buf);
×
466
      taosMemoryFree(tmp);
×
467
      break;
×
468
    }
469
    case TSDB_DATA_TYPE_TIMESTAMP:
453,435✔
470
      shellFormatTimestamp(buf, sizeof(buf), *(int64_t *)val, precision);
453,435✔
471
      taosFprintfFile(pFile, "%s%s%s", quotationStr, buf, quotationStr);
453,435✔
472
      break;
453,435✔
473
    default:
×
474
      break;
×
475
  }
476
}
477

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

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

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

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

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

507
  int64_t numOfRows = 0;
43✔
508
  do {
509
    int32_t *length = taos_fetch_lengths(tres);
323,439✔
510
    for (int32_t i = 0; i < num_fields; i++) {
2,509,422✔
511
      if (i > 0) {
2,185,983✔
512
        taosFprintfFile(pFile, ",");
1,862,544✔
513
      }
514
      shellDumpFieldToFile(pFile, (const char *)row[i], fields + i, length[i], precision);
2,185,983✔
515
    }
516
    taosFprintfFile(pFile, "\r\n");
323,439✔
517

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

522
  taosCloseFile(&pFile);
43✔
523

524
  return numOfRows;
43✔
525
}
526

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

531
  while (pos < length) {
42,795,877✔
532
    TdWchar wc;
533
    int32_t bytes = taosMbToWchar(&wc, str + pos, MB_CUR_MAX);
41,876,248✔
534
    if (bytes <= 0) {
41,876,248✔
535
      break;
715,989✔
536
    }
537

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

549
    if (w <= 0) {
41,876,239!
550
      continue;
84,699✔
551
    }
552

553
    if (width <= 0) {
41,876,239✔
554
      printf("%lc", wc);
84,699✔
555
      continue;
84,699✔
556
    }
557

558
    totalCols += w;
41,791,540✔
559
    if (totalCols > width) {
41,791,540✔
560
      break;
715,980✔
561
    }
562
    if (totalCols <= (width - 3)) {
41,075,560✔
563
      printf("%lc", wc);
38,543,001✔
564
      cols += w;
38,543,001✔
565
    } else {
566
      tail[tailLen] = wc;
2,532,559✔
567
      tailLen++;
2,532,559✔
568
    }
569
  }
570

571
  if (totalCols > width) {
1,635,618✔
572
    // width could be 1 or 2, so printf("...") cannot be used
573
    for (int32_t i = 0; i < 3; i++) {
2,863,920✔
574
      if (cols >= width) {
2,147,940!
575
        break;
×
576
      }
577
      putchar('.');
2,147,940✔
578
      ++cols;
2,147,940✔
579
    }
580
  } else {
581
    for (int32_t i = 0; i < tailLen; i++) {
1,304,266✔
582
      printf("%lc", tail[i]);
384,628✔
583
    }
584
    cols = totalCols;
919,638✔
585
  }
586

587
  for (; cols < width; cols++) {
9,473,249✔
588
    putchar(' ');
7,837,631✔
589
  }
590
}
1,635,618✔
591

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

595
  if (width == 0) {
1,673,876!
596
    printf("%s", str);
×
597
  } else if (len > width) {
1,673,876!
598
    if (width <= 3) {
×
599
      printf("%.*s.", width - 1, str);
×
600
    } else {
601
      printf("%.*s...", width - 3, str);
×
602
    }
603
  } else {
604
    printf("%s%*.s", str, width - len, "");
1,673,876✔
605
  }
606
}
1,673,876✔
607

608
void shellPrintGeometry(const unsigned char *val, int32_t length, int32_t width) {
×
609
  if (length == 0) {  // empty value
×
610
    shellPrintString("", width);
×
611
    return;
×
612
  }
613

614
  int32_t code = TSDB_CODE_FAILED;
×
615

616
  code = initCtxAsText();
×
617
  if (code != TSDB_CODE_SUCCESS) {
×
618
    shellPrintString(getGeosErrMsg(code), width);
×
619
    return;
×
620
  }
621

622
  char *outputWKT = NULL;
×
623
  code = doAsText(val, length, &outputWKT);
×
624
  if (code != TSDB_CODE_SUCCESS) {
×
625
    shellPrintString(getGeosErrMsg(code), width);  // should NOT happen
×
626
    return;
×
627
  }
628

629
  shellPrintString(outputWKT, width);
×
630

631
  geosFreeBuffer(outputWKT);
×
632
}
633

634
void shellPrintField(const char *val, TAOS_FIELD *field, int32_t width, int32_t length, int32_t precision) {
8,899,319✔
635
  if (val == NULL) {
8,899,319✔
636
    shellPrintString(TSDB_DATA_NULL_STR, width);
1,593,887✔
637
    return;
1,593,887✔
638
  }
639

640
  int n = 0;
7,305,432✔
641
#define LENGTH 64
642
  char buf[LENGTH] = {0};
7,305,432✔
643
  switch (field->type) {
7,305,432!
644
    case TSDB_DATA_TYPE_BOOL:
79,989✔
645
      shellPrintString(((((int32_t)(*((char *)val))) == TSDB_FALSE) ? "false" : "true"), width);
79,989✔
646
      break;
79,989✔
647
    case TSDB_DATA_TYPE_TINYINT:
103,395✔
648
      printf("%*d", width, *((int8_t *)val));
103,395✔
649
      break;
103,395✔
650
    case TSDB_DATA_TYPE_UTINYINT:
109✔
651
      printf("%*u", width, *((uint8_t *)val));
109✔
652
      break;
109✔
653
    case TSDB_DATA_TYPE_SMALLINT:
100,910✔
654
      printf("%*d", width, *((int16_t *)val));
100,910✔
655
      break;
100,910✔
656
    case TSDB_DATA_TYPE_USMALLINT:
×
657
      printf("%*u", width, *((uint16_t *)val));
×
658
      break;
×
659
    case TSDB_DATA_TYPE_INT:
105,317✔
660
      printf("%*d", width, *((int32_t *)val));
105,317✔
661
      break;
105,317✔
662
    case TSDB_DATA_TYPE_UINT:
×
663
      printf("%*u", width, *((uint32_t *)val));
×
664
      break;
×
665
    case TSDB_DATA_TYPE_BIGINT:
1,061,519✔
666
      printf("%*" PRId64, width, *((int64_t *)val));
1,061,519✔
667
      break;
1,061,519✔
668
    case TSDB_DATA_TYPE_UBIGINT:
×
669
      printf("%*" PRIu64, width, *((uint64_t *)val));
×
670
      break;
×
671
    case TSDB_DATA_TYPE_FLOAT:
113,874✔
672
      if (tsEnableScience) {
113,874!
673
        printf("%*.7e", width, GET_FLOAT_VAL(val));
×
674
      } else {
675
        n = tsnprintf(buf, LENGTH, "%*.7f", width, GET_FLOAT_VAL(val));
113,874✔
676
        if (n > SHELL_FLOAT_WIDTH) {
113,874✔
677
          printf("%*.7e", width, GET_FLOAT_VAL(val));
17,304✔
678
        } else {
679
          printf("%s", buf);
96,570✔
680
        }
681
      }
682
      break;
113,874✔
683
    case TSDB_DATA_TYPE_DOUBLE:
488,532✔
684
      if (tsEnableScience) {
488,532!
685
        snprintf(buf, LENGTH, "%*.15e", width, GET_DOUBLE_VAL(val));
×
686
        printf("%s", buf);
×
687
      } else {
688
        n = tsnprintf(buf, LENGTH, "%*.15f", width, GET_DOUBLE_VAL(val));
488,532✔
689
        if (n > SHELL_DOUBLE_WIDTH) {
488,532✔
690
          printf("%*.15e", width, GET_DOUBLE_VAL(val));
59,799✔
691
        } else {
692
          printf("%*s", width, buf);
428,733✔
693
        }
694
      }
695
      break;
488,532✔
696
    case TSDB_DATA_TYPE_VARBINARY: {
×
697
      void    *data = NULL;
×
698
      uint32_t size = 0;
×
699
      if (taosAscii2Hex(val, length, &data, &size) < 0) {
×
700
        break;
×
701
      }
702
      shellPrintNChar(data, size, width);
×
703
      taosMemoryFree(data);
×
704
      break;
×
705
    }
706
    case TSDB_DATA_TYPE_BINARY:
1,635,618✔
707
    case TSDB_DATA_TYPE_NCHAR:
708
    case TSDB_DATA_TYPE_JSON:
709
      shellPrintNChar(val, length, width);
1,635,618✔
710
      break;
1,635,618✔
711
    case TSDB_DATA_TYPE_GEOMETRY:
×
712
      shellPrintGeometry(val, length, width);
×
713
      break;
×
714
    case TSDB_DATA_TYPE_TIMESTAMP:
3,616,169✔
715
      shellFormatTimestamp(buf, sizeof(buf), *(int64_t *)val, precision);
3,616,169✔
716
      printf("%s", buf);
3,616,169✔
717
      break;
3,616,169✔
718
    default:
×
719
      break;
×
720
  }
721
}
722

723
// show whole result for this query return true, like limit or describe
724
bool shellIsShowWhole(const char *sql) {
×
725
  // limit
726
  if (taosStrCaseStr(sql, " limit ") != NULL) {
×
727
    return true;
×
728
  }
729
  // describe
730
  if (taosStrCaseStr(sql, "describe ") != NULL) {
×
731
    return true;
×
732
  }
733
  // show
734
  if (taosStrCaseStr(sql, "show ") != NULL) {
×
735
    return true;
×
736
  }
737
  // explain
738
  if (taosStrCaseStr(sql, "explain ") != NULL) {
×
739
    return true;
×
740
  }
741

742
  return false;
×
743
}
744

745
bool shellIsShowQuery(const char *sql) {
×
746
  // todo refactor
747
  if (taosStrCaseStr(sql, "show ") != NULL) {
×
748
    return true;
×
749
  }
750

751
  return false;
×
752
}
753

754
void init_dump_info(tsDumpInfo *dump_info, TAOS_RES *tres, const char *sql, bool vertical) {
79,282✔
755
  dump_info->sql = sql;
79,282✔
756
  dump_info->vertical = vertical;
79,282✔
757
  tsem_init(&dump_info->sem, 0, 0);
79,282✔
758
  dump_info->numOfAllRows = 0;
79,282✔
759

760
  dump_info->numFields = taos_num_fields(tres);
79,282✔
761
  dump_info->fields = taos_fetch_fields(tres);
79,282✔
762
  dump_info->precision = taos_result_precision(tres);
79,282✔
763

764
  dump_info->resShowMaxNum = UINT64_MAX;
79,282✔
765

766
  if (shell.args.commands == NULL && shell.args.file[0] == 0 && !shellIsShowWhole(dump_info->sql)) {
79,282!
767
    dump_info->resShowMaxNum = SHELL_DEFAULT_RES_SHOW_NUM;
×
768
  }
769

770
  if (vertical) {
79,282✔
771
    dump_info->maxColNameLen = 0;
59✔
772
    for (int32_t col = 0; col < dump_info->numFields; col++) {
120✔
773
      int32_t len = (int32_t)strlen(dump_info->fields[col].name);
61✔
774
      if (len > dump_info->maxColNameLen) {
61!
775
        dump_info->maxColNameLen = len;
61✔
776
      }
777
    }
778
  } else {
779
    for (int32_t col = 0; col < dump_info->numFields; col++) {
225,766✔
780
      dump_info->width[col] = shellCalcColWidth(dump_info->fields + col, dump_info->precision);
146,543✔
781
    }
782
  }
783
}
79,282✔
784

785
void shellVerticalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
59✔
786
  TAOS_ROW row = taos_fetch_row(tres);
59✔
787
  if (row == NULL) {
59!
788
    printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
789
    return;
×
790
  }
791

792
  int64_t numOfPintRows = dump_info->numOfAllRows;
59✔
793
  int     numOfPrintRowsThisOne = 0;
59✔
794

795
  while (row != NULL) {
1,473!
796
    printf("*************************** %" PRId64 ".row ***************************\r\n", numOfPintRows + 1);
1,473✔
797

798
    int32_t *length = taos_fetch_lengths(tres);
1,473✔
799

800
    for (int32_t i = 0; i < dump_info->numFields; i++) {
2,950✔
801
      TAOS_FIELD *field = dump_info->fields + i;
1,477✔
802

803
      int32_t padding = (int32_t)(dump_info->maxColNameLen - strlen(field->name));
1,477✔
804
      printf("%*.s%s: ", padding, " ", field->name);
1,477✔
805

806
      shellPrintField((const char *)row[i], field, 0, length[i], dump_info->precision);
1,477✔
807
      putchar('\r');
1,477✔
808
      putchar('\n');
1,477✔
809
    }
810

811
    numOfPintRows++;
1,473✔
812
    numOfPrintRowsThisOne++;
1,473✔
813

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

825
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
1,473✔
826
      return;
59✔
827
    }
828

829
    row = taos_fetch_row(tres);
1,414✔
830
  }
831
  return;
×
832
}
833

834
int32_t shellCalcColWidth(TAOS_FIELD *field, int32_t precision) {
146,543✔
835
  int32_t width = (int32_t)strlen(field->name);
146,543✔
836

837
  switch (field->type) {
146,543!
838
    case TSDB_DATA_TYPE_NULL:
×
839
      return TMAX(4, width);  // null
×
840
    case TSDB_DATA_TYPE_BOOL:
913✔
841
      return TMAX(5, width);  // 'false'
913✔
842

843
    case TSDB_DATA_TYPE_TINYINT:
1,164✔
844
    case TSDB_DATA_TYPE_UTINYINT:
845
      return TMAX(4, width);  // '-127'
1,164✔
846

847
    case TSDB_DATA_TYPE_SMALLINT:
3,915✔
848
    case TSDB_DATA_TYPE_USMALLINT:
849
      return TMAX(6, width);  // '-32767'
3,915✔
850

851
    case TSDB_DATA_TYPE_INT:
2,572✔
852
    case TSDB_DATA_TYPE_UINT:
853
      return TMAX(11, width);  // '-2147483648'
2,572✔
854

855
    case TSDB_DATA_TYPE_BIGINT:
29,290✔
856
    case TSDB_DATA_TYPE_UBIGINT:
857
      return TMAX(21, width);  // '-9223372036854775807'
29,290✔
858

859
    case TSDB_DATA_TYPE_FLOAT:
1,325✔
860
      return TMAX(SHELL_FLOAT_WIDTH, width);
1,325✔
861

862
    case TSDB_DATA_TYPE_DOUBLE:
19,789✔
863
      return TMAX(SHELL_DOUBLE_WIDTH, width);
19,789✔
864

865
    case TSDB_DATA_TYPE_BINARY:
45,583✔
866
    case TSDB_DATA_TYPE_GEOMETRY:
867
      if (field->bytes > shell.args.displayWidth) {
45,583✔
868
        return TMAX(shell.args.displayWidth, width);
39,287✔
869
      } else {
870
        return TMAX(field->bytes + 2, width);
6,296✔
871
      }
872
    case TSDB_DATA_TYPE_VARBINARY: {
×
873
      int32_t bytes = field->bytes * 2 + 2;
×
874
      if (bytes > shell.args.displayWidth) {
×
875
        return TMAX(shell.args.displayWidth, width);
×
876
      } else {
877
        return TMAX(bytes + 2, width);
×
878
      }
879
    }
880
    case TSDB_DATA_TYPE_NCHAR:
9,396✔
881
    case TSDB_DATA_TYPE_JSON: {
882
      uint16_t bytes = field->bytes * TSDB_NCHAR_SIZE;
9,396✔
883
      if (bytes > shell.args.displayWidth) {
9,396!
884
        return TMAX(shell.args.displayWidth, width);
9,396✔
885
      } else {
886
        return TMAX(bytes + 2, width);
×
887
      }
888
    }
889

890
    case TSDB_DATA_TYPE_TIMESTAMP:
32,596✔
891
      if (shell.args.is_raw_time) {
32,596!
892
        return TMAX(14, width);
×
893
      }
894
      if (precision == TSDB_TIME_PRECISION_NANO) {
32,596!
895
        return TMAX(29, width);
×
896
      } else if (precision == TSDB_TIME_PRECISION_MICRO) {
32,596!
897
        return TMAX(26, width);  // '2020-01-01 00:00:00.000000'
×
898
      } else {
899
        return TMAX(23, width);  // '2020-01-01 00:00:00.000'
32,596✔
900
      }
901

902
    default:
×
903
      ASSERT(false);
×
904
  }
905

906
  return 0;
×
907
}
908

909
void shellPrintHeader(TAOS_FIELD *fields, int32_t *width, int32_t num_fields) {
74,361✔
910
  int32_t rowWidth = 0;
74,361✔
911
  for (int32_t col = 0; col < num_fields; col++) {
205,598✔
912
    TAOS_FIELD *field = fields + col;
131,237✔
913
    int32_t     padding = (int32_t)(width[col] - strlen(field->name));
131,237✔
914
    int32_t     left = padding / 2;
131,237✔
915
    printf(" %*.s%s%*.s |", left, " ", field->name, padding - left, " ");
131,237✔
916
    rowWidth += width[col] + 3;
131,237✔
917
  }
918

919
  putchar('\r');
74,361✔
920
  putchar('\n');
74,361✔
921
  for (int32_t i = 0; i < rowWidth; i++) {
3,851,849✔
922
    putchar('=');
3,777,488✔
923
  }
924
  putchar('\r');
74,361✔
925
  putchar('\n');
74,361✔
926
}
74,361✔
927

928
void shellHorizontalPrintResult(TAOS_RES *tres, tsDumpInfo *dump_info) {
76,611✔
929
  TAOS_ROW row = taos_fetch_row(tres);
76,611✔
930
  if (row == NULL) {
76,611!
931
    printf("\033[31mtaos_fetch_row failed.\033[0m\n");
×
932
    return;
×
933
  }
934

935
  int64_t numOfPintRows = dump_info->numOfAllRows;
76,611✔
936
  int     numOfPrintRowsThisOne = 0;
76,611✔
937
  if (numOfPintRows == 0) {
76,611✔
938
    shellPrintHeader(dump_info->fields, dump_info->width, dump_info->numFields);
74,361✔
939
  }
940

941
  while (row != NULL) {
2,853,182!
942
    int32_t *length = taos_fetch_lengths(tres);
2,853,182✔
943
    for (int32_t i = 0; i < dump_info->numFields; i++) {
11,751,024✔
944
      putchar(' ');
8,897,842✔
945
      shellPrintField((const char *)row[i], dump_info->fields + i, dump_info->width[i], length[i],
8,897,842✔
946
                      dump_info->precision);
947
      putchar(' ');
8,897,842✔
948
      putchar('|');
8,897,842✔
949
    }
950
    putchar('\r');
2,853,182✔
951
    putchar('\n');
2,853,182✔
952

953
    numOfPintRows++;
2,853,182✔
954
    numOfPrintRowsThisOne++;
2,853,182✔
955

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

971
    if (numOfPrintRowsThisOne == dump_info->numOfRows) {
2,853,182✔
972
      return;
76,611✔
973
    }
974

975
    row = taos_fetch_row(tres);
2,776,571✔
976
  }
977
  return;
×
978
}
979

980
void shellDumpResultCallback(void *param, TAOS_RES *tres, int num_of_rows) {
155,952✔
981
  tsDumpInfo *dump_info = (tsDumpInfo *)param;
155,952✔
982
  if (num_of_rows > 0) {
155,952✔
983
    dump_info->numOfRows = num_of_rows;
76,670✔
984
    if (dump_info->numOfAllRows < dump_info->resShowMaxNum) {
76,670!
985
      if (dump_info->vertical) {
76,670✔
986
        shellVerticalPrintResult(tres, dump_info);
59✔
987
      } else {
988
        shellHorizontalPrintResult(tres, dump_info);
76,611✔
989
      }
990
    }
991
    dump_info->numOfAllRows += num_of_rows;
76,670✔
992
    if (!shellCmdkilled) {
76,670!
993
      taos_fetch_rows_a(tres, shellDumpResultCallback, param);
76,670✔
994
    } else {
995
      tsem_post(&dump_info->sem);
×
996
    }
997
  } else {
998
    if (num_of_rows < 0) {
79,282!
999
      printf("\033[31masync retrieve failed, code: %d\033[0m\n", num_of_rows);
×
1000
    }
1001
    tsem_post(&dump_info->sem);
79,282✔
1002
  }
1003
}
155,952✔
1004

1005
int64_t shellDumpResult(TAOS_RES *tres, char *fname, int32_t *error_no, bool vertical, const char *sql) {
79,325✔
1006
  int64_t num_of_rows = 0;
79,325✔
1007
  if (fname != NULL) {
79,325✔
1008
    num_of_rows = shellDumpResultToFile(fname, tres);
43✔
1009
  } else {
1010
    tsDumpInfo dump_info;
1011
    if (!shellCmdkilled) {
79,282!
1012
      init_dump_info(&dump_info, tres, sql, vertical);
79,282✔
1013
      taos_fetch_rows_a(tres, shellDumpResultCallback, &dump_info);
79,282✔
1014
      tsem_wait(&dump_info.sem);
79,282✔
1015
      num_of_rows = dump_info.numOfAllRows;
79,282✔
1016
    }
1017
  }
1018

1019
  *error_no = shellCmdkilled ? TSDB_CODE_TSC_QUERY_KILLED : taos_errno(tres);
79,325!
1020
  return num_of_rows;
79,325✔
1021
}
1022

1023
void shellReadHistory() {
2,220✔
1024
  SShellHistory *pHistory = &shell.history;
2,220✔
1025
  TdFilePtr      pFile = taosOpenFile(pHistory->file, TD_FILE_READ | TD_FILE_STREAM);
2,220✔
1026
  if (pFile == NULL) return;
2,220!
1027

1028
  char   *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
2,220✔
1029
  int32_t read_size = 0;
2,220✔
1030
  while ((read_size = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) > 0) {
22,822,615✔
1031
    line[read_size - 1] = '\0';
22,820,395✔
1032
    taosMemoryFree(pHistory->hist[pHistory->hend]);
22,820,395✔
1033
    pHistory->hist[pHistory->hend] = taosStrdup(line);
22,820,395✔
1034

1035
    pHistory->hend = (pHistory->hend + 1) % SHELL_MAX_HISTORY_SIZE;
22,820,395✔
1036

1037
    if (pHistory->hend == pHistory->hstart) {
22,820,395✔
1038
      pHistory->hstart = (pHistory->hstart + 1) % SHELL_MAX_HISTORY_SIZE;
20,602,615✔
1039
    }
1040
  }
1041

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

1058
    /* coverity[+retval] */
1059
    taosFsyncFile(pFile);
1✔
1060
    taosCloseFile(&pFile);
1✔
1061
  }
1062
  pHistory->hstart = pHistory->hend;
2,220✔
1063
}
1064

1065
void shellWriteHistory() {
2,220✔
1066
  SShellHistory *pHistory = &shell.history;
2,220✔
1067
  if (pHistory->hend == pHistory->hstart) return;
2,220!
1068
  TdFilePtr pFile = taosOpenFile(pHistory->file, TD_FILE_CREATE | TD_FILE_WRITE | TD_FILE_STREAM | TD_FILE_APPEND);
2,220✔
1069
  if (pFile == NULL) return;
2,220!
1070

1071
  for (int32_t i = pHistory->hstart; i != pHistory->hend;) {
4,441✔
1072
    if (pHistory->hist[i] != NULL) {
2,221!
1073
      taosFprintfFile(pFile, "%s\n", pHistory->hist[i]);
2,221✔
1074
      taosMemoryFree(pHistory->hist[i]);
2,221✔
1075
      pHistory->hist[i] = NULL;
2,221✔
1076
    }
1077
    i = (i + 1) % SHELL_MAX_HISTORY_SIZE;
2,221✔
1078
  }
1079
  taosCloseFile(&pFile);
2,220✔
1080
}
1081

1082
void shellCleanupHistory() {
2,220✔
1083
  SShellHistory *pHistory = &shell.history;
2,220✔
1084
  for (int32_t i = 0; i < SHELL_MAX_HISTORY_SIZE; ++i) {
2,222,220✔
1085
    if (pHistory->hist[i] != NULL) {
2,220,000✔
1086
      taosMemoryFree(pHistory->hist[i]);
2,217,779✔
1087
      pHistory->hist[i] = NULL;
2,217,779✔
1088
    }
1089
  }
1090
}
2,220✔
1091

1092
void shellPrintError(TAOS_RES *tres, int64_t st) {
2,846✔
1093
  int64_t et = taosGetTimestampUs();
2,846✔
1094
  fprintf(stderr, "\r\nDB error: %s (%.6fs)\r\n", taos_errstr(tres), (et - st) / 1E6);
2,846✔
1095
  taos_free_result(tres);
2,846✔
1096
}
2,846✔
1097

1098
bool shellIsCommentLine(char *line) {
208,086✔
1099
  if (line == NULL) return true;
208,086!
1100
  return shellRegexMatch(line, "^\\s*#.*", REG_EXTENDED);
208,086✔
1101
}
1102

1103
void shellSourceFile(const char *file) {
826✔
1104
  int32_t read_len = 0;
826✔
1105
  char   *cmd = taosMemoryCalloc(1, TSDB_MAX_ALLOWED_SQL_LEN + 1);
826✔
1106
  size_t  cmd_len = 0;
826✔
1107
  char    fullname[PATH_MAX] = {0};
826✔
1108
  char    sourceFileCommand[PATH_MAX + 8] = {0};
826✔
1109

1110
  if (taosExpandDir(file, fullname, PATH_MAX) != 0) {
826!
1111
    tstrncpy(fullname, file, PATH_MAX);
×
1112
  }
1113

1114
  sprintf(sourceFileCommand, "source %s;", fullname);
826✔
1115
  shellRecordCommandToHistory(sourceFileCommand);
826✔
1116

1117
  TdFilePtr pFile = taosOpenFile(fullname, TD_FILE_READ | TD_FILE_STREAM);
826✔
1118
  if (pFile == NULL) {
826✔
1119
    fprintf(stderr, "failed to open file %s\r\n", fullname);
25✔
1120
    taosMemoryFree(cmd);
25✔
1121
    return;
25✔
1122
  }
1123

1124
  char *line = taosMemoryMalloc(TSDB_MAX_ALLOWED_SQL_LEN + 1);
801✔
1125
  while ((read_len = taosGetsFile(pFile, TSDB_MAX_ALLOWED_SQL_LEN, line)) > 0) {
208,972✔
1126
    if (cmd_len + read_len >= TSDB_MAX_ALLOWED_SQL_LEN) {
208,171!
1127
      printf("read command line too long over 1M, ignore this line. cmd_len = %d read_len=%d \n", (int32_t)cmd_len,
×
1128
             read_len);
1129
      cmd_len = 0;
×
1130
      memset(line, 0, TSDB_MAX_ALLOWED_SQL_LEN + 1);
×
1131
      continue;
×
1132
    }
1133
    line[--read_len] = '\0';
208,171✔
1134

1135
    if (read_len == 0 || shellIsCommentLine(line)) {  // line starts with #
208,171!
1136
      continue;
85✔
1137
    }
1138

1139
    if (line[read_len - 1] == '\\') {
208,086!
1140
      line[read_len - 1] = ' ';
×
1141
      memcpy(cmd + cmd_len, line, read_len);
×
1142
      cmd_len += read_len;
×
1143
      continue;
×
1144
    }
1145

1146
    if (line[read_len - 1] == '\r') {
208,086!
1147
      line[read_len - 1] = ' ';
×
1148
    }
1149

1150
    memcpy(cmd + cmd_len, line, read_len);
208,086✔
1151
    printf("%s%s\r\n", shell.info.promptHeader, cmd);
208,086✔
1152
    shellRunCommand(cmd, false);
208,086✔
1153
    memset(cmd, 0, TSDB_MAX_ALLOWED_SQL_LEN);
208,086✔
1154
    cmd_len = 0;
208,086✔
1155
  }
1156

1157
  taosMemoryFree(cmd);
801✔
1158
  taosMemoryFreeClear(line);
801!
1159
  taosCloseFile(&pFile);
801✔
1160
}
1161

1162
bool shellGetGrantInfo(char *buf) {
5✔
1163
  bool community = true;
5✔
1164
  char sinfo[256] = {0};
5✔
1165
  tstrncpy(sinfo, taos_get_server_info(shell.conn), sizeof(sinfo));
5✔
1166
  strtok(sinfo, "\r\n");
5✔
1167

1168
  char sql[] = "show grants";
5✔
1169

1170
  TAOS_RES *tres = taos_query(shell.conn, sql);
5✔
1171

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

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

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

1202
    tstrncpy(serverVersion, row[0], 64);
5✔
1203
    memcpy(expiretime, row[1], fields[1].bytes);
5✔
1204
    memcpy(expired, row[2], fields[2].bytes);
5✔
1205

1206
    if (strcmp(serverVersion, "community") == 0) {
5!
1207
      community = true;
×
1208
    } else if (strcmp(expiretime, "unlimited") == 0) {
5!
1209
      community = false;
×
1210
      sprintf(buf, "Server is %s, %s and will never expire.\r\n", serverVersion, sinfo);
×
1211
    } else {
1212
      community = false;
5✔
1213
      sprintf(buf, "Server is %s, %s and will expire at %s.\r\n", serverVersion, sinfo, expiretime);
5✔
1214
    }
1215

1216
    taos_free_result(tres);
5✔
1217
  }
1218

1219
  fprintf(stdout, "\r\n");
5✔
1220
  return community;
5✔
1221
}
1222

1223
#ifdef WINDOWS
1224
BOOL shellQueryInterruptHandler(DWORD fdwCtrlType) {
1225
  tsem_post(&shell.cancelSem);
1226
  return TRUE;
1227
}
1228
#else
1229
void shellQueryInterruptHandler(int32_t signum, void *sigInfo, void *context) { tsem_post(&shell.cancelSem); }
6✔
1230
#endif
1231

1232
void shellCleanup(void *arg) { taosResetTerminalMode(); }
5✔
1233

1234
void *shellCancelHandler(void *arg) {
5✔
1235
  setThreadName("shellCancelHandler");
5✔
1236
  while (1) {
1237
    if (shell.exit == true) {
15✔
1238
      break;
5✔
1239
    }
1240

1241
    if (tsem_wait(&shell.cancelSem) != 0) {
10!
1242
      taosMsleep(10);
×
1243
      continue;
×
1244
    }
1245

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

1263
  return NULL;
5✔
1264
}
1265

1266
void *shellThreadLoop(void *arg) {
5✔
1267
  setThreadName("shellThreadLoop");
5✔
1268
  taosGetOldTerminalMode();
5✔
1269
  taosThreadCleanupPush(shellCleanup, NULL);
5!
1270

1271
  do {
1272
    char *command = taosMemoryMalloc(SHELL_MAX_COMMAND_SIZE);
5✔
1273
    if (command == NULL) {
5!
1274
      printf("failed to malloc command\r\n");
×
1275
      break;
×
1276
    }
1277

1278
    do {
1279
      memset(command, 0, SHELL_MAX_COMMAND_SIZE);
10✔
1280
      taosSetTerminalMode();
10✔
1281

1282
      if (shellReadCommand(command) != 0) {
10✔
1283
        break;
5✔
1284
      }
1285

1286
      taosResetTerminalMode();
5✔
1287
    } while (shellRunCommand(command, true) == 0);
5!
1288

1289
    taosMemoryFreeClear(command);
5!
1290
    shellWriteHistory();
5✔
1291
    shellExit();
5✔
1292
  } while (0);
1293

1294
  taosThreadCleanupPop(1);
5✔
1295
  return NULL;
5✔
1296
}
1297

1298
int32_t shellExecute() {
2,232✔
1299
  printf(shell.info.clientVersion, shell.info.cusName, taos_get_client_info(), shell.info.cusName);
2,232✔
1300
  fflush(stdout);
2,232✔
1301

1302
  SShellArgs *pArgs = &shell.args;
2,232✔
1303
#ifdef WEBSOCKET
1304
  if (shell.args.restful || shell.args.cloud) {
1305
    if (shell_conn_ws_server(1)) {
1306
      return -1;
1307
    }
1308
  } else {
1309
#endif
1310
    if (shell.args.auth == NULL) {
2,232✔
1311
      shell.conn = taos_connect(pArgs->host, pArgs->user, pArgs->password, pArgs->database, pArgs->port);
2,230✔
1312
    } else {
1313
      shell.conn = taos_connect_auth(pArgs->host, pArgs->user, pArgs->auth, pArgs->database, pArgs->port);
2✔
1314
    }
1315

1316
    if (shell.conn == NULL) {
2,232✔
1317
      printf("failed to connect to server, reason: %s\n", taos_errstr(NULL));
12✔
1318
      fflush(stdout);
12✔
1319
      return -1;
12✔
1320
    }
1321
#ifdef WEBSOCKET
1322
  }
1323
#endif
1324

1325
  bool runOnce = pArgs->commands != NULL || pArgs->file[0] != 0;
2,220✔
1326
  shellSetConn(shell.conn, runOnce);
2,220✔
1327
  shellReadHistory();
2,220✔
1328

1329
  if (shell.args.is_bi_mode) {
2,220!
1330
    // need set bi mode
1331
    printf("Set BI mode is true.\n");
×
1332
#ifndef WEBSOCKET
1333
    taos_set_conn_mode(shell.conn, TAOS_CONN_MODE_BI, 1);
×
1334
#endif
1335
  }
1336

1337
  if (runOnce) {
2,220✔
1338
    if (pArgs->commands != NULL) {
2,215✔
1339
      printf("%s%s\r\n", shell.info.promptHeader, pArgs->commands);
1,390✔
1340
      char *cmd = taosStrdup(pArgs->commands);
1,390✔
1341
      shellRunCommand(cmd, true);
1,390✔
1342
      taosMemoryFree(cmd);
1,390✔
1343
    }
1344

1345
    if (pArgs->file[0] != 0) {
2,215✔
1346
      shellSourceFile(pArgs->file);
825✔
1347
    }
1348
#ifdef WEBSOCKET
1349
    if (shell.args.restful || shell.args.cloud) {
1350
      ws_close(shell.ws_conn);
1351
    } else {
1352
#endif
1353
      taos_close(shell.conn);
2,215✔
1354
#ifdef WEBSOCKET
1355
    }
1356
#endif
1357

1358
    shellWriteHistory();
2,215✔
1359
    shellCleanupHistory();
2,215✔
1360
    return 0;
2,215✔
1361
  }
1362

1363
  if (tsem_init(&shell.cancelSem, 0, 0) != 0) {
5!
1364
    printf("failed to create cancel semaphore\r\n");
×
1365
    return -1;
×
1366
  }
1367

1368
  TdThread spid = {0};
5✔
1369
  taosThreadCreate(&spid, NULL, shellCancelHandler, NULL);
5✔
1370

1371
  taosSetSignal(SIGTERM, shellQueryInterruptHandler);
5✔
1372
  taosSetSignal(SIGHUP, shellQueryInterruptHandler);
5✔
1373
  taosSetSignal(SIGINT, shellQueryInterruptHandler);
5✔
1374

1375
#ifdef WEBSOCKET
1376
  if (!shell.args.restful && !shell.args.cloud) {
1377
#endif
1378
    char *buf = taosMemoryMalloc(512);
5✔
1379
    bool  community = shellGetGrantInfo(buf);
5✔
1380
#ifndef WINDOWS
1381
    printfIntroduction(community);
5✔
1382
#else
1383
#ifndef WEBSOCKET
1384
  if (community) {
1385
    showAD(false);
1386
  }
1387
#endif
1388
#endif
1389
    // printf version
1390
    if (!community) {
5!
1391
      printf("%s\n", buf);
5✔
1392
    }
1393
    taosMemoryFree(buf);
5✔
1394

1395
#ifdef WEBSOCKET
1396
  }
1397
#endif
1398
  while (1) {
1399
    taosThreadCreate(&shell.pid, NULL, shellThreadLoop, NULL);
5✔
1400
    taosThreadJoin(shell.pid, NULL);
5✔
1401
    taosThreadClear(&shell.pid);
5✔
1402
    if (shell.exit) {
5!
1403
      tsem_post(&shell.cancelSem);
5✔
1404
      break;
5✔
1405
    }
1406
  }
1407
#ifndef WEBSOCKET
1408
  // commnuity
1409
  if (community) {
5!
1410
    showAD(true);
×
1411
  }
1412
#endif
1413

1414
  taosThreadJoin(spid, NULL);
5✔
1415

1416
  shellCleanupHistory();
5✔
1417
  taos_kill_query(shell.conn);
5✔
1418
  taos_close(shell.conn);
5✔
1419

1420
  return 0;
5✔
1421
}
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