mysql.cc 82.9 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000-2003 MySQL AB
unknown's avatar
unknown committed
2

unknown's avatar
unknown committed
3 4 5 6
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
unknown's avatar
unknown committed
7

unknown's avatar
unknown committed
8 9 10 11
   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.  See the
   GNU General Public License for more details.
unknown's avatar
unknown committed
12

unknown's avatar
unknown committed
13 14 15 16 17 18 19 20 21
   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/* mysql command tool
 * Commands compatible with mSQL by David J. Hughes
 *
 * Written by:
 *   Michael 'Monty' Widenius
unknown's avatar
merge  
unknown committed
22 23 24 25 26 27 28
 *   Andi Gutmans  <andi@zend.com>
 *   Zeev Suraski  <zeev@zend.com>
 *   Jani Tolonen  <jani@mysql.com>
 *   Matt Wagner   <matt@mysql.com>
 *   Jeremy Cole   <jcole@mysql.com>
 *   Tonu Samuel   <tonu@mysql.com>
 *   Harrison Fisk <hcfisk@buffalo.edu>
unknown's avatar
unknown committed
29 30 31
 *
 **/

unknown's avatar
unknown committed
32
#include "client_priv.h"
unknown's avatar
unknown committed
33
#include <m_ctype.h>
34
#include <stdarg.h>
unknown's avatar
unknown committed
35 36
#include <my_dir.h>
#ifndef __GNU_LIBRARY__
unknown's avatar
unknown committed
37
#define __GNU_LIBRARY__		      // Skip warnings in getopt.h
unknown's avatar
unknown committed
38 39 40
#endif
#include "my_readline.h"
#include <signal.h>
unknown's avatar
unknown committed
41
#include <violite.h>
unknown's avatar
unknown committed
42

unknown's avatar
unknown committed
43 44 45 46
#if defined(USE_LIBEDIT_INTERFACE) && defined(HAVE_LOCALE_H)
#include <locale.h>
#endif

unknown's avatar
unknown committed
47
const char *VER= "14.1";
48

unknown's avatar
unknown committed
49 50 51
/* Don't try to make a nice table if the data is too big */
#define MAX_COLUMN_LENGTH	     1024

unknown's avatar
unknown committed
52
gptr sql_alloc(unsigned size);	     // Don't use mysqld alloc for these
unknown's avatar
unknown committed
53 54 55 56 57 58 59 60 61 62 63 64 65 66
void sql_element_free(void *ptr);
#include "sql_string.h"

extern "C" {
#if defined(HAVE_CURSES_H) && defined(HAVE_TERM_H)
#include <curses.h>
#include <term.h>
#else
#if defined(HAVE_TERMIOS_H)
#include <termios.h>
#include <unistd.h>
#elif defined(HAVE_TERMBITS_H)
#include <termbits.h>
#elif defined(HAVE_ASM_TERMBITS_H) && (!defined __GLIBC__ || !(__GLIBC__ > 2 || __GLIBC__ == 2 && __GLIBC_MINOR__ > 0))
unknown's avatar
unknown committed
67
#include <asm/termbits.h>		// Standard linux
unknown's avatar
unknown committed
68 69 70 71 72 73 74 75
#endif
#undef VOID
#if defined(HAVE_TERMCAP_H)
#include <termcap.h>
#else
#ifdef HAVE_CURSES_H
#include <curses.h>
#endif
unknown's avatar
unknown committed
76
#undef SYSV				// hack to avoid syntax error
unknown's avatar
unknown committed
77 78 79 80 81 82
#ifdef HAVE_TERM_H
#include <term.h>
#endif
#endif
#endif

unknown's avatar
unknown committed
83
#undef bcmp				// Fix problem with new readline
unknown's avatar
unknown committed
84
#if defined( __WIN__) || defined(OS2)
unknown's avatar
unknown committed
85
#include <conio.h>
unknown's avatar
unknown committed
86
#elif !defined(__NETWARE__)
unknown's avatar
unknown committed
87 88 89 90 91 92 93 94
#include <readline/readline.h>
#define HAVE_READLINE
#endif
  //int vidattr(long unsigned int attrs);	// Was missing in sun curses
}

#if !defined(HAVE_VIDATTR)
#undef vidattr
unknown's avatar
unknown committed
95
#define vidattr(A) {}			// Can't get this to work
unknown's avatar
unknown committed
96 97
#endif

98
#ifdef FN_NO_CASE_SENCE
99
#define cmp_database(cs,A,B) my_strcasecmp((cs), (A), (B))
unknown's avatar
unknown committed
100
#else
101
#define cmp_database(cs,A,B) strcmp((A),(B))
unknown's avatar
unknown committed
102 103
#endif

unknown's avatar
unknown committed
104 105 106 107
#if !defined( __WIN__) && !defined( OS2) && !defined(__NETWARE__) && (!defined(HAVE_mit_thread) || !defined(THREAD))
#define USE_POPEN
#endif

unknown's avatar
unknown committed
108 109
#include "completion_hash.h"

unknown's avatar
merge  
unknown committed
110
#define PROMPT_CHAR '\\'
unknown's avatar
unknown committed
111
#define DEFAULT_DELIMITER ";"
unknown's avatar
merge  
unknown committed
112

unknown's avatar
unknown committed
113 114 115 116 117 118 119 120 121 122 123
typedef struct st_status
{
  int exit_status;
  ulong query_start_line;
  char *file_name;
  LINE_BUFFER *line_buff;
  bool batch,add_to_history;
} STATUS;


static HashTable ht;
124
static char **defaults_argv;
unknown's avatar
unknown committed
125 126 127 128 129

enum enum_info_type { INFO_INFO,INFO_ERROR,INFO_RESULT};
typedef enum enum_info_type INFO_TYPE;

static MYSQL mysql;			/* The connection */
130 131
static my_bool info_flag=0,ignore_errors=0,wait_flag=0,quick=0,
               connected=0,opt_raw_data=0,unbuffered=0,output_tables=0,
unknown's avatar
unknown committed
132
	       rehash=1,skip_updates=0,safe_updates=0,one_database=0,
unknown's avatar
merge  
unknown committed
133
	       opt_compress=0, using_opt_local_infile=0,
134 135
	       vertical=0, line_numbers=1, column_names=1,opt_html=0,
               opt_xml=0,opt_nopager=1, opt_outfile=0, named_cmds= 0,
136
               tty_password= 0, opt_nobeep=0, opt_reconnect=1;
unknown's avatar
merge  
unknown committed
137
static uint verbose=0,opt_silent=0,opt_mysql_port=0, opt_local_infile=0;
unknown's avatar
unknown committed
138 139 140
static my_string opt_mysql_unix_port=0;
static int connect_flag=CLIENT_INTERACTIVE;
static char *current_host,*current_db,*current_user=0,*opt_password=0,
unknown's avatar
unknown committed
141
            *current_prompt=0, *delimiter_str= 0,
142
            *default_charset= (char*) MYSQL_DEFAULT_CHARSET_NAME;
unknown's avatar
unknown committed
143 144
static char *histfile;
static String glob_buffer,old_buffer;
unknown's avatar
merge  
unknown committed
145 146
static String processed_prompt;
static char *full_username=0,*part_username=0,*default_prompt=0;
unknown's avatar
unknown committed
147
static int wait_time = 5;
unknown's avatar
unknown committed
148
static STATUS status;
149
static ulong select_limit,max_join_size,opt_connect_timeout=0;
unknown's avatar
unknown committed
150
static char mysql_charsets_dir[FN_REFLEN+1];
unknown's avatar
unknown committed
151
static const char *xmlmeta[] = {
152 153 154 155
  "&", "&amp;",
  "<", "&lt;",
  0, 0
};
unknown's avatar
merge  
unknown committed
156 157 158 159 160 161 162 163
static const char *day_names[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
static const char *month_names[]={"Jan","Feb","Mar","Apr","May","Jun","Jul",
			    "Aug","Sep","Oct","Nov","Dec"};
static char default_pager[FN_REFLEN];
static char pager[FN_REFLEN], outfile[FN_REFLEN];
static FILE *PAGER, *OUTFILE;
static MEM_ROOT hash_mem_root;
static uint prompt_counter;
unknown's avatar
unknown committed
164 165
static char delimiter[16]= DEFAULT_DELIMITER;
static uint delimiter_length= 1;
unknown's avatar
unknown committed
166

167 168 169 170
#ifdef HAVE_SMEM
static char *shared_memory_base_name=0;
#endif
static uint opt_protocol=0;
171
static CHARSET_INFO *charset_info= &my_charset_latin1;
172
			   
unknown's avatar
unknown committed
173 174 175 176 177 178
#include "sslopt-vars.h"

#ifndef DBUG_OFF
const char *default_dbug_option="d:t:o,/tmp/mysql.trace";
#endif

unknown's avatar
unknown committed
179 180 181
void tee_fprintf(FILE *file, const char *fmt, ...);
void tee_fputs(const char *s, FILE *file);
void tee_puts(const char *s, FILE *file);
182
void tee_putc(int c, FILE *file);
unknown's avatar
unknown committed
183 184 185 186
/* The names of functions that actually do the manipulation. */
static int get_options(int argc,char **argv);
static int com_quit(String *str,char*),
	   com_go(String *str,char*), com_ego(String *str,char*),
187
	   com_print(String *str,char*),
unknown's avatar
unknown committed
188 189 190
	   com_help(String *str,char*), com_clear(String *str,char*),
	   com_connect(String *str,char*), com_status(String *str,char*),
	   com_use(String *str,char*), com_source(String *str, char*),
191
	   com_rehash(String *str, char*), com_tee(String *str, char*),
unknown's avatar
unknown committed
192
           com_notee(String *str, char*),
unknown's avatar
unknown committed
193
           com_prompt(String *str, char*), com_delimiter(String *str, char*);
unknown's avatar
unknown committed
194

unknown's avatar
unknown committed
195
#ifdef USE_POPEN
196
static int com_nopager(String *str, char*), com_pager(String *str, char*),
unknown's avatar
unknown committed
197
           com_edit(String *str,char*), com_shell(String *str, char *);
198 199
#endif

unknown's avatar
unknown committed
200 201 202
static int read_lines(bool execute_commands);
static int sql_connect(char *host,char *database,char *user,char *password,
		       uint silent);
203 204 205
static int put_info(const char *str,INFO_TYPE info,uint error=0,
		    const char *sql_state=0);
static int put_error(MYSQL *mysql);
unknown's avatar
unknown committed
206
static void safe_put_field(const char *pos,ulong length);
unknown's avatar
unknown committed
207
static void xmlencode_print(const char *src, uint length);
unknown's avatar
unknown committed
208 209
static void init_pager();
static void end_pager();
unknown's avatar
unknown committed
210
static void init_tee(const char *);
unknown's avatar
unknown committed
211
static void end_tee();
unknown's avatar
merge  
unknown committed
212
static const char* construct_prompt();
213
static char *get_arg(char *line, my_bool get_next_arg);
unknown's avatar
merge  
unknown committed
214 215
static void init_username();
static void add_int_to_prompt(int toadd);
unknown's avatar
unknown committed
216 217 218 219 220 221 222 223 224 225 226 227 228

/* A structure which contains information on the commands this program
   can understand. */

typedef struct {
  const char *name;		/* User printable name of the function. */
  char cmd_char;		/* msql command character */
  int (*func)(String *str,char *); /* Function to call to do the job. */
  bool takes_params;		/* Max parameters for command */
  const char *doc;		/* Documentation for this function.  */
} COMMANDS;

static COMMANDS commands[] = {
unknown's avatar
unknown committed
229 230
  { "help",   'h', com_help,   1, "Display this help." },
  { "?",      '?', com_help,   1, "Synonym for `help'." },
unknown's avatar
unknown committed
231
  { "clear",  'c', com_clear,  0, "Clear command."},
unknown's avatar
unknown committed
232
  { "connect",'r', com_connect,1,
unknown's avatar
unknown committed
233
    "Reconnect to the server. Optional arguments are db and host." },
unknown's avatar
unknown committed
234
#ifdef USE_POPEN
unknown's avatar
unknown committed
235
  { "edit",   'e', com_edit,   0, "Edit command with $EDITOR."},
236
#endif
unknown's avatar
unknown committed
237
  { "ego",    'G', com_ego,    0,
unknown's avatar
unknown committed
238 239 240
    "Send command to mysql server, display result vertically."},
  { "exit",   'q', com_quit,   0, "Exit mysql. Same as quit."},
  { "go",     'g', com_go,     0, "Send command to mysql server." },
unknown's avatar
unknown committed
241
#ifdef USE_POPEN
unknown's avatar
unknown committed
242 243 244
  { "nopager",'n', com_nopager,0, "Disable pager, print to stdout." },
#endif
  { "notee",  't', com_notee,  0, "Don't write into outfile." },
unknown's avatar
unknown committed
245
#ifdef USE_POPEN
unknown's avatar
unknown committed
246 247 248 249
  { "pager",  'P', com_pager,  1, 
    "Set PAGER [to_pager]. Print the query results via PAGER." },
#endif
  { "print",  'p', com_print,  0, "Print current command." },
unknown's avatar
merge  
unknown committed
250
  { "prompt", 'R', com_prompt, 1, "Change your mysql prompt."},
unknown's avatar
unknown committed
251 252
  { "quit",   'q', com_quit,   0, "Quit mysql." },
  { "rehash", '#', com_rehash, 0, "Rebuild completion hash." },
unknown's avatar
unknown committed
253
  { "source", '.', com_source, 1,
unknown's avatar
unknown committed
254 255
    "Execute a SQL script file. Takes a file name as an argument."},
  { "status", 's', com_status, 0, "Get status information from the server."},
unknown's avatar
unknown committed
256
#ifdef USE_POPEN
257 258
  { "system", '!', com_shell,  1, "Execute a system shell command."},
#endif
unknown's avatar
unknown committed
259 260
  { "tee",    'T', com_tee,    1, 
    "Set outfile [to_outfile]. Append everything into given outfile." },
unknown's avatar
unknown committed
261
  { "use",    'u', com_use,    1,
unknown's avatar
unknown committed
262
    "Use another database. Takes database name as argument." },
unknown's avatar
unknown committed
263 264
  { "delimiter", 'd', com_delimiter,    1,
    "Set query delimiter. " },
unknown's avatar
unknown committed
265
  /* Get bash-like expansion for some commands */
unknown's avatar
unknown committed
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
  { "create table",     0, 0, 0, ""},
  { "create database",  0, 0, 0, ""},
  { "drop",             0, 0, 0, ""},
  { "select",           0, 0, 0, ""},
  { "insert",           0, 0, 0, ""},
  { "replace",          0, 0, 0, ""},
  { "update",           0, 0, 0, ""},
  { "delete",           0, 0, 0, ""},
  { "explain",          0, 0, 0, ""},
  { "show databases",   0, 0, 0, ""},
  { "show fields from", 0, 0, 0, ""},
  { "show keys from",   0, 0, 0, ""},
  { "show tables",      0, 0, 0, ""},
  { "load data from",   0, 0, 0, ""},
  { "alter table",      0, 0, 0, ""},
  { "set option",       0, 0, 0, ""},
  { "lock tables",      0, 0, 0, ""},
  { "unlock tables",    0, 0, 0, ""},
  { (char *)NULL,       0, 0, 0, ""}
unknown's avatar
unknown committed
285 286 287
};

static const char *load_default_groups[]= { "mysql","client",0 };
unknown's avatar
unknown committed
288 289
static const char *server_default_groups[]=
{ "server", "embedded", "mysql_SERVER", 0 };
unknown's avatar
unknown committed
290 291

#ifdef HAVE_READLINE
292 293 294
extern "C" int add_history(const char *command); /* From readline directory */
extern "C" int read_history(const char *command);
extern "C" int write_history(const char *command);
unknown's avatar
unknown committed
295 296 297 298
static void initialize_readline (char *name);
#endif

static COMMANDS *find_command (char *name,char cmd_name);
299 300
static bool add_line(String &buffer,char *line,char *in_string,
                     bool *ml_comment);
unknown's avatar
unknown committed
301 302 303
static void remove_cntrl(String &buffer);
static void print_table_data(MYSQL_RES *result);
static void print_table_data_html(MYSQL_RES *result);
304
static void print_table_data_xml(MYSQL_RES *result);
unknown's avatar
unknown committed
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
static void print_tab_data(MYSQL_RES *result);
static void print_table_data_vertically(MYSQL_RES *result);
static ulong start_timer(void);
static void end_timer(ulong start_time,char *buff);
static void mysql_end_timer(ulong start_time,char *buff);
static void nice_time(double sec,char *buff,bool part_second);
static sig_handler mysql_end(int sig);


int main(int argc,char *argv[])
{
  char buff[80];

  MY_INIT(argv[0]);
  DBUG_ENTER("main");
  DBUG_PROCESS(argv[0]);
unknown's avatar
unknown committed
321 322
  
  delimiter_str= delimiter;
unknown's avatar
merge  
unknown committed
323 324 325 326 327 328
  default_prompt = my_strdup(getenv("MYSQL_PS1") ? 
			     getenv("MYSQL_PS1") : 
			     "mysql> ",MYF(MY_WME));
  current_prompt = my_strdup(default_prompt,MYF(MY_WME));
  prompt_counter=0;

unknown's avatar
unknown committed
329 330
  outfile[0]=0;			// no (default) outfile
  strmov(pager, "stdout");	// the default, if --pager wasn't given
331 332 333 334 335
  {
    char *tmp=getenv("PAGER");
    if (tmp)
      strmov(default_pager,tmp);
  }
unknown's avatar
unknown committed
336 337 338 339 340 341 342 343 344
  if (!isatty(0) || !isatty(1))
  {
    status.batch=1; opt_silent=1;
    ignore_errors=0;
  }
  else
    status.add_to_history=1;
  status.exit_status=1;
  load_defaults("my",load_default_groups,&argc,&argv);
345
  defaults_argv=argv;
346
  if (get_options(argc, (char **) argv))
unknown's avatar
unknown committed
347
  {
348
    free_defaults(defaults_argv);
unknown's avatar
unknown committed
349 350 351 352 353
    my_end(0);
    exit(1);
  }
  if (status.batch && !status.line_buff &&
      !(status.line_buff=batch_readline_init(max_allowed_packet+512,stdin)))
354 355
  {
    free_defaults(defaults_argv);
unknown's avatar
unknown committed
356
    exit(1);
357
  }
unknown's avatar
unknown committed
358
  glob_buffer.realloc(512);
359 360 361
  mysql_server_init(0, NULL, (char**) server_default_groups);
  completion_hash_init(&ht, 128);
  init_alloc_root(&hash_mem_root, 16384, 0);
362
  bzero((char*) &mysql, sizeof(mysql));
unknown's avatar
unknown committed
363 364 365
  if (sql_connect(current_host,current_db,current_user,opt_password,
		  opt_silent))
  {
366 367 368
    quick=1;					// Avoid history
    status.exit_status=1;
    mysql_end(-1);
unknown's avatar
unknown committed
369 370 371 372
  }
  if (!status.batch)
    ignore_errors=1;				// Don't abort monitor
  signal(SIGINT, mysql_end);			// Catch SIGINT to clean up
unknown's avatar
unknown committed
373
  signal(SIGQUIT, mysql_end);			// Catch SIGQUIT to clean up
unknown's avatar
unknown committed
374

unknown's avatar
unknown committed
375
  /*
376
    Run in interactive mode like the ingres/postgres monitor
unknown's avatar
unknown committed
377 378 379 380 381 382 383 384 385 386 387
  */

  put_info("Welcome to the MySQL monitor.  Commands end with ; or \\g.",
	   INFO_INFO);
  sprintf((char*) glob_buffer.ptr(),
	  "Your MySQL connection id is %ld to server version: %s\n",
	  mysql_thread_id(&mysql),mysql_get_server_info(&mysql));
  put_info((char*) glob_buffer.ptr(),INFO_INFO);

#ifdef HAVE_READLINE
  initialize_readline(my_progname);
388
  if (!status.batch && !quick && !opt_html && !opt_xml)
unknown's avatar
unknown committed
389
  {
390
    /* read-history from file, default ~/.mysql_history*/
unknown's avatar
unknown committed
391 392 393 394
    if (getenv("MYSQL_HISTFILE"))
      histfile=my_strdup(getenv("MYSQL_HISTFILE"),MYF(MY_WME));
    else if (getenv("HOME"))
    {
unknown's avatar
unknown committed
395 396
      histfile=(char*) my_malloc((uint) strlen(getenv("HOME"))
				 + (uint) strlen("/.mysql_history")+2,
unknown's avatar
unknown committed
397 398 399 400 401 402 403
				 MYF(MY_WME));
      if (histfile)
	sprintf(histfile,"%s/.mysql_history",getenv("HOME"));
    }
    if (histfile)
    {
      if (verbose)
unknown's avatar
unknown committed
404
	tee_fprintf(stdout, "Reading history-file %s\n",histfile);
unknown's avatar
unknown committed
405 406 407 408
      read_history(histfile);
    }
  }
#endif
409 410 411
  sprintf(buff, "%s",
	  "Type 'help;' or '\\h' for help. Type '\\c' to clear the buffer.\n");
#ifdef NOT_YET
unknown's avatar
unknown committed
412
	  "Type 'help [[%]function name[%]]' to get help on usage of function.\n");
413
#endif
unknown's avatar
unknown committed
414 415
  put_info(buff,INFO_INFO);
  status.exit_status=read_lines(1);		// read lines and execute them
unknown's avatar
unknown committed
416 417
  if (opt_outfile)
    end_tee();
unknown's avatar
unknown committed
418 419 420 421 422 423 424 425
  mysql_end(0);
#ifndef _lint
  DBUG_RETURN(0);				// Keep compiler happy
#endif
}

