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

#define __USE_XOPEN

#include "shellAuto.h"
X
Xiaoyu Wang 已提交
19
#include "shellInt.h"
A
Alex Duan 已提交
20
#include "shellTire.h"
A
Alex Duan 已提交
21 22 23 24 25 26 27 28
#include "tthread.h"

//
// ------------- define area  ---------------
//
#define UNION_ALL " union all "

// extern function
X
Xiaoyu Wang 已提交
29 30 31 32 33 34
void  shellClearScreen(int32_t ecmd_pos, int32_t cursor_pos);
void  shellGetPrevCharSize(const char* str, int32_t pos, int32_t* size, int32_t* width);
void  shellShowOnScreen(SShellCmd* cmd);
void  shellInsertChar(SShellCmd* cmd, char* c, int size);
void  shellInsertStr(SShellCmd* cmd, char* str, int size);
bool  appendAfterSelect(TAOS* con, SShellCmd* cmd, char* p, int32_t len);
35
char* tireSearchWord(int type, char* pre);
X
Xiaoyu Wang 已提交
36
bool  updateTireValue(int type, bool autoFill);
A
Alex Duan 已提交
37 38 39

typedef struct SAutoPtr {
  STire* p;
40 41
  int    ref;
} SAutoPtr;
A
Alex Duan 已提交
42

43 44 45 46 47 48 49
typedef struct SWord {
  int           type;  // word type , see WT_ define
  char*         word;
  int32_t       len;
  struct SWord* next;
  bool          free;  // if true need free
} SWord;
A
Alex Duan 已提交
50 51

typedef struct {
52 53
  char*   source;
  int32_t source_len;  // valid data length in source
A
Alex Duan 已提交
54 55 56
  int32_t count;
  SWord*  head;
  // matched information
57 58 59
  int32_t matchIndex;  // matched word index in words
  int32_t matchLen;    // matched length at matched word
} SWords;
A
Alex Duan 已提交
60 61

SWords shellCommands[] = {
62 63 64
    {"alter database <db_name> <alter_db_options> <anyword> <alter_db_options> <anyword> <alter_db_options> <anyword> "
     "<alter_db_options> <anyword> <alter_db_options> <anyword> ;",
     0, 0, NULL},
65 66 67 68 69 70
    {"alter dnode <dnode_id> \"resetlog\";", 0, 0, NULL},
    {"alter dnode <dnode_id> \"debugFlag\" \"141\";", 0, 0, NULL},
    {"alter dnode <dnode_id> \"monitor\" \"0\";", 0, 0, NULL},
    {"alter dnode <dnode_id> \"monitor\" \"1\";", 0, 0, NULL},
    {"alter all dnodes \"resetlog\";", 0, 0, NULL},
    {"alter all dnodes \"debugFlag\" \"141\";", 0, 0, NULL},
A
Alex Duan 已提交
71
    {"alter all dnodes \"monitor\" \"0\";", 0, 0, NULL},
72
    {"alter all dnodes \"monitor\" \"1\";", 0, 0, NULL},
73
    {"alter table <tb_name> <tb_actions> <anyword> ;", 0, 0, NULL},
74 75 76 77 78 79
    {"alter local \"resetlog\";", 0, 0, NULL},
    {"alter local \"DebugFlag\" \"143\";", 0, 0, NULL},
    {"alter local \"cDebugFlag\" \"143\";", 0, 0, NULL},
    {"alter local \"uDebugFlag\" \"143\";", 0, 0, NULL},
    {"alter local \"rpcDebugFlag\" \"143\";", 0, 0, NULL},
    {"alter local \"tmrDebugFlag\" \"143\";", 0, 0, NULL},
80 81 82 83 84 85
    {"alter topic", 0, 0, NULL},
    {"alter user <user_name> <user_actions> <anyword> ;", 0, 0, NULL},
    // 20
    {"create table <anyword> using <stb_name> tags(", 0, 0, NULL},
    {"create database <anyword> <db_options> <anyword> <db_options> <anyword> <db_options> <anyword> <db_options> "
     "<anyword> <db_options> <anyword> <db_options> <anyword> <db_options> <anyword> <db_options> <anyword> "
A
Alex Duan 已提交
86
     "<db_options> <anyword> <db_options> <anyword> ;", 0, 0, NULL},
87 88
    {"create dnode <anyword>", 0, 0, NULL},
    {"create index <anyword> on <stb_name> ()", 0, 0, NULL},
89 90 91 92
    {"create mnode on dnode <dnode_id> ;", 0, 0, NULL},
    {"create qnode on dnode <dnode_id> ;", 0, 0, NULL},
    {"create stream <anyword> into <anyword> as select", 0, 0, NULL},  // 26 append sub sql
    {"create topic <anyword> as select", 0, 0, NULL},                  // 27 append sub sql
A
Alex Duan 已提交
93 94
    {"create function <anyword> as <anyword> outputtype <data_types> language <udf_language>", 0, 0, NULL},
    {"create aggregate function  <anyword> as <anyword> outputtype <data_types> bufsize <anyword> language <udf_language>", 0, 0, NULL},
95 96 97 98 99
    {"create user <anyword> pass <anyword> sysinfo 0;", 0, 0, NULL},
    {"create user <anyword> pass <anyword> sysinfo 1;", 0, 0, NULL},
    {"describe <all_table>", 0, 0, NULL},
    {"delete from <all_table> where ", 0, 0, NULL},
    {"drop database <db_name>", 0, 0, NULL},
A
Alex Duan 已提交
100
    {"drop index <anyword>", 0, 0, NULL},
101 102 103 104 105 106
    {"drop table <all_table>", 0, 0, NULL},
    {"drop dnode <dnode_id>", 0, 0, NULL},
    {"drop mnode on dnode <dnode_id> ;", 0, 0, NULL},
    {"drop qnode on dnode <dnode_id> ;", 0, 0, NULL},
    {"drop user <user_name> ;", 0, 0, NULL},
    // 40
A
Alex Duan 已提交
107
    {"drop function <udf_name> ;", 0, 0, NULL},
108 109
    {"drop consumer group <anyword> on ", 0, 0, NULL},
    {"drop topic <topic_name> ;", 0, 0, NULL},
A
Alex Duan 已提交
110
    {"drop stream <stream_name> ;", 0, 0, NULL},
111
    {"explain select", 0, 0, NULL},  // 44 append sub sql
112
    {"flush database <db_name> ;", 0, 0, NULL},
113
    {"help;", 0, 0, NULL},
114 115 116 117 118 119 120 121
    {"grant all on <anyword> to <user_name> ;", 0, 0, NULL},
    {"grant read on <anyword> to <user_name> ;", 0, 0, NULL},
    {"grant write on <anyword> to <user_name> ;", 0, 0, NULL},
    {"kill connection <anyword> ;", 0, 0, NULL},
    {"kill query ", 0, 0, NULL},
    {"kill transaction ", 0, 0, NULL},
    {"merge vgroup ", 0, 0, NULL},
    {"reset query cache;", 0, 0, NULL},
122 123 124 125
    {"restore dnode <dnode_id> ;", 0, 0, NULL},
    {"restore vnode on dnode <dnode_id> ;", 0, 0, NULL},
    {"restore mnode on dnode <dnode_id> ;", 0, 0, NULL},
    {"restore qnode on dnode <dnode_id> ;", 0, 0, NULL},
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
    {"revoke all on <anyword> from <user_name> ;", 0, 0, NULL},
    {"revoke read on <anyword> from <user_name> ;", 0, 0, NULL},
    {"revoke write on <anyword> from <user_name> ;", 0, 0, NULL},
    {"select * from <all_table>", 0, 0, NULL},
    {"select client_version();", 0, 0, NULL},
    // 60
    {"select current_user();", 0, 0, NULL},
    {"select database();", 0, 0, NULL},
    {"select server_version();", 0, 0, NULL},
    {"select server_status();", 0, 0, NULL},
    {"select now();", 0, 0, NULL},
    {"select today();", 0, 0, NULL},
    {"select timezone();", 0, 0, NULL},
    {"set max_binary_display_width ", 0, 0, NULL},
    {"show apps;", 0, 0, NULL},
    {"show create database <db_name> \\G;", 0, 0, NULL},
    {"show create stable <stb_name> \\G;", 0, 0, NULL},
    {"show create table <tb_name> \\G;", 0, 0, NULL},
    {"show connections;", 0, 0, NULL},
    {"show cluster;", 0, 0, NULL},
146
    {"show cluster alive;", 0, 0, NULL},
147 148 149 150 151 152 153 154 155 156 157 158 159
    {"show databases;", 0, 0, NULL},
    {"show dnodes;", 0, 0, NULL},
    {"show dnode <dnode_id> variables;", 0, 0, NULL},
    {"show functions;", 0, 0, NULL},
    {"show mnodes;", 0, 0, NULL},
    {"show queries;", 0, 0, NULL},
    // 80
    {"show query <anyword> ;", 0, 0, NULL},
    {"show qnodes;", 0, 0, NULL},
    {"show stables;", 0, 0, NULL},
    {"show stables like ", 0, 0, NULL},
    {"show streams;", 0, 0, NULL},
    {"show scores;", 0, 0, NULL},
A
Alex Duan 已提交
160
    {"show snodes;", 0, 0, NULL},
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    {"show subscriptions;", 0, 0, NULL},
    {"show tables;", 0, 0, NULL},
    {"show tables like", 0, 0, NULL},
    {"show table distributed <all_table>", 0, 0, NULL},
    {"show tags from <tb_name>", 0, 0, NULL},
    {"show tags from <db_name>", 0, 0, NULL},
    {"show topics;", 0, 0, NULL},
    {"show transactions;", 0, 0, NULL},
    {"show users;", 0, 0, NULL},
    {"show variables;", 0, 0, NULL},
    {"show local variables;", 0, 0, NULL},
    {"show vnodes <dnode_id>", 0, 0, NULL},
    {"show vgroups;", 0, 0, NULL},
    {"show consumers;", 0, 0, NULL},
    {"show grants;", 0, 0, NULL},
    {"split vgroup ", 0, 0, NULL},
    {"insert into <tb_name> values(", 0, 0, NULL},
    {"insert into <tb_name> using <stb_name> tags(", 0, 0, NULL},
    {"insert into <tb_name> using <stb_name> <anyword> values(", 0, 0, NULL},
    {"insert into <tb_name> file ", 0, 0, NULL},
    {"trim database <db_name>", 0, 0, NULL},
    {"use <db_name>", 0, 0, NULL},
    {"quit", 0, 0, NULL}};