sig_handler mysql_end(int sig)
{
426
  mysql_close(&mysql);
unknown's avatar
unknown committed
427
#ifdef HAVE_READLINE
428
  if (!status.batch && !quick && !opt_html && !opt_xml)
unknown's avatar
unknown committed
429 430 431
  {
    /* write-history */
    if (verbose)
unknown's avatar
unknown committed
432
      tee_fprintf(stdout, "Writing history-file %s\n",histfile);
unknown's avatar
unknown committed
433 434 435 436
    write_history(histfile);
  }
  batch_readline_end(status.line_buff);
  completion_hash_free(&ht);
437 438
  free_root(&hash_mem_root,MYF(0));

unknown's avatar
unknown committed
439
#endif
440 441
  if (sig >= 0)
    put_info(sig ? "Aborted" : "Bye", INFO_RESULT);
unknown's avatar
unknown committed
442 443
  glob_buffer.free();
  old_buffer.free();
unknown's avatar
merge  
unknown committed
444
  processed_prompt.free();
unknown's avatar
unknown committed
445 446 447 448 449 450
  my_free(opt_password,MYF(MY_ALLOW_ZERO_PTR));
  my_free(opt_mysql_unix_port,MYF(MY_ALLOW_ZERO_PTR));
  my_free(histfile,MYF(MY_ALLOW_ZERO_PTR));
  my_free(current_db,MYF(MY_ALLOW_ZERO_PTR));
  my_free(current_host,MYF(MY_ALLOW_ZERO_PTR));
  my_free(current_user,MYF(MY_ALLOW_ZERO_PTR));
unknown's avatar
merge  
unknown committed
451 452 453
  my_free(full_username,MYF(MY_ALLOW_ZERO_PTR));
  my_free(part_username,MYF(MY_ALLOW_ZERO_PTR));
  my_free(default_prompt,MYF(MY_ALLOW_ZERO_PTR));
454 455 456
#ifdef HAVE_SMEM
  my_free(shared_memory_base_name,MYF(MY_ALLOW_ZERO_PTR));
#endif
unknown's avatar
merge  
unknown committed
457
  my_free(current_prompt,MYF(MY_ALLOW_ZERO_PTR));
unknown's avatar
unknown committed
458
  mysql_server_end();
459
  free_defaults(defaults_argv);
unknown's avatar
unknown committed
460 461 462 463
  my_end(info_flag ? MY_CHECK_ERROR | MY_GIVE_INFO : 0);
  exit(status.exit_status);
}

464 465

static struct my_option my_long_options[] =
unknown's avatar
unknown committed
466
{
467 468 469 470
  {"help", '?', "Display this help and exit.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0,
   0, 0, 0, 0, 0},
  {"auto-rehash", OPT_AUTO_REHASH,
   "Enable automatic rehashing. One doesn't need to use 'rehash' to get table and field completion, but startup and reconnecting may take a longer time. Disable with --disable-auto-rehash.",
471
   (gptr*) &rehash, (gptr*) &rehash, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0},
472
  {"no-auto-rehash", 'A',
unknown's avatar
unknown committed
473
   "No automatic rehashing. One has to use 'rehash' to get table and field completion. This gives a quicker start of mysql and disables rehashing on reconnect. WARNING: options deprecated; use --disable-auto-rehash instead.",
474 475 476 477 478 479
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"batch", 'B',
   "Print results with a tab as separator, each row on new line. Doesn't use history file.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"character-sets-dir", OPT_CHARSETS_DIR,
   "Directory where character sets are.", (gptr*) &charsets_dir,
   (gptr*) &charsets_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
480 481 482
  {"default-character-set", OPT_DEFAULT_CHARSET,
   "Set the default character set.", (gptr*) &default_charset,
   (gptr*) &default_charset, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
483 484 485
  {"compress", 'C', "Use compression in server/client protocol.",
   (gptr*) &opt_compress, (gptr*) &opt_compress, 0, GET_BOOL, NO_ARG, 0, 0, 0,
   0, 0, 0},
unknown's avatar
unknown committed
486
#ifndef DBUG_OFF
487 488 489
  {"debug", '#', "Output debug log.", (gptr*) &default_dbug_option,
   (gptr*) &default_dbug_option, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
#endif
490
  {"database", 'D', "Database to use.", (gptr*) &current_db,
491
   (gptr*) &current_db, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
492 493
  {"delimiter", OPT_DELIMITER, "Delimiter to be used.", (gptr*) &delimiter_str,
   (gptr*) &delimiter_str, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
494 495 496 497 498 499 500 501
  {"execute", 'e', "Execute command and quit. (Output like with --batch).", 0,
   0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"vertical", 'E', "Print the output of a query (rows) vertically.",
   (gptr*) &vertical, (gptr*) &vertical, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0,
   0},
  {"force", 'f', "Continue even if we get an sql error.",
   (gptr*) &ignore_errors, (gptr*) &ignore_errors, 0, GET_BOOL, NO_ARG, 0, 0,
   0, 0, 0, 0},
502
  {"no-named-commands", 'g',
unknown's avatar
unknown committed
503
   "Named commands are disabled. Use \\* form only, or use named commands only in the beginning of a line ending with a semicolon (;) Since version 10.9 the client now starts with this option ENABLED by default! Disable with '-G'. Long format commands still work from the first line. WARNING: option deprecated; use --disable-named-commands instead.",
504 505
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"named-commands", 'G',
506
   "Enable named commands. Named commands mean this program's internal commands; see mysql> help . When enabled, the named commands can be used from any line of the query, otherwise only from the first line, before an enter. Disable with --disable-named-commands. This option is disabled by default.",
507 508
   (gptr*) &named_cmds, (gptr*) &named_cmds, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
   0, 0},
unknown's avatar
unknown committed
509
  {"ignore-spaces", 'i', "Ignore space after function names.", 0, 0, 0,
510
   GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
merge  
unknown committed
511
  {"local-infile", OPT_LOCAL_INFILE, "Enable/disable LOAD DATA LOCAL INFILE.",
512 513
   (gptr*) &opt_local_infile,
   (gptr*) &opt_local_infile, 0, GET_BOOL, OPT_ARG, 0, 0, 0, 0, 0, 0},
514 515
  {"no-beep", 'b', "Turn off beep on error.", (gptr*) &opt_nobeep,
   (gptr*) &opt_nobeep, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, 
516
  {"host", 'h', "Connect to host.", (gptr*) &current_host,
517
   (gptr*) &current_host, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
518 519 520 521 522 523
  {"html", 'H', "Produce HTML output.", (gptr*) &opt_html, (gptr*) &opt_html,
   0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"xml", 'X', "Produce XML output", (gptr*) &opt_xml, (gptr*) &opt_xml, 0,
   GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"line-numbers", OPT_LINE_NUMBERS, "Write line numbers for errors.",
   (gptr*) &line_numbers, (gptr*) &line_numbers, 0, GET_BOOL,
524
   NO_ARG, 1, 0, 0, 0, 0, 0},  
unknown's avatar
unknown committed
525
  {"skip-line-numbers", 'L', "Don't write line number for errors. WARNING: -L is deprecated, use long version of this option instead.", 0, 0, 0, GET_NO_ARG,
526
   NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
527
#ifdef USE_POPEN
528
  {"no-pager", OPT_NOPAGER,
unknown's avatar
unknown committed
529
   "Disable pager and print to stdout. See interactive help (\\h) also. WARNING: option deprecated; use --disable-pager instead.",
530
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
531
#endif
unknown's avatar
unknown committed
532
  {"no-tee", OPT_NOTEE, "Disable outfile. See interactive help (\\h) also. WARNING: option deprecated; use --disable-tee instead", 0, 0, 0, GET_NO_ARG,
533 534 535 536 537
   NO_ARG, 0, 0, 0, 0, 0, 0},
  {"unbuffered", 'n', "Flush buffer after each query.", (gptr*) &unbuffered,
   (gptr*) &unbuffered, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"column-names", OPT_COLUMN_NAMES, "Write column names in results.",
   (gptr*) &column_names, (gptr*) &column_names, 0, GET_BOOL,
538
   NO_ARG, 1, 0, 0, 0, 0, 0},
539
  {"skip-column-names", 'N',
unknown's avatar
unknown committed
540
   "Don't write column names in results. WARNING: -N is deprecated, use long version of this options instead.",
541 542
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"set-variable", 'O',
unknown's avatar
unknown committed
543
   "Change the value of a variable. Please note that this option is deprecated; you can set variables directly with --variable-name=value.",
544 545 546 547
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"one-database", 'o',
   "Only update the default database. This is useful for skipping updates to other database in the update log.",
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
548
#ifdef USE_POPEN
549 550 551
  {"pager", OPT_PAGER,
   "Pager to use to display results. If you don't supply an option the default pager is taken from your ENV variable PAGER. Valid pagers are less, more, cat [> filename], etc. See interactive help (\\h) also. This option does not work in batch mode.",
   0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
552
#endif
553 554 555
  {"password", 'p',
   "Password to use when connecting to server. If password is not given it's asked from the tty.",
   0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
556
#ifdef __WIN__
557 558
  {"pipe", 'W', "Use named pipes to connect to server.", 0, 0, 0, GET_NO_ARG,
   NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
559
#endif
560 561 562
  {"port", 'P', "Port number to use for connection.", (gptr*) &opt_mysql_port,
   (gptr*) &opt_mysql_port, 0, GET_UINT, REQUIRED_ARG, MYSQL_PORT, 0, 0, 0, 0,
   0},
563
  {"prompt", OPT_PROMPT, "Set the mysql prompt to this value.",
564
   (gptr*) &current_prompt, (gptr*) &current_prompt, 0, GET_STR_ALLOC,
565
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
566
  {"protocol", OPT_MYSQL_PROTOCOL, "The protocol of connection (tcp,socket,pipe,memory).",
567
   0, 0, 0, GET_STR,  REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
568
  {"quick", 'q',
569
   "Don't cache result, print it row by row. This may slow down the server if the output is suspended. Doesn't use history file.",
570
   (gptr*) &quick, (gptr*) &quick, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
571
  {"raw", 'r', "Write fields without conversion. Used with --batch.",
572 573
   (gptr*) &opt_raw_data, (gptr*) &opt_raw_data, 0, GET_BOOL, NO_ARG, 0, 0, 0,
   0, 0, 0},
574 575
  {"reconnect", OPT_RECONNECT, "Reconnect if the connection is lost. Disable with --disable-reconnect. This option is enabled by default.", 
   (gptr*) &opt_reconnect, (gptr*) &opt_reconnect, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0},
576 577
  {"silent", 's', "Be more silent.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0,
   0, 0},
578 579
#ifdef HAVE_SMEM
  {"shared_memory_base_name", OPT_SHARED_MEMORY_BASE_NAME,
580
   "Base name of shared memory.", (gptr*) &shared_memory_base_name, (gptr*) &shared_memory_base_name, 
581 582
   0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#endif
583
  {"socket", 'S', "Socket file to use for connection.",
584
   (gptr*) &opt_mysql_unix_port, (gptr*) &opt_mysql_unix_port, 0, GET_STR_ALLOC,
585
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
586
#include "sslopt-longopts.h"
587 588 589 590 591 592 593
  {"table", 't', "Output in table format.", (gptr*) &output_tables,
   (gptr*) &output_tables, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"debug-info", 'T', "Print some debug info at exit.", (gptr*) &info_flag,
   (gptr*) &info_flag, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"tee", OPT_TEE,
   "Append everything into outfile. See interactive help (\\h) also. Does not work in batch mode.",
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
594
#ifndef DONT_ALLOW_USER_CHANGE
595
  {"user", 'u', "User for login if not current user.", (gptr*) &current_user,
596
   (gptr*) &current_user, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
597
#endif
598 599 600
  {"safe-updates", 'U', "Only allow UPDATE and DELETE that uses keys.",
   (gptr*) &safe_updates, (gptr*) &safe_updates, 0, GET_BOOL, OPT_ARG, 0, 0,
   0, 0, 0, 0},
601 602 603
  {"i-am-a-dummy", 'U', "Synonym for option --safe-updates, -U.",
   (gptr*) &safe_updates, (gptr*) &safe_updates, 0, GET_BOOL, OPT_ARG, 0, 0,
   0, 0, 0, 0},
604
  {"verbose", 'v', "Write more. (-v -v -v gives the table output format).", 0,
605 606 607 608 609 610
   0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"version", 'V', "Output version information and exit.", 0, 0, 0,
   GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"wait", 'w', "Wait and retry if connection is down.", 0, 0, 0, GET_NO_ARG,
   NO_ARG, 0, 0, 0, 0, 0, 0},
  {"connect_timeout", OPT_CONNECT_TIMEOUT, "", (gptr*) &opt_connect_timeout,
611
   (gptr*) &opt_connect_timeout, 0, GET_ULONG, REQUIRED_ARG, 0, 0, 3600*12, 0,
612 613
   0, 1},
  {"max_allowed_packet", OPT_MAX_ALLOWED_PACKET, "",
614
   (gptr*) &max_allowed_packet, (gptr*) &max_allowed_packet, 0, GET_ULONG,
615 616 617
   REQUIRED_ARG, 16 *1024L*1024L, 4096, 512*1024L*1024L, MALLOC_OVERHEAD,
   1024, 0},
  {"net_buffer_length", OPT_NET_BUFFER_LENGTH, "",
618
   (gptr*) &net_buffer_length, (gptr*) &net_buffer_length, 0, GET_ULONG,
619 620
   REQUIRED_ARG, 16384, 1024, 512*1024*1024L, MALLOC_OVERHEAD, 1024, 0},
  {"select_limit", OPT_SELECT_LIMIT, "", (gptr*) &select_limit,
621
   (gptr*) &select_limit, 0, GET_ULONG, REQUIRED_ARG, 1000L, 1, ~0L, 0, 1, 0},
622
  {"max_join_size", OPT_MAX_JOIN_SIZE, "", (gptr*) &max_join_size,
623
   (gptr*) &max_join_size, 0, GET_ULONG, REQUIRED_ARG, 1000000L, 1, ~0L, 0, 1,
624 625
   0},
  { 0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
unknown's avatar
unknown committed
626 627 628 629 630
};


static void usage(int version)
{
631 632
  printf("%s  Ver %s Distrib %s, for %s (%s)\n",
	 my_progname, VER, MYSQL_SERVER_VERSION, SYSTEM_TYPE, MACHINE_TYPE);
unknown's avatar
unknown committed
633 634
  if (version)
    return;
unknown's avatar
merge  
unknown committed
635
  printf("\
636
Copyright (C) 2002 MySQL AB\n\
unknown's avatar
merge  
unknown committed
637 638
This software comes with ABSOLUTELY NO WARRANTY. This is free software,\n\
and you are welcome to modify and redistribute it under the GPL license\n");
unknown's avatar
unknown committed
639
  printf("Usage: %s [OPTIONS] [database]\n", my_progname);
640
  my_print_help(my_long_options);
641
  print_defaults("my", load_default_groups);
642
  my_print_variables(my_long_options);
unknown's avatar
unknown committed
643 644
}

645 646 647
static my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
	       char *argument)
unknown's avatar
unknown committed
648
{
649
  switch(optid) {
unknown's avatar
unknown committed
650 651 652 653
  case OPT_CHARSETS_DIR:
    strmov(mysql_charsets_dir, argument);
    charsets_dir = mysql_charsets_dir;
    break;
unknown's avatar
unknown committed
654 655 656 657 658 659 660 661
  case OPT_DELIMITER:
    if (argument == disabled_my_option)
      strmov(delimiter, DEFAULT_DELIMITER);
    else
      strmake(delimiter, argument, sizeof(delimiter) - 1);
    delimiter_length= strlen(delimiter);
    delimiter_str= delimiter;
    break;
unknown's avatar
unknown committed
662 663 664 665 666 667
  case OPT_LOCAL_INFILE:
    using_opt_local_infile=1;
    break;
  case OPT_TEE:
    if (argument == disabled_my_option)
    {
unknown's avatar
unknown committed
668 669
      if (opt_outfile)
	end_tee();
unknown's avatar
unknown committed
670 671
    }
    else
unknown's avatar
unknown committed
672
      init_tee(argument);
unknown's avatar
unknown committed
673 674
    break;
  case OPT_NOTEE:
unknown's avatar
unknown committed
675
    printf("WARNING: option deprecated; use --disable-tee instead.\n");
unknown's avatar
unknown committed
676 677 678 679
    if (opt_outfile)
      end_tee();
    break;
  case OPT_PAGER:
680 681
    if (argument == disabled_my_option)
      opt_nopager= 1;
unknown's avatar
unknown committed
682
    else
683 684 685 686 687 688 689 690
    {
      opt_nopager= 0;
      if (argument)
	strmov(pager, argument);
      else
	strmov(pager, default_pager);
      strmov(default_pager, pager);
    }
unknown's avatar
unknown committed
691 692
    break;
  case OPT_NOPAGER:
unknown's avatar
unknown committed
693
    printf("WARNING: option deprecated; use --disable-pager instead.\n");
unknown's avatar
unknown committed
694
    opt_nopager= 1;
695 696
  case OPT_MYSQL_PROTOCOL:
  {
697 698
    if ((opt_protocol = find_type(argument, &sql_protocol_typelib,0)) ==
	~(ulong) 0)
699 700 701 702 703 704
    {
      fprintf(stderr, "Unknown option to protocol: %s\n", argument);
      exit(1);
    }
    break;
  }
unknown's avatar
unknown committed
705 706 707 708 709 710 711 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 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
    break;
  case 'A':
    rehash= 0;
    break;
  case 'N':
    column_names= 0;
    break;
  case 'e':
    status.batch= 1;
    status.add_to_history= 0;
    batch_readline_end(status.line_buff);	// If multiple -e
    if (!(status.line_buff= batch_readline_command(argument)))
      return 1;
    ignore_errors= 0;
    break;
  case 'o':
    if (argument == disabled_my_option)
      one_database= 0;
    else
      one_database= skip_updates= 1;
    break;
  case 'p':
    if (argument == disabled_my_option)
      argument= (char*) "";			// Don't require password
    if (argument)
    {
      char *start= argument;
      my_free(opt_password, MYF(MY_ALLOW_ZERO_PTR));
      opt_password= my_strdup(argument, MYF(MY_FAE));
      while (*argument) *argument++= 'x';		// Destroy argument
      if (*start)
	start[1]=0 ;
    }
    else
      tty_password= 1;
    break;
  case '#':
    DBUG_PUSH(argument ? argument : default_dbug_option);
    info_flag= 1;
    break;
  case 's':
    if (argument == disabled_my_option)
      opt_silent= 0;
    else
      opt_silent++;
    break;
  case 'v':
    if (argument == disabled_my_option)
      verbose= 0;
    else
      verbose++;
    break;
  case 'B':
    if (!status.batch)
    {
      status.batch= 1;
      status.add_to_history= 0;
      opt_silent++;				// more silent
    }
    break;
  case 'W':
unknown's avatar
unknown committed
766
#ifdef __WIN__
767
    opt_protocol = MYSQL_PROTOCOL_PIPE;
unknown's avatar
unknown committed
768
#endif
unknown's avatar
unknown committed
769
    break;
770
#include <sslopt-case.h>
unknown's avatar
unknown committed
771 772 773 774 775 776 777
  case 'V':
    usage(1);
    exit(0);
  case 'I':
  case '?':
    usage(0);
    exit(0);
unknown's avatar
unknown committed
778
  }
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
  return 0;
}


static int get_options(int argc, char **argv)
{
  char *tmp, *pagpoint;
  int ho_error;

  tmp= (char *) getenv("MYSQL_HOST");
  if (tmp)
    current_host= my_strdup(tmp, MYF(MY_WME));

  pagpoint= getenv("PAGER");
  if (!((char*) (pagpoint)))
  {
    strmov(pager, "stdout");
    opt_nopager= 1;
  }
  else
    strmov(pager, pagpoint);
  strmov(default_pager, pager);

  if ((ho_error=handle_options(&argc, &argv, my_long_options, get_one_option)))
803
    exit(ho_error);
804

unknown's avatar
unknown committed
805 806 807 808
  if (status.batch) /* disable pager and outfile in this case */
  {
    strmov(default_pager, "stdout");
    strmov(pager, "stdout");
809 810
    opt_nopager= 1;
    opt_outfile= 0;
811
    opt_reconnect= 0;
812
    connect_flag= 0; /* Not in interactive mode */
unknown's avatar
unknown committed
813
  }
814 815
  if (!(charset_info= get_charset_by_csname(default_charset, 
					    MY_CS_PRIMARY, MYF(MY_WME))))
816
    exit(1);
unknown's avatar
unknown committed
817 818 819 820 821 822 823
  if (argc > 1)
  {
    usage(0);
    exit(1);
  }
  if (argc == 1)
  {
unknown's avatar
unknown committed
824
    skip_updates= 0;
825 826
    my_free(current_db, MYF(MY_ALLOW_ZERO_PTR));
    current_db= my_strdup(*argv, MYF(MY_WME));
unknown's avatar
unknown committed
827 828
  }
  if (tty_password)
829
    opt_password= get_tty_password(NullS);
unknown's avatar
unknown committed
830 831 832 833 834
  return(0);
}

static int read_lines(bool execute_commands)
{
unknown's avatar
unknown committed
835
#if defined( __WIN__) || defined(OS2) || defined(__NETWARE__)
unknown's avatar
unknown committed
836 837 838 839 840
  char linebuffer[254];
#endif
  char	*line;
  char	in_string=0;
  ulong line_number=0;
841
  bool ml_comment= 0;  
unknown's avatar
unknown committed
842 843
  COMMANDS *com;
  status.exit_status=1;
844
  
unknown's avatar
unknown committed
845 846 847 848 849 850 851 852 853 854
  for (;;)
  {
    if (status.batch || !execute_commands)
    {
      line=batch_readline(status.line_buff);
      line_number++;
      if (!glob_buffer.length())
	status.query_start_line=line_number;
    }
    else
unknown's avatar
unknown committed
855
    {
unknown's avatar
unknown committed
856 857 858 859
      char *prompt= (char*) (glob_buffer.is_empty() ? construct_prompt() :
			     !in_string ? "    -> " :
			     in_string == '\'' ?
			     "    '> " : "    \"> ");
860 861
      if (opt_outfile && glob_buffer.is_empty())
	fflush(OUTFILE);
unknown's avatar
unknown committed
862 863 864 865 866 867

#if defined( __WIN__) || defined(OS2) || defined(__NETWARE__)
      tee_fputs(prompt, stdout);
#ifdef __NETWARE__
      line=fgets(linebuffer, sizeof(linebuffer)-1, stdin);
      /* Remove the '\n' */
unknown's avatar
unknown committed
868
      {
unknown's avatar
unknown committed
869
        char *p = strrchr(line, '\n');
870 871
        if (p != NULL)
          *p = '\0';
unknown's avatar
unknown committed
872
      }
unknown's avatar
unknown committed
873 874 875 876 877 878 879 880 881 882
#else
      linebuffer[0]= (char) sizeof(linebuffer);
      line= _cgets(linebuffer);
#endif /* __NETWARE__ */
#else
      if (opt_outfile)
	fputs(prompt, OUTFILE);
      line= readline(prompt);
#endif /* defined( __WIN__) || defined(OS2) || defined(__NETWARE__) */

unknown's avatar
unknown committed
883 884
      if (opt_outfile)
	fprintf(OUTFILE, "%s\n", line);
885
    }
unknown's avatar
unknown committed
886 887 888 889 890 891 892 893
    if (!line)					// End of file
    {
      status.exit_status=0;
      break;
    }
    if (!in_string && (line[0] == '#' ||
		       (line[0] == '-' && line[1] == '-') ||
		       line[0] == 0))
unknown's avatar
unknown committed
894
      continue;					// Skip comment lines
unknown's avatar
unknown committed
895

896 897 898 899
    /*
      Check if line is a mysql command line
      (We want to allow help, print and clear anywhere at line start
    */
900
    if (execute_commands && (named_cmds || glob_buffer.is_empty()) 
unknown's avatar
unknown committed
901
	&& !in_string && (com=find_command(line,0)))
unknown's avatar
unknown committed
902 903 904 905 906 907 908 909 910 911 912
    {
      if ((*com->func)(&glob_buffer,line) > 0)
	break;
      if (glob_buffer.is_empty())		// If buffer was emptied
	in_string=0;
#ifdef HAVE_READLINE
      if (status.add_to_history)
	add_history(line);
#endif
      continue;
    }
913
    if (add_line(glob_buffer,line,&in_string,&ml_comment))
unknown's avatar
unknown committed
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
      break;
  }
  /* if in batch mode, send last query even if it doesn't end with \g or go */

  if ((status.batch || !execute_commands) && !status.exit_status)
  {
    remove_cntrl(glob_buffer);
    if (!glob_buffer.is_empty())
    {
      status.exit_status=1;
      if (com_go(&glob_buffer,line) <= 0)
	status.exit_status=0;
    }
  }
  return status.exit_status;
}


static COMMANDS *find_command (char *name,char cmd_char)
{
  uint len;
  char *end;

  if (!name)
  {
    len=0;
    end=0;
  }
  else
  {
944
    while (my_isspace(charset_info,*name))
unknown's avatar
unknown committed
945
      name++;
unknown's avatar
unknown committed
946
    if (strstr(name, delimiter) || strstr(name, "\\g"))
unknown's avatar
unknown committed
947 948 949 950
      return ((COMMANDS *) 0);
    if ((end=strcont(name," \t")))
    {
      len=(uint) (end - name);
951
      while (my_isspace(charset_info,*end))
unknown's avatar
unknown committed
952 953 954 955 956
	end++;
      if (!*end)
	end=0;					// no arguments to function
    }
    else
unknown's avatar
unknown committed
957
      len=(uint) strlen(name);
unknown's avatar
unknown committed
958 959 960 961 962
  }

  for (uint i= 0; commands[i].name; i++)
  {
    if (commands[i].func &&
963
	((name && 
964 965
	  !my_strnncoll(charset_info,(uchar*)name,len,
				     (uchar*)commands[i].name,len) &&
unknown's avatar
unknown committed
966 967 968 969 970 971 972 973 974
	  !commands[i].name[len] &&
	  (!end || (end && commands[i].takes_params))) ||
	 !name && commands[i].cmd_char == cmd_char))
      return (&commands[i]);
  }
  return ((COMMANDS *) 0);
}


975 976
static bool add_line(String &buffer,char *line,char *in_string,
                     bool *ml_comment)
unknown's avatar
unknown committed
977 978
{
  uchar inchar;
unknown's avatar
unknown committed
979
  char buff[80], *pos, *out;
unknown's avatar
unknown committed
980 981 982 983 984 985 986 987 988
  COMMANDS *com;

  if (!line[0] && buffer.is_empty())
    return 0;
#ifdef HAVE_READLINE
  if (status.add_to_history && line[0])
    add_history(line);
#endif
#ifdef USE_MB
unknown's avatar
unknown committed
989
  char *strend=line+(uint) strlen(line);
unknown's avatar
unknown committed
990 991 992 993
#endif

  for (pos=out=line ; (inchar= (uchar) *pos) ; pos++)
  {
994
    if (my_isspace(charset_info,inchar) && out == line && 
995
        buffer.is_empty())
unknown's avatar
unknown committed
996 997 998
      continue;
#ifdef USE_MB
    int l;
999 1000
    if (use_mb(charset_info) &&
        (l = my_ismbchar(charset_info, pos, strend))) {
unknown's avatar
unknown committed
1001 1002 1003 1004 1005 1006
	while (l--)
	    *out++ = *pos++;
	pos--;
	continue;
    }
#endif
1007
    if (!*ml_comment && inchar == '\\')
unknown's avatar
unknown committed
1008 1009 1010
    {
      // Found possbile one character command like \c

unknown's avatar
unknown committed
1011 1012
      if (!(inchar = (uchar) *++pos))
	break;				// readline adds one '\'
unknown's avatar
unknown committed
1013
      if (*in_string || inchar == 'N')	// \N is short for NULL
unknown's avatar
unknown committed
1014 1015 1016 1017 1018 1019 1020
      {					// Don't allow commands in string
	*out++='\\';
	*out++= (char) inchar;
	continue;
      }
      if ((com=find_command(NullS,(char) inchar)))
      {
1021
	const String tmp(line,(uint) (out-line), charset_info);
unknown's avatar
unknown committed
1022 1023 1024 1025 1026
	buffer.append(tmp);
	if ((*com->func)(&buffer,pos-1) > 0)
	  return 1;				// Quit
	if (com->takes_params)
	{
unknown's avatar
unknown committed
1027 1028 1029 1030
	  for (pos++ ;
	       *pos && (*pos != *delimiter ||
			!is_prefix(pos + 1, delimiter + 1)) ; pos++)
	    ;	// Remove parameters
unknown's avatar
unknown committed
1031 1032
	  if (!*pos)
	    pos--;
unknown's avatar
unknown committed
1033 1034
	  else 
	    pos+= delimiter_length - 1; // Point at last delim char
unknown's avatar
unknown committed
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
	}
	out=line;
      }
      else
      {
	sprintf(buff,"Unknown command '\\%c'.",inchar);
	if (put_info(buff,INFO_ERROR) > 0)
	  return 1;
	*out++='\\';
	*out++=(char) inchar;
	continue;
      }
    }
unknown's avatar
unknown committed
1048 1049 1050 1051 1052 1053

    else if (!*ml_comment && (*pos == *delimiter &&
			      is_prefix(pos + 1, delimiter + 1)) &&
	     !*in_string)
    {					
      uint old_delimiter_length= delimiter_length;
unknown's avatar
unknown committed
1054
      if (out != line)
unknown's avatar
unknown committed
1055 1056
	buffer.append(line, (uint) (out - line));	// Add this line
      if ((com= find_command(buffer.c_ptr(), 0)))
unknown's avatar
unknown committed
1057
      {
unknown's avatar
unknown committed
1058
	if ((*com->func)(&buffer, buffer.c_ptr()) > 0)
unknown's avatar
unknown committed
1059 1060 1061 1062
	  return 1;				// Quit
      }
      else
      {
unknown's avatar
unknown committed
1063
	int error= com_go(&buffer, 0);
unknown's avatar
unknown committed
1064 1065 1066 1067 1068 1069
	if (error)
	{
	  return error < 0 ? 0 : 1;		// < 0 is not fatal
	}
      }
      buffer.length(0);
unknown's avatar
unknown committed
1070 1071
      out= line;
      pos+= old_delimiter_length - 1;
unknown's avatar
unknown committed
1072
    }
1073 1074
    else if (!*ml_comment && (!*in_string && (inchar == '#' ||
			      inchar == '-' && pos[1] == '-' &&
1075
			      my_isspace(charset_info,pos[2]))))
unknown's avatar
unknown committed
1076
      break;					// comment to end of line
unknown's avatar
unknown committed
1077 1078
    else if (!*in_string && inchar == '/' && *(pos+1) == '*' &&
	     *(pos+2) != '!')
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
    {
      pos++;
      *ml_comment= 1;
      if (out != line)
      {
        buffer.append(line,(uint) (out-line));
        out=line;
      }
    }
    else if (*ml_comment && !*in_string && inchar == '*' && *(pos+1) == '/')
    {
      pos++;
      *ml_comment= 0;
    }      
unknown's avatar
unknown committed
1093 1094 1095 1096
    else
    {						// Add found char to buffer
      if (inchar == *in_string)
	*in_string=0;
1097
      else if (!*in_string && (inchar == '\'' || inchar == '"' || inchar == '`'))
unknown's avatar
unknown committed
1098
	*in_string=(char) inchar;
1099 1100
      if (!(*ml_comment))
        *out++ = (char) inchar;
unknown's avatar
unknown committed
1101 1102 1103 1104 1105 1106 1107 1108
    }
  }
  if (out != line || !buffer.is_empty())
  {
    *out++='\n';
    uint length=(uint) (out-line);
    if (buffer.length() + length >= buffer.alloced_length())
      buffer.realloc(buffer.length()+length+IO_SIZE);
1109
    if (!(*ml_comment) && buffer.append(line,length))
unknown's avatar
unknown committed
1110 1111 1112 1113 1114
      return 1;
  }
  return 0;
}

1115 1116 1117
/*****************************************************************
	    Interface to Readline Completion
******************************************************************/
unknown's avatar
unknown committed
1118 1119 1120

#ifdef HAVE_READLINE

unknown's avatar
unknown committed
1121 1122
static char *new_command_generator(const char *text, int);
static char **new_mysql_completion (const char *text, int start, int end);
unknown's avatar
unknown committed
1123

1124 1125 1126 1127 1128
/*
  Tell the GNU Readline library how to complete.  We want to try to complete
  on command names if this is the first word in the line, or on filenames
  if not.
*/
unknown's avatar
unknown committed
1129

1130 1131 1132 1133 1134
#if defined(USE_NEW_READLINE_INTERFACE) || defined(USE_LIBEDIT_INTERFACE)
char *no_completion(const char*,int)
#else
int no_completion()
#endif
unknown's avatar
unknown committed
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
{
  return 0;					/* No filename completion */
}

static void initialize_readline (char *name)
{
  /* Allow conditional parsing of the ~/.inputrc file. */
  rl_readline_name = name;

  /* Tell the completer that we want a crack first. */
1145 1146 1147 1148
#if defined(USE_NEW_READLINE_INTERFACE)
  rl_attempted_completion_function= (rl_completion_func_t*)&new_mysql_completion;
  rl_completion_entry_function= (rl_compentry_func_t*)&no_completion;
#elif defined(USE_LIBEDIT_INTERFACE)
unknown's avatar
unknown committed
1149 1150 1151
#ifdef HAVE_LOCALE_H
  setlocale(LC_ALL,""); /* so as libedit use isprint */
#endif
1152 1153
  rl_attempted_completion_function= (CPPFunction*)&new_mysql_completion;
  rl_completion_entry_function= (CPFunction*)&no_completion;
1154
#else
1155 1156
  rl_attempted_completion_function= (CPPFunction*)&new_mysql_completion;
  rl_completion_entry_function= (Function*)&no_completion;
1157
#endif
unknown's avatar
unknown committed
1158 1159
}

1160 1161 1162 1163 1164 1165
/*
  Attempt to complete on the contents of TEXT.  START and END show the
  region of TEXT that contains the word to complete.  We can use the
  entire line in case we want to do some simple parsing.  Return the
  array of matches, or NULL if there aren't any.
*/
unknown's avatar
unknown committed
1166

unknown's avatar
unknown committed
1167
static char **new_mysql_completion (const char *text,
unknown's avatar
unknown committed
1168 1169 1170 1171
				    int start __attribute__((unused)),
				    int end __attribute__((unused)))
{
  if (!status.batch && !quick)
1172
#if defined(USE_NEW_READLINE_INTERFACE)
unknown's avatar
unknown committed
1173
    return rl_completion_matches(text, new_command_generator);
1174 1175 1176
#else
    return completion_matches((char *)text, (CPFunction *)new_command_generator);
#endif
unknown's avatar
unknown committed
1177 1178 1179 1180
  else
    return (char**) 0;
}

unknown's avatar
unknown committed
1181
static char *new_command_generator(const char *text,int state)
unknown's avatar
unknown committed
1182 1183 1184 1185 1186 1187 1188
{
  static int textlen;
  char *ptr;
  static Bucket *b;
  static entry *e;
  static uint i;

1189
  if (!state)
unknown's avatar
unknown committed
1190
    textlen=(uint) strlen(text);
unknown's avatar
unknown committed
1191

1192 1193 1194 1195
  if (textlen>0)
  {						/* lookup in the hash */
    if (!state)
    {
unknown's avatar
unknown committed
1196 1197
      uint len;

unknown's avatar
unknown committed
1198
      b = find_all_matches(&ht,text,(uint) strlen(text),&len);
1199
      if (!b)
unknown's avatar
unknown committed
1200 1201 1202 1203
	return NullS;
      e = b->pData;
    }

1204 1205
    if (e)
    {
unknown's avatar
unknown committed
1206 1207 1208 1209
      ptr= strdup(e->str);
      e = e->pNext;
      return ptr;
    }
1210 1211 1212
  }
  else
  { /* traverse the entire hash, ugly but works */
unknown's avatar
unknown committed
1213

1214 1215
    if (!state)
    {
unknown's avatar
unknown committed
1216
      /* find the first used bucket */
1217 1218 1219 1220
      for (i=0 ; i < ht.nTableSize ; i++)
      {
	if (ht.arBuckets[i])
	{
unknown's avatar
unknown committed
1221 1222 1223 1224 1225 1226 1227
	  b = ht.arBuckets[i];
	  e = b->pData;
	  break;
	}
      }
    }
    ptr= NullS;
1228 1229 1230
    while (e && !ptr)
    {					/* find valid entry in bucket */
      if ((uint) strlen(e->str) == b->nKeyLength)
unknown's avatar
unknown committed
1231 1232 1233
	ptr = strdup(e->str);
      /* find the next used entry */
      e = e->pNext;
1234 1235
      if (!e)
      { /* find the next used bucket */
unknown's avatar
unknown committed
1236
	b = b->pNext;
1237 1238 1239 1240 1241 1242
	if (!b)
	{
	  for (i++ ; i<ht.nTableSize; i++)
	  {
	    if (ht.arBuckets[i])
	    {
unknown's avatar
unknown committed
1243 1244 1245 1246 1247 1248
	      b = ht.arBuckets[i];
	      e = b->pData;
	      break;
	    }
	  }
	}
1249 1250
	else
	  e = b->pData;
unknown's avatar
unknown committed
1251 1252
      }
    }
1253
    if (ptr)
unknown's avatar
unknown committed
1254 1255 1256 1257 1258 1259 1260 1261
      return ptr;
  }
  return NullS;
}


/* Build up the completion hash */

unknown's avatar
unknown committed
1262
static void build_completion_hash(bool rehash, bool write_info)
unknown's avatar
unknown committed
1263 1264
{
  COMMANDS *cmd=commands;
1265 1266
  MYSQL_RES *databases=0,*tables=0;
  MYSQL_RES *fields;
unknown's avatar
unknown committed
1267 1268 1269 1270 1271 1272 1273
  static char ***field_names= 0;
  MYSQL_ROW database_row,table_row;
  MYSQL_FIELD *sql_field;
  char buf[NAME_LEN*2+2];		 // table name plus field name plus 2
  int i,j,num_fields;
  DBUG_ENTER("build_completion_hash");

1274
  if (status.batch || quick || !current_db)
unknown's avatar
unknown committed
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
    DBUG_VOID_RETURN;			// We don't need completion in batches

  if (tables)
  {
    mysql_free_result(tables);
    tables=0;
  }

  /* hash SQL commands */
  while (cmd->name) {
    add_word(&ht,(char*) cmd->name);
    cmd++;
  }
unknown's avatar
unknown committed
1288
  if (!rehash)
unknown's avatar
unknown committed
1289 1290
    DBUG_VOID_RETURN;

1291 1292 1293 1294 1295 1296
  /* Free old used memory */
  if (field_names)
    field_names=0;
  completion_hash_clean(&ht);
  free_root(&hash_mem_root,MYF(0));

unknown's avatar
unknown committed
1297 1298 1299
  /* hash MySQL functions (to be implemented) */

  /* hash all database names */
1300 1301
  if (mysql_query(&mysql,"show databases") == 0)
  {
unknown's avatar
unknown committed
1302 1303 1304 1305 1306
    if (!(databases = mysql_store_result(&mysql)))
      put_info(mysql_error(&mysql),INFO_INFO);
    else
    {
      while ((database_row=mysql_fetch_row(databases)))
1307 1308 1309 1310 1311 1312
      {
	char *str=strdup_root(&hash_mem_root, (char*) database_row[0]);
	if (str)
	  add_word(&ht,(char*) str);
      }
      mysql_free_result(databases);
unknown's avatar
unknown committed
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323
    }
  }
  /* hash all table names */
  if (mysql_query(&mysql,"show tables")==0)
  {
    if (!(tables = mysql_store_result(&mysql)))
      put_info(mysql_error(&mysql),INFO_INFO);
    else
    {
      if (mysql_num_rows(tables) > 0 && !opt_silent && write_info)
      {
unknown's avatar
unknown committed
1324
	tee_fprintf(stdout, "\
unknown's avatar
unknown committed
1325 1326 1327 1328 1329
Reading table information for completion of table and column names\n\
You can turn off this feature to get a quicker startup with -A\n\n");
      }
      while ((table_row=mysql_fetch_row(tables)))
      {
1330 1331 1332 1333
	char *str=strdup_root(&hash_mem_root, (char*) table_row[0]);
	if (str &&
	    !completion_hash_exists(&ht,(char*) str, (uint) strlen(str)))
	  add_word(&ht,str);
unknown's avatar
unknown committed
1334 1335 1336 1337 1338
      }
    }
  }

  /* hash all field names, both with the table prefix and without it */
unknown's avatar
unknown committed
1339 1340
  if (!tables)					/* no tables */
  {
unknown's avatar
unknown committed
1341 1342 1343
    DBUG_VOID_RETURN;
  }
  mysql_data_seek(tables,0);
1344 1345 1346 1347
  if (!(field_names= (char ***) alloc_root(&hash_mem_root,sizeof(char **) *
					   (uint) (mysql_num_rows(tables)+1))))
  {
    mysql_free_result(tables);
unknown's avatar
unknown committed
1348
    DBUG_VOID_RETURN;
1349
  }
unknown's avatar
unknown committed
1350 1351 1352 1353 1354 1355
  i=0;
  while ((table_row=mysql_fetch_row(tables)))
  {
    if ((fields=mysql_list_fields(&mysql,(const char*) table_row[0],NullS)))
    {
      num_fields=mysql_num_fields(fields);
1356 1357 1358 1359
      if (!(field_names[i] = (char **) alloc_root(&hash_mem_root,
						  sizeof(char *) *
						  (num_fields*2+1))))
	break;
1360
      field_names[i][num_fields*2]= '\0';
unknown's avatar
unknown committed
1361 1362 1363 1364
      j=0;
      while ((sql_field=mysql_fetch_field(fields)))
      {
	sprintf(buf,"%s.%s",table_row[0],sql_field->name);
1365
	field_names[i][j] = strdup_root(&hash_mem_root,buf);
unknown's avatar
unknown committed
1366
	add_word(&ht,field_names[i][j]);
1367 1368
	field_names[i][num_fields+j] = strdup_root(&hash_mem_root,
						   sql_field->name);
unknown's avatar
unknown committed
1369
	if (!completion_hash_exists(&ht,field_names[i][num_fields+j],
unknown's avatar
unknown committed
1370
				    (uint) strlen(field_names[i][num_fields+j])))
unknown's avatar
unknown committed
1371 1372 1373
	  add_word(&ht,field_names[i][num_fields+j]);
	j++;
      }
1374
      mysql_free_result(fields);
unknown's avatar
unknown committed
1375 1376
    }
    else
unknown's avatar
unknown committed
1377
    {
unknown's avatar
unknown committed
1378 1379
      tee_fprintf(stdout,
		  "Didn't find any fields in table '%s'\n",table_row[0]);
1380
      field_names[i]= 0;
unknown's avatar
unknown committed
1381
    }
unknown's avatar
unknown committed
1382 1383
    i++;
  }
1384
  mysql_free_result(tables);
unknown's avatar
unknown committed
1385
  field_names[i]=0;				// End pointer
unknown's avatar
unknown committed
1386 1387 1388 1389 1390 1391 1392
  DBUG_VOID_RETURN;
}

	/* for gnu readline */

#ifndef HAVE_INDEX
extern "C" {
1393
extern char *index(const char *,int c),*rindex(const char *,int);
unknown's avatar
unknown committed
1394

1395
char *index(const char *s,int c)
unknown's avatar
unknown committed
1396 1397 1398 1399 1400 1401 1402 1403
{
  for (;;)
  {
     if (*s == (char) c) return (char*) s;
     if (!*s++) return NullS;
  }
}

1404
char *rindex(const char *s,int c)
unknown's avatar
unknown committed
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415
{
  reg3 char *t;

  t = NullS;
  do if (*s == (char) c) t = (char*) s; while (*s++);
  return (char*) t;
}
}
#endif
#endif /* HAVE_READLINE */

1416

unknown's avatar
unknown committed
1417 1418
static int reconnect(void)
{
1419
  if (opt_reconnect)
unknown's avatar
unknown committed
1420 1421 1422
  {
    put_info("No connection. Trying to reconnect...",INFO_INFO);
    (void) com_connect((String *) 0, 0);
1423 1424
    if (rehash)
      com_rehash(NULL, NULL);
unknown's avatar
unknown committed
1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
  }
  if (!connected)
    return put_info("Can't connect to the server\n",INFO_ERROR);
  return 0;
}


/***************************************************************************
 The different commands
***************************************************************************/

unknown's avatar
unknown committed
1436 1437 1438 1439 1440 1441
int mysql_real_query_for_lazy(const char *buf, int length)
{
  for (uint retry=0;; retry++)
  {
    if (!mysql_real_query(&mysql,buf,length))
      return 0;    
1442
    int error= put_error(&mysql);
1443
    if (mysql_errno(&mysql) != CR_SERVER_GONE_ERROR || retry > 1 ||
1444
      !opt_reconnect)
unknown's avatar
unknown committed
1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456
      return error;
    if (reconnect())
      return error;
  }
}

int mysql_store_result_for_lazy(MYSQL_RES **result)
{
  if ((*result=mysql_store_result(&mysql)))
    return 0;

  if (mysql_error(&mysql)[0])
1457
    return put_error(&mysql);
unknown's avatar
unknown committed
1458 1459 1460
  return 0;
}

unknown's avatar
unknown committed
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
static void print_help_item(MYSQL_ROW *cur, int num_name, int num_cat, char *last_char)
{
  char ccat= (*cur)[num_cat][0];
  if (*last_char != ccat)
  {
    put_info(ccat == 'Y' ? "categories :" : "topics :", INFO_INFO);
    *last_char= ccat;
  }
  tee_fprintf(PAGER, "   %s\n", (*cur)[num_name]);
}
1471

unknown's avatar
unknown committed
1472
static int com_server_help(String *buffer __attribute__((unused)),
1473
			   char *line __attribute__((unused)), char *help_arg)
unknown's avatar
unknown committed
1474 1475 1476 1477
{
  MYSQL_ROW cur;
  const char *server_cmd= buffer->ptr();
  char cmd_buf[100];
1478
  MYSQL_RES *result;
unknown's avatar
unknown committed
1479
  MYSQL_FIELD *fields;
1480
  int error;
unknown's avatar
unknown committed
1481
  
1482
  if (help_arg[0] != '\'')
unknown's avatar
unknown committed
1483
  {
1484
    (void) strxnmov(cmd_buf, sizeof(cmd_buf), "help '", help_arg, "'", NullS);
unknown's avatar
unknown committed
1485 1486
    server_cmd= cmd_buf;
  }
unknown's avatar
unknown committed
1487
  
unknown's avatar
unknown committed
1488 1489 1490 1491 1492 1493 1494 1495 1496
  if (!status.batch)
  {
    old_buffer= *buffer;
    old_buffer.copy();
  }

  if (!connected && reconnect())
    return 1;

unknown's avatar
unknown committed
1497 1498
  if ((error= mysql_real_query_for_lazy(server_cmd,strlen(server_cmd))) ||
      (error= mysql_store_result_for_lazy(&result)))
unknown's avatar
unknown committed
1499 1500 1501 1502
    return error;

  if (result)
  {
unknown's avatar
unknown committed
1503 1504 1505 1506
    unsigned int num_fields= mysql_num_fields(result);
    my_ulonglong num_rows= mysql_num_rows(result);
    fields= mysql_fetch_fields(result);
    if (num_fields==3 && num_rows==1)
unknown's avatar
unknown committed
1507 1508
    {
      if (!(cur= mysql_fetch_row(result)))
1509 1510 1511 1512
      {
	error= -1;
	goto err;
      }
unknown's avatar
unknown committed
1513 1514

      init_pager();
unknown's avatar
unknown committed
1515 1516 1517 1518 1519
      tee_fprintf(PAGER,   "Name: \'%s\'\n", cur[0]);
      tee_fprintf(PAGER,   "Description:\n%s", cur[1]);
      if (cur[2] && *((char*)cur[2]))
	tee_fprintf(PAGER, "Examples:\n%s", cur[2]);
      tee_fprintf(PAGER,   "\n");
unknown's avatar
unknown committed
1520 1521
      end_pager();
    }
unknown's avatar
unknown committed
1522
    else if (num_fields >= 2 && num_rows)
unknown's avatar
unknown committed
1523 1524
    {
      init_pager();
unknown's avatar
unknown committed
1525 1526 1527 1528
      char last_char;
      
      int num_name, num_cat;
      if (num_fields == 2)
1529
      {
unknown's avatar
unknown committed
1530 1531 1532 1533 1534
	put_info("Many help items for your request exist", INFO_INFO);
	put_info("For more specific request please type 'help <item>' where item is one of next", INFO_INFO);
	num_name= 0;
	num_cat= 1;
	last_char= '_';
unknown's avatar
unknown committed
1535
      }
unknown's avatar
unknown committed
1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546
      else if ((cur= mysql_fetch_row(result)))
      {
	tee_fprintf(PAGER, "You asked help about help category: \"%s\"\n", cur[0]);
	put_info("For a more information type 'help <item>' where item is one of the following", INFO_INFO);
	num_name= 1;
	num_cat= 2;
	print_help_item(&cur,1,2,&last_char);
      }
      
      while ((cur= mysql_fetch_row(result)))
	print_help_item(&cur,num_name,num_cat,&last_char);
unknown's avatar
unknown committed
1547 1548 1549 1550 1551
      tee_fprintf(PAGER, "\n");
      end_pager();
    }
    else
    {
unknown's avatar
unknown committed
1552 1553
      put_info("\nNothing found", INFO_INFO);
      put_info("Please try to run 'help contents' for list of all accessible topics\n", INFO_INFO);
unknown's avatar
unknown committed
1554 1555 1556
    }
  }

1557
err:
unknown's avatar
unknown committed
1558 1559 1560 1561
  mysql_free_result(result);
  return error;
}

unknown's avatar
unknown committed
1562
static int
1563 1564
com_help(String *buffer __attribute__((unused)),
	 char *line __attribute__((unused)))
unknown's avatar
unknown committed
1565 1566
{
  reg1 int i;
unknown's avatar
unknown committed
1567
  char * help_arg= strchr(line,' ');
unknown's avatar
unknown committed
1568

unknown's avatar
unknown committed
1569
  if (help_arg)
unknown's avatar
unknown committed
1570
  {
unknown's avatar
unknown committed
1571
    return com_server_help(buffer,line,help_arg+1);
unknown's avatar
unknown committed
1572
  }
unknown's avatar
unknown committed
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587
  else
  {
    put_info("\nFor the complete MySQL Manual online visit:\n   http://www.mysql.com/documentation\n", INFO_INFO);
    put_info("For info on technical support from MySQL developers visit:\n   http://www.mysql.com/support\n", INFO_INFO);
    put_info("For info on MySQL books, utilities, consultants, etc. visit:\n   http://www.mysql.com/portal\n", INFO_INFO);
    put_info("List of all MySQL commands:", INFO_INFO);
    if (!named_cmds)
      put_info("Note that all text commands must be first on line and end with ';'",INFO_INFO);
    for (i = 0; commands[i].name; i++)
    {
      if (commands[i].func)
        tee_fprintf(stdout, "%s\t(\\%c)\t%s\n", commands[i].name,
		    commands[i].cmd_char, commands[i].doc);
    }
  }
1588 1589
  if (connected && mysql_get_server_version(&mysql) >= 40100)
    put_info("\nFor server side help, type 'help all'\n", INFO_INFO);
unknown's avatar
unknown committed
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
  return 0;
}


	/* ARGSUSED */
static int
com_clear(String *buffer,char *line __attribute__((unused)))
{
  buffer->length(0);
  return 0;
}


/*
1604 1605 1606 1607
  Execute command
  Returns: 0  if ok
          -1 if not fatal error
	  1  if fatal error
unknown's avatar
unknown committed
1608 1609 1610 1611 1612 1613
*/


static int
com_go(String *buffer,char *line __attribute__((unused)))
{
1614
  char		buff[200], time_buff[32], *pos;
unknown's avatar
unknown committed
1615
  MYSQL_RES	*result;
1616
  ulong		timer, warnings;
unknown's avatar
unknown committed
1617 1618 1619 1620 1621 1622 1623 1624
  uint		error=0;

  if (!status.batch)
  {
    old_buffer= *buffer;			// Save for edit command
    old_buffer.copy();
  }

1625
  /* Remove garbage for nicer messages */
unknown's avatar
unknown committed
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
  LINT_INIT(buff[0]);
  remove_cntrl(*buffer);

  if (buffer->is_empty())
  {
    if (status.batch)				// Ignore empty quries
      return 0;
    return put_info("No query specified\n",INFO_ERROR);

  }
  if (!connected && reconnect())
  {
    buffer->length(0);				// Remove query on error
1639
    return opt_reconnect ? -1 : 1;          // Fatal error
unknown's avatar
unknown committed
1640 1641 1642 1643 1644
  }
  if (verbose)
    (void) com_print(buffer,0);

  if (skip_updates &&
1645
      (buffer->length() < 4 || my_strnncoll(charset_info,
unknown's avatar
unknown committed
1646 1647
					    (const uchar*)buffer->ptr(),4,
					    (const uchar*)"SET ",4)))
unknown's avatar
unknown committed
1648 1649 1650 1651 1652 1653
  {
    (void) put_info("Ignoring query to other database",INFO_INFO);
    return 0;
  }

  timer=start_timer();
unknown's avatar
unknown committed
1654 1655 1656

  error= mysql_real_query_for_lazy(buffer->ptr(),buffer->length());
  if (error)
unknown's avatar
unknown committed
1657
  {
unknown's avatar
unknown committed
1658 1659
    buffer->length(0); // Remove query on error
    return error;
unknown's avatar
unknown committed
1660
  }
unknown's avatar
unknown committed
1661

unknown's avatar
unknown committed
1662 1663 1664 1665 1666 1667
  error=0;
  buffer->length(0);

  if (quick)
  {
    if (!(result=mysql_use_result(&mysql)) && mysql_field_count(&mysql))
1668
      return put_error(&mysql);
unknown's avatar
unknown committed
1669 1670 1671
  }
  else
  {
unknown's avatar
unknown committed
1672 1673 1674
    error= mysql_store_result_for_lazy(&result);
    if (error)
      return error;
unknown's avatar
unknown committed
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
  }

  if (verbose >= 3 || !opt_silent)
    mysql_end_timer(timer,time_buff);
  else
    time_buff[0]=0;
  if (result)
  {
    if (!mysql_num_rows(result) && ! quick)
    {
1685
      strmov(buff, "Empty set");
unknown's avatar
unknown committed
1686 1687 1688
    }
    else
    {
unknown's avatar
unknown committed
1689
      init_pager();
unknown's avatar
unknown committed
1690 1691
      if (opt_html)
	print_table_data_html(result);
1692 1693
      else if (opt_xml)
	print_table_data_xml(result);
unknown's avatar
unknown committed
1694 1695 1696 1697 1698 1699
      else if (vertical)
	print_table_data_vertically(result);
      else if (opt_silent && verbose <= 2 && !output_tables)
	print_tab_data(result);
      else
	print_table_data(result);
1700
      sprintf(buff,"%ld %s in set",
unknown's avatar
unknown committed
1701
	      (long) mysql_num_rows(result),
1702
	      (long) mysql_num_rows(result) == 1 ? "row" : "rows");
unknown's avatar
unknown committed
1703
      end_pager();
unknown's avatar
unknown committed
1704 1705 1706
    }
  }
  else if (mysql_affected_rows(&mysql) == ~(ulonglong) 0)
1707
    strmov(buff,"Query OK");
unknown's avatar
unknown committed
1708
  else
1709
    sprintf(buff,"Query OK, %ld %s affected",
unknown's avatar
unknown committed
1710
	    (long) mysql_affected_rows(&mysql),
1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
	    (long) mysql_affected_rows(&mysql) == 1 ? "row" : "rows");

  pos=strend(buff);
  if ((warnings= mysql_warning_count(&mysql)))
  {
    *pos++= ',';
    *pos++= ' ';
    pos=int2str(warnings, pos, 10);
    pos=strmov(pos, " warning");
    if (warnings != 1)
      *pos++= 's';
  }
  strmov(pos, time_buff);
unknown's avatar
unknown committed
1724 1725 1726 1727 1728 1729
  put_info(buff,INFO_RESULT);
  if (mysql_info(&mysql))
    put_info(mysql_info(&mysql),INFO_RESULT);
  put_info("",INFO_RESULT);			// Empty row

  if (result && !mysql_eof(result))	/* Something wrong when using quick */
1730
    error= put_error(&mysql);
unknown's avatar
unknown committed
1731 1732 1733 1734 1735 1736
  else if (unbuffered)
    fflush(stdout);
  mysql_free_result(result);
  return error;				/* New command follows */
}

unknown's avatar
unknown committed
1737 1738 1739

static void init_pager()
{
unknown's avatar
unknown committed
1740
#ifdef USE_POPEN
unknown's avatar
unknown committed
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
  if (!opt_nopager)
  {
    if (!(PAGER= popen(pager, "w")))
    {
      tee_fprintf(stdout, "popen() failed! defaulting PAGER to stdout!\n");
      PAGER= stdout;
    }
  }
  else
#endif
    PAGER= stdout;
}

static void end_pager()
{
unknown's avatar
unknown committed
1756
#ifdef USE_POPEN
unknown's avatar
unknown committed
1757 1758 1759 1760 1761
  if (!opt_nopager)
    pclose(PAGER);
#endif
}

1762

unknown's avatar
unknown committed
1763
static void init_tee(const char *file_name)
unknown's avatar
unknown committed
1764
{
1765
  FILE* new_outfile;
unknown's avatar
unknown committed
1766
  if (opt_outfile)
1767
    end_tee();
unknown's avatar
unknown committed
1768 1769 1770 1771 1772
  if (!(new_outfile= my_fopen(file_name, O_APPEND | O_WRONLY, MYF(MY_WME))))
  {
    tee_fprintf(stdout, "Error logging to file '%s'\n", file_name);
    return;
  }
1773
  OUTFILE = new_outfile;
unknown's avatar
unknown committed
1774 1775 1776 1777
  strmake(outfile, file_name, FN_REFLEN-1);
  tee_fprintf(stdout, "Logging to file '%s'\n", file_name);
  opt_outfile= 1;
  return;
unknown's avatar
unknown committed
1778 1779
}

1780

unknown's avatar
unknown committed
1781 1782 1783
static void end_tee()
{
  my_fclose(OUTFILE, MYF(0));
unknown's avatar
unknown committed
1784
  OUTFILE= 0;
unknown's avatar
unknown committed
1785
  opt_outfile= 0;
unknown's avatar
unknown committed
1786 1787 1788
  return;
}

unknown's avatar
unknown committed
1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
static int
com_ego(String *buffer,char *line)
{
  int result;
  bool oldvertical=vertical;
  vertical=1;
  result=com_go(buffer,line);
  vertical=oldvertical;
  return result;
}

unknown's avatar
unknown committed
1800 1801 1802 1803 1804 1805
static void
print_field_types(MYSQL_RES *result)
{
  MYSQL_FIELD	*field;  
  while ((field = mysql_fetch_field(result)))
  {
unknown's avatar
unknown committed
1806 1807
    tee_fprintf(PAGER,"'%s.%s.%s.%s' %d %d %d %d %d\n",
		field->catalog, field->db, field->table, field->name,
unknown's avatar
unknown committed
1808 1809 1810 1811 1812 1813 1814
		(int) field->type,
		field->length, field->max_length, 
		field->flags, field->decimals);
  }
  tee_puts("", PAGER);
}

unknown's avatar
unknown committed
1815 1816 1817 1818 1819 1820 1821 1822 1823 1824

static void
print_table_data(MYSQL_RES *result)
{
  String separator(256);
  MYSQL_ROW	cur;
  MYSQL_FIELD	*field;
  bool		*num_flag;

  num_flag=(bool*) my_alloca(sizeof(bool)*mysql_num_fields(result));
unknown's avatar
unknown committed
1825 1826 1827 1828 1829
  if (info_flag)
  {
    print_field_types(result);
    mysql_field_seek(result,0);
  }
1830
  separator.copy("+",1,charset_info);
unknown's avatar
unknown committed
1831 1832
  while ((field = mysql_fetch_field(result)))
  {
1833
    uint length= column_names ? field->name_length : 0;
unknown's avatar
unknown committed
1834 1835 1836 1837 1838 1839 1840 1841 1842 1843
    if (quick)
      length=max(length,field->length);
    else
      length=max(length,field->max_length);
    if (length < 4 && !IS_NOT_NULL(field->flags))
      length=4;					// Room for "NULL"
    field->max_length=length+1;
    separator.fill(separator.length()+length+2,'-');
    separator.append('+');
  }
unknown's avatar
unknown committed
1844
  tee_puts(separator.c_ptr(), PAGER);
1845
  if (column_names)
unknown's avatar
unknown committed
1846 1847
  {
    mysql_field_seek(result,0);
unknown's avatar
unknown committed
1848
    (void) tee_fputs("|", PAGER);
unknown's avatar
unknown committed
1849 1850
    for (uint off=0; (field = mysql_fetch_field(result)) ; off++)
    {
unknown's avatar
unknown committed
1851 1852
      tee_fprintf(PAGER, " %-*s|",min(field->max_length,MAX_COLUMN_LENGTH),
		  field->name);
unknown's avatar
unknown committed
1853 1854
      num_flag[off]= IS_NUM(field->type);
    }
unknown's avatar
unknown committed
1855 1856
    (void) tee_fputs("\n", PAGER);
    tee_puts(separator.c_ptr(), PAGER);
unknown's avatar
unknown committed
1857 1858
  }

unknown's avatar
unknown committed
1859
  while ((cur= mysql_fetch_row(result)))
unknown's avatar
unknown committed
1860
  {
unknown's avatar
unknown committed
1861
    (void) tee_fputs("|", PAGER);
unknown's avatar
unknown committed
1862 1863
    mysql_field_seek(result, 0);
    for (uint off= 0; off < mysql_num_fields(result); off++)
unknown's avatar
unknown committed
1864
    {
unknown's avatar
unknown committed
1865 1866 1867
      const char *str= cur[off] ? cur[off] : "NULL";
      field= mysql_fetch_field(result);
      uint length= field->max_length;
unknown's avatar
unknown committed
1868 1869
      if (length > MAX_COLUMN_LENGTH)
      {
unknown's avatar
unknown committed
1870 1871
	tee_fputs(str, PAGER);
	tee_fputs(" |", PAGER);
unknown's avatar
unknown committed
1872 1873
      }
      else
unknown's avatar
unknown committed
1874
      tee_fprintf(PAGER, num_flag[off] ? "%*s |" : " %-*s|",
unknown's avatar
unknown committed
1875
		  length, str);
unknown's avatar
unknown committed
1876
    }
unknown's avatar
unknown committed
1877
    (void) tee_fputs("\n", PAGER);
unknown's avatar
unknown committed
1878
  }
unknown's avatar
unknown committed
1879
  tee_puts(separator.c_ptr(), PAGER);
unknown's avatar
unknown committed
1880 1881 1882
  my_afree((gptr) num_flag);
}

unknown's avatar
unknown committed
1883

unknown's avatar
unknown committed
1884 1885 1886
static void
print_table_data_html(MYSQL_RES *result)
{
unknown's avatar
unknown committed
1887 1888
  MYSQL_ROW	cur;
  MYSQL_FIELD	*field;
unknown's avatar
unknown committed
1889 1890

  mysql_field_seek(result,0);
unknown's avatar
unknown committed
1891
  (void) tee_fputs("<TABLE BORDER=1><TR>", PAGER);
1892
  if (column_names)
unknown's avatar
unknown committed
1893 1894 1895
  {
    while((field = mysql_fetch_field(result)))
    {
unknown's avatar
unknown committed
1896 1897 1898
      tee_fprintf(PAGER, "<TH>%s</TH>", (field->name ? 
					 (field->name[0] ? field->name : 
					  " &nbsp; ") : "NULL"));
unknown's avatar
unknown committed
1899
    }
unknown's avatar
unknown committed
1900
    (void) tee_fputs("</TR>", PAGER);
unknown's avatar
unknown committed
1901 1902 1903
  }
  while ((cur = mysql_fetch_row(result)))
  {
unknown's avatar
unknown committed
1904
    (void) tee_fputs("<TR>", PAGER);
unknown's avatar
unknown committed
1905 1906 1907
    for (uint i=0; i < mysql_num_fields(result); i++)
    {
      ulong *lengths=mysql_fetch_lengths(result);
unknown's avatar
unknown committed
1908
      (void) tee_fputs("<TD>", PAGER);
unknown's avatar
unknown committed
1909
      safe_put_field(cur[i],lengths[i]);
unknown's avatar
unknown committed
1910
      (void) tee_fputs("</TD>", PAGER);
unknown's avatar
unknown committed
1911
    }
unknown's avatar
unknown committed
1912
    (void) tee_fputs("</TR>", PAGER);
unknown's avatar
unknown committed
1913
  }
unknown's avatar
unknown committed
1914
  (void) tee_fputs("</TABLE>", PAGER);
unknown's avatar
unknown committed
1915 1916 1917
}


1918 1919 1920 1921 1922 1923 1924 1925
static void
print_table_data_xml(MYSQL_RES *result)
{
  MYSQL_ROW   cur;
  MYSQL_FIELD *fields;

  mysql_field_seek(result,0);

unknown's avatar
unknown committed
1926
  tee_fputs("<?xml version=\"1.0\"?>\n\n<resultset statement=\"", PAGER);
unknown's avatar
merge  
unknown committed
1927
  xmlencode_print(glob_buffer.ptr(), strlen(glob_buffer.ptr()));
unknown's avatar
unknown committed
1928
  tee_fputs("\">", PAGER);
1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939

  fields = mysql_fetch_fields(result);
  while ((cur = mysql_fetch_row(result)))
  {
    (void) tee_fputs("\n  <row>\n", PAGER);
    for (uint i=0; i < mysql_num_fields(result); i++)
    {
      ulong *lengths=mysql_fetch_lengths(result);
      tee_fprintf(PAGER, "\t<%s>", (fields[i].name ?
				  (fields[i].name[0] ? fields[i].name :
				   " &nbsp; ") : "NULL"));
unknown's avatar
unknown committed
1940
      xmlencode_print(cur[i], lengths[i]);
1941 1942 1943 1944 1945 1946 1947 1948 1949
      tee_fprintf(PAGER, "</%s>\n", (fields[i].name ?
				     (fields[i].name[0] ? fields[i].name :
				      " &nbsp; ") : "NULL"));
    }
    (void) tee_fputs("  </row>\n", PAGER);
  }
  (void) tee_fputs("</resultset>\n", PAGER);
}

unknown's avatar
unknown committed
1950 1951 1952 1953 1954 1955 1956 1957 1958 1959

static void
print_table_data_vertically(MYSQL_RES *result)
{
  MYSQL_ROW	cur;
  uint		max_length=0;
  MYSQL_FIELD	*field;

  while ((field = mysql_fetch_field(result)))
  {
1960
    uint length= field->name_length;
unknown's avatar
unknown committed
1961 1962 1963 1964 1965 1966 1967 1968 1969
    if (length > max_length)
      max_length= length;
    field->max_length=length;
  }

  mysql_field_seek(result,0);
  for (uint row_count=1; (cur= mysql_fetch_row(result)); row_count++)
  {
    mysql_field_seek(result,0);
unknown's avatar
unknown committed
1970 1971
    tee_fprintf(PAGER, 
		"*************************** %d. row ***************************\n", row_count);
unknown's avatar
unknown committed
1972 1973 1974
    for (uint off=0; off < mysql_num_fields(result); off++)
    {
      field= mysql_fetch_field(result);
unknown's avatar
unknown committed
1975 1976
      tee_fprintf(PAGER, "%*s: ",(int) max_length,field->name);
      tee_fprintf(PAGER, "%s\n",cur[off] ? (char*) cur[off] : "NULL");
unknown's avatar
unknown committed
1977 1978 1979 1980
    }
  }
}

unknown's avatar
unknown committed
1981

unknown's avatar
unknown committed
1982
static const char
unknown's avatar
unknown committed
1983 1984
*array_value(const char **array, char key)
{
1985
  int x;
unknown's avatar
unknown committed
1986 1987 1988
  for (x= 0; array[x]; x+= 2)
    if (*array[x] == key)
      return array[x + 1];
1989 1990 1991
  return 0;
}

unknown's avatar
unknown committed
1992

unknown's avatar
unknown committed
1993
static void
unknown's avatar
unknown committed
1994
xmlencode_print(const char *src, uint length)
unknown's avatar
unknown committed
1995
{
unknown's avatar
unknown committed
1996 1997 1998
  if (!src)
    tee_fputs("NULL", PAGER);
  else
unknown's avatar
unknown committed
1999
  {
unknown's avatar
unknown committed
2000 2001 2002 2003 2004 2005 2006 2007 2008
    for (const char *p = src; *p && length; *p++, length--)
    {
      const char *t;
      if ((t = array_value(xmlmeta, *p)))
	tee_fputs(t, PAGER);
      else
	tee_putc(*p, PAGER);
    }
  }
2009
}
unknown's avatar
unknown committed
2010

unknown's avatar
unknown committed
2011 2012 2013 2014 2015

static void
safe_put_field(const char *pos,ulong length)
{
  if (!pos)
unknown's avatar
unknown committed
2016
    tee_fputs("NULL", PAGER);
unknown's avatar
unknown committed
2017 2018 2019
  else
  {
    if (opt_raw_data)
unknown's avatar
unknown committed
2020
      tee_fputs(pos, PAGER);
unknown's avatar
unknown committed
2021 2022 2023 2024
    else for (const char *end=pos+length ; pos != end ; pos++)
    {
#ifdef USE_MB
      int l;
2025 2026
      if (use_mb(charset_info) &&
          (l = my_ismbchar(charset_info, pos, end)))
unknown's avatar
unknown committed
2027
      {
unknown's avatar
unknown committed
2028
	  while (l--)
2029
	    tee_putc(*pos++, PAGER);
unknown's avatar
unknown committed
2030 2031 2032 2033 2034
	  pos--;
	  continue;
      }
#endif
      if (!*pos)
unknown's avatar
unknown committed
2035
	tee_fputs("\\0", PAGER); // This makes everything hard
unknown's avatar
unknown committed
2036
      else if (*pos == '\t')
unknown's avatar
unknown committed
2037
	tee_fputs("\\t", PAGER); // This would destroy tab format
unknown's avatar
unknown committed
2038
      else if (*pos == '\n')
unknown's avatar
unknown committed
2039
	tee_fputs("\\n", PAGER); // This too
unknown's avatar
unknown committed
2040
      else if (*pos == '\\')
unknown's avatar
unknown committed
2041
	tee_fputs("\\\\", PAGER);
2042
	else
2043
	tee_putc(*pos, PAGER);
unknown's avatar
unknown committed
2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055
    }
  }
}


static void
print_tab_data(MYSQL_RES *result)
{
  MYSQL_ROW	cur;
  MYSQL_FIELD	*field;
  ulong		*lengths;

2056
  if (opt_silent < 2 && column_names)
unknown's avatar
unknown committed
2057 2058 2059 2060 2061
  {
    int first=0;
    while ((field = mysql_fetch_field(result)))
    {
      if (first++)
unknown's avatar
unknown committed
2062 2063
	(void) tee_fputs("\t", PAGER);
      (void) tee_fputs(field->name, PAGER);
unknown's avatar
unknown committed
2064
    }
unknown's avatar
unknown committed
2065
    (void) tee_fputs("\n", PAGER);
unknown's avatar
unknown committed
2066 2067 2068 2069 2070 2071 2072
  }
  while ((cur = mysql_fetch_row(result)))
  {
    lengths=mysql_fetch_lengths(result);
    safe_put_field(cur[0],lengths[0]);
    for (uint off=1 ; off < mysql_num_fields(result); off++)
    {
unknown's avatar
unknown committed
2073
      (void) tee_fputs("\t", PAGER);
unknown's avatar
unknown committed
2074
      safe_put_field(cur[off], lengths[off]);
unknown's avatar
unknown committed
2075
    }
unknown's avatar
unknown committed
2076
    (void) tee_fputs("\n", PAGER);
unknown's avatar
unknown committed
2077 2078 2079
  }
}

unknown's avatar
unknown committed
2080 2081 2082 2083 2084 2085 2086
static int
com_tee(String *buffer, char *line __attribute__((unused)))
{
  char file_name[FN_REFLEN], *end, *param;

  if (status.batch)
    return 0;
2087
  while (my_isspace(charset_info,*line))
unknown's avatar
unknown committed
2088 2089 2090 2091 2092
    line++;
  if (!(param = strchr(line, ' '))) // if outfile wasn't given, use the default
  {
    if (!strlen(outfile))
    {
unknown's avatar
unknown committed
2093
      printf("No previous outfile available, you must give a filename!\n");
unknown's avatar
unknown committed
2094 2095
      return 0;
    }
2096 2097 2098 2099 2100 2101 2102
    else if (opt_outfile)
    {
      tee_fprintf(stdout, "Currently logging to file '%s'\n", outfile);
      return 0;
    }
    else
      param = outfile;			//resume using the old outfile
unknown's avatar
unknown committed
2103
  }
2104 2105

  /* eliminate the spaces before the parameters */
2106
  while (my_isspace(charset_info,*param))
2107 2108 2109
    param++;
  end= strmake(file_name, param, sizeof(file_name) - 1);
  /* remove end space from command line */
2110 2111
  while (end > file_name && (my_isspace(charset_info,end[-1]) || 
			     my_iscntrl(charset_info,end[-1])))
2112 2113
    end--;
  end[0]= 0;
unknown's avatar
unknown committed
2114
  if (end == file_name)
unknown's avatar
unknown committed
2115 2116 2117 2118
  {
    printf("No outfile specified!\n");
    return 0;
  }
unknown's avatar
unknown committed
2119
  init_tee(file_name);
unknown's avatar
unknown committed
2120 2121 2122
  return 0;
}

2123

unknown's avatar
unknown committed
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133
static int
com_notee(String *buffer __attribute__((unused)),
	  char *line __attribute__((unused)))
{
  if (opt_outfile)
    end_tee();
  tee_fprintf(stdout, "Outfile disabled.\n");
  return 0;
}

2134
/*
2135
  Sorry, this command is not available in Windows.
2136 2137
*/

unknown's avatar
unknown committed
2138
#ifdef USE_POPEN
unknown's avatar
unknown committed
2139 2140 2141 2142 2143 2144 2145 2146
static int
com_pager(String *buffer, char *line __attribute__((unused)))
{
  char pager_name[FN_REFLEN], *end, *param;

  if (status.batch)
    return 0;
  /* Skip space from file name */
2147
  while (my_isspace(charset_info,*line))
unknown's avatar
unknown committed
2148
    line++;
unknown's avatar
unknown committed
2149
  if (!(param= strchr(line, ' '))) // if pager was not given, use the default
unknown's avatar
unknown committed
2150
  {
unknown's avatar
unknown committed
2151
    if (!default_pager[0])
unknown's avatar
unknown committed
2152
    {
unknown's avatar
unknown committed
2153
      tee_fprintf(stdout, "Default pager wasn't set, using stdout.\n");
unknown's avatar
unknown committed
2154 2155 2156 2157 2158 2159 2160 2161 2162
      opt_nopager=1;
      strmov(pager, "stdout");
      PAGER= stdout;
      return 0;
    }
    strmov(pager, default_pager);
  }
  else
  {
2163
    while (my_isspace(charset_info,*param))
unknown's avatar
unknown committed
2164 2165
      param++;
    end=strmake(pager_name, param, sizeof(pager_name)-1);
2166 2167
    while (end > pager_name && (my_isspace(charset_info,end[-1]) || 
                                my_iscntrl(charset_info,end[-1])))
unknown's avatar
unknown committed
2168 2169 2170
      end--;
    end[0]=0;
    strmov(pager, pager_name);
2171
    strmov(default_pager, pager_name);
unknown's avatar
unknown committed
2172 2173 2174 2175 2176 2177
  }
  opt_nopager=0;
  tee_fprintf(stdout, "PAGER set to %s\n", pager);
  return 0;
}

2178

unknown's avatar
unknown committed
2179 2180 2181 2182 2183 2184 2185 2186 2187
static int
com_nopager(String *buffer __attribute__((unused)),
	    char *line __attribute__((unused)))
{
  strmov(pager, "stdout");
  opt_nopager=1;
  tee_fprintf(stdout, "PAGER set to stdout\n");
  return 0;
}
2188
#endif
unknown's avatar
unknown committed
2189

unknown's avatar
unknown committed
2190

2191
/*
2192
  Sorry, you can't send the result to an editor in Win32
2193 2194
*/

unknown's avatar
unknown committed
2195
#ifdef USE_POPEN
unknown's avatar
unknown committed
2196 2197 2198
static int
com_edit(String *buffer,char *line __attribute__((unused)))
{
2199
  char	filename[FN_REFLEN],buff[160];
unknown's avatar
unknown committed
2200 2201 2202
  int	fd,tmp;
  const char *editor;

2203 2204
  if ((fd=create_temp_file(filename,NullS,"sql", O_CREAT | O_WRONLY,
			   MYF(MY_WME))) < 0)
unknown's avatar
unknown committed
2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233
    goto err;
  if (buffer->is_empty() && !old_buffer.is_empty())
    (void) my_write(fd,(byte*) old_buffer.ptr(),old_buffer.length(),
		    MYF(MY_WME));
  else
    (void) my_write(fd,(byte*) buffer->ptr(),buffer->length(),MYF(MY_WME));
  (void) my_close(fd,MYF(0));

  if (!(editor = (char *)getenv("EDITOR")) &&
      !(editor = (char *)getenv("VISUAL")))
    editor = "vi";
  strxmov(buff,editor," ",filename,NullS);
  (void) system(buff);

  MY_STAT stat_arg;
  if (!my_stat(filename,&stat_arg,MYF(MY_WME)))
    goto err;
  if ((fd = my_open(filename,O_RDONLY, MYF(MY_WME))) < 0)
    goto err;
  (void) buffer->alloc((uint) stat_arg.st_size);
  if ((tmp=read(fd,(char*) buffer->ptr(),buffer->alloced_length())) >= 0L)
    buffer->length((uint) tmp);
  else
    buffer->length(0);
  (void) my_close(fd,MYF(0));
  (void) my_delete(filename,MYF(MY_WME));
err:
  return 0;
}
2234 2235
#endif

unknown's avatar
unknown committed
2236 2237 2238 2239 2240 2241 2242

/* If arg is given, exit without errors. This happens on command 'quit' */

static int
com_quit(String *buffer __attribute__((unused)),
	 char *line __attribute__((unused)))
{
unknown's avatar
unknown committed
2243 2244 2245 2246
#ifdef __NETWARE__
  // let the screen auto close on a normal shutdown
  setscreenmode(SCR_AUTOCLOSE_ON_EXIT);
#endif
unknown's avatar
unknown committed
2247 2248 2249 2250 2251 2252 2253 2254 2255
  status.exit_status=0;
  return 1;
}

static int
com_rehash(String *buffer __attribute__((unused)),
	 char *line __attribute__((unused)))
{
#ifdef HAVE_READLINE
unknown's avatar
unknown committed
2256
  build_completion_hash(1, 0);
unknown's avatar
unknown committed
2257 2258 2259 2260
#endif
  return 0;
}

2261

unknown's avatar
unknown committed
2262
#ifdef USE_POPEN
2263 2264 2265 2266 2267 2268 2269 2270 2271
static int
com_shell(String *buffer, char *line __attribute__((unused)))
{
  char *shell_cmd;
  if (!(shell_cmd = strchr(line, ' ')))
  {
    put_info("Usage: \\! shell-command", INFO_ERROR);
    return -1;
  }
2272 2273 2274 2275 2276
  /*
    The output of the shell command does not
    get directed to the pager or the outfile
  */
  if (system(shell_cmd) == -1)
2277 2278 2279 2280 2281 2282 2283 2284 2285
  {
    put_info(strerror(errno), INFO_ERROR, errno);
    return -1;
  }
  return 0;
}
#endif


unknown's avatar
unknown committed
2286 2287 2288
static int
com_print(String *buffer,char *line __attribute__((unused)))
{
unknown's avatar
unknown committed
2289 2290
  tee_puts("--------------", stdout);
  (void) tee_fputs(buffer->c_ptr(), stdout);
unknown's avatar
unknown committed
2291
  if (!buffer->length() || (*buffer)[buffer->length()-1] != '\n')
2292
    tee_putc('\n', stdout);
unknown's avatar
unknown committed
2293
  tee_puts("--------------\n", stdout);
unknown's avatar
unknown committed
2294 2295 2296 2297 2298 2299 2300
  return 0;					/* If empty buffer */
}

	/* ARGSUSED */
static int
com_connect(String *buffer, char *line)
{
2301
  char *tmp, buff[256];
unknown's avatar
unknown committed
2302
  bool save_rehash= rehash;
unknown's avatar
unknown committed
2303 2304
  int error;

2305
  bzero(buff, sizeof(buff));
unknown's avatar
unknown committed
2306 2307
  if (buffer)
  {
2308 2309 2310
    strmov(buff, line);
    tmp= get_arg(buff, 0);
    if (tmp && *tmp)
unknown's avatar
unknown committed
2311
    {
2312 2313 2314 2315
      my_free(current_db, MYF(MY_ALLOW_ZERO_PTR));
      current_db= my_strdup(tmp, MYF(MY_WME));
      tmp= get_arg(buff, 1);
      if (tmp)
unknown's avatar
unknown committed
2316 2317 2318 2319 2320 2321
      {
	my_free(current_host,MYF(MY_ALLOW_ZERO_PTR));
	current_host=my_strdup(tmp,MYF(MY_WME));
      }
    }
    else
unknown's avatar
unknown committed
2322
      rehash= 0;				// Quick re-connect
unknown's avatar
unknown committed
2323 2324 2325
    buffer->length(0);				// command used
  }
  else
unknown's avatar
unknown committed
2326
    rehash= 0;
unknown's avatar
unknown committed
2327
  error=sql_connect(current_host,current_db,current_user,opt_password,0);
unknown's avatar
unknown committed
2328
  rehash= save_rehash;
unknown's avatar
unknown committed
2329 2330 2331 2332 2333 2334

  if (connected)
  {
    sprintf(buff,"Connection id:    %ld",mysql_thread_id(&mysql));
    put_info(buff,INFO_INFO);
    sprintf(buff,"Current database: %s\n",
unknown's avatar
unknown committed
2335
	    current_db ? current_db : "*** NONE ***");
unknown's avatar
unknown committed
2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
    put_info(buff,INFO_INFO);
  }
  return error;
}


static int com_source(String *buffer, char *line)
{
  char source_name[FN_REFLEN], *end, *param;
  LINE_BUFFER *line_buff;
  int error;
  STATUS old_status;
  FILE *sql_file;

  /* Skip space from file name */
2351
  while (my_isspace(charset_info,*line))
unknown's avatar
unknown committed
2352
    line++;
unknown's avatar
unknown committed
2353 2354 2355
  if (!(param = strchr(line, ' ')))		// Skip command name
    return put_info("Usage: \\. <filename> | source <filename>", 
		    INFO_ERROR, 0);
2356
  while (my_isspace(charset_info,*param))
unknown's avatar
unknown committed
2357 2358
    param++;
  end=strmake(source_name,param,sizeof(source_name)-1);
2359 2360
  while (end > source_name && (my_isspace(charset_info,end[-1]) || 
                               my_iscntrl(charset_info,end[-1])))
unknown's avatar
unknown committed
2361 2362
    end--;
  end[0]=0;
unknown's avatar
unknown committed
2363
  unpack_filename(source_name,source_name);
unknown's avatar
unknown committed
2364
  /* open file name */
unknown's avatar
unknown committed
2365
  if (!(sql_file = my_fopen(source_name, O_RDONLY | O_BINARY,MYF(0))))
unknown's avatar
unknown committed
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393
  {
    char buff[FN_REFLEN+60];
    sprintf(buff,"Failed to open file '%s', error: %d", source_name,errno);
    return put_info(buff, INFO_ERROR, 0);
  }

  if (!(line_buff=batch_readline_init(max_allowed_packet+512,sql_file)))
  {
    my_fclose(sql_file,MYF(0));
    return put_info("Can't initialize batch_readline", INFO_ERROR, 0);
  }

  /* Save old status */
  old_status=status;
  bfill((char*) &status,sizeof(status),(char) 0);

  status.batch=old_status.batch;		// Run in batch mode
  status.line_buff=line_buff;
  status.file_name=source_name;
  glob_buffer.length(0);			// Empty command buffer
  error=read_lines(0);				// Read lines from file
  status=old_status;				// Continue as before
  my_fclose(sql_file,MYF(0));
  batch_readline_end(line_buff);
  return error;
}


unknown's avatar
unknown committed
2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413
	/* ARGSUSED */
static int
com_delimiter(String *buffer __attribute__((unused)), char *line)
{
  char buff[256], *tmp;

  strmake(buff, line, sizeof(buff) - 1);
  tmp= get_arg(buff, 0);

  if (!tmp || !*tmp)
  {
    put_info("DELIMITER must be followed by a 'delimiter' character or string",
	     INFO_ERROR);
    return 0;
  }
  strmake(delimiter, tmp, sizeof(delimiter) - 1);
  delimiter_length= strlen(delimiter);
  return 0;
}

unknown's avatar
unknown committed
2414 2415 2416 2417 2418 2419 2420
	/* ARGSUSED */
static int
com_use(String *buffer __attribute__((unused)), char *line)
{
  char *tmp;
  char buff[256];

2421
  bzero(buff, sizeof(buff));
2422
  strmov(buff, line);
2423
  tmp= get_arg(buff, 0);
2424
  if (!tmp || !*tmp)
unknown's avatar
unknown committed
2425
  {
2426
    put_info("USE must be followed by a database name", INFO_ERROR);
unknown's avatar
unknown committed
2427 2428
    return 0;
  }
2429
  if (!current_db || cmp_database(charset_info, current_db, tmp))
unknown's avatar
unknown committed
2430 2431
  {
    if (one_database)
2432
      skip_updates= 1;
unknown's avatar
unknown committed
2433 2434 2435 2436 2437 2438 2439
    else
    {
      /*
	reconnect once if connection is down or if connection was found to
	be down during query
      */
      if (!connected && reconnect())
2440
      return opt_reconnect ? -1 : 1;                        // Fatal error
unknown's avatar
unknown committed
2441 2442 2443
      if (mysql_select_db(&mysql,tmp))
      {
	if (mysql_errno(&mysql) != CR_SERVER_GONE_ERROR)
2444
	  return put_error(&mysql);
unknown's avatar
unknown committed
2445 2446

	if (reconnect())
2447
        return opt_reconnect ? -1 : 1;                      // Fatal error
unknown's avatar
unknown committed
2448
	if (mysql_select_db(&mysql,tmp))
2449
	  return put_error(&mysql);
unknown's avatar
unknown committed
2450
      }
unknown's avatar
unknown committed
2451 2452
      my_free(current_db,MYF(MY_ALLOW_ZERO_PTR));
      current_db=my_strdup(tmp,MYF(MY_WME));
unknown's avatar
unknown committed
2453
#ifdef HAVE_READLINE
unknown's avatar
unknown committed
2454
      build_completion_hash(rehash, 1);
unknown's avatar
unknown committed
2455 2456 2457 2458
#endif
    }
  }
  else
2459
    skip_updates= 0;
unknown's avatar
unknown committed
2460 2461 2462 2463 2464
  put_info("Database changed",INFO_INFO);
  return 0;
}


2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475
/*
  Gets argument from a command on the command line. If get_next_arg is
  not defined, skips the command and returns the first argument. The
  line is modified by adding zero to the end of the argument. If
  get_next_arg is defined, then the function searches for end of string
  first, after found, returns the next argument and adds zero to the
  end. If you ever wish to use this feature, remember to initialize all
  items in the array to zero first.
*/

char *get_arg(char *line, my_bool get_next_arg)
2476
{
unknown's avatar
unknown committed
2477
  char *ptr, *start;
2478
  my_bool quoted= 0, valid_arg= 0;
2479
  char qtype= 0;
2480 2481

  ptr= line;
2482 2483
  if (get_next_arg)
  {
unknown's avatar
unknown committed
2484 2485
    for (; *ptr; ptr++) ;
    if (*(ptr + 1))
2486 2487 2488 2489 2490
      ptr++;
  }
  else
  {
    /* skip leading white spaces */
2491
    while (my_isspace(charset_info, *ptr))
2492 2493 2494
      ptr++;
    if (*ptr == '\\') // short command was used
      ptr+= 2;
2495
    while (*ptr &&!my_isspace(charset_info, *ptr)) // skip command
2496 2497
      ptr++;
  }
2498 2499
  if (!*ptr)
    return NullS;
2500
  while (my_isspace(charset_info, *ptr))
2501
    ptr++;
2502
  if (*ptr == '\'' || *ptr == '\"' || *ptr == '`')
2503
  {
2504
    qtype= *ptr;
2505 2506 2507
    quoted= 1;
    ptr++;
  }
unknown's avatar
unknown committed
2508
  for (start=ptr ; *ptr; ptr++)
2509
  {
unknown's avatar
unknown committed
2510
    if (*ptr == '\\' && ptr[1]) // escaped character
2511
    {
unknown's avatar
unknown committed
2512 2513
      // Remove the backslash
      strmov(ptr, ptr+1);
2514
    }
2515
    else if ((!quoted && *ptr == ' ') || (quoted && *ptr == qtype))
2516 2517 2518 2519 2520
    {
      *ptr= 0;
      break;
    }
  }
unknown's avatar
unknown committed
2521 2522
  valid_arg= ptr != start;
  return valid_arg ? start : NullS;
2523 2524 2525
}


unknown's avatar
unknown committed
2526 2527 2528 2529
static int
sql_real_connect(char *host,char *database,char *user,char *password,
		 uint silent)
{
2530 2531
  mysql_close(&mysql);
  connected= 0;
unknown's avatar
unknown committed
2532
  mysql_init(&mysql);
unknown's avatar
unknown committed
2533
  if (opt_connect_timeout)
2534 2535
  {
    uint timeout=opt_connect_timeout;
unknown's avatar
unknown committed
2536
    mysql_options(&mysql,MYSQL_OPT_CONNECT_TIMEOUT,
2537 2538
		  (char*) &timeout);
  }
unknown's avatar
unknown committed
2539 2540
  if (opt_compress)
    mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);
unknown's avatar
merge  
unknown committed
2541 2542
  if (using_opt_local_infile)
    mysql_options(&mysql,MYSQL_OPT_LOCAL_INFILE, (char*) &opt_local_infile);
unknown's avatar
unknown committed
2543 2544 2545
#ifdef HAVE_OPENSSL
  if (opt_use_ssl)
    mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
2546
		  opt_ssl_capath, opt_ssl_cipher);
2547 2548 2549 2550 2551 2552
#endif
  if (opt_protocol)
    mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
#ifdef HAVE_SMEM
  if (shared_memory_base_name)
    mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
unknown's avatar
unknown committed
2553 2554 2555 2556 2557 2558 2559 2560 2561
#endif
  if (safe_updates)
  {
    char init_command[100];
    sprintf(init_command,
	    "SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=%lu,SQL_MAX_JOIN_SIZE=%lu",
	    select_limit,max_join_size);
    mysql_options(&mysql, MYSQL_INIT_COMMAND, init_command);
  }
2562
  mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset);
2563 2564
  if (!mysql_real_connect(&mysql, host, user, password,
			  database, opt_mysql_port, opt_mysql_unix_port,
unknown's avatar
unknown committed
2565
			  connect_flag | CLIENT_MULTI_QUERIES))
unknown's avatar
unknown committed
2566 2567 2568 2569 2570
  {
    if (!silent ||
	(mysql_errno(&mysql) != CR_CONN_HOST_ERROR &&
	 mysql_errno(&mysql) != CR_CONNECTION_ERROR))
    {
2571
      (void) put_error(&mysql);
unknown's avatar
unknown committed
2572 2573 2574 2575 2576 2577
      (void) fflush(stdout);
      return ignore_errors ? -1 : 1;		// Abort
    }
    return -1;					// Retryable
  }
  connected=1;
2578
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
2579
  mysql.reconnect=info_flag ? 1 : 0; // We want to know if this happens
2580
#endif
unknown's avatar
unknown committed
2581
#ifdef HAVE_READLINE
unknown's avatar
unknown committed
2582
  build_completion_hash(rehash, 1);
unknown's avatar
unknown committed
2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599
#endif
  return 0;
}


static int
sql_connect(char *host,char *database,char *user,char *password,uint silent)
{
  bool message=0;
  uint count=0;
  int error;
  for (;;)
  {
    if ((error=sql_real_connect(host,database,user,password,wait_flag)) >= 0)
    {
      if (count)
      {
unknown's avatar
unknown committed
2600
	tee_fputs("\n", stderr);
unknown's avatar
unknown committed
2601 2602 2603 2604 2605 2606 2607 2608 2609
	(void) fflush(stderr);
      }
      return error;
    }
    if (!wait_flag)
      return ignore_errors ? -1 : 1;
    if (!message && !silent)
    {
      message=1;
unknown's avatar
unknown committed
2610
      tee_fputs("Waiting",stderr); (void) fflush(stderr);
unknown's avatar
unknown committed
2611
    }
unknown's avatar
unknown committed
2612
    (void) sleep(wait_time);
unknown's avatar
unknown committed
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626
    if (!silent)
    {
      putc('.',stderr); (void) fflush(stderr);
      count++;
    }
  }
}



static int
com_status(String *buffer __attribute__((unused)),
	   char *line __attribute__((unused)))
{
unknown's avatar
merge  
unknown committed
2627
  const char *status;
unknown's avatar
unknown committed
2628
  tee_puts("--------------", stdout);
unknown's avatar
unknown committed
2629 2630 2631 2632 2633
  usage(1);					/* Print version */
  if (connected)
  {
    MYSQL_RES *result;
    LINT_INIT(result);
unknown's avatar
unknown committed
2634
    tee_fprintf(stdout, "\nConnection id:\t\t%ld\n",mysql_thread_id(&mysql));
unknown's avatar
unknown committed
2635 2636 2637 2638
    if (!mysql_query(&mysql,"select DATABASE(),USER()") &&
	(result=mysql_use_result(&mysql)))
    {
      MYSQL_ROW cur=mysql_fetch_row(result);
unknown's avatar
unknown committed
2639 2640
      tee_fprintf(stdout, "Current database:\t%s\n",cur[0]);
      tee_fprintf(stdout, "Current user:\t\t%s\n",cur[1]);
unknown's avatar
unknown committed
2641 2642
      (void) mysql_fetch_row(result);		// Read eof
    }
2643 2644
#ifdef HAVE_OPENSSL
    if (mysql.net.vio->ssl_ && SSL_get_cipher(mysql.net.vio->ssl_))
unknown's avatar
unknown committed
2645
      tee_fprintf(stdout, "SSL:\t\t\tCipher in use is %s\n",
2646 2647 2648
		  SSL_get_cipher(mysql.net.vio->ssl_));
    else
#endif /* HAVE_OPENSSL */
unknown's avatar
unknown committed
2649
      tee_puts("SSL:\t\t\tNot in use", stdout);
unknown's avatar
unknown committed
2650 2651 2652 2653
  }
  else
  {
    vidattr(A_BOLD);
unknown's avatar
unknown committed
2654
    tee_fprintf(stdout, "\nNo connection\n");
unknown's avatar
unknown committed
2655 2656 2657 2658 2659 2660
    vidattr(A_NORMAL);
    return 0;
  }
  if (skip_updates)
  {
    vidattr(A_BOLD);
unknown's avatar
unknown committed
2661
    tee_fprintf(stdout, "\nAll updates ignored to this database\n");
unknown's avatar
unknown committed
2662 2663
    vidattr(A_NORMAL);
  }
unknown's avatar
unknown committed
2664
#ifdef USE_POPEN
unknown's avatar
unknown committed
2665
  tee_fprintf(stdout, "Current pager:\t\t%s\n", pager);
2666
  tee_fprintf(stdout, "Using outfile:\t\t'%s'\n", opt_outfile ? outfile : "");
unknown's avatar
unknown committed
2667
#endif
unknown's avatar
unknown committed
2668
  tee_fprintf(stdout, "Using delimiter:\t%s\n", delimiter);
unknown's avatar
unknown committed
2669 2670 2671
  tee_fprintf(stdout, "Server version:\t\t%s\n", mysql_get_server_info(&mysql));
  tee_fprintf(stdout, "Protocol version:\t%d\n", mysql_get_proto_info(&mysql));
  tee_fprintf(stdout, "Connection:\t\t%s\n", mysql_get_host_info(&mysql));
unknown's avatar
unknown committed
2672
  tee_fprintf(stdout, "Client characterset:\t%s\n",
2673
	      charset_info->name);
unknown's avatar
unknown committed
2674
  tee_fprintf(stdout, "Server characterset:\t%s\n", mysql.charset->name);
2675
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
2676
  if (strstr(mysql_get_host_info(&mysql),"TCP/IP") || ! mysql.unix_socket)
unknown's avatar
unknown committed
2677
    tee_fprintf(stdout, "TCP port:\t\t%d\n", mysql.port);
unknown's avatar
unknown committed
2678
  else
unknown's avatar
unknown committed
2679
    tee_fprintf(stdout, "UNIX socket:\t\t%s\n", mysql.unix_socket);
2680 2681
  if (mysql.net.compress)
    tee_fprintf(stdout, "Protocol:\t\tCompressed\n");
2682
#endif
2683

unknown's avatar
unknown committed
2684 2685 2686
  if ((status=mysql_stat(&mysql)) && !mysql_error(&mysql)[0])
  {
    ulong sec;
unknown's avatar
unknown committed
2687 2688 2689 2690
    char buff[40];
    const char *pos= strchr(status,' ');
    /* print label */
    tee_fprintf(stdout, "%.*s\t\t\t", (int) (pos-status), status);
unknown's avatar
unknown committed
2691 2692 2693
    if ((status=str2int(pos,10,0,LONG_MAX,(long*) &sec)))
    {
      nice_time((double) sec,buff,0);
unknown's avatar
unknown committed
2694
      tee_puts(buff, stdout);			/* print nice time */
unknown's avatar
unknown committed
2695 2696 2697 2698
      while (*status == ' ') status++;		/* to next info */
    }
    if (status)
    {
2699
      tee_putc('\n', stdout);
unknown's avatar
unknown committed
2700
      tee_puts(status, stdout);
unknown's avatar
unknown committed
2701 2702 2703 2704 2705
    }
  }
  if (safe_updates)
  {
    vidattr(A_BOLD);
unknown's avatar
unknown committed
2706
    tee_fprintf(stdout, "\nNote that you are running in safe_update_mode:\n");
unknown's avatar
unknown committed
2707
    vidattr(A_NORMAL);
unknown's avatar
unknown committed
2708
    tee_fprintf(stdout, "\
unknown's avatar
unknown committed
2709 2710 2711
UPDATEs and DELETEs that don't use a key in the WHERE clause are not allowed.\n\
(One can force an UPDATE/DELETE by adding LIMIT # at the end of the command.)\n\
SELECT has an automatic 'LIMIT %lu' if LIMIT is not used.\n\
unknown's avatar
unknown committed
2712
Max number of examined row combination in a join is set to: %lu\n\n",
unknown's avatar
unknown committed
2713
select_limit, max_join_size);
unknown's avatar
unknown committed
2714
  }
unknown's avatar
unknown committed
2715
  tee_puts("--------------\n", stdout);
unknown's avatar
unknown committed
2716 2717 2718 2719 2720
  return 0;
}


static int
2721
put_info(const char *str,INFO_TYPE info_type, uint error, const char *sqlstate)
unknown's avatar
unknown committed
2722
{
2723
  FILE *file= (info_type == INFO_ERROR ? stderr : stdout);
unknown's avatar
unknown committed
2724
  static int inited=0;
unknown's avatar
unknown committed
2725

unknown's avatar
unknown committed
2726 2727 2728 2729
  if (status.batch)
  {
    if (info_type == INFO_ERROR)
    {
2730 2731
      (void) fflush(file);
      fprintf(file,"ERROR");
unknown's avatar
unknown committed
2732
      if (error)
2733
	(void) fprintf(file," %d",error);
2734
      if (status.query_start_line && line_numbers)
unknown's avatar
unknown committed
2735
      {
2736
	(void) fprintf(file," at line %lu",status.query_start_line);
unknown's avatar
unknown committed
2737
	if (status.file_name)
2738
	  (void) fprintf(file," in file: '%s'", status.file_name);
unknown's avatar
unknown committed
2739
      }
2740 2741
      (void) fprintf(file,": %s\n",str);
      (void) fflush(file);
unknown's avatar
unknown committed
2742 2743 2744 2745
      if (!ignore_errors)
	return 1;
    }
    else if (info_type == INFO_RESULT && verbose > 1)
2746
      tee_puts(str, file);
unknown's avatar
unknown committed
2747
    if (unbuffered)
2748
      fflush(file);
unknown's avatar
unknown committed
2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761
    return info_type == INFO_ERROR ? -1 : 0;
  }
  if (!opt_silent || info_type == INFO_ERROR)
  {
    if (!inited)
    {
      inited=1;
#ifdef HAVE_SETUPTERM
      (void) setupterm((char *)0, 1, (int *) 0);
#endif
    }
    if (info_type == INFO_ERROR)
    {
2762
      if (!opt_nobeep)
unknown's avatar
merge  
unknown committed
2763
	putchar('\007');		      	/* This should make a bell */
unknown's avatar
unknown committed
2764 2765
      vidattr(A_STANDOUT);
      if (error)
2766 2767 2768 2769 2770 2771
      {
	if (sqlstate)
          (void) tee_fprintf(file, "ERROR %d (%s): ", error, sqlstate);
        else
          (void) tee_fprintf(file, "ERROR %d: ", error);
      }
unknown's avatar
unknown committed
2772
      else
2773
        tee_puts("ERROR: ", file);
unknown's avatar
unknown committed
2774 2775 2776
    }
    else
      vidattr(A_BOLD);
2777
    (void) tee_puts(str, file);
unknown's avatar
unknown committed
2778 2779 2780
    vidattr(A_NORMAL);
  }
  if (unbuffered)
2781
    fflush(file);
unknown's avatar
unknown committed
2782 2783 2784
  return info_type == INFO_ERROR ? -1 : 0;
}

unknown's avatar
unknown committed
2785

2786 2787 2788 2789 2790 2791 2792 2793
static int
put_error(MYSQL *mysql)
{
  return put_info(mysql_error(mysql), INFO_ERROR, mysql_errno(mysql),
		  mysql_sqlstate(mysql));
}  


unknown's avatar
unknown committed
2794 2795 2796 2797
static void remove_cntrl(String &buffer)
{
  char *start,*end;
  end=(start=(char*) buffer.ptr())+buffer.length();
2798
  while (start < end && !my_isgraph(charset_info,end[-1]))
unknown's avatar
unknown committed
2799 2800 2801 2802 2803
    end--;
  buffer.length((uint) (end-start));
}


unknown's avatar
unknown committed
2804 2805 2806 2807 2808
void tee_fprintf(FILE *file, const char *fmt, ...)
{
  va_list args;

  va_start(args, fmt);
unknown's avatar
unknown committed
2809
  (void) vfprintf(file, fmt, args);
unknown's avatar
unknown committed
2810 2811 2812
#ifdef OS2
  fflush( file);
#endif
unknown's avatar
unknown committed
2813
  if (opt_outfile)
unknown's avatar
unknown committed
2814
    (void) vfprintf(OUTFILE, fmt, args);
unknown's avatar
unknown committed
2815 2816 2817 2818 2819 2820 2821
  va_end(args);
}


void tee_fputs(const char *s, FILE *file)
{
  fputs(s, file);
unknown's avatar
unknown committed
2822 2823 2824
#ifdef OS2
  fflush( file);
#endif
unknown's avatar
unknown committed
2825 2826 2827 2828 2829 2830 2831 2832 2833
  if (opt_outfile)
    fputs(s, OUTFILE);
}


void tee_puts(const char *s, FILE *file)
{
  fputs(s, file);
  fputs("\n", file);
unknown's avatar
unknown committed
2834 2835 2836
#ifdef OS2
  fflush( file);
#endif
unknown's avatar
unknown committed
2837 2838 2839 2840 2841 2842 2843
  if (opt_outfile)
  {
    fputs(s, OUTFILE);
    fputs("\n", OUTFILE);
  }
}

2844 2845 2846
void tee_putc(int c, FILE *file)
{
  putc(c, file);
unknown's avatar
unknown committed
2847 2848 2849
#ifdef OS2
  fflush( file);
#endif
2850 2851 2852 2853
  if (opt_outfile)
    putc(c, OUTFILE);
}

unknown's avatar
unknown committed
2854
#if defined( __WIN__) || defined( OS2) || defined(__NETWARE__)
unknown's avatar
unknown committed
2855 2856 2857
#include <time.h>
#else
#include <sys/times.h>
2858
#ifdef _SC_CLK_TCK				// For mit-pthreads
unknown's avatar
unknown committed
2859 2860 2861
#undef CLOCKS_PER_SEC
#define CLOCKS_PER_SEC (sysconf(_SC_CLK_TCK))
#endif
2862
#endif
unknown's avatar
unknown committed
2863 2864 2865

static ulong start_timer(void)
{
unknown's avatar
unknown committed
2866
#if defined( __WIN__) || defined( OS2) || defined(__NETWARE__)
unknown's avatar
unknown committed
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920
 return clock();
#else
  struct tms tms_tmp;
  return times(&tms_tmp);
#endif
}


static void nice_time(double sec,char *buff,bool part_second)
{
  ulong tmp;
  if (sec >= 3600.0*24)
  {
    tmp=(ulong) floor(sec/(3600.0*24));
    sec-=3600.0*24*tmp;
    buff=int2str((long) tmp,buff,10);
    buff=strmov(buff,tmp > 1 ? " days " : " day ");
  }
  if (sec >= 3600.0)
  {
    tmp=(ulong) floor(sec/3600.0);
    sec-=3600.0*tmp;
    buff=int2str((long) tmp,buff,10);
    buff=strmov(buff,tmp > 1 ? " hours " : " hour ");
  }
  if (sec >= 60.0)
  {
    tmp=(ulong) floor(sec/60.0);
    sec-=60.0*tmp;
    buff=int2str((long) tmp,buff,10);
    buff=strmov(buff," min ");
  }
  if (part_second)
    sprintf(buff,"%.2f sec",sec);
  else
    sprintf(buff,"%d sec",(int) sec);
}


static void end_timer(ulong start_time,char *buff)
{
  nice_time((double) (start_timer() - start_time) /
	    CLOCKS_PER_SEC,buff,1);
}


static void mysql_end_timer(ulong start_time,char *buff)
{
  buff[0]=' ';
  buff[1]='(';
  end_timer(start_time,buff+2);
  strmov(strend(buff),")");
}

2921 2922
static const char* construct_prompt()
{
unknown's avatar
merge  
unknown committed
2923 2924 2925 2926 2927 2928
  //erase the old prompt
  processed_prompt.free();
  //get the date struct
  time_t  lclock = time(NULL);
  struct tm *t = localtime(&lclock);
  //parse thru the settings for the prompt
2929 2930 2931
  for (char *c = current_prompt; *c ; *c++)
  {
    if (*c != PROMPT_CHAR)
unknown's avatar
merge  
unknown committed
2932
	processed_prompt.append(*c);
2933 2934
    else
    {
unknown's avatar
merge  
unknown committed
2935 2936 2937 2938 2939 2940 2941 2942 2943
      switch (*++c) {
      case '\0':
	//stop it from going beyond if ends with %
	c--;
	break;
      case 'c':
	add_int_to_prompt(++prompt_counter);
	break;
      case 'v':
2944 2945 2946 2947
	if (connected)
	  processed_prompt.append(mysql_get_server_info(&mysql));
	else
	  processed_prompt.append("not_connected");
unknown's avatar
merge  
unknown committed
2948 2949 2950 2951 2952 2953
	break;
      case 'd':
	processed_prompt.append(current_db ? current_db : "(none)");
	break;
      case 'h':
      {
2954 2955
	const char *prompt;
	prompt= connected ? mysql_get_host_info(&mysql) : "not_connected";
unknown's avatar
merge  
unknown committed
2956 2957 2958 2959 2960 2961 2962 2963 2964 2965
	if (strstr(prompt, "Localhost"))
	  processed_prompt.append("localhost");
	else
	{
	  const char *end=strcend(prompt,' ');
	  processed_prompt.append(prompt, (uint) (end-prompt));
	}
	break;
      }
      case 'p':
2966
#ifndef EMBEDDED_LIBRARY
2967 2968 2969 2970 2971
	if (!connected)
	{
	  processed_prompt.append("not_connected");
	  break;
	}
unknown's avatar
merge  
unknown committed
2972
	if (strstr(mysql_get_host_info(&mysql),"TCP/IP") ||
unknown's avatar
unknown committed
2973
	    !mysql.unix_socket)
unknown's avatar
merge  
unknown committed
2974 2975
	  add_int_to_prompt(mysql.port);
	else
2976 2977
	{
	  char *pos=strrchr(mysql.unix_socket,'/');
unknown's avatar
unknown committed
2978
 	  processed_prompt.append(pos ? pos+1 : mysql.unix_socket);
2979
	}
2980
#endif
unknown's avatar
merge  
unknown committed
2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069
	break;
      case 'U':
	if (!full_username)
	  init_username();
	processed_prompt.append(full_username);
	break;
      case 'u':
	if (!full_username)
	  init_username();
	processed_prompt.append(part_username);
	break;
      case PROMPT_CHAR:
	processed_prompt.append(PROMPT_CHAR);
	break;
      case 'n':
	processed_prompt.append('\n');
	break;
      case ' ':
      case '_':
	processed_prompt.append(' ');
	break;
      case 'R':
	add_int_to_prompt(t->tm_hour);
	break;
      case 'r':
	int getHour;
	getHour = t->tm_hour % 12;
	if (getHour == 0)
	  getHour=12;
	add_int_to_prompt(getHour);
	break;
      case 'm':
	if (t->tm_min < 10)
	  processed_prompt.append('0');
	add_int_to_prompt(t->tm_min);
	break;
      case 'y':
	int getYear;
	getYear = t->tm_year % 100;
	if (getYear < 10)
	  processed_prompt.append('0');
	add_int_to_prompt(getYear);
	break;
      case 'Y':
	add_int_to_prompt(t->tm_year+1900);
	break;
      case 'D':
	char* dateTime;
	time_t lclock;
	lclock = time(NULL);
	dateTime = ctime(&lclock);
	processed_prompt.append(strtok(dateTime,"\n"));
	break;
      case 's':
	add_int_to_prompt(t->tm_sec);
	break;
      case 'w':
	processed_prompt.append(day_names[t->tm_wday]);
	break;
      case 'P':
	processed_prompt.append(t->tm_hour < 12 ? "am" : "pm");
	break;
      case 'o':
	add_int_to_prompt(t->tm_mon+1);
	break;
      case 'O':
	processed_prompt.append(month_names[t->tm_mon]);
	break;
      case '\'':
	processed_prompt.append("'");
	break;
      case '"':
	processed_prompt.append('"');
	break;
      case 'S':
	processed_prompt.append(';');
	break;
      case 't':
	processed_prompt.append('\t');
	break;
      default:
	processed_prompt.append(c);
      }
    }
  }
  processed_prompt.append('\0');
  return processed_prompt.ptr();
}

3070 3071 3072

static void add_int_to_prompt(int toadd)
{
unknown's avatar
merge  
unknown committed
3073 3074 3075 3076 3077
  char buffer[16];
  int10_to_str(toadd,buffer,10);
  processed_prompt.append(buffer);
}

3078 3079
static void init_username()
{
unknown's avatar
merge  
unknown committed
3080 3081 3082 3083 3084 3085 3086
  my_free(full_username,MYF(MY_ALLOW_ZERO_PTR));
  my_free(part_username,MYF(MY_ALLOW_ZERO_PTR));

  MYSQL_RES *result;
  LINT_INIT(result);
  if (!mysql_query(&mysql,"select USER()") &&
      (result=mysql_use_result(&mysql)))
3087 3088 3089 3090 3091 3092
  {
    MYSQL_ROW cur=mysql_fetch_row(result);
    full_username=my_strdup(cur[0],MYF(MY_WME));
    part_username=my_strdup(strtok(cur[0],"@"),MYF(MY_WME));
    (void) mysql_fetch_row(result);		// Read eof
  }
unknown's avatar
merge  
unknown committed
3093 3094
}

3095 3096 3097
static int com_prompt(String *buffer, char *line)
{
  char *ptr=strchr(line, ' ');
unknown's avatar
merge  
unknown committed
3098 3099
  prompt_counter = 0;
  my_free(current_prompt,MYF(MY_ALLOW_ZERO_PTR));
3100 3101
  current_prompt=my_strdup(ptr ? ptr+1 : default_prompt,MYF(MY_WME));
  if (!ptr)
unknown's avatar
merge  
unknown committed
3102 3103 3104 3105 3106 3107
    tee_fprintf(stdout, "Returning to default PROMPT of %s\n", default_prompt);
  else
    tee_fprintf(stdout, "PROMPT set to '%s'\n", current_prompt);
  return 0;
}

3108
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119
/* Keep sql_string library happy */

gptr sql_alloc(unsigned int Size)
{
  return my_malloc(Size,MYF(MY_WME));
}

void sql_element_free(void *ptr)
{
  my_free((gptr) ptr,MYF(0));
}
3120
#endif /* EMBEDDED_LIBRARY */