char* keywords[] = {
    "and ",         "asc ",      "desc ",     "from ",    "fill(",         "limit ",    "where ",
    "interval(",    "order by ", "order by ", "offset ",  "or ",           "group by ", "now()",
    "session(",     "sliding ",  "slimit ",   "soffset ", "state_window(", "today() ",  "union all select ",
    "partition by "};

char* functions[] = {
    "count(",         "sum(",
    "avg(",           "last(",
    "last_row(",      "top(",
    "interp(",        "max(",
    "min(",           "now()",
    "today()",        "percentile(",
    "tail(",          "pow(",
    "abs(",           "atan(",
    "acos(",          "asin(",
    "apercentile(",   "bottom(",
    "cast(",          "ceil(",
    "char_length(",   "cos(",
    "concat(",        "concat_ws(",
    "csum(",          "diff(",
    "derivative(",    "elapsed(",
    "first(",         "floor(",
    "hyperloglog(",   "histogram(",
    "irate(",         "leastsquares(",
    "length(",        "log(",
    "lower(",         "ltrim(",
    "mavg(",          "mode(",
    "tan(",           "round(",
    "rtrim(",         "sample(",
    "sin(",           "spread(",
    "substr(",        "statecount(",
    "stateduration(", "stddev(",
    "sqrt(",          "timediff(",
    "timezone(",      "timetruncate(",
    "twa(",           "to_unixtimestamp(",
    "unique(",        "upper(",
A
Alex Duan 已提交
222 223
};

224 225 226
char* tb_actions[] = {
    "add column ", "modify column ", "drop column ", "rename column ", "add tag ",
    "modify tag ", "drop tag ",      "rename tag ",  "set tag ",
A
Alex Duan 已提交
227 228
};

229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
char* user_actions[] = {"pass ", "enable ", "sysinfo "};

char* tb_options[] = {"comment ", "watermark ", "max_delay ", "ttl ", "rollup(", "sma("};

char* db_options[] = {"keep ",
                      "replica ",
                      "precision ",
                      "strict ",
                      "buffer ",
                      "cachemodel ",
                      "cachesize ",
                      "comp ",
                      "duration ",
                      "wal_fsync_period",
                      "maxrows ",
                      "minrows ",
                      "pages ",
                      "pagesize ",
                      "retentions ",
                      "wal_level ",
                      "vgroups ",
                      "single_stable ",
                      "wal_retention_period ",
                      "wal_roll_period ",
                      "wal_retention_size ",
                      "wal_segment_size "};

X
Xiaoyu Wang 已提交
256
char* alter_db_options[] = {"cachemodel ", "replica ", "keep ", "cachesize ", "wal_fsync_period ", "wal_level "};
257 258 259 260 261 262 263 264 265 266 267 268 269

char* data_types[] = {"timestamp",    "int",
                      "int unsigned", "varchar(16)",
                      "float",        "double",
                      "binary(16)",   "nchar(16)",
                      "bigint",       "bigint unsigned",
                      "smallint",     "smallint unsigned",
                      "tinyint",      "tinyint unsigned",
                      "bool",         "json"};

char* key_tags[] = {"tags("};

char* key_select[] = {"select "};
A
Alex Duan 已提交
270

271
char* key_systable[] = {
A
Alex Duan 已提交
272 273 274 275 276 277
    "ins_dnodes",        "ins_mnodes",     "ins_modules",      "ins_qnodes",  "ins_snodes",          "ins_cluster",
    "ins_databases",     "ins_functions",  "ins_indexes",      "ins_stables", "ins_tables",          "ins_tags",
    "ins_users",         "ins_grants",     "ins_vgroups",      "ins_configs", "ins_dnode_variables", "ins_topics",
    "ins_subscriptions", "ins_streams",    "ins_stream_tasks", "ins_vnodes",  "ins_user_privileges", "perf_connections",
    "perf_queries",      "perf_consumers", "perf_trans",       "perf_apps"};

A
Alex Duan 已提交
278
char* udf_language[] = {"\'Python\'", "\'C\'"};
A
Alex Duan 已提交
279

A
Alex Duan 已提交
280
//
sangshuduo's avatar
sangshuduo 已提交
281
//  ------- global variant define ---------
A
Alex Duan 已提交
282
//
283 284 285 286 287
int32_t firstMatchIndex = -1;  // first match shellCommands index
int32_t lastMatchIndex = -1;   // last match shellCommands index
int32_t curMatchIndex = -1;    // current match shellCommands index
int32_t lastWordBytes = -1;    // printShow last word length
bool    waitAutoFill = false;
A
Alex Duan 已提交
288 289 290 291

//
//   ----------- global var array define -----------
//
292 293 294 295 296 297 298
#define WT_VAR_DBNAME         0
#define WT_VAR_STABLE         1
#define WT_VAR_TABLE          2
#define WT_VAR_DNODEID        3
#define WT_VAR_USERNAME       4
#define WT_VAR_TOPIC          5
#define WT_VAR_STREAM         6
A
Alex Duan 已提交
299 300 301
#define WT_VAR_UDFNAME        7

#define WT_FROM_DB_MAX        7  // max get content from db
302
#define WT_FROM_DB_CNT (WT_FROM_DB_MAX + 1)
A
Alex Duan 已提交
303

A
Alex Duan 已提交
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
#define WT_VAR_ALLTABLE       8
#define WT_VAR_FUNC           9
#define WT_VAR_KEYWORD        10
#define WT_VAR_TBACTION       11
#define WT_VAR_DBOPTION       12
#define WT_VAR_ALTER_DBOPTION 13
#define WT_VAR_DATATYPE       14
#define WT_VAR_KEYTAGS        15
#define WT_VAR_ANYWORD        16
#define WT_VAR_TBOPTION       17
#define WT_VAR_USERACTION     18
#define WT_VAR_KEYSELECT      19
#define WT_VAR_SYSTABLE       20
#define WT_VAR_LANGUAGE       21

#define WT_VAR_CNT 22


322
#define WT_TEXT 0xFF
A
Alex Duan 已提交
323

324
char dbName[256] = "";  // save use database name;
A
Alex Duan 已提交
325
// tire array
326
STire*        tires[WT_VAR_CNT];
A
Alex Duan 已提交
327
TdThreadMutex tiresMutex;
328
// save thread handle obtain var name from db server
A
Alex Duan 已提交
329 330
TdThread* threads[WT_FROM_DB_CNT];
// obtain var name  with sql from server
A
Alex Duan 已提交
331
char varTypes[WT_VAR_CNT][64] = {
A
Alex Duan 已提交
332
    "<db_name>",    "<stb_name>",  "<tb_name>",  "<dnode_id>",  "<user_name>",    "<topic_name>", "<stream_name>",
A
Alex Duan 已提交
333
    "<udf_name>",   "<all_table>", "<function>", "<keyword>",    "<tb_actions>",   "<db_options>", "<alter_db_options>",
A
Alex Duan 已提交
334
    "<data_types>", "<key_tags>",  "<anyword>",  "<tb_options>", "<user_actions>", "<key_select>", "<sys_table>", "<udf_language>"};
A
Alex Duan 已提交
335

336
char varSqls[WT_FROM_DB_CNT][64] = {"show databases;", "show stables;", "show tables;", "show dnodes;",
A
Alex Duan 已提交
337
                                    "show users;",     "show topics;",  "show streams;", "show functions;"};
A
Alex Duan 已提交
338 339

// var words current cursor, if user press any one key except tab, cursorVar can be reset to -1
340 341
int  cursorVar = -1;
bool varMode = false;  // enter var names list mode
A
Alex Duan 已提交
342

343 344
TAOS*      varCon = NULL;
SShellCmd* varCmd = NULL;
345
bool       varRunOnce = false;
346 347
SMatch*    lastMatch = NULL;  // save last match result
int        cntDel = 0;        // delete byte count after next press tab
A
Alex Duan 已提交
348 349 350

// show auto tab introduction
void printfIntroduction() {
351
  printf("  ********************************  Tab Completion  ************************************\n");
sangshuduo's avatar
sangshuduo 已提交
352
  char secondLine[160] = "\0";
353
  sprintf(secondLine, "  *   The %s CLI supports tab completion for a variety of items, ", shell.info.cusName);
sangshuduo's avatar
sangshuduo 已提交
354 355
  printf("%s", secondLine);
  int secondLineLen = strlen(secondLine);
356
  while (87 - (secondLineLen++) > 0) {
sangshuduo's avatar
sangshuduo 已提交
357 358 359
    printf(" ");
  }
  printf("*\n");
X
Xiaoyu Wang 已提交
360 361 362 363 364 365 366 367 368 369 370
  printf("  *   including database names, table names, function names and keywords.              *\n");
  printf("  *   The full list of shortcut keys is as follows:                                    *\n");
  printf("  *    [ TAB ]        ......  complete the current word                                *\n");
  printf("  *                   ......  if used on a blank line, display all supported commands  *\n");
  printf("  *    [ Ctrl + A ]   ......  move cursor to the st[A]rt of the line                   *\n");
  printf("  *    [ Ctrl + E ]   ......  move cursor to the [E]nd of the line                     *\n");
  printf("  *    [ Ctrl + W ]   ......  move cursor to the middle of the line                    *\n");
  printf("  *    [ Ctrl + L ]   ......  clear the entire screen                                  *\n");
  printf("  *    [ Ctrl + K ]   ......  clear the screen after the cursor                        *\n");
  printf("  *    [ Ctrl + U ]   ......  clear the screen before the cursor                       *\n");
  printf("  **************************************************************************************\n\n");
A
Alex Duan 已提交
371 372 373
}

void showHelp() {
sangshuduo's avatar
sangshuduo 已提交
374
  printf("\nThe %s CLI supports the following commands:", shell.info.cusName);
375 376
  printf(
      "\n\
A
Alex Duan 已提交
377 378
  ----- A ----- \n\
    alter database <db_name> <db_options> \n\
A
Alex Duan 已提交
379 380 381
    alter dnode <dnode_id> 'resetlog';\n\
    alter dnode <dnode_id> 'monitor' '0';\n\
    alter dnode <dnode_id> 'monitor' \"1\";\n\
382 383 384 385 386
    alter dnode <dnode_id> \"debugflag\" \"143\";\n\
    alter all dnodes \"monitor\" \"0\";\n\
    alter all dnodes \"monitor\" \"1\";\n\
    alter all dnodes \"resetlog\";\n\
    alter all dnodes \"debugFlag\" \n\
A
Alex Duan 已提交
387
    alter table <tb_name> <tb_actions> ;\n\
388 389
    alter local \"resetlog\";\n\
    alter local \"DebugFlag\" \"143\";\n\
A
Alex Duan 已提交
390 391
    alter topic\n\
    alter user <user_name> <user_actions> ...\n\
A
Alex Duan 已提交
392 393
  ----- C ----- \n\
    create table <tb_name> using <stb_name> tags ...\n\
A
Alex Duan 已提交
394
    create database <db_name> <db_options>  ...\n\
395
    create dnode \"fqdn:port\" ...\n\
396
    create index <index_name> on <stb_name> (tag_column_name);\n\
A
Alex Duan 已提交
397 398 399 400
    create mnode on dnode <dnode_id> ;\n\
    create qnode on dnode <dnode_id> ;\n\
    create stream <stream_name> into <stb_name> as select ...\n\
    create topic <topic_name> as select ...\n\
A
Alex Duan 已提交
401
    create function <udf_name> as <file_name> outputtype <data_types> language \'C\' | \'Python\' ;\n\
A
Alex Duan 已提交
402
    create aggregate function  <udf_name> as <file_name> outputtype <data_types> bufsize <bufsize_bytes> language \'C\' | \'Python\';\n\
A
Alex Duan 已提交
403
    create user <user_name> pass <password> ...\n\
A
Alex Duan 已提交
404
  ----- D ----- \n\
A
Alex Duan 已提交
405 406
    describe <all_table>\n\
    delete from <all_table> where ...\n\
A
Alex Duan 已提交
407 408 409
    drop database <db_name>;\n\
    drop table <all_table>;\n\
    drop dnode <dnode_id>;\n\
A
Alex Duan 已提交
410 411 412
    drop mnode on dnode <dnode_id> ;\n\
    drop qnode on dnode <dnode_id> ;\n\
    drop user <user_name> ;\n\
A
Alex Duan 已提交
413
    drop function <udf_name>;\n\
A
Alex Duan 已提交
414 415 416
    drop consumer group ... \n\
    drop topic <topic_name> ;\n\
    drop stream <stream_name> ;\n\
417
    drop index <index_name>;\n\
A
Alex Duan 已提交
418 419
  ----- E ----- \n\
    explain select clause ...\n\
420
  ----- F ----- \n\
A
Alex Duan 已提交
421
    flush database <db_name>;\n\
422 423
  ----- H ----- \n\
    help;\n\
A
Alex Duan 已提交
424 425 426 427 428 429 430
  ----- I ----- \n\
    insert into <tb_name> values(...) ;\n\
    insert into <tb_name> using <stb_name> tags(...) values(...) ;\n\
  ----- G ----- \n\
    grant all   on <priv_level> to <user_name> ;\n\
    grant read  on <priv_level> to <user_name> ;\n\
    grant write on <priv_level> to <user_name> ;\n\
A
Alex Duan 已提交
431 432 433
  ----- K ----- \n\
    kill connection <connection_id>; \n\
    kill query <query_id>; \n\
A
Alex Duan 已提交
434 435 436 437 438
    kill transaction <transaction_id>;\n\
  ----- M ----- \n\
    merge vgroup ...\n\
  ----- R ----- \n\
    reset query cache;\n\
439 440 441 442
    restore dnode <dnode_id> ;\n\
    restore vnode on dnode <dnode_id> ;\n\
    restore mnode on dnode <dnode_id> ;\n\
    restore qnode on dnode <dnode_id> ;\n\
A
Alex Duan 已提交
443 444 445
    revoke all   on <priv_level> from <user_name> ;\n\
    revoke read  on <priv_level> from <user_name> ;\n\
    revoke write on <priv_level> from <user_name> ;\n\
A
Alex Duan 已提交
446 447 448 449
  ----- S ----- \n\
    select * from <all_table> where ... \n\
    select client_version();\n\
    select current_user();\n\
A
Alex Duan 已提交
450
    select database();\n\
A
Alex Duan 已提交
451
    select server_version();\n\
A
Alex Duan 已提交
452 453 454 455 456 457
    select server_status();\n\
    select now();\n\
    select today();\n\
    select timezone();\n\
    set max_binary_display_width ...\n\
    show apps;\n\
A
Alex Duan 已提交
458 459 460 461
    show create database <db_name>;\n\
    show create stable <stb_name>;\n\
    show create table <tb_name>;\n\
    show connections;\n\
A
Alex Duan 已提交
462
    show cluster;\n\
463
    show cluster alive;\n\
A
Alex Duan 已提交
464 465
    show databases;\n\
    show dnodes;\n\
A
Alex Duan 已提交
466
    show dnode <dnode_id> variables;\n\
A
Alex Duan 已提交
467 468 469
    show functions;\n\
    show mnodes;\n\
    show queries;\n\
A
Alex Duan 已提交
470 471 472
    show query <query_id> ;\n\
    show qnodes;\n\
    show snodes;\n\
A
Alex Duan 已提交
473
    show stables;\n\
A
Alex Duan 已提交
474
    show stables like \n\
A
Alex Duan 已提交
475 476
    show streams;\n\
    show scores;\n\
A
Alex Duan 已提交
477
    show subscriptions;\n\
A
Alex Duan 已提交
478
    show tables;\n\
A
Alex Duan 已提交
479 480 481 482 483 484
    show tables like\n\
    show table distributed <all_table>;\n\
    show tags from <tb_name>\n\
    show tags from <db_name>\n\
    show topics;\n\
    show transactions;\n\
A
Alex Duan 已提交
485 486
    show users;\n\
    show variables;\n\
A
Alex Duan 已提交
487 488
    show local variables;\n\
    show vnodes <dnode_id>\n\
A
Alex Duan 已提交
489
    show vgroups;\n\
A
Alex Duan 已提交
490 491 492 493 494
    show consumers;\n\
    show grants;\n\
    split vgroup ...\n\
  ----- T ----- \n\
    trim database <db_name>;\n\
A
Alex Duan 已提交
495 496 497 498
  ----- U ----- \n\
    use <db_name>;");

  printf("\n\n");
499 500 501 502

  // define in getDuration() function
  printf(
      "\
A
Alex Duan 已提交
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
  Timestamp expression Format:\n\
    b - nanosecond \n\
    u - microsecond \n\
    a - millisecond \n\
    s - second \n\
    m - minute \n\
    h - hour \n\
    d - day \n\
    w - week \n\
    now - current time \n\
  Example : \n\
    select * from t1 where ts > now - 2w + 3d and ts <= now - 1w -2h ;\n");
  printf("\n");
}

//
//  -------------------  parse words --------------------------
//

#define SHELL_COMMAND_COUNT() (sizeof(shellCommands) / sizeof(SWords))

// get at
525 526
SWord* atWord(SWords* command, int32_t index) {
  SWord* word = command->head;
A
Alex Duan 已提交
527
  for (int32_t i = 0; i < index; i++) {
528
    if (word == NULL) return NULL;
A
Alex Duan 已提交
529 530 531 532 533 534 535 536 537 538
    word = word->next;
  }

  return word;
}

#define MATCH_WORD(x) atWord(x, x->matchIndex)

int wordType(const char* p, int32_t len) {
  for (int i = 0; i < WT_VAR_CNT; i++) {
539
    if (strncmp(p, varTypes[i], len) == 0) return i;
A
Alex Duan 已提交
540 541 542 543 544
  }
  return WT_TEXT;
}

// add word
545 546
SWord* addWord(const char* p, int32_t len, bool pattern) {
  SWord* word = (SWord*)taosMemoryMalloc(sizeof(SWord));
A
Alex Duan 已提交
547
  memset(word, 0, sizeof(SWord));
548 549
  word->word = (char*)p;
  word->len = len;
A
Alex Duan 已提交
550 551

  // check format
552
  if (pattern && len > 0) {
A
Alex Duan 已提交
553 554 555 556 557 558 559 560 561
    word->type = wordType(p, len);
  } else {
    word->type = WT_TEXT;
  }

  return word;
}

// parse one command
562 563
void parseCommand(SWords* command, bool pattern) {
  char*   p = command->source;
A
Alex Duan 已提交
564
  int32_t start = 0;
565
  int32_t size = command->source_len > 0 ? command->source_len : strlen(p);
A
Alex Duan 已提交
566 567 568 569 570 571 572

  bool lastBlank = false;
  for (int i = 0; i <= size; i++) {
    if (p[i] == ' ' || i == size) {
      // check continue blank like '    '
      if (p[i] == ' ') {
        if (lastBlank) {
573
          start++;
A
Alex Duan 已提交
574 575
          continue;
        }
576
        if (i == 0) {  // first blank
A
Alex Duan 已提交
577
          lastBlank = true;
578
          start++;
A
Alex Duan 已提交
579 580 581
          continue;
        }
        lastBlank = true;
582
      }
A
Alex Duan 已提交
583 584 585 586 587 588

      // found split or string end , append word
      if (command->head == NULL) {
        command->head = addWord(p + start, i - start, pattern);
        command->count = 1;
      } else {
589
        SWord* word = command->head;
A
Alex Duan 已提交
590 591 592
        while (word->next) {
          word = word->next;
        }
593 594
        word->next = addWord(p + start, i - start, pattern);
        command->count++;
A
Alex Duan 已提交
595 596 597 598 599 600 601 602 603
      }
      start = i + 1;
    } else {
      lastBlank = false;
    }
  }
}

// free SShellCmd
604
void freeCommand(SWords* command) {
A
Alex Duan 已提交
605
  SWord* item = command->head;
606
  command->head = NULL;
607
  // loop
A
Alex Duan 已提交
608 609 610
  while (item) {
    SWord* tmp = item;
    item = item->next;
A
Alex Duan 已提交
611
    // if malloc need free
612
    if (tmp->free && tmp->word) taosMemoryFree(tmp->word);
A
Alex Duan 已提交
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
    taosMemoryFree(tmp);
  }
}

void GenerateVarType(int type, char** p, int count) {
  STire* tire = createTire(TIRE_LIST);
  for (int i = 0; i < count; i++) {
    insertWord(tire, p[i]);
  }

  taosThreadMutexLock(&tiresMutex);
  tires[type] = tire;
  taosThreadMutexUnlock(&tiresMutex);
}

//
//  -------------------- shell auto ----------------
//

sangshuduo's avatar
sangshuduo 已提交
632
// init shell auto function , shell start call once
A
Alex Duan 已提交
633 634 635
bool shellAutoInit() {
  // command
  int32_t count = SHELL_COMMAND_COUNT();
636
  for (int32_t i = 0; i < count; i++) {
A
Alex Duan 已提交
637 638 639 640 641 642 643 644 645 646 647
    parseCommand(shellCommands + i, true);
  }

  // tires
  memset(tires, 0, sizeof(STire*) * WT_VAR_CNT);
  taosThreadMutexInit(&tiresMutex, NULL);

  // threads
  memset(threads, 0, sizeof(TdThread*) * WT_FROM_DB_CNT);

  // generate varType
648 649 650 651 652 653 654 655 656 657
  GenerateVarType(WT_VAR_FUNC, functions, sizeof(functions) / sizeof(char*));
  GenerateVarType(WT_VAR_KEYWORD, keywords, sizeof(keywords) / sizeof(char*));
  GenerateVarType(WT_VAR_DBOPTION, db_options, sizeof(db_options) / sizeof(char*));
  GenerateVarType(WT_VAR_ALTER_DBOPTION, alter_db_options, sizeof(alter_db_options) / sizeof(char*));
  GenerateVarType(WT_VAR_TBACTION, tb_actions, sizeof(tb_actions) / sizeof(char*));
  GenerateVarType(WT_VAR_DATATYPE, data_types, sizeof(data_types) / sizeof(char*));
  GenerateVarType(WT_VAR_KEYTAGS, key_tags, sizeof(key_tags) / sizeof(char*));
  GenerateVarType(WT_VAR_TBOPTION, tb_options, sizeof(tb_options) / sizeof(char*));
  GenerateVarType(WT_VAR_USERACTION, user_actions, sizeof(user_actions) / sizeof(char*));
  GenerateVarType(WT_VAR_KEYSELECT, key_select, sizeof(key_select) / sizeof(char*));
658
  GenerateVarType(WT_VAR_SYSTABLE, key_systable, sizeof(key_systable) / sizeof(char*));
A
Alex Duan 已提交
659
  GenerateVarType(WT_VAR_LANGUAGE, udf_language, sizeof(udf_language) / sizeof(char*));
A
Alex Duan 已提交
660 661 662 663 664

  return true;
}

// set conn
665 666 667
void shellSetConn(TAOS* conn, bool runOnce) {
  varCon = conn;
  varRunOnce = runOnce;
A
Alex Duan 已提交
668
  // init database and stable
669
  if (!runOnce) updateTireValue(WT_VAR_DBNAME, false);
A
Alex Duan 已提交
670
}
A
Alex Duan 已提交
671

sangshuduo's avatar
sangshuduo 已提交
672
// exit shell auto function, shell exit call once
A
Alex Duan 已提交
673 674 675
void shellAutoExit() {
  // free command
  int32_t count = SHELL_COMMAND_COUNT();
676
  for (int32_t i = 0; i < count; i++) {
A
Alex Duan 已提交
677 678 679 680 681 682 683 684 685
    freeCommand(shellCommands + i);
  }

  // free tires
  taosThreadMutexLock(&tiresMutex);
  for (int32_t i = 0; i < WT_VAR_CNT; i++) {
    if (tires[i]) {
      freeTire(tires[i]);
      tires[i] = NULL;
686
    }
A
Alex Duan 已提交
687 688
  }
  taosThreadMutexUnlock(&tiresMutex);
sangshuduo's avatar
sangshuduo 已提交
689
  // destroy
A
Alex Duan 已提交
690 691 692
  taosThreadMutexDestroy(&tiresMutex);

  // free threads
A
Alex Duan 已提交
693
  for (int32_t i = 0; i < WT_FROM_DB_CNT; i++) {
A
Alex Duan 已提交
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    if (threads[i]) {
      taosDestroyThread(threads[i]);
      threads[i] = NULL;
    }
  }

  // free lastMatch
  if (lastMatch) {
    freeMatch(lastMatch);
    lastMatch = NULL;
  }
}

//
//  -------------------  auto ptr for tires --------------------------
//
sangshuduo's avatar
sangshuduo 已提交
710
bool setNewAutoPtr(int type, STire* pNew) {
711
  if (pNew == NULL) return false;
A
Alex Duan 已提交
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745

  taosThreadMutexLock(&tiresMutex);
  STire* pOld = tires[type];
  if (pOld != NULL) {
    // previous have value, release self ref count
    if (--pOld->ref == 0) {
      freeTire(pOld);
    }
  }

  // set new
  tires[type] = pNew;
  tires[type]->ref = 1;
  taosThreadMutexUnlock(&tiresMutex);

  return true;
}

// get ptr
STire* getAutoPtr(int type) {
  if (tires[type] == NULL) {
    return NULL;
  }

  taosThreadMutexLock(&tiresMutex);
  tires[type]->ref++;
  taosThreadMutexUnlock(&tiresMutex);

  return tires[type];
}

// put back tire to tires[type], if tire not equal tires[type].p, need free tire
void putBackAutoPtr(int type, STire* tire) {
  if (tire == NULL) {
746
    return;
A
Alex Duan 已提交
747 748 749 750
  }

  taosThreadMutexLock(&tiresMutex);
  if (tires[type] != tire) {
751
    // update by out,  can't put back , so free
A
Alex Duan 已提交
752
    if (--tire->ref == 1) {
sangshuduo's avatar
sangshuduo 已提交
753
      // support multi thread getAutoPtr
A
Alex Duan 已提交
754 755
      freeTire(tire);
    }
756

A
Alex Duan 已提交
757 758
  } else {
    tires[type]->ref--;
X
xinsheng Ren 已提交
759
    ASSERT(tires[type]->ref > 0);
A
Alex Duan 已提交
760 761 762
  }
  taosThreadMutexUnlock(&tiresMutex);

763
  return;
A
Alex Duan 已提交
764 765 766 767 768 769
}

//
//  -------------------  var Word --------------------------
//

770
#define MAX_CACHED_CNT 100000  // max cached rows 10w
A
Alex Duan 已提交
771 772
// write sql result to var name, return write rows cnt
int writeVarNames(int type, TAOS_RES* tres) {
773
  // fetch row
A
Alex Duan 已提交
774 775 776 777 778
  TAOS_ROW row = taos_fetch_row(tres);
  if (row == NULL) {
    return 0;
  }

779
  TAOS_FIELD* fields = taos_fetch_fields(tres);
A
Alex Duan 已提交
780
  // create new tires
781
  char   tireType = type == WT_VAR_TABLE ? TIRE_TREE : TIRE_LIST;
A
Alex Duan 已提交
782 783 784 785
  STire* tire = createTire(tireType);

  // enum rows
  char name[1024];
786
  int  numOfRows = 0;
A
Alex Duan 已提交
787 788
  do {
    int32_t* lengths = taos_fetch_lengths(tres);
789 790 791
    int32_t  bytes = lengths[0];
    if (fields[0].type == TSDB_DATA_TYPE_INT) {
      sprintf(name, "%d", *(int16_t*)row[0]);
A
Alex Duan 已提交
792 793 794
    } else {
      memcpy(name, row[0], bytes);
    }
795 796

    name[bytes] = 0;  // set string end
A
Alex Duan 已提交
797 798 799
    // insert to tire
    insertWord(tire, name);

800
    if (++numOfRows > MAX_CACHED_CNT) {
A
Alex Duan 已提交
801 802 803 804 805 806 807
      break;
    }

    row = taos_fetch_row(tres);
  } while (row != NULL);

  // replace old tire
sangshuduo's avatar
sangshuduo 已提交
808
  setNewAutoPtr(type, tire);
A
Alex Duan 已提交
809 810 811 812

  return numOfRows;
}

813 814
void setThreadNull(int type) {
  taosThreadMutexLock(&tiresMutex);
X
Xiaoyu Wang 已提交
815
  if (threads[type]) {
816 817
    taosMemoryFree(threads[type]);
  }
818 819 820 821
  threads[type] = NULL;
  taosThreadMutexUnlock(&tiresMutex);
}

822
bool firstMatchCommand(TAOS* con, SShellCmd* cmd);
A
Alex Duan 已提交
823
//
824
//  thread obtain var thread from db server
A
Alex Duan 已提交
825 826
//
void* varObtainThread(void* param) {
827
  int type = *(int*)param;
A
Alex Duan 已提交
828 829 830 831 832 833 834 835 836
  taosMemoryFree(param);

  if (varCon == NULL || type > WT_FROM_DB_MAX) {
    return NULL;
  }

  TAOS_RES* pSql = taos_query(varCon, varSqls[type]);
  if (taos_errno(pSql)) {
    taos_free_result(pSql);
837
    setThreadNull(type);
A
Alex Duan 已提交
838 839 840 841 842 843 844 845 846
    return NULL;
  }

  // write var names from pSql
  int cnt = writeVarNames(type, pSql);

  // free sql
  taos_free_result(pSql);

847
  // check need call auto tab
A
Alex Duan 已提交
848 849 850 851 852
  if (cnt > 0 && waitAutoFill) {
    // press tab key by program
    firstMatchCommand(varCon, varCmd);
  }

853
  setThreadNull(type);
A
Alex Duan 已提交
854 855 856
  return NULL;
}

A
Alex Duan 已提交
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
// return true is need update value by async
bool updateTireValue(int type, bool autoFill) {
  // TYPE CONTEXT GET FROM DB
  taosThreadMutexLock(&tiresMutex);

  // check need obtain from server
  if (tires[type] == NULL) {
    waitAutoFill = autoFill;
    // need async obtain var names from db sever
    if (threads[type] != NULL) {
      if (taosThreadRunning(threads[type])) {
        // thread running , need not obtain again, return
        taosThreadMutexUnlock(&tiresMutex);
        return NULL;
      }
      // destroy previous thread handle for new create thread handle
      taosDestroyThread(threads[type]);
      threads[type] = NULL;
    }

    // create new
    void* param = taosMemoryMalloc(sizeof(int));
    *((int*)param) = type;
    threads[type] = taosCreateThread(varObtainThread, param);
    taosThreadMutexUnlock(&tiresMutex);
    return true;
  }
  taosThreadMutexUnlock(&tiresMutex);

  return false;
}

A
Alex Duan 已提交
889 890 891
// only match next one word from all match words, return valuue must free by caller
char* matchNextPrefix(STire* tire, char* pre) {
  SMatch* match = NULL;
X
Xiaoyu Wang 已提交
892
  if (tire == NULL) return NULL;
A
Alex Duan 已提交
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908

  // re-use last result
  if (lastMatch) {
    if (strcmp(pre, lastMatch->pre) == 0) {
      // same pre
      match = lastMatch;
    }
  }

  if (match == NULL) {
    // not same with last result
    if (pre[0] == 0) {
      // EMPTY PRE
      match = enumAll(tire);
    } else {
      // NOT EMPTY
909 910 911
      match = (SMatch*)taosMemoryMalloc(sizeof(SMatch));
      memset(match, 0, sizeof(SMatch));
      matchPrefix(tire, pre, match);
A
Alex Duan 已提交
912
    }
913

A
Alex Duan 已提交
914 915
    // save to lastMatch
    if (match) {
916
      if (lastMatch) freeMatch(lastMatch);
A
Alex Duan 已提交
917 918 919 920 921 922 923
      lastMatch = match;
    }
  }

  // check valid
  if (match == NULL || match->head == NULL) {
    // no one matched
924
    return NULL;
A
Alex Duan 已提交
925 926 927 928 929
  }

  if (cursorVar == -1) {
    // first
    cursorVar = 0;
930
    return taosStrdup(match->head->word);
A
Alex Duan 已提交
931 932 933
  }

  // according to cursorVar , calculate next one
934
  int         i = 0;
A
Alex Duan 已提交
935 936 937 938 939 940 941 942 943 944 945
  SMatchNode* item = match->head;
  while (item) {
    if (i == cursorVar + 1) {
      // found next position ok
      if (item->next == NULL) {
        // match last item, reset cursorVar to head
        cursorVar = -1;
      } else {
        cursorVar = i;
      }

946
      return taosStrdup(item->word);
A
Alex Duan 已提交
947 948 949 950 951 952 953
    }

    // check end item
    if (item->next == NULL) {
      // if cursorVar > var list count, return last and reset cursorVar
      cursorVar = -1;

954
      return taosStrdup(item->word);
A
Alex Duan 已提交
955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
    }

    // move next
    item = item->next;
    i++;
  }

  return NULL;
}

// search pre word from tire tree, return value must free by caller
char* tireSearchWord(int type, char* pre) {
  if (type == WT_TEXT) {
    return NULL;
  }

971
  if (type > WT_FROM_DB_MAX) {
A
Alex Duan 已提交
972 973
    // NOT FROM DB , tires[type] alwary not null
    STire* tire = tires[type];
974 975
    if (tire == NULL) return NULL;
    return matchNextPrefix(tire, pre);
A
Alex Duan 已提交
976 977
  }

X
Xiaoyu Wang 已提交
978
  if (updateTireValue(type, true)) {
A
Alex Duan 已提交
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
    return NULL;
  }

  // can obtain var names from local
  STire* tire = getAutoPtr(type);
  if (tire == NULL) {
    return NULL;
  }

  char* str = matchNextPrefix(tire, pre);
  // used finish, put back pointer to autoptr array
  putBackAutoPtr(type, tire);

  return str;
}

995
// match var word, word1 is pattern , word2 is input from shell
A
Alex Duan 已提交
996
bool matchVarWord(SWord* word1, SWord* word2) {
997
  // search input word from tire tree
A
Alex Duan 已提交
998 999 1000 1001 1002 1003 1004 1005 1006 1007
  char pre[512];
  memcpy(pre, word2->word, word2->len);
  pre[word2->len] = 0;

  char* str = NULL;
  if (word1->type == WT_VAR_ALLTABLE) {
    // ALL_TABLE
    str = tireSearchWord(WT_VAR_STABLE, pre);
    if (str == NULL) {
      str = tireSearchWord(WT_VAR_TABLE, pre);
1008
      if (str == NULL) return false;
A
Alex Duan 已提交
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    }
  } else {
    // OTHER
    str = tireSearchWord(word1->type, pre);
    if (str == NULL) {
      // not found or word1->type variable list not obtain from server, return not match
      return false;
    }
  }

  // free previous malloc
1020
  if (word1->free && word1->word) {
A
Alex Duan 已提交
1021 1022 1023 1024 1025
    taosMemoryFree(word1->word);
  }

  // save
  word1->word = str;
1026 1027 1028
  word1->len = strlen(str);
  word1->free = true;  // need free

A
Alex Duan 已提交
1029 1030 1031 1032 1033 1034 1035
  return true;
}

//
//  -------------------  match words --------------------------
//

1036 1037 1038 1039
// compare command cmdPattern come from shellCommands , cmdInput come from user input
int32_t compareCommand(SWords* cmdPattern, SWords* cmdInput) {
  SWord* wordPattern = cmdPattern->head;
  SWord* wordInput = cmdInput->head;
A
Alex Duan 已提交
1040

1041
  if (wordPattern == NULL || wordInput == NULL) {
A
Alex Duan 已提交
1042 1043 1044
    return -1;
  }

1045 1046
  for (int32_t i = 0; i < cmdPattern->count; i++) {
    if (wordPattern->type == WT_TEXT) {
A
Alex Duan 已提交
1047
      // WT_TEXT match
1048 1049 1050
      if (wordPattern->len == wordInput->len) {
        if (strncasecmp(wordPattern->word, wordInput->word, wordPattern->len) != 0) return -1;
      } else if (wordPattern->len < wordInput->len) {
A
Alex Duan 已提交
1051 1052
        return -1;
      } else {
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
        // wordPattern->len > wordInput->len
        if (strncasecmp(wordPattern->word, wordInput->word, wordInput->len) == 0) {
          if (i + 1 == cmdInput->count) {
            // last word return match
            cmdPattern->matchIndex = i;
            cmdPattern->matchLen = wordInput->len;
            return i;
          } else {
            return -1;
          }
A
Alex Duan 已提交
1063 1064 1065 1066 1067 1068
        } else {
          return -1;
        }
      }
    } else {
      // WT_VAR auto match any one word
1069 1070 1071 1072
      if (wordInput->next == NULL) {  // input words last one
        if (matchVarWord(wordPattern, wordInput)) {
          cmdPattern->matchIndex = i;
          cmdPattern->matchLen = wordInput->len;
A
Alex Duan 已提交
1073 1074 1075 1076 1077 1078 1079 1080
          varMode = true;
          return i;
        }
        return -1;
      }
    }

    // move next
1081 1082 1083
    wordPattern = wordPattern->next;
    wordInput = wordInput->next;
    if (wordPattern == NULL || wordInput == NULL) {
A
Alex Duan 已提交
1084 1085 1086 1087 1088 1089 1090 1091
      return -1;
    }
  }

  return -1;
}

// match command
1092
SWords* matchCommand(SWords* input, bool continueSearch) {
A
Alex Duan 已提交
1093
  int32_t count = SHELL_COMMAND_COUNT();
1094 1095
  for (int32_t i = 0; i < count; i++) {
    SWords* shellCommand = shellCommands + i;
A
Alex Duan 已提交
1096
    if (continueSearch && lastMatchIndex != -1 && i <= lastMatchIndex) {
sangshuduo's avatar
sangshuduo 已提交
1097
      // new match must greater than lastMatchIndex
A
Alex Duan 已提交
1098 1099 1100 1101 1102 1103 1104 1105
      if (varMode && i == lastMatchIndex) {
        // do nothing, var match on lastMatchIndex
      } else {
        continue;
      }
    }

    // command is large
1106
    if (input->count > shellCommand->count) {
A
Alex Duan 已提交
1107 1108 1109 1110 1111 1112
      continue;
    }

    // compare
    int32_t index = compareCommand(shellCommand, input);
    if (index != -1) {
1113
      if (firstMatchIndex == -1) firstMatchIndex = i;
A
Alex Duan 已提交
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
      curMatchIndex = i;
      return &shellCommands[i];
    }
  }

  // not match
  return NULL;
}

//
//  -------------------  print screen --------------------------
//

// delete char count
1128
void deleteCount(SShellCmd* cmd, int count) {
A
Alex Duan 已提交
1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
  int size = 0;
  int width = 0;
  int prompt_size = 6;
  shellClearScreen(cmd->endOffset + prompt_size, cmd->screenOffset + prompt_size);

  // loop delete
  while (--count >= 0 && cmd->cursorOffset > 0) {
    shellGetPrevCharSize(cmd->command, cmd->cursorOffset, &size, &width);
    memmove(cmd->command + cmd->cursorOffset - size, cmd->command + cmd->cursorOffset,
            cmd->commandSize - cmd->cursorOffset);
    cmd->commandSize -= size;
    cmd->cursorOffset -= size;
    cmd->screenOffset -= width;
    cmd->endOffset -= width;
  }
}

// show screen
1147
void printScreen(TAOS* con, SShellCmd* cmd, SWords* match) {
A
Alex Duan 已提交
1148 1149 1150
  // modify SShellCmd
  if (firstMatchIndex == -1 || curMatchIndex == -1) {
    // no match
1151
    return;
A
Alex Duan 已提交
1152 1153
  }

1154 1155 1156
  // first tab press
  const char* str = NULL;
  int         strLen = 0;
A
Alex Duan 已提交
1157 1158 1159

  if (firstMatchIndex == curMatchIndex && lastWordBytes == -1) {
    // first press tab
1160
    SWord* word = MATCH_WORD(match);
A
Alex Duan 已提交
1161 1162 1163 1164 1165
    str = word->word + match->matchLen;
    strLen = word->len - match->matchLen;
    lastMatchIndex = firstMatchIndex;
    lastWordBytes = word->len;
  } else {
1166
    if (lastWordBytes == -1) return;
A
Alex Duan 已提交
1167 1168
    deleteCount(cmd, lastWordBytes);

1169
    SWord* word = MATCH_WORD(match);
A
Alex Duan 已提交
1170 1171 1172 1173 1174 1175
    str = word->word;
    strLen = word->len;
    // set current to last
    lastMatchIndex = curMatchIndex;
    lastWordBytes = word->len;
  }
1176

A
Alex Duan 已提交
1177
  // insert new
A
Alex Duan 已提交
1178
  shellInsertStr(cmd, (char*)str, strLen);
A
Alex Duan 已提交
1179 1180 1181
}

// main key press tab , matched return true else false
1182
bool firstMatchCommand(TAOS* con, SShellCmd* cmd) {
X
Xiaoyu Wang 已提交
1183
  if (con == NULL || cmd == NULL) return false;
A
Alex Duan 已提交
1184
  // parse command
1185
  SWords* input = (SWords*)taosMemoryMalloc(sizeof(SWords));
A
Alex Duan 已提交
1186 1187 1188 1189 1190 1191
  memset(input, 0, sizeof(SWords));
  input->source = cmd->command;
  input->source_len = cmd->commandSize;
  parseCommand(input, false);

  // if have many , default match first, if press tab again , switch to next
1192
  curMatchIndex = -1;
A
Alex Duan 已提交
1193
  lastMatchIndex = -1;
1194
  SWords* match = matchCommand(input, true);
A
Alex Duan 已提交
1195 1196 1197 1198 1199 1200 1201 1202 1203
  if (match == NULL) {
    // not match , nothing to do
    freeCommand(input);
    taosMemoryFree(input);
    return false;
  }

  // print to screen
  printScreen(con, cmd, match);
wafwerar's avatar
wafwerar 已提交
1204 1205 1206 1207
#ifdef WINDOWS
  printf("\r");
  shellShowOnScreen(cmd);
#endif
A
Alex Duan 已提交
1208 1209 1210 1211 1212 1213
  freeCommand(input);
  taosMemoryFree(input);
  return true;
}

// create input source
1214
void createInputFromFirst(SWords* input, SWords* firstMatch) {
A
Alex Duan 已提交
1215 1216 1217 1218
  //
  // if next pressTabKey , input context come from firstMatch, set matched length with source_len
  //
  input->source = (char*)taosMemoryMalloc(1024);
1219
  memset((void*)input->source, 0, 1024);
A
Alex Duan 已提交
1220

1221
  SWord* word = firstMatch->head;
A
Alex Duan 已提交
1222

1223
  // source_len = full match word->len + half match with firstMatch->matchLen
A
Alex Duan 已提交
1224 1225 1226
  for (int i = 0; i < firstMatch->matchIndex && word; i++) {
    // combine source from each word
    strncpy(input->source + input->source_len, word->word, word->len);
sangshuduo's avatar
sangshuduo 已提交
1227
    strcat(input->source, " ");          // append blank space
1228
    input->source_len += word->len + 1;  // 1 is blank length
A
Alex Duan 已提交
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    // move next
    word = word->next;
  }
  // appand half matched word for last
  if (word) {
    strncpy(input->source + input->source_len, word->word, firstMatch->matchLen);
    input->source_len += firstMatch->matchLen;
  }
}

// user press Tabkey again is named next , matched return true else false
1240
bool nextMatchCommand(TAOS* con, SShellCmd* cmd, SWords* firstMatch) {
A
Alex Duan 已提交
1241 1242 1243
  if (firstMatch == NULL || firstMatch->head == NULL) {
    return false;
  }
1244
  SWords* input = (SWords*)taosMemoryMalloc(sizeof(SWords));
A
Alex Duan 已提交
1245 1246 1247 1248 1249 1250 1251 1252 1253
  memset(input, 0, sizeof(SWords));

  // create input from firstMatch
  createInputFromFirst(input, firstMatch);

  // parse input
  parseCommand(input, false);

  // if have many , default match first, if press tab again , switch to next
1254
  SWords* match = matchCommand(input, true);
A
Alex Duan 已提交
1255 1256 1257
  if (match == NULL) {
    // if not match , reset all index
    firstMatchIndex = -1;
1258
    curMatchIndex = -1;
A
Alex Duan 已提交
1259 1260 1261
    match = matchCommand(input, false);
    if (match == NULL) {
      freeCommand(input);
1262
      if (input->source) taosMemoryFree(input->source);
A
Alex Duan 已提交
1263 1264 1265 1266 1267 1268 1269
      taosMemoryFree(input);
      return false;
    }
  }

  // print to screen
  printScreen(con, cmd, match);
wafwerar's avatar
wafwerar 已提交
1270 1271 1272 1273
#ifdef WINDOWS
  printf("\r");
  shellShowOnScreen(cmd);
#endif
A
Alex Duan 已提交
1274 1275

  // free
A
Alex Duan 已提交
1276
  freeCommand(input);
A
Alex Duan 已提交
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
  if (input->source) {
    taosMemoryFree(input->source);
    input->source = NULL;
  }
  taosMemoryFree(input);

  return true;
}

// fill with type
1287
bool fillWithType(TAOS* con, SShellCmd* cmd, char* pre, int type) {
A
Alex Duan 已提交
1288 1289
  // get type
  STire* tire = tires[type];
1290
  char*  str = matchNextPrefix(tire, pre);
A
Alex Duan 已提交
1291 1292 1293 1294 1295
  if (str == NULL) {
    return false;
  }

  // need insert part string
1296
  char* part = str + strlen(pre);
A
Alex Duan 已提交
1297 1298 1299

  // show
  int count = strlen(part);
A
Alex Duan 已提交
1300
  shellInsertStr(cmd, part, count);
1301
  cntDel = count;  // next press tab delete current append count
A
Alex Duan 已提交
1302 1303 1304 1305 1306 1307

  taosMemoryFree(str);
  return true;
}

// fill with type
1308
bool fillTableName(TAOS* con, SShellCmd* cmd, char* pre) {
A
Alex Duan 已提交
1309
  // search stable and table
1310
  char* str = tireSearchWord(WT_VAR_STABLE, pre);
A
Alex Duan 已提交
1311 1312
  if (str == NULL) {
    str = tireSearchWord(WT_VAR_TABLE, pre);
1313
    if (str == NULL) return false;
A
Alex Duan 已提交
1314 1315 1316
  }

  // need insert part string
1317
  char* part = str + strlen(pre);
A
Alex Duan 已提交
1318 1319

  // delete autofill count last append
1320
  if (cntDel > 0) {
A
Alex Duan 已提交
1321 1322 1323 1324 1325 1326
    deleteCount(cmd, cntDel);
    cntDel = 0;
  }

  // show
  int count = strlen(part);
A
Alex Duan 已提交
1327
  shellInsertStr(cmd, part, count);
1328 1329
  cntDel = count;  // next press tab delete current append count

A
Alex Duan 已提交
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340
  taosMemoryFree(str);
  return true;
}

//
// find last word from sql select clause
//  example :
//  1 select cou -> press tab  select count(
//  2 select count(*),su -> select count(*), sum(
//  3 select count(*), su -> select count(*), sum(
//
1341 1342 1343 1344
char* lastWord(char* p) {
  // get near from end revert find ' ' and ','
  char* p1 = strrchr(p, ' ');
  char* p2 = strrchr(p, ',');
A
Alex Duan 已提交
1345 1346

  if (p1 && p2) {
1347
    return p1 > p2 ? p1 + 1 : p2 + 1;
A
Alex Duan 已提交
1348 1349
  } else if (p1) {
    return p1 + 1;
1350
  } else if (p2) {
A
Alex Duan 已提交
1351 1352 1353
    return p2 + 1;
  } else {
    return p;
1354
  }
A
Alex Duan 已提交
1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
}

bool fieldsInputEnd(char* sql) {
  // not in '()'
  char* p1 = strrchr(sql, '(');
  char* p2 = strrchr(sql, ')');
  if (p1 && p2 == NULL) {
    // like select count( '  '
    return false;
  } else if (p1 && p2 && p1 > p2) {
    // like select sum(age), count( ' '
    return false;
  }

  // not in ','
1370 1371 1372
  char* p3 = strrchr(sql, ',');
  char* p = p3;
  // like select ts, age,'    '
A
Alex Duan 已提交
1373 1374
  if (p) {
    ++p;
1375 1376 1377 1378
    bool  allBlank = true;  // after last ','  all char is blank
    int   cnt = 0;          // blank count , like '    ' as one blank
    char* plast = NULL;     // last blank position
    while (*p) {
A
Alex Duan 已提交
1379 1380
      if (*p == ' ') {
        plast = p;
1381
        cnt++;
A
Alex Duan 已提交
1382 1383 1384 1385 1386 1387 1388
      } else {
        allBlank = false;
      }
      ++p;
    }

    // any one word is not blank
1389
    if (allBlank) {
A
Alex Duan 已提交
1390 1391 1392 1393 1394 1395 1396 1397 1398
      return false;
    }

    // like 'select count(*),sum(age) fr' need return true
    if (plast && plast > p3 && p2 > p1 && plast > p2 && p1 > p3) {
      return true;
    }

    // if last char not ' ', then not end field, like 'select count(*), su' can fill sum(
1399
    if (sql[strlen(sql) - 1] != ' ' && cnt <= 1) {
A
Alex Duan 已提交
1400 1401 1402 1403
      return false;
    }
  }

1404 1405
  char* p4 = strrchr(sql, ' ');
  if (p4 == NULL) {
A
Alex Duan 已提交
1406 1407 1408 1409 1410 1411 1412 1413
    // only one word
    return false;
  }

  return true;
}

// need insert from
1414 1415 1416
bool needInsertFrom(char* sql, int len) {
  // last is blank
  if (sql[len - 1] != ' ') {
A
Alex Duan 已提交
1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
    // insert from keyword
    return false;
  }

  //  select fields input is end
  if (!fieldsInputEnd(sql)) {
    return false;
  }

  // can insert from keyword
  return true;
}

A
Alex Duan 已提交
1430
// p is string following select keyword
1431
bool appendAfterSelect(TAOS* con, SShellCmd* cmd, char* sql, int32_t len) {
A
Alex Duan 已提交
1432
  char* p = strndup(sql, len);
A
Alex Duan 已提交
1433 1434

  // union all
1435
  char* p1;
A
Alex Duan 已提交
1436 1437
  do {
    p1 = strstr(p, UNION_ALL);
1438
    if (p1) {
A
Alex Duan 已提交
1439 1440 1441 1442
      p = p1 + strlen(UNION_ALL);
    }
  } while (p1);

1443 1444 1445 1446
  char* from = strstr(p, " from ");
  // last word , maybe empty string or some letters of a string
  char* last = lastWord(p);
  bool  ret = false;
A
Alex Duan 已提交
1447 1448
  if (from == NULL) {
    bool fieldEnd = fieldsInputEnd(p);
A
Alex Duan 已提交
1449
    // check fields input end then insert from keyword
1450
    if (fieldEnd && p[len - 1] == ' ') {
A
Alex Duan 已提交
1451
      shellInsertStr(cmd, "from", 4);
A
Alex Duan 已提交
1452
      taosMemoryFree(p);
A
Alex Duan 已提交
1453 1454 1455
      return true;
    }

sangshuduo's avatar
sangshuduo 已提交
1456
    // fill function
1457
    if (fieldEnd) {
A
Alex Duan 已提交
1458 1459 1460 1461 1462
      // fields is end , need match keyword
      ret = fillWithType(con, cmd, last, WT_VAR_KEYWORD);
    } else {
      ret = fillWithType(con, cmd, last, WT_VAR_FUNC);
    }
1463

A
Alex Duan 已提交
1464
    taosMemoryFree(p);
A
Alex Duan 已提交
1465 1466 1467 1468
    return ret;
  }

  // have from
1469
  char* blank = strstr(from + 6, " ");
A
Alex Duan 已提交
1470 1471 1472 1473 1474 1475 1476
  if (blank == NULL) {
    // no table name, need fill
    ret = fillTableName(con, cmd, last);
  } else {
    ret = fillWithType(con, cmd, last, WT_VAR_KEYWORD);
  }

A
Alex Duan 已提交
1477
  taosMemoryFree(p);
A
Alex Duan 已提交
1478 1479 1480
  return ret;
}

A
Alex Duan 已提交
1481 1482
int32_t searchAfterSelect(char* p, int32_t len) {
  // select * from st;
1483
  if (strncasecmp(p, "select ", 7) == 0) {
A
Alex Duan 已提交
1484
    // check nest query
1485 1486 1487 1488
    char* p1 = p + 7;
    while (1) {
      char* p2 = strstr(p1, "select ");
      if (p2 == NULL) break;
A
Alex Duan 已提交
1489 1490 1491 1492 1493 1494 1495
      p1 = p2 + 7;
    }

    return p1 - p;
  }

  // explain as select * from st;
1496
  if (strncasecmp(p, "explain select ", 15) == 0) {
A
Alex Duan 已提交
1497 1498 1499 1500
    return 15;
  }

  char* as_pos_end = strstr(p, " as select ");
1501
  if (as_pos_end == NULL) return -1;
A
Alex Duan 已提交
1502 1503 1504
  as_pos_end += 11;

  // create stream <stream_name> as select
1505 1506 1507
  if (strncasecmp(p, "create stream ", 14) == 0) {
    return as_pos_end - p;
    ;
A
Alex Duan 已提交
1508 1509 1510
  }

  // create topic <topic_name> as select
1511
  if (strncasecmp(p, "create topic ", 13) == 0) {
A
Alex Duan 已提交
1512 1513 1514 1515 1516 1517
    return as_pos_end - p;
  }

  return -1;
}

1518
bool matchSelectQuery(TAOS* con, SShellCmd* cmd) {
A
Alex Duan 已提交
1519 1520 1521 1522 1523 1524 1525
  // if continue press Tab , delete bytes by previous autofill
  if (cntDel > 0) {
    deleteCount(cmd, cntDel);
    cntDel = 0;
  }

  // match select ...
1526 1527
  int   len = cmd->commandSize;
  char* p = cmd->command;
A
Alex Duan 已提交
1528 1529 1530 1531 1532 1533 1534 1535

  // remove prefix blank
  while (p[0] == ' ' && len > 0) {
    p++;
    len--;
  }

  // special range
1536
  if (len < 7 || len > 512) {
A
Alex Duan 已提交
1537 1538 1539 1540
    return false;
  }

  // search
1541
  char*   sql_cp = strndup(p, len);
A
Alex Duan 已提交
1542 1543
  int32_t n = searchAfterSelect(sql_cp, len);
  taosMemoryFree(sql_cp);
1544 1545
  if (n == -1 || n > len) return false;
  p += n;
A
Alex Duan 已提交
1546 1547 1548 1549 1550 1551
  len -= n;

  // append
  return appendAfterSelect(con, cmd, p, len);
}

A
Alex Duan 已提交
1552
// if is input create fields or tags area, return true
1553
bool isCreateFieldsArea(char* p) {
X
Xiaoyu Wang 已提交
1554
  // put to while, support like create table st(ts timestamp, bin1 binary(16), bin2 + blank + TAB
1555
  char* p1 = taosStrdup(p);
X
Xiaoyu Wang 已提交
1556
  bool  ret = false;
1557 1558 1559 1560 1561 1562 1563
  while (1) {
    char* left = strrchr(p1, '(');
    if (left == NULL) {
      // like 'create table st'
      ret = false;
      break;
    }
A
Alex Duan 已提交
1564

1565 1566 1567 1568 1569 1570
    char* right = strrchr(p1, ')');
    if (right == NULL) {
      // like 'create table st( '
      ret = true;
      break;
    }
A
Alex Duan 已提交
1571

1572 1573 1574 1575 1576
    if (left > right) {
      // like 'create table st( ts timestamp, age int) tags(area '
      ret = true;
      break;
    }
X
Xiaoyu Wang 已提交
1577

1578 1579
    // set string end by small for next strrchr search
    *left = 0;
A
Alex Duan 已提交
1580
  }
1581
  taosMemoryFree(p1);
A
Alex Duan 已提交
1582

1583
  return ret;
A
Alex Duan 已提交
1584 1585
}

1586
bool matchCreateTable(TAOS* con, SShellCmd* cmd) {
A
Alex Duan 已提交
1587 1588 1589 1590 1591 1592 1593
  // if continue press Tab , delete bytes by previous autofill
  if (cntDel > 0) {
    deleteCount(cmd, cntDel);
    cntDel = 0;
  }

  // match select ...
1594 1595
  int   len = cmd->commandSize;
  char* p = cmd->command;
A
Alex Duan 已提交
1596 1597 1598 1599 1600 1601 1602 1603

  // remove prefix blank
  while (p[0] == ' ' && len > 0) {
    p++;
    len--;
  }

  // special range
1604
  if (len < 7 || len > 1024) {
A
Alex Duan 已提交
1605 1606 1607
    return false;
  }

1608 1609
  // select and from
  if (strncasecmp(p, "create table ", 13) != 0) {
A
Alex Duan 已提交
1610 1611 1612 1613 1614 1615 1616
    // not select query clause
    return false;
  }
  p += 13;
  len -= 13;

  char* ps = strndup(p, len);
1617 1618
  bool  ret = false;
  char* last = lastWord(ps);
A
Alex Duan 已提交
1619 1620 1621 1622 1623 1624 1625 1626 1627

  // check in create fields or tags input area
  if (isCreateFieldsArea(ps)) {
    ret = fillWithType(con, cmd, last, WT_VAR_DATATYPE);
  }

  // tags
  if (!ret) {
    // find only one ')' , can insert tags
1628
    char* p1 = strchr(ps, ')');
A
Alex Duan 已提交
1629
    if (p1) {
1630
      if (strchr(p1 + 1, ')') == NULL && strstr(p1 + 1, "tags") == NULL) {
A
Alex Duan 已提交
1631 1632 1633 1634 1635 1636
        // can insert tags keyword
        ret = fillWithType(con, cmd, last, WT_VAR_KEYTAGS);
      }
    }
  }

A
Alex Duan 已提交
1637 1638
  // tb options
  if (!ret) {
sangshuduo's avatar
sangshuduo 已提交
1639
    // find like create table st (...) tags(..)  <here is fill tb option area>
1640
    char* p1 = strchr(ps, ')');  // first ')' end
A
Alex Duan 已提交
1641
    if (p1) {
1642
      if (strchr(p1 + 1, ')')) {  // second ')' end
A
Alex Duan 已提交
1643 1644 1645 1646 1647 1648
        // here is tb options area, can insert option
        ret = fillWithType(con, cmd, last, WT_VAR_TBOPTION);
      }
    }
  }

A
Alex Duan 已提交
1649 1650 1651 1652
  taosMemoryFree(ps);
  return ret;
}

1653 1654
bool matchOther(TAOS* con, SShellCmd* cmd) {
  int   len = cmd->commandSize;
A
Alex Duan 已提交
1655 1656
  char* p = cmd->command;

A
Alex Duan 已提交
1657
  // '\\'
A
Alex Duan 已提交
1658 1659 1660
  if (p[len - 1] == '\\') {
    // append '\G'
    char a[] = "G;";
A
Alex Duan 已提交
1661
    shellInsertStr(cmd, a, 2);
A
Alex Duan 已提交
1662 1663
    return true;
  }
A
Alex Duan 已提交
1664 1665

  // too small
1666
  if (len < 8) return false;
A
Alex Duan 已提交
1667 1668 1669 1670 1671 1672 1673 1674

  // like 'from ( '
  char* sql = strndup(p, len);
  char* last = lastWord(sql);

  if (strcmp(last, "from(") == 0) {
    fillWithType(con, cmd, "", WT_VAR_KEYSELECT);
    taosMemoryFree(sql);
1675
    return true;
A
Alex Duan 已提交
1676 1677
  }
  if (strncmp(last, "(", 1) == 0) {
1678
    last += 1;
A
Alex Duan 已提交
1679 1680 1681 1682 1683 1684
  }

  char* from = strstr(sql, " from");
  // find last ' from'
  while (from) {
    char* p1 = strstr(from + 5, " from");
1685
    if (p1 == NULL) break;
A
Alex Duan 已提交
1686 1687 1688 1689 1690
    from = p1;
  }

  if (from) {
    // find next is '('
1691 1692 1693
    char* p2 = from + 5;
    bool  found = false;   // found 'from ... ( ...'  ... is any count of blank
    bool  found1 = false;  // found '('
A
Alex Duan 已提交
1694
    while (1) {
1695
      if (p2 == last || *p2 == '\0') {
A
Alex Duan 已提交
1696 1697 1698 1699 1700
        // last word or string end
        if (found1) {
          found = true;
        }
        break;
1701
      } else if (*p2 == '(') {
A
Alex Duan 已提交
1702
        found1 = true;
1703
      } else if (*p2 == ' ') {
A
Alex Duan 已提交
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720
        // do nothing
      } else {
        // have any other char
        break;
      }

      // move next
      p2++;
    }

    if (found) {
      fillWithType(con, cmd, last, WT_VAR_KEYSELECT);
      taosMemoryFree(sql);
      return true;
    }
  }

1721
  // INSERT
A
Alex Duan 已提交
1722 1723

  taosMemoryFree(sql);
1724

A
Alex Duan 已提交
1725 1726 1727
  return false;
}

1728 1729 1730
// last match if nothing matched
bool matchEnd(TAOS* con, SShellCmd* cmd) {
  // str dump
X
Xiaoyu Wang 已提交
1731
  bool  ret = false;
1732 1733
  char* ps = strndup(cmd->command, cmd->commandSize);
  char* last = lastWord(ps);
X
Xiaoyu Wang 已提交
1734 1735
  char* elast = strrchr(last, '.');  // find end last
  if (elast) {
A
Alex Duan 已提交
1736
    last = elast + 1;
A
Alex Duan 已提交
1737 1738
  }

A
Alex Duan 已提交
1739
  // less one char can match
X
Xiaoyu Wang 已提交
1740
  if (strlen(last) == 0) {
1741
    goto _return;
1742 1743 1744
  }
  if (strcmp(last, " ") == 0) {
    goto _return;
1745 1746 1747
  }

  // match database
X
Xiaoyu Wang 已提交
1748
  if (elast == NULL) {
A
Alex Duan 已提交
1749 1750 1751 1752 1753
    // dot need not completed with dbname
    if (fillWithType(con, cmd, last, WT_VAR_DBNAME)) {
      ret = true;
      goto _return;
    }
1754 1755
  }

1756
  if (fillWithType(con, cmd, last, WT_VAR_SYSTABLE)) {
1757
    ret = true;
1758 1759 1760 1761 1762 1763 1764 1765
    goto _return;
  }

_return:
  taosMemoryFree(ps);
  return ret;
}

A
Alex Duan 已提交
1766
// main key press tab
1767
void pressTabKey(SShellCmd* cmd) {
1768
  // check empty tab key
1769
  if (cmd->commandSize == 0) {
1770
    // have multi line tab key
X
Xiaoyu Wang 已提交
1771
    if (cmd->bufferSize == 0) {
1772 1773
      showHelp();
    }
A
Alex Duan 已提交
1774
    shellShowOnScreen(cmd);
1775 1776
    return;
  }
A
Alex Duan 已提交
1777 1778 1779 1780 1781 1782 1783

  // save connection to global
  varCmd = cmd;
  bool matched = false;

  // manual match like create table st( ...
  matched = matchCreateTable(varCon, cmd);
1784
  if (matched) return;
A
Alex Duan 已提交
1785

1786
  // shellCommands match
A
Alex Duan 已提交
1787 1788 1789 1790 1791
  if (firstMatchIndex == -1) {
    matched = firstMatchCommand(varCon, cmd);
  } else {
    matched = nextMatchCommand(varCon, cmd, &shellCommands[firstMatchIndex]);
  }
1792
  if (matched) return;
A
Alex Duan 已提交
1793 1794 1795 1796

  // NOT MATCHED ANYONE
  // match other like '\G' ...
  matched = matchOther(varCon, cmd);
1797
  if (matched) return;
A
Alex Duan 已提交
1798 1799 1800

  // manual match like select * from ...
  matched = matchSelectQuery(varCon, cmd);
1801
  if (matched) return;
A
Alex Duan 已提交
1802

1803 1804 1805
  // match end
  matched = matchEnd(varCon, cmd);

1806
  return;
A
Alex Duan 已提交
1807 1808 1809 1810 1811 1812
}

// press othr key
void pressOtherKey(char c) {
  // reset global variant
  firstMatchIndex = -1;
1813 1814 1815
  lastMatchIndex = -1;
  curMatchIndex = -1;
  lastWordBytes = -1;
A
Alex Duan 已提交
1816 1817

  // var names
1818 1819
  cursorVar = -1;
  varMode = false;
A
Alex Duan 已提交
1820
  waitAutoFill = false;
1821
  cntDel = 0;
A
Alex Duan 已提交
1822 1823 1824 1825 1826 1827 1828 1829

  if (lastMatch) {
    freeMatch(lastMatch);
    lastMatch = NULL;
  }
}

// put name into name, return name length
1830 1831
int getWordName(char* p, char* name, int nameLen) {
  // remove prefix blank
A
Alex Duan 已提交
1832 1833 1834 1835 1836 1837
  while (*p == ' ') {
    p++;
  }

  // get databases name;
  int i = 0;
1838 1839
  while (p[i] != 0 && i < nameLen - 1) {
    name[i] = p[i];
A
Alex Duan 已提交
1840
    i++;
1841
    if (p[i] == ' ' || p[i] == ';' || p[i] == '(') {
A
Alex Duan 已提交
1842 1843 1844 1845 1846 1847 1848 1849 1850 1851
      // name end
      break;
    }
  }
  name[i] = 0;

  return i;
}

// deal use db, if have  'use' return true
1852 1853 1854
bool dealUseDB(char* sql) {
  // check use keyword
  if (strncasecmp(sql, "use ", 4) != 0) {
A
Alex Duan 已提交
1855 1856
    return false;
  }
1857 1858 1859

  char  db[256];
  char* p = sql + 4;
A
Alex Duan 已提交
1860
  if (getWordName(p, db, sizeof(db)) == 0) {
1861
    // no name , return
A
Alex Duan 已提交
1862 1863 1864 1865 1866
    return true;
  }

  //  dbName is previous use open db name
  if (strcasecmp(db, dbName) == 0) {
1867
    // same , no need switch
A
Alex Duan 已提交
1868 1869 1870 1871 1872 1873 1874 1875
    return true;
  }

  // switch new db
  taosThreadMutexLock(&tiresMutex);
  // STABLE set null
  STire* tire = tires[WT_VAR_STABLE];
  tires[WT_VAR_STABLE] = NULL;
1876
  if (tire) {
A
Alex Duan 已提交
1877 1878 1879 1880 1881
    freeTire(tire);
  }
  // TABLE set null
  tire = tires[WT_VAR_TABLE];
  tires[WT_VAR_TABLE] = NULL;
1882
  if (tire) {
A
Alex Duan 已提交
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892
    freeTire(tire);
  }
  // save
  strcpy(dbName, db);
  taosThreadMutexUnlock(&tiresMutex);

  return true;
}

// deal create, if have 'create' return true
1893 1894 1895
bool dealCreateCommand(char* sql) {
  // check keyword
  if (strncasecmp(sql, "create ", 7) != 0) {
A
Alex Duan 已提交
1896 1897
    return false;
  }
1898 1899 1900

  char  name[1024];
  char* p = sql + 7;
A
Alex Duan 已提交
1901
  if (getWordName(p, name, sizeof(name)) == 0) {
1902
    // no name , return
A
Alex Duan 已提交
1903 1904 1905 1906 1907 1908 1909 1910
    return true;
  }

  int type = -1;
  //  dbName is previous use open db name
  if (strcasecmp(name, "database") == 0) {
    type = WT_VAR_DBNAME;
  } else if (strcasecmp(name, "table") == 0) {
1911
    if (strstr(sql, " tags") != NULL && strstr(sql, " using ") == NULL)
A
Alex Duan 已提交
1912 1913 1914 1915 1916
      type = WT_VAR_STABLE;
    else
      type = WT_VAR_TABLE;
  } else if (strcasecmp(name, "user") == 0) {
    type = WT_VAR_USERNAME;
A
Alex Duan 已提交
1917 1918 1919 1920
  } else if (strcasecmp(name, "topic") == 0) {
    type = WT_VAR_TOPIC;
  } else if (strcasecmp(name, "stream") == 0) {
    type = WT_VAR_STREAM;
A
Alex Duan 已提交
1921
  } else {
1922
    // no match , return
A
Alex Duan 已提交
1923 1924 1925 1926 1927 1928 1929 1930
    return true;
  }

  // move next
  p += strlen(name);

  // get next word , that is table name
  if (getWordName(p, name, sizeof(name)) == 0) {
1931
    // no name , return
A
Alex Duan 已提交
1932 1933 1934 1935 1936 1937 1938
    return true;
  }

  // switch new db
  taosThreadMutexLock(&tiresMutex);
  // STABLE set null
  STire* tire = tires[type];
1939
  if (tire) {
A
Alex Duan 已提交
1940 1941 1942 1943 1944 1945 1946 1947
    insertWord(tire, name);
  }
  taosThreadMutexUnlock(&tiresMutex);

  return true;
}

// deal create, if have 'drop' return true
1948 1949 1950
bool dealDropCommand(char* sql) {
  // check keyword
  if (strncasecmp(sql, "drop ", 5) != 0) {
A
Alex Duan 已提交
1951 1952
    return false;
  }
1953 1954 1955

  char  name[1024];
  char* p = sql + 5;
A
Alex Duan 已提交
1956
  if (getWordName(p, name, sizeof(name)) == 0) {
1957
    // no name , return
A
Alex Duan 已提交
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
    return true;
  }

  int type = -1;
  //  dbName is previous use open db name
  if (strcasecmp(name, "database") == 0) {
    type = WT_VAR_DBNAME;
  } else if (strcasecmp(name, "table") == 0) {
    type = WT_VAR_ALLTABLE;
  } else if (strcasecmp(name, "dnode") == 0) {
    type = WT_VAR_DNODEID;
  } else if (strcasecmp(name, "user") == 0) {
    type = WT_VAR_USERNAME;
A
Alex Duan 已提交
1971 1972 1973 1974
  } else if (strcasecmp(name, "topic") == 0) {
    type = WT_VAR_TOPIC;
  } else if (strcasecmp(name, "stream") == 0) {
    type = WT_VAR_STREAM;
A
Alex Duan 已提交
1975
  } else {
1976
    // no match , return
A
Alex Duan 已提交
1977 1978 1979 1980 1981 1982 1983 1984
    return true;
  }

  // move next
  p += strlen(name);

  // get next word , that is table name
  if (getWordName(p, name, sizeof(name)) == 0) {
1985
    // no name , return
A
Alex Duan 已提交
1986 1987 1988 1989 1990 1991
    return true;
  }

  // switch new db
  taosThreadMutexLock(&tiresMutex);
  // STABLE set null
1992
  if (type == WT_VAR_ALLTABLE) {
A
Alex Duan 已提交
1993 1994 1995
    bool del = false;
    // del in stable
    STire* tire = tires[WT_VAR_STABLE];
1996
    if (tire) del = deleteWord(tire, name);
A
Alex Duan 已提交
1997
    // del in table
1998
    if (!del) {
A
Alex Duan 已提交
1999
      tire = tires[WT_VAR_TABLE];
2000
      if (tire) del = deleteWord(tire, name);
A
Alex Duan 已提交
2001 2002 2003 2004
    }
  } else {
    // OTHER TYPE
    STire* tire = tires[type];
2005
    if (tire) deleteWord(tire, name);
A
Alex Duan 已提交
2006 2007 2008 2009 2010 2011 2012 2013
  }
  taosThreadMutexUnlock(&tiresMutex);

  return true;
}

// callback autotab module after shell sql execute
void callbackAutoTab(char* sqlstr, TAOS* pSql, bool usedb) {
2014
  char* sql = sqlstr;
A
Alex Duan 已提交
2015 2016 2017 2018 2019
  // remove prefix blank
  while (*sql == ' ') {
    sql++;
  }

2020
  if (dealUseDB(sql)) {
A
Alex Duan 已提交
2021
    // change to new db
A
Alex Duan 已提交
2022
    if (!varRunOnce) updateTireValue(WT_VAR_STABLE, false);
2023
    return;
A
Alex Duan 已提交
2024 2025 2026
  }

  // create command add name to autotab
2027 2028
  if (dealCreateCommand(sql)) {
    return;
A
Alex Duan 已提交
2029 2030 2031
  }

  // drop command remove name from autotab
2032 2033
  if (dealDropCommand(sql)) {
    return;
A
Alex Duan 已提交
2034 2035
  }

2036
  return;
A
Alex Duan 已提交
2037
}