mysql.cc 109 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
   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
unknown's avatar
unknown committed
5
   the Free Software Foundation; version 2 of the License.
unknown's avatar
unknown committed
6

unknown's avatar
unknown committed
7 8 9 10
   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
11

unknown's avatar
unknown committed
12 13 14 15 16 17 18 19 20
   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
21 22 23 24 25 26
 *   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>
27
 *   Harrison Fisk <harrison@mysql.com>
unknown's avatar
unknown committed
28 29 30
 *
 **/

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

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

46
const char *VER= "14.14";
47

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

51 52 53
/* Buffer to hold 'version' and 'version_comment' */
#define MAX_SERVER_VERSION_LENGTH     128

54 55 56
/* Array of options to pass to libemysqld */
#define MAX_SERVER_ARGS               64

57
void* sql_alloc(unsigned size);	     // Don't use mysqld alloc for these
unknown's avatar
unknown committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71
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
72
#include <asm/termbits.h>		// Standard linux
unknown's avatar
unknown committed
73 74 75 76 77 78 79 80
#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
81
#undef SYSV				// hack to avoid syntax error
unknown's avatar
unknown committed
82 83 84 85 86 87
#ifdef HAVE_TERM_H
#include <term.h>
#endif
#endif
#endif

unknown's avatar
unknown committed
88
#undef bcmp				// Fix problem with new readline
89
#if defined( __WIN__)
unknown's avatar
unknown committed
90
#include <conio.h>
unknown's avatar
unknown committed
91
#elif !defined(__NETWARE__)
unknown's avatar
unknown committed
92 93 94 95 96 97 98 99
#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
100
#define vidattr(A) {}			// Can't get this to work
unknown's avatar
unknown committed
101 102
#endif

103
#ifdef FN_NO_CASE_SENCE
104
#define cmp_database(cs,A,B) my_strcasecmp((cs), (A), (B))
unknown's avatar
unknown committed
105
#else
106
#define cmp_database(cs,A,B) strcmp((A),(B))
unknown's avatar
unknown committed
107 108
#endif

109
#if !defined( __WIN__) && !defined(__NETWARE__) && !defined(THREAD)
unknown's avatar
unknown committed
110 111 112
#define USE_POPEN
#endif

unknown's avatar
unknown committed
113 114
#include "completion_hash.h"

unknown's avatar
merge  
unknown committed
115
#define PROMPT_CHAR '\\'
unknown's avatar
unknown committed
116
#define DEFAULT_DELIMITER ";"
unknown's avatar
merge  
unknown committed
117

unknown's avatar
unknown committed
118 119 120 121 122 123 124 125 126 127 128
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;
129
static char **defaults_argv;
unknown's avatar
unknown committed
130 131 132 133 134

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

static MYSQL mysql;			/* The connection */
135
static my_bool ignore_errors=0,wait_flag=0,quick=0,
136
               connected=0,opt_raw_data=0,unbuffered=0,output_tables=0,
137
	       opt_rehash=1,skip_updates=0,safe_updates=0,one_database=0,
unknown's avatar
merge  
unknown committed
138
	       opt_compress=0, using_opt_local_infile=0,
139 140
	       vertical=0, line_numbers=1, column_names=1,opt_html=0,
               opt_xml=0,opt_nopager=1, opt_outfile=0, named_cmds= 0,
unknown's avatar
unknown committed
141
	       tty_password= 0, opt_nobeep=0, opt_reconnect=1,
142
	       default_charset_used= 0, opt_secure_auth= 0,
143
               default_pager_set= 0, opt_sigint_ignore= 0,
144
               show_warnings= 0, executing_query= 0, interrupted_query= 0;
145
static my_bool debug_info_flag, debug_check_flag;
146
static my_bool column_types_flag;
147
static ulong opt_max_allowed_packet, opt_net_buffer_length;
unknown's avatar
merge  
unknown committed
148
static uint verbose=0,opt_silent=0,opt_mysql_port=0, opt_local_infile=0;
149
static uint my_end_arg;
150
static char * opt_mysql_unix_port=0;
unknown's avatar
unknown committed
151 152
static int connect_flag=CLIENT_INTERACTIVE;
static char *current_host,*current_db,*current_user=0,*opt_password=0,
unknown's avatar
unknown committed
153
            *current_prompt=0, *delimiter_str= 0,
154
            *default_charset= (char*) MYSQL_DEFAULT_CHARSET_NAME;
unknown's avatar
unknown committed
155
static char *histfile;
156
static char *histfile_tmp;
unknown's avatar
unknown committed
157
static String glob_buffer,old_buffer;
unknown's avatar
merge  
unknown committed
158 159
static String processed_prompt;
static char *full_username=0,*part_username=0,*default_prompt=0;
unknown's avatar
unknown committed
160
static int wait_time = 5;
unknown's avatar
unknown committed
161
static STATUS status;
162
static ulong select_limit,max_join_size,opt_connect_timeout=0;
unknown's avatar
unknown committed
163
static char mysql_charsets_dir[FN_REFLEN+1];
unknown's avatar
unknown committed
164
static const char *xmlmeta[] = {
165 166
  "&", "&amp;",
  "<", "&lt;",
167 168
  ">", "&gt;",
  "\"", "&quot;",
169 170
  0, 0
};
unknown's avatar
merge  
unknown committed
171 172 173 174 175 176 177 178
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
179 180
static char delimiter[16]= DEFAULT_DELIMITER;
static uint delimiter_length= 1;
unknown's avatar
unknown committed
181

182 183 184 185
#ifdef HAVE_SMEM
static char *shared_memory_base_name=0;
#endif
static uint opt_protocol=0;
186
static CHARSET_INFO *charset_info= &my_charset_latin1;
187

unknown's avatar
unknown committed
188 189 190 191
#include "sslopt-vars.h"

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

unknown's avatar
unknown committed
192 193 194
void tee_fprintf(FILE *file, const char *fmt, ...);
void tee_fputs(const char *s, FILE *file);
void tee_puts(const char *s, FILE *file);
195
void tee_putc(int c, FILE *file);
196
static void tee_print_sized_data(const char *, unsigned int, unsigned int, bool);
unknown's avatar
unknown committed
197 198 199 200
/* 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*),
201
	   com_print(String *str,char*),
unknown's avatar
unknown committed
202 203 204
	   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*),
205
	   com_rehash(String *str, char*), com_tee(String *str, char*),
206
           com_notee(String *str, char*), com_charset(String *str,char*),
207 208
           com_prompt(String *str, char*), com_delimiter(String *str, char*),
     com_warnings(String *str, char*), com_nowarnings(String *str, char*);
unknown's avatar
unknown committed
209

unknown's avatar
unknown committed
210
#ifdef USE_POPEN
211
static int com_nopager(String *str, char*), com_pager(String *str, char*),
unknown's avatar
unknown committed
212
           com_edit(String *str,char*), com_shell(String *str, char *);
213 214
#endif

215
static int read_and_execute(bool interactive);
unknown's avatar
unknown committed
216 217
static int sql_connect(char *host,char *database,char *user,char *password,
		       uint silent);
218
static const char *server_version_string(MYSQL *mysql);
219 220 221
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
222
static void safe_put_field(const char *pos,ulong length);
unknown's avatar
unknown committed
223
static void xmlencode_print(const char *src, uint length);
unknown's avatar
unknown committed
224 225
static void init_pager();
static void end_pager();
unknown's avatar
unknown committed
226
static void init_tee(const char *);
unknown's avatar
unknown committed
227
static void end_tee();
unknown's avatar
merge  
unknown committed
228
static const char* construct_prompt();
229
static char *get_arg(char *line, my_bool get_next_arg);
unknown's avatar
merge  
unknown committed
230 231
static void init_username();
static void add_int_to_prompt(int toadd);
unknown's avatar
unknown committed
232 233 234 235 236 237 238 239 240 241 242 243 244

/* 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
245
  { "?",      '?', com_help,   1, "Synonym for `help'." },
unknown's avatar
unknown committed
246
  { "clear",  'c', com_clear,  0, "Clear command."},
unknown's avatar
unknown committed
247
  { "connect",'r', com_connect,1,
unknown's avatar
unknown committed
248
    "Reconnect to the server. Optional arguments are db and host." },
249
  { "delimiter", 'd', com_delimiter,    1,
unknown's avatar
unknown committed
250
    "Set statement delimiter. NOTE: Takes the rest of the line as new delimiter." },
unknown's avatar
unknown committed
251
#ifdef USE_POPEN
unknown's avatar
unknown committed
252
  { "edit",   'e', com_edit,   0, "Edit command with $EDITOR."},
253
#endif
unknown's avatar
unknown committed
254
  { "ego",    'G', com_ego,    0,
unknown's avatar
unknown committed
255 256 257
    "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." },
258
  { "help",   'h', com_help,   1, "Display this help." },
unknown's avatar
unknown committed
259
#ifdef USE_POPEN
unknown's avatar
unknown committed
260 261 262
  { "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
263
#ifdef USE_POPEN
unknown's avatar
unknown committed
264 265 266 267
  { "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
268
  { "prompt", 'R', com_prompt, 1, "Change your mysql prompt."},
unknown's avatar
unknown committed
269 270
  { "quit",   'q', com_quit,   0, "Quit mysql." },
  { "rehash", '#', com_rehash, 0, "Rebuild completion hash." },
unknown's avatar
unknown committed
271
  { "source", '.', com_source, 1,
unknown's avatar
unknown committed
272
    "Execute an SQL script file. Takes a file name as an argument."},
unknown's avatar
unknown committed
273
  { "status", 's', com_status, 0, "Get status information from the server."},
unknown's avatar
unknown committed
274
#ifdef USE_POPEN
275 276
  { "system", '!', com_shell,  1, "Execute a system shell command."},
#endif
unknown's avatar
unknown committed
277 278
  { "tee",    'T', com_tee,    1, 
    "Set outfile [to_outfile]. Append everything into given outfile." },
unknown's avatar
unknown committed
279
  { "use",    'u', com_use,    1,
unknown's avatar
unknown committed
280
    "Use another database. Takes database name as argument." },
281 282
  { "charset",    'C', com_charset,    1,
    "Switch to another charset. Might be needed for processing binlog with multi-byte charsets." },
283
  { "warnings", 'W', com_warnings,  0,
284
    "Show warnings after every statement." },
285
  { "nowarning", 'w', com_nowarnings, 0,
286
    "Don't show warnings after every statement." },
unknown's avatar
unknown committed
287
  /* Get bash-like expansion for some commands */
unknown's avatar
unknown committed
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  { "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
307 308 309
};

static const char *load_default_groups[]= { "mysql","client",0 };
310 311 312 313

static int         embedded_server_arg_count= 0;
static char       *embedded_server_args[MAX_SERVER_ARGS];
static const char *embedded_server_groups[]=
unknown's avatar
unknown committed
314
{ "server", "embedded", "mysql_SERVER", 0 };
unknown's avatar
unknown committed
315 316

#ifdef HAVE_READLINE
317 318 319 320
/*
 HIST_ENTRY is defined for libedit, but not for the real readline
 Need to redefine it for real readline to find it
*/
unknown's avatar
unknown committed
321
#if !defined(HAVE_HIST_ENTRY)
322 323 324 325 326 327
typedef struct _hist_entry {
  const char      *line;
  const char      *data;
} HIST_ENTRY; 
#endif

328 329 330
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);
331 332 333
extern "C" HIST_ENTRY *history_get(int num);
extern "C" int history_length;
static int not_in_history(const char *line);
unknown's avatar
unknown committed
334
static void initialize_readline (char *name);
335
static void fix_history(String *final_command);
unknown's avatar
unknown committed
336 337
#endif

338
static COMMANDS *find_command(char *name,char cmd_name);
339 340
static bool add_line(String &buffer,char *line,char *in_string,
                     bool *ml_comment);
unknown's avatar
unknown committed
341 342 343
static void remove_cntrl(String &buffer);
static void print_table_data(MYSQL_RES *result);
static void print_table_data_html(MYSQL_RES *result);
344
static void print_table_data_xml(MYSQL_RES *result);
unknown's avatar
unknown committed
345 346
static void print_tab_data(MYSQL_RES *result);
static void print_table_data_vertically(MYSQL_RES *result);
347
static void print_warnings(void);
unknown's avatar
unknown committed
348 349 350 351 352
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);
353
static sig_handler handle_sigint(int sig);
unknown's avatar
unknown committed
354 355 356 357 358 359 360 361

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
362 363
  
  delimiter_str= delimiter;
unknown's avatar
merge  
unknown committed
364 365 366 367 368 369
  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
370 371
  outfile[0]=0;			// no (default) outfile
  strmov(pager, "stdout");	// the default, if --pager wasn't given
372 373
  {
    char *tmp=getenv("PAGER");
374 375 376 377 378
    if (tmp && strlen(tmp))
    {
      default_pager_set= 1;
      strmov(default_pager, tmp);
    }
379
  }
unknown's avatar
unknown committed
380 381 382 383 384 385 386 387
  if (!isatty(0) || !isatty(1))
  {
    status.batch=1; opt_silent=1;
    ignore_errors=0;
  }
  else
    status.add_to_history=1;
  status.exit_status=1;
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402

  {
    /* 
     The file descriptor-layer may be out-of-sync with the file-number layer,
     so we make sure that "stdout" is really open.  If its file is closed then
     explicitly close the FD layer. 
    */
    int stdout_fileno_copy;
    stdout_fileno_copy= dup(fileno(stdout)); /* Okay if fileno fails. */
    if (stdout_fileno_copy == -1)
      fclose(stdout);
    else
      close(stdout_fileno_copy);             /* Clean up dup(). */
  }

unknown's avatar
unknown committed
403
  load_defaults("my",load_default_groups,&argc,&argv);
404
  defaults_argv=argv;
405
  if (get_options(argc, (char **) argv))
unknown's avatar
unknown committed
406
  {
407
    free_defaults(defaults_argv);
unknown's avatar
unknown committed
408 409 410 411
    my_end(0);
    exit(1);
  }
  if (status.batch && !status.line_buff &&
412
      !(status.line_buff=batch_readline_init(opt_max_allowed_packet+512,stdin)))
413 414
  {
    free_defaults(defaults_argv);
415
    my_end(0);
unknown's avatar
unknown committed
416
    exit(1);
417
  }
418 419
  if (mysql_server_init(embedded_server_arg_count, embedded_server_args, 
                        (char**) embedded_server_groups))
420 421
  {
    free_defaults(defaults_argv);
422
    my_end(0);
unknown's avatar
unknown committed
423
    exit(1);
424
  }
unknown's avatar
unknown committed
425
  glob_buffer.realloc(512);
426 427
  completion_hash_init(&ht, 128);
  init_alloc_root(&hash_mem_root, 16384, 0);
428
  bzero((char*) &mysql, sizeof(mysql));
unknown's avatar
unknown committed
429 430 431
  if (sql_connect(current_host,current_db,current_user,opt_password,
		  opt_silent))
  {
432 433 434
    quick=1;					// Avoid history
    status.exit_status=1;
    mysql_end(-1);
unknown's avatar
unknown committed
435 436 437
  }
  if (!status.batch)
    ignore_errors=1;				// Don't abort monitor
438 439 440 441

  if (opt_sigint_ignore)
    signal(SIGINT, SIG_IGN);
  else
442
    signal(SIGINT, handle_sigint);              // Catch SIGINT to clean up
unknown's avatar
unknown committed
443
  signal(SIGQUIT, mysql_end);			// Catch SIGQUIT to clean up
unknown's avatar
unknown committed
444 445 446 447

  put_info("Welcome to the MySQL monitor.  Commands end with ; or \\g.",
	   INFO_INFO);
  sprintf((char*) glob_buffer.ptr(),
448 449
	  "Your MySQL connection id is %lu\nServer version: %s\n",
	  mysql_thread_id(&mysql), server_version_string(&mysql));
unknown's avatar
unknown committed
450 451 452
  put_info((char*) glob_buffer.ptr(),INFO_INFO);

#ifdef HAVE_READLINE
453
  initialize_readline((char*) my_progname);
454
  if (!status.batch && !quick && !opt_html && !opt_xml)
unknown's avatar
unknown committed
455
  {
456
    /* read-history from file, default ~/.mysql_history*/
unknown's avatar
unknown committed
457 458 459 460
    if (getenv("MYSQL_HISTFILE"))
      histfile=my_strdup(getenv("MYSQL_HISTFILE"),MYF(MY_WME));
    else if (getenv("HOME"))
    {
unknown's avatar
unknown committed
461 462
      histfile=(char*) my_malloc((uint) strlen(getenv("HOME"))
				 + (uint) strlen("/.mysql_history")+2,
unknown's avatar
unknown committed
463 464 465
				 MYF(MY_WME));
      if (histfile)
	sprintf(histfile,"%s/.mysql_history",getenv("HOME"));
466 467 468 469 470 471 472 473
      char link_name[FN_REFLEN];
      if (my_readlink(link_name, histfile, 0) == 0 &&
          strncmp(link_name, "/dev/null", 10) == 0)
      {
        /* The .mysql_history file is a symlink to /dev/null, don't use it */
        my_free(histfile, MYF(MY_ALLOW_ZERO_PTR));
        histfile= 0;
      }
unknown's avatar
unknown committed
474 475 476 477
    }
    if (histfile)
    {
      if (verbose)
unknown's avatar
unknown committed
478
	tee_fprintf(stdout, "Reading history-file %s\n",histfile);
unknown's avatar
unknown committed
479
      read_history(histfile);
480 481 482 483 484 485 486
      if (!(histfile_tmp= (char*) my_malloc((uint) strlen(histfile) + 5,
					    MYF(MY_WME))))
      {
	fprintf(stderr, "Couldn't allocate memory for temp histfile!\n");
	exit(1);
      }
      sprintf(histfile_tmp, "%s.TMP", histfile);
unknown's avatar
unknown committed
487 488 489
    }
  }
#endif
490
  sprintf(buff, "%s",
491
#ifndef NOT_YET
492
	  "Type 'help;' or '\\h' for help. Type '\\c' to clear the buffer.\n");
493
#else
unknown's avatar
unknown committed
494
	  "Type 'help [[%]function name[%]]' to get help on usage of function.\n");
495
#endif
unknown's avatar
unknown committed
496
  put_info(buff,INFO_INFO);
497
  status.exit_status= read_and_execute(!status.batch);
unknown's avatar
unknown committed
498 499
  if (opt_outfile)
    end_tee();
unknown's avatar
unknown committed
500 501 502 503 504 505 506 507
  mysql_end(0);
#ifndef _lint
  DBUG_RETURN(0);				// Keep compiler happy
#endif
}

sig_handler mysql_end(int sig)
{
508
  mysql_close(&mysql);
unknown's avatar
unknown committed
509
#ifdef HAVE_READLINE
510
  if (!status.batch && !quick && !opt_html && !opt_xml && histfile)
unknown's avatar
unknown committed
511 512 513
  {
    /* write-history */
    if (verbose)
unknown's avatar
unknown committed
514
      tee_fprintf(stdout, "Writing history-file %s\n",histfile);
515 516
    if (!write_history(histfile_tmp))
      my_rename(histfile_tmp, histfile, MYF(MY_WME));
unknown's avatar
unknown committed
517 518 519
  }
  batch_readline_end(status.line_buff);
  completion_hash_free(&ht);
520 521
  free_root(&hash_mem_root,MYF(0));

unknown's avatar
unknown committed
522
#endif
523 524
  if (sig >= 0)
    put_info(sig ? "Aborted" : "Bye", INFO_RESULT);
unknown's avatar
unknown committed
525 526
  glob_buffer.free();
  old_buffer.free();
unknown's avatar
merge  
unknown committed
527
  processed_prompt.free();
unknown's avatar
unknown committed
528 529 530
  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));
531
  my_free(histfile_tmp,MYF(MY_ALLOW_ZERO_PTR));
unknown's avatar
unknown committed
532 533 534
  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
535 536 537
  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));
538 539 540
#ifdef HAVE_SMEM
  my_free(shared_memory_base_name,MYF(MY_ALLOW_ZERO_PTR));
#endif
unknown's avatar
merge  
unknown committed
541
  my_free(current_prompt,MYF(MY_ALLOW_ZERO_PTR));
542 543
  while (embedded_server_arg_count > 1)
    my_free(embedded_server_args[--embedded_server_arg_count],MYF(0));
unknown's avatar
unknown committed
544
  mysql_server_end();
545
  free_defaults(defaults_argv);
546
  my_end(my_end_arg);
unknown's avatar
unknown committed
547 548 549
  exit(status.exit_status);
}

550

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
/*
  This function handles sigint calls
  If query is in process, kill query
  no query in process, terminate like previous behavior
 */
sig_handler handle_sigint(int sig)
{
  char kill_buffer[40];
  MYSQL *kill_mysql= NULL;

  /* terminate if no query being executed, or we already tried interrupting */
  if (!executing_query || interrupted_query)
    mysql_end(sig);

  kill_mysql= mysql_init(kill_mysql);
  if (!mysql_real_connect(kill_mysql,current_host, current_user, opt_password,
                          "", opt_mysql_port, opt_mysql_unix_port,0))
    mysql_end(sig);

  /* kill_buffer is always big enough because max length of %lu is 15 */
  sprintf(kill_buffer, "KILL /*!50000 QUERY */ %lu", mysql_thread_id(&mysql));
  mysql_real_query(kill_mysql, kill_buffer, strlen(kill_buffer));
  mysql_close(kill_mysql);
  tee_fprintf(stdout, "Query aborted by Ctrl+C\n");

  interrupted_query= 1;
}


580
static struct my_option my_long_options[] =
unknown's avatar
unknown committed
581
{
582 583
  {"help", '?', "Display this help and exit.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0,
   0, 0, 0, 0, 0},
584 585
  {"help", 'I', "Synonym for -?", 0, 0, 0, GET_NO_ARG, NO_ARG, 0,
   0, 0, 0, 0, 0},
unknown's avatar
unknown committed
586
#ifdef __NETWARE__
587
  {"autoclose", OPT_AUTO_CLOSE, "Auto close the screen on exit for Netware.",
unknown's avatar
unknown committed
588 589
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
#endif
590 591
  {"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.",
592
   (uchar**) &opt_rehash, (uchar**) &opt_rehash, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0,
593
   0, 0},
594
  {"no-auto-rehash", 'A',
unknown's avatar
unknown committed
595
   "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.",
596 597
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"batch", 'B',
unknown's avatar
unknown committed
598
   "Don't use history file. Disable interactive behavior. (Enables --silent)", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
599
  {"character-sets-dir", OPT_CHARSETS_DIR,
600 601
   "Directory where character sets are.", (uchar**) &charsets_dir,
   (uchar**) &charsets_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
602
  {"column-type-info", OPT_COLUMN_TYPES, "Display column type information.",
603
   (uchar**) &column_types_flag, (uchar**) &column_types_flag,
604
   0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
605
  {"compress", 'C', "Use compression in server/client protocol.",
606
   (uchar**) &opt_compress, (uchar**) &opt_compress, 0, GET_BOOL, NO_ARG, 0, 0, 0,
607
   0, 0, 0},
608

609 610
#ifdef DBUG_OFF
  {"debug", '#', "This is a non-debug version. Catch this and exit",
unknown's avatar
unknown committed
611
   0,0, 0, GET_DISABLED, OPT_ARG, 0, 0, 0, 0, 0, 0},
612
#else
613 614
  {"debug", '#', "Output debug log", (uchar**) &default_dbug_option,
   (uchar**) &default_dbug_option, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
615
#endif
616 617 618 619 620
  {"debug-check", OPT_DEBUG_CHECK, "Check memory and open file usage at exit .",
   (uchar**) &debug_check_flag, (uchar**) &debug_check_flag, 0,
   GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"debug-info", 'T', "Print some debug info at exit.", (uchar**) &debug_info_flag,
   (uchar**) &debug_info_flag, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
621 622
  {"database", 'D', "Database to use.", (uchar**) &current_db,
   (uchar**) &current_db, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
623
  {"default-character-set", OPT_DEFAULT_CHARSET,
624 625 626 627
   "Set the default character set.", (uchar**) &default_charset,
   (uchar**) &default_charset, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"delimiter", OPT_DELIMITER, "Delimiter to be used.", (uchar**) &delimiter_str,
   (uchar**) &delimiter_str, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
628
  {"execute", 'e', "Execute command and quit. (Disables --force and history file)", 0,
629 630
   0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"vertical", 'E', "Print the output of a query (rows) vertically.",
631
   (uchar**) &vertical, (uchar**) &vertical, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0,
632 633
   0},
  {"force", 'f', "Continue even if we get an sql error.",
634
   (uchar**) &ignore_errors, (uchar**) &ignore_errors, 0, GET_BOOL, NO_ARG, 0, 0,
635 636
   0, 0, 0, 0},
  {"named-commands", 'G',
637
   "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.",
638
   (uchar**) &named_cmds, (uchar**) &named_cmds, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
639
   0, 0},
640 641 642
  {"no-named-commands", 'g',
   "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.",
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
643
  {"ignore-spaces", 'i', "Ignore space after function names.", 0, 0, 0,
644
   GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
merge  
unknown committed
645
  {"local-infile", OPT_LOCAL_INFILE, "Enable/disable LOAD DATA LOCAL INFILE.",
646 647 648 649 650 651 652
   (uchar**) &opt_local_infile,
   (uchar**) &opt_local_infile, 0, GET_BOOL, OPT_ARG, 0, 0, 0, 0, 0, 0},
  {"no-beep", 'b', "Turn off beep on error.", (uchar**) &opt_nobeep,
   (uchar**) &opt_nobeep, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0}, 
  {"host", 'h', "Connect to host.", (uchar**) &current_host,
   (uchar**) &current_host, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"html", 'H', "Produce HTML output.", (uchar**) &opt_html, (uchar**) &opt_html,
653
   0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
654
  {"xml", 'X', "Produce XML output", (uchar**) &opt_xml, (uchar**) &opt_xml, 0,
655 656
   GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"line-numbers", OPT_LINE_NUMBERS, "Write line numbers for errors.",
657
   (uchar**) &line_numbers, (uchar**) &line_numbers, 0, GET_BOOL,
658
   NO_ARG, 1, 0, 0, 0, 0, 0},  
unknown's avatar
unknown committed
659
  {"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,
660
   NO_ARG, 0, 0, 0, 0, 0, 0},
661 662
  {"unbuffered", 'n', "Flush buffer after each query.", (uchar**) &unbuffered,
   (uchar**) &unbuffered, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
663
  {"column-names", OPT_COLUMN_NAMES, "Write column names in results.",
664
   (uchar**) &column_names, (uchar**) &column_names, 0, GET_BOOL,
665
   NO_ARG, 1, 0, 0, 0, 0, 0},
666
  {"skip-column-names", 'N',
unknown's avatar
unknown committed
667
   "Don't write column names in results. WARNING: -N is deprecated, use long version of this options instead.",
668 669
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"set-variable", 'O',
unknown's avatar
unknown committed
670
   "Change the value of a variable. Please note that this option is deprecated; you can set variables directly with --variable-name=value.",
671
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
672
  {"sigint-ignore", OPT_SIGINT_IGNORE, "Ignore SIGINT (CTRL-C)",
673
   (uchar**) &opt_sigint_ignore,  (uchar**) &opt_sigint_ignore, 0, GET_BOOL,
674
   NO_ARG, 0, 0, 0, 0, 0, 0},
675 676 677
  {"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
678
#ifdef USE_POPEN
679
  {"pager", OPT_PAGER,
680
   "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. Disable with --disable-pager. This option is disabled by default.",
681
   0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
682 683 684
  {"no-pager", OPT_NOPAGER,
   "Disable pager and print to stdout. See interactive help (\\h) also. WARNING: option deprecated; use --disable-pager instead.",
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
685
#endif
686 687 688
  {"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
689
#ifdef __WIN__
690 691
  {"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
692
#endif
693 694
  {"port", 'P', "Port number to use for connection.", (uchar**) &opt_mysql_port,
   (uchar**) &opt_mysql_port, 0, GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0,
695
   0},
696
  {"prompt", OPT_PROMPT, "Set the mysql prompt to this value.",
697
   (uchar**) &current_prompt, (uchar**) &current_prompt, 0, GET_STR_ALLOC,
698
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
699
  {"protocol", OPT_MYSQL_PROTOCOL, "The protocol of connection (tcp,socket,pipe,memory).",
700
   0, 0, 0, GET_STR,  REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
701
  {"quick", 'q',
702
   "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.",
703
   (uchar**) &quick, (uchar**) &quick, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
704
  {"raw", 'r', "Write fields without conversion. Used with --batch.",
705
   (uchar**) &opt_raw_data, (uchar**) &opt_raw_data, 0, GET_BOOL, NO_ARG, 0, 0, 0,
706
   0, 0, 0},
707
  {"reconnect", OPT_RECONNECT, "Reconnect if the connection is lost. Disable with --disable-reconnect. This option is enabled by default.", 
708
   (uchar**) &opt_reconnect, (uchar**) &opt_reconnect, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
709
  {"silent", 's', "Be more silent. Print results with a tab as separator, each row on new line.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0,
710
   0, 0},
711
#ifdef HAVE_SMEM
712
  {"shared-memory-base-name", OPT_SHARED_MEMORY_BASE_NAME,
713
   "Base name of shared memory.", (uchar**) &shared_memory_base_name, (uchar**) &shared_memory_base_name, 
714 715
   0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#endif
unknown's avatar
unknown committed
716
  {"socket", 'S', "Socket file to use for connection.",
717
   (uchar**) &opt_mysql_unix_port, (uchar**) &opt_mysql_unix_port, 0, GET_STR_ALLOC,
718
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
719
#include "sslopt-longopts.h"
720 721
  {"table", 't', "Output in table format.", (uchar**) &output_tables,
   (uchar**) &output_tables, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
722
  {"tee", OPT_TEE,
723
   "Append everything into outfile. See interactive help (\\h) also. Does not work in batch mode. Disable with --disable-tee. This option is disabled by default.",
724
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
725 726
  {"no-tee", OPT_NOTEE, "Disable outfile. See interactive help (\\h) also. WARNING: option deprecated; use --disable-tee instead", 0, 0, 0, GET_NO_ARG,
   NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
727
#ifndef DONT_ALLOW_USER_CHANGE
728 729
  {"user", 'u', "User for login if not current user.", (uchar**) &current_user,
   (uchar**) &current_user, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
730
#endif
731
  {"safe-updates", 'U', "Only allow UPDATE and DELETE that uses keys.",
732
   (uchar**) &safe_updates, (uchar**) &safe_updates, 0, GET_BOOL, NO_ARG, 0, 0,
733
   0, 0, 0, 0},
734
  {"i-am-a-dummy", 'U', "Synonym for option --safe-updates, -U.",
735
   (uchar**) &safe_updates, (uchar**) &safe_updates, 0, GET_BOOL, NO_ARG, 0, 0,
736
   0, 0, 0, 0},
737
  {"verbose", 'v', "Write more. (-v -v -v gives the table output format).", 0,
738 739 740 741 742
   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},
743 744
  {"connect_timeout", OPT_CONNECT_TIMEOUT,
   "Number of seconds before connection timeout.",
745 746
   (uchar**) &opt_connect_timeout,
   (uchar**) &opt_connect_timeout, 0, GET_ULONG, REQUIRED_ARG, 0, 0, 3600*12, 0,
unknown's avatar
unknown committed
747
   0, 0},
748 749
  {"max_allowed_packet", OPT_MAX_ALLOWED_PACKET,
   "Max packet length to send to, or receive from server",
750
   (uchar**) &opt_max_allowed_packet, (uchar**) &opt_max_allowed_packet, 0, GET_ULONG,
751 752
   REQUIRED_ARG, 16 *1024L*1024L, 4096, (longlong) 2*1024L*1024L*1024L,
   MALLOC_OVERHEAD, 1024, 0},
753 754
  {"net_buffer_length", OPT_NET_BUFFER_LENGTH,
   "Buffer for TCP/IP and socket communication",
755
   (uchar**) &opt_net_buffer_length, (uchar**) &opt_net_buffer_length, 0, GET_ULONG,
756
   REQUIRED_ARG, 16384, 1024, 512*1024*1024L, MALLOC_OVERHEAD, 1024, 0},
757 758
  {"select_limit", OPT_SELECT_LIMIT,
   "Automatic limit for SELECT when using --safe-updates",
759 760
   (uchar**) &select_limit,
   (uchar**) &select_limit, 0, GET_ULONG, REQUIRED_ARG, 1000L, 1, ~0L, 0, 1, 0},
761 762
  {"max_join_size", OPT_MAX_JOIN_SIZE,
   "Automatic limit for rows in a join when using --safe-updates",
763 764
   (uchar**) &max_join_size,
   (uchar**) &max_join_size, 0, GET_ULONG, REQUIRED_ARG, 1000000L, 1, ~0L, 0, 1,
765
   0},
unknown's avatar
unknown committed
766
  {"secure-auth", OPT_SECURE_AUTH, "Refuse client connecting to server if it"
767 768
    " uses old (pre-4.1.1) protocol", (uchar**) &opt_secure_auth,
    (uchar**) &opt_secure_auth, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
769 770
  {"server-arg", OPT_SERVER_ARG, "Send embedded server this as a parameter.",
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
771
  {"show-warnings", OPT_SHOW_WARNINGS, "Show warnings after every statement.",
772
    (uchar**) &show_warnings, (uchar**) &show_warnings, 0, GET_BOOL, NO_ARG, 
773
    0, 0, 0, 0, 0, 0},
774
  { 0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
unknown's avatar
unknown committed
775 776 777 778 779
};


static void usage(int version)
{
unknown's avatar
unknown committed
780 781 782 783
  /* Divert all help information on NetWare to logger screen. */
#ifdef __NETWARE__
#define printf	consoleprintf
#endif
784 785 786 787 788 789 790

#if defined(USE_LIBEDIT_INTERFACE)
  const char* readline= "";
#else
  const char* readline= "readline";
#endif

791
#ifdef HAVE_READLINE
792 793 794
  printf("%s  Ver %s Distrib %s, for %s (%s) using %s %s\n",
	 my_progname, VER, MYSQL_SERVER_VERSION, SYSTEM_TYPE, MACHINE_TYPE,
         readline, rl_library_version);
795
#else
796
  printf("%s  Ver %s Distrib %s, for %s (%s)\n", my_progname, VER,
797 798 799
	MYSQL_SERVER_VERSION, SYSTEM_TYPE, MACHINE_TYPE);
#endif

unknown's avatar
unknown committed
800 801
  if (version)
    return;
unknown's avatar
merge  
unknown committed
802
  printf("\
803
Copyright (C) 2002 MySQL AB\n\
unknown's avatar
merge  
unknown committed
804 805
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
806
  printf("Usage: %s [OPTIONS] [database]\n", my_progname);
807
  my_print_help(my_long_options);
808
  print_defaults("my", load_default_groups);
809
  my_print_variables(my_long_options);
unknown's avatar
unknown committed
810 811 812 813
  NETWARE_SET_SCREEN_MODE(1);
#ifdef __NETWARE__
#undef printf
#endif
unknown's avatar
unknown committed
814 815
}

unknown's avatar
unknown committed
816

817 818 819
static my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
	       char *argument)
unknown's avatar
unknown committed
820
{
821
  switch(optid) {
unknown's avatar
unknown committed
822 823 824 825 826
#ifdef __NETWARE__
  case OPT_AUTO_CLOSE:
    setscreenmode(SCR_AUTOCLOSE_ON_EXIT);
    break;
#endif
unknown's avatar
unknown committed
827
  case OPT_CHARSETS_DIR:
unknown's avatar
unknown committed
828
    strmake(mysql_charsets_dir, argument, sizeof(mysql_charsets_dir) - 1);
unknown's avatar
unknown committed
829 830
    charsets_dir = mysql_charsets_dir;
    break;
unknown's avatar
unknown committed
831 832 833
  case  OPT_DEFAULT_CHARSET:
    default_charset_used= 1;
    break;
unknown's avatar
unknown committed
834
  case OPT_DELIMITER:
835 836
    if (argument == disabled_my_option) 
    {
unknown's avatar
unknown committed
837
      strmov(delimiter, DEFAULT_DELIMITER);
838 839 840 841 842 843 844 845 846 847 848 849 850 851
    }
    else 
    {
      /* Check that delimiter does not contain a backslash */
      if (!strstr(argument, "\\")) 
      {
        strmake(delimiter, argument, sizeof(delimiter) - 1);
      }
      else 
      {
        put_info("DELIMITER cannot contain a backslash character", INFO_ERROR);
        return 0;
      } 
    }
852
    delimiter_length= (uint)strlen(delimiter);
unknown's avatar
unknown committed
853 854
    delimiter_str= delimiter;
    break;
unknown's avatar
unknown committed
855 856 857 858 859 860
  case OPT_LOCAL_INFILE:
    using_opt_local_infile=1;
    break;
  case OPT_TEE:
    if (argument == disabled_my_option)
    {
unknown's avatar
unknown committed
861 862
      if (opt_outfile)
	end_tee();
unknown's avatar
unknown committed
863 864
    }
    else
unknown's avatar
unknown committed
865
      init_tee(argument);
unknown's avatar
unknown committed
866 867
    break;
  case OPT_NOTEE:
unknown's avatar
unknown committed
868
    printf("WARNING: option deprecated; use --disable-tee instead.\n");
unknown's avatar
unknown committed
869 870 871 872
    if (opt_outfile)
      end_tee();
    break;
  case OPT_PAGER:
873 874
    if (argument == disabled_my_option)
      opt_nopager= 1;
unknown's avatar
unknown committed
875
    else
876 877
    {
      opt_nopager= 0;
878 879 880
      if (argument && strlen(argument))
      {
	default_pager_set= 1;
unknown's avatar
unknown committed
881
	strmake(pager, argument, sizeof(pager) - 1);
882 883 884
	strmov(default_pager, pager);
      }
      else if (default_pager_set)
885
	strmov(pager, default_pager);
886 887
      else
	opt_nopager= 1;
888
    }
unknown's avatar
unknown committed
889 890
    break;
  case OPT_NOPAGER:
unknown's avatar
unknown committed
891
    printf("WARNING: option deprecated; use --disable-pager instead.\n");
unknown's avatar
unknown committed
892
    opt_nopager= 1;
893
    break;
894
  case OPT_MYSQL_PROTOCOL:
895 896
    opt_protocol= find_type_or_exit(argument, &sql_protocol_typelib,
                                    opt->name);
897
    break;
898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
  case OPT_SERVER_ARG:
#ifdef EMBEDDED_LIBRARY
    /*
      When the embedded server is being tested, the client needs to be
      able to pass command-line arguments to the embedded server so it can
      locate the language files and data directory.
    */
    if (!embedded_server_arg_count)
    {
      embedded_server_arg_count= 1;
      embedded_server_args[0]= (char*) "";
    }
    if (embedded_server_arg_count == MAX_SERVER_ARGS-1 ||
        !(embedded_server_args[embedded_server_arg_count++]=
          my_strdup(argument, MYF(MY_FAE))))
    {
        put_info("Can't use server argument", INFO_ERROR);
        return 0;
    }
#else /*EMBEDDED_LIBRARY */
    printf("WARNING: --server-arg option not supported in this configuration.\n");
#endif
    break;
unknown's avatar
unknown committed
921
  case 'A':
922
    opt_rehash= 0;
unknown's avatar
unknown committed
923 924 925 926 927 928 929
    break;
  case 'N':
    column_names= 0;
    break;
  case 'e':
    status.batch= 1;
    status.add_to_history= 0;
unknown's avatar
unknown committed
930 931 932
    if (!status.line_buff)
      ignore_errors= 0;                         // do it for the first -e only
    if (!(status.line_buff= batch_readline_command(status.line_buff, argument)))
unknown's avatar
unknown committed
933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
      return 1;
    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 ;
952
      tty_password= 0;
unknown's avatar
unknown committed
953 954 955 956 957 958
    }
    else
      tty_password= 1;
    break;
  case '#':
    DBUG_PUSH(argument ? argument : default_dbug_option);
959
    debug_info_flag= 1;
unknown's avatar
unknown committed
960 961 962 963 964 965 966 967 968 969 970 971 972 973
    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':
unknown's avatar
unknown committed
974 975
    status.batch= 1;
    status.add_to_history= 0;
976
    set_if_bigger(opt_silent,1);                         // more silent
unknown's avatar
unknown committed
977 978
    break;
  case 'W':
unknown's avatar
unknown committed
979
#ifdef __WIN__
980
    opt_protocol = MYSQL_PROTOCOL_PIPE;
unknown's avatar
unknown committed
981
#endif
unknown's avatar
unknown committed
982
    break;
983
#include <sslopt-case.h>
unknown's avatar
unknown committed
984 985 986 987 988 989 990
  case 'V':
    usage(1);
    exit(0);
  case 'I':
  case '?':
    usage(0);
    exit(0);
unknown's avatar
unknown committed
991
  }
992 993 994 995 996 997 998 999
  return 0;
}


static int get_options(int argc, char **argv)
{
  char *tmp, *pagpoint;
  int ho_error;
1000
  MYSQL_PARAMETERS *mysql_params= mysql_get_parameters();
1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015

  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);

1016 1017 1018
  opt_max_allowed_packet= *mysql_params->p_max_allowed_packet;
  opt_net_buffer_length= *mysql_params->p_net_buffer_length;

1019
  if ((ho_error=handle_options(&argc, &argv, my_long_options, get_one_option)))
1020
    exit(ho_error);
1021

1022 1023 1024
  *mysql_params->p_max_allowed_packet= opt_max_allowed_packet;
  *mysql_params->p_net_buffer_length= opt_net_buffer_length;

unknown's avatar
unknown committed
1025 1026 1027 1028
  if (status.batch) /* disable pager and outfile in this case */
  {
    strmov(default_pager, "stdout");
    strmov(pager, "stdout");
1029
    opt_nopager= 1;
1030
    default_pager_set= 0;
1031
    opt_outfile= 0;
1032
    opt_reconnect= 0;
1033
    connect_flag= 0; /* Not in interactive mode */
unknown's avatar
unknown committed
1034
  }
unknown's avatar
unknown committed
1035
  
1036 1037
  if (strcmp(default_charset, charset_info->csname) &&
      !(charset_info= get_charset_by_csname(default_charset, 
1038
					    MY_CS_PRIMARY, MYF(MY_WME))))
1039
    exit(1);
unknown's avatar
unknown committed
1040 1041 1042 1043 1044 1045 1046
  if (argc > 1)
  {
    usage(0);
    exit(1);
  }
  if (argc == 1)
  {
unknown's avatar
unknown committed
1047
    skip_updates= 0;
1048 1049
    my_free(current_db, MYF(MY_ALLOW_ZERO_PTR));
    current_db= my_strdup(*argv, MYF(MY_WME));
unknown's avatar
unknown committed
1050 1051
  }
  if (tty_password)
1052
    opt_password= get_tty_password(NullS);
1053 1054 1055 1056
  if (debug_info_flag)
    my_end_arg= MY_CHECK_ERROR | MY_GIVE_INFO;
  if (debug_check_flag)
    my_end_arg= MY_CHECK_ERROR;
unknown's avatar
unknown committed
1057 1058 1059
  return(0);
}

1060
static int read_and_execute(bool interactive)
unknown's avatar
unknown committed
1061
{
1062
#if defined(__NETWARE__)
unknown's avatar
unknown committed
1063
  char linebuffer[254];
1064
  String buffer;
unknown's avatar
unknown committed
1065
#endif
1066 1067 1068 1069 1070
#if defined(__WIN__)
  String tmpbuf;
  String buffer;
#endif

unknown's avatar
unknown committed
1071 1072 1073
  char	*line;
  char	in_string=0;
  ulong line_number=0;
1074
  bool ml_comment= 0;  
unknown's avatar
unknown committed
1075 1076
  COMMANDS *com;
  status.exit_status=1;
1077
  
unknown's avatar
unknown committed
1078 1079
  for (;;)
  {
1080
    if (!interactive)
unknown's avatar
unknown committed
1081 1082 1083 1084 1085 1086 1087
    {
      line=batch_readline(status.line_buff);
      line_number++;
      if (!glob_buffer.length())
	status.query_start_line=line_number;
    }
    else
unknown's avatar
unknown committed
1088
    {
1089 1090
      char *prompt= (char*) (ml_comment ? "   /*> " :
                             glob_buffer.is_empty() ?  construct_prompt() :
unknown's avatar
unknown committed
1091 1092
			     !in_string ? "    -> " :
			     in_string == '\'' ?
1093 1094 1095
			     "    '> " : (in_string == '`' ?
			     "    `> " :
			     "    \"> "));
1096 1097
      if (opt_outfile && glob_buffer.is_empty())
	fflush(OUTFILE);
unknown's avatar
unknown committed
1098

1099
#if defined( __WIN__) || defined(__NETWARE__)
unknown's avatar
unknown committed
1100
      tee_fputs(prompt, stdout);
1101
#if defined(__NETWARE__)
unknown's avatar
unknown committed
1102 1103
      line=fgets(linebuffer, sizeof(linebuffer)-1, stdin);
      /* Remove the '\n' */
unknown's avatar
unknown committed
1104
      if (line)
unknown's avatar
unknown committed
1105
      {
unknown's avatar
unknown committed
1106
        char *p = strrchr(line, '\n');
1107 1108
        if (p != NULL)
          *p = '\0';
unknown's avatar
unknown committed
1109
      }
1110
#else defined(__WIN__)
1111 1112
      if (!tmpbuf.is_alloced())
        tmpbuf.alloc(65535);
1113
      tmpbuf.length(0);
1114
      buffer.length(0);
1115
      size_t clen;
1116 1117
      do
      {
1118
	line= my_cgets((char*)tmpbuf.ptr(), tmpbuf.alloced_length()-1, &clen);
1119 1120 1121 1122 1123
        buffer.append(line, clen);
        /* 
           if we got buffer fully filled than there is a chance that
           something else is still in console input buffer
        */
1124
      } while (tmpbuf.alloced_length() <= clen);
1125 1126 1127 1128 1129 1130
      /* 
        An empty line is returned from my_cgets when there's error reading :
        Ctrl-c for example
      */
      if (line)
        line= buffer.c_ptr();
unknown's avatar
unknown committed
1131 1132 1133 1134 1135
#endif /* __NETWARE__ */
#else
      if (opt_outfile)
	fputs(prompt, OUTFILE);
      line= readline(prompt);
1136
#endif /* defined( __WIN__) || defined(__NETWARE__) */
unknown's avatar
unknown committed
1137

unknown's avatar
unknown committed
1138 1139 1140 1141 1142
      /*
        When Ctrl+d or Ctrl+z is pressed, the line may be NULL on some OS
        which may cause coredump.
      */
      if (opt_outfile && line)
unknown's avatar
unknown committed
1143
	fprintf(OUTFILE, "%s\n", line);
1144
    }
unknown's avatar
unknown committed
1145 1146 1147 1148 1149 1150 1151 1152
    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
1153
      continue;					// Skip comment lines
unknown's avatar
unknown committed
1154

1155 1156 1157 1158
    /*
      Check if line is a mysql command line
      (We want to allow help, print and clear anywhere at line start
    */
1159
    if ((named_cmds || glob_buffer.is_empty())
1160
	&& !ml_comment && !in_string && (com=find_command(line,0)))
unknown's avatar
unknown committed
1161 1162 1163 1164 1165 1166
    {
      if ((*com->func)(&glob_buffer,line) > 0)
	break;
      if (glob_buffer.is_empty())		// If buffer was emptied
	in_string=0;
#ifdef HAVE_READLINE
1167
      if (interactive && status.add_to_history && not_in_history(line))
unknown's avatar
unknown committed
1168 1169 1170 1171
	add_history(line);
#endif
      continue;
    }
1172
    if (add_line(glob_buffer,line,&in_string,&ml_comment))
unknown's avatar
unknown committed
1173 1174 1175 1176
      break;
  }
  /* if in batch mode, send last query even if it doesn't end with \g or go */

1177
  if (!interactive && !status.exit_status)
unknown's avatar
unknown committed
1178 1179 1180 1181 1182 1183 1184 1185 1186
  {
    remove_cntrl(glob_buffer);
    if (!glob_buffer.is_empty())
    {
      status.exit_status=1;
      if (com_go(&glob_buffer,line) <= 0)
	status.exit_status=0;
    }
  }
1187

1188
#if defined( __WIN__) || defined(__NETWARE__)
1189 1190
  buffer.free();
#endif
1191 1192 1193 1194
#if defined( __WIN__)
  tmpbuf.free();
#endif

unknown's avatar
unknown committed
1195 1196 1197 1198
  return status.exit_status;
}


1199
static COMMANDS *find_command(char *name,char cmd_char)
unknown's avatar
unknown committed
1200 1201 1202
{
  uint len;
  char *end;
1203 1204
  DBUG_ENTER("find_command");
  DBUG_PRINT("enter",("name: '%s'  char: %d", name ? name : "NULL", cmd_char));
unknown's avatar
unknown committed
1205 1206 1207 1208 1209 1210 1211 1212

  if (!name)
  {
    len=0;
    end=0;
  }
  else
  {
1213
    while (my_isspace(charset_info,*name))
unknown's avatar
unknown committed
1214
      name++;
unknown's avatar
unknown committed
1215
    /*
1216 1217 1218
      If there is an \\g in the row or if the row has a delimiter but
      this is not a delimiter command, let add_line() take care of
      parsing the row and calling find_command()
unknown's avatar
unknown committed
1219 1220
    */
    if (strstr(name, "\\g") || (strstr(name, delimiter) &&
1221 1222 1223 1224 1225
                                !(strlen(name) >= 9 &&
                                  !my_strnncoll(charset_info,
                                                (uchar*) name, 9,
                                                (const uchar*) "delimiter",
                                                9))))
1226
      DBUG_RETURN((COMMANDS *) 0);
unknown's avatar
unknown committed
1227 1228 1229
    if ((end=strcont(name," \t")))
    {
      len=(uint) (end - name);
1230
      while (my_isspace(charset_info,*end))
unknown's avatar
unknown committed
1231 1232 1233 1234 1235
	end++;
      if (!*end)
	end=0;					// no arguments to function
    }
    else
unknown's avatar
unknown committed
1236
      len=(uint) strlen(name);
unknown's avatar
unknown committed
1237 1238 1239 1240 1241
  }

  for (uint i= 0; commands[i].name; i++)
  {
    if (commands[i].func &&
1242
	((name &&
1243 1244
	  !my_strnncoll(charset_info,(uchar*)name,len,
				     (uchar*)commands[i].name,len) &&
unknown's avatar
unknown committed
1245 1246 1247
	  !commands[i].name[len] &&
	  (!end || (end && commands[i].takes_params))) ||
	 !name && commands[i].cmd_char == cmd_char))
1248 1249 1250 1251
    {
      DBUG_PRINT("exit",("found command: %s", commands[i].name));
      DBUG_RETURN(&commands[i]);
    }
unknown's avatar
unknown committed
1252
  }
1253
  DBUG_RETURN((COMMANDS *) 0);
unknown's avatar
unknown committed
1254 1255 1256
}


1257 1258
static bool add_line(String &buffer,char *line,char *in_string,
                     bool *ml_comment)
unknown's avatar
unknown committed
1259 1260
{
  uchar inchar;
unknown's avatar
unknown committed
1261
  char buff[80], *pos, *out;
unknown's avatar
unknown committed
1262
  COMMANDS *com;
unknown's avatar
unknown committed
1263
  bool need_space= 0;
1264
  bool ss_comment= 0;
1265
  DBUG_ENTER("add_line");
unknown's avatar
unknown committed
1266 1267

  if (!line[0] && buffer.is_empty())
1268
    DBUG_RETURN(0);
unknown's avatar
unknown committed
1269
#ifdef HAVE_READLINE
1270
  if (status.add_to_history && line[0] && not_in_history(line))
unknown's avatar
unknown committed
1271 1272 1273
    add_history(line);
#endif
#ifdef USE_MB
1274
  char *end_of_line=line+(uint) strlen(line);
unknown's avatar
unknown committed
1275 1276 1277 1278
#endif

  for (pos=out=line ; (inchar= (uchar) *pos) ; pos++)
  {
1279
    if (my_isspace(charset_info,inchar) && out == line && 
1280
        buffer.is_empty())
unknown's avatar
unknown committed
1281 1282
      continue;
#ifdef USE_MB
1283
    int length;
1284
    if (use_mb(charset_info) &&
unknown's avatar
unknown committed
1285
        (length= my_ismbchar(charset_info, pos, end_of_line)))
1286
    {
1287 1288
      if (!*ml_comment)
      {
unknown's avatar
unknown committed
1289
        while (length--)
1290 1291 1292 1293
          *out++ = *pos++;
        pos--;
      }
      else
unknown's avatar
unknown committed
1294
        pos+= length - 1;
1295
      continue;
unknown's avatar
unknown committed
1296 1297
    }
#endif
1298 1299
    if (!*ml_comment && inchar == '\\' &&
        !(mysql.server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES))
unknown's avatar
unknown committed
1300 1301 1302
    {
      // Found possbile one character command like \c

unknown's avatar
unknown committed
1303 1304
      if (!(inchar = (uchar) *++pos))
	break;				// readline adds one '\'
unknown's avatar
unknown committed
1305
      if (*in_string || inchar == 'N')	// \N is short for NULL
unknown's avatar
unknown committed
1306 1307 1308 1309 1310 1311 1312
      {					// Don't allow commands in string
	*out++='\\';
	*out++= (char) inchar;
	continue;
      }
      if ((com=find_command(NullS,(char) inchar)))
      {
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
        const String tmp(line,(uint) (out-line), charset_info);
        buffer.append(tmp);
        if ((*com->func)(&buffer,pos-1) > 0)
          DBUG_RETURN(1);                       // Quit
        if (com->takes_params)
        {
          if (ss_comment)
          {
            /*
              If a client-side macro appears inside a server-side comment,
              discard all characters in the comment after the macro (that is,
              until the end of the comment rather than the next delimiter)
            */
            for (pos++; *pos && (*pos != '*' || *(pos + 1) != '/'); pos++)
              ;
            pos--;
          }
          else
          {
            for (pos++ ;
                 *pos && (*pos != *delimiter ||
                          !is_prefix(pos + 1, delimiter + 1)) ; pos++)
              ;	// Remove parameters
            if (!*pos)
              pos--;
            else 
              pos+= delimiter_length - 1; // Point at last delim char
          }
        }
        out=line;
unknown's avatar
unknown committed
1343 1344 1345 1346 1347
      }
      else
      {
	sprintf(buff,"Unknown command '\\%c'.",inchar);
	if (put_info(buff,INFO_ERROR) > 0)
1348
	  DBUG_RETURN(1);
unknown's avatar
unknown committed
1349 1350 1351 1352 1353
	*out++='\\';
	*out++=(char) inchar;
	continue;
      }
    }
1354 1355 1356 1357
    else if (!*ml_comment && !*in_string &&
             (*pos == *delimiter && is_prefix(pos + 1, delimiter + 1) ||
              buffer.length() == 0 && (out - line) >= 9 &&
              !my_strcasecmp(charset_info, line, "delimiter")))
unknown's avatar
unknown committed
1358 1359
    {					
      uint old_delimiter_length= delimiter_length;
unknown's avatar
unknown committed
1360
      if (out != line)
unknown's avatar
unknown committed
1361 1362
	buffer.append(line, (uint) (out - line));	// Add this line
      if ((com= find_command(buffer.c_ptr(), 0)))
unknown's avatar
unknown committed
1363
      {
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
        if (com->func == com_delimiter)
        {
          /*
            Delimiter wants the get rest of the given line as argument to
            allow one to change ';' to ';;' and back
          */
          char *end= strend(pos);
          buffer.append(pos, (uint) (end - pos));
          /* Ensure pos will point at \0 after the pos+= below */
          pos= end - old_delimiter_length + 1;
        }
unknown's avatar
unknown committed
1375
	if ((*com->func)(&buffer, buffer.c_ptr()) > 0)
1376
	  DBUG_RETURN(1);                       // Quit
unknown's avatar
unknown committed
1377 1378 1379
      }
      else
      {
unknown's avatar
unknown committed
1380
	if (com_go(&buffer, 0) > 0)             // < 0 is not fatal
1381
	  DBUG_RETURN(1);
unknown's avatar
unknown committed
1382 1383
      }
      buffer.length(0);
unknown's avatar
unknown committed
1384 1385
      out= line;
      pos+= old_delimiter_length - 1;
unknown's avatar
unknown committed
1386
    }
1387 1388
    else if (!*ml_comment && (!*in_string && (inchar == '#' ||
			      inchar == '-' && pos[1] == '-' &&
1389
			      my_isspace(charset_info,pos[2]))))
unknown's avatar
unknown committed
1390
      break;					// comment to end of line
unknown's avatar
unknown committed
1391 1392
    else if (!*in_string && inchar == '/' && *(pos+1) == '*' &&
	     *(pos+2) != '!')
1393 1394 1395 1396 1397 1398 1399 1400 1401
    {
      pos++;
      *ml_comment= 1;
      if (out != line)
      {
        buffer.append(line,(uint) (out-line));
        out=line;
      }
    }
1402
    else if (*ml_comment && !ss_comment && inchar == '*' && *(pos + 1) == '/')
1403 1404 1405
    {
      pos++;
      *ml_comment= 0;
unknown's avatar
unknown committed
1406
      need_space= 1;
1407
    }      
unknown's avatar
unknown committed
1408 1409
    else
    {						// Add found char to buffer
1410 1411 1412 1413 1414
      if (!*in_string && inchar == '/' && *(pos + 1) == '*' &&
          *(pos + 2) == '!')
        ss_comment= 1;
      else if (!*in_string && ss_comment && inchar == '*' && *(pos + 1) == '/')
        ss_comment= 0;
unknown's avatar
unknown committed
1415
      if (inchar == *in_string)
1416
	*in_string= 0;
1417 1418 1419 1420
      else if (!*ml_comment && !*in_string &&
	       (inchar == '\'' || inchar == '"' || inchar == '`'))
	*in_string= (char) inchar;
      if (!*ml_comment)
unknown's avatar
unknown committed
1421 1422 1423 1424 1425 1426
      {
        if (need_space && !my_isspace(charset_info, (char)inchar))
        {
          *out++= ' ';
          need_space= 0;
        }
1427
	*out++= (char) inchar;
unknown's avatar
unknown committed
1428
      }
unknown's avatar
unknown committed
1429 1430 1431 1432 1433 1434 1435 1436
    }
  }
  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);
1437
    if (!(*ml_comment) && buffer.append(line,length))
1438
      DBUG_RETURN(1);
unknown's avatar
unknown committed
1439
  }
1440
  DBUG_RETURN(0);
unknown's avatar
unknown committed
1441 1442
}

1443 1444 1445
/*****************************************************************
	    Interface to Readline Completion
******************************************************************/
unknown's avatar
unknown committed
1446 1447 1448

#ifdef HAVE_READLINE

unknown's avatar
unknown committed
1449 1450
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
1451

1452 1453 1454 1455 1456
/*
  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
1457

1458 1459 1460
#if defined(USE_NEW_READLINE_INTERFACE) || defined(USE_LIBEDIT_INTERFACE)
char *no_completion(const char*,int)
#else
1461
char *no_completion()
1462
#endif
unknown's avatar
unknown committed
1463 1464 1465 1466
{
  return 0;					/* No filename completion */
}

1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
/*	glues pieces of history back together if in pieces   */
static void fix_history(String *final_command) 
{
  int total_lines = 1;
  char *ptr = final_command->c_ptr();
  String fixed_buffer; 	/* Converted buffer */
  char str_char = '\0';  /* Character if we are in a string or not */
  
  /* find out how many lines we have and remove newlines */
  while (*ptr != '\0') 
  {
    switch (*ptr) {
      /* string character */
    case '"':
    case '\'':
    case '`':
      if (str_char == '\0')	/* open string */
	str_char = *ptr;
      else if (str_char == *ptr)   /* close string */
	str_char = '\0';
      fixed_buffer.append(ptr,1);
      break;
    case '\n':
      /* 
	 not in string, change to space
	 if in string, leave it alone 
      */
      fixed_buffer.append(str_char == '\0' ? " " : "\n");
      total_lines++;
      break;
    case '\\':
      fixed_buffer.append('\\');
      /* need to see if the backslash is escaping anything */
      if (str_char) 
      {
	ptr++;
	/* special characters that need escaping */
	if (*ptr == '\'' || *ptr == '"' || *ptr == '\\')
	  fixed_buffer.append(ptr,1);
	else
	  ptr--;
      }
      break;
      
    default:
      fixed_buffer.append(ptr,1);
    }
    ptr++;
  }
  if (total_lines > 1)			
    add_history(fixed_buffer.ptr());
}

/*	
  returns 0 if line matches the previous history entry
  returns 1 if the line doesn't match the previous history entry
*/
static int not_in_history(const char *line) 
{
  HIST_ENTRY *oldhist = history_get(history_length);
  
  if (oldhist == 0)
    return 1;
  if (strcmp(oldhist->line,line) == 0)
    return 0;
  return 1;
}

unknown's avatar
unknown committed
1535 1536 1537 1538 1539 1540
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. */
1541 1542 1543 1544
#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
1545 1546 1547
#ifdef HAVE_LOCALE_H
  setlocale(LC_ALL,""); /* so as libedit use isprint */
#endif
1548
  rl_attempted_completion_function= (CPPFunction*)&new_mysql_completion;
1549
  rl_completion_entry_function= &no_completion;
1550
#else
1551
  rl_attempted_completion_function= (CPPFunction*)&new_mysql_completion;
1552
  rl_completion_entry_function= &no_completion;
1553
#endif
unknown's avatar
unknown committed
1554 1555
}

1556 1557 1558 1559 1560 1561
/*
  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
1562

unknown's avatar
unknown committed
1563
static char **new_mysql_completion (const char *text,
unknown's avatar
unknown committed
1564 1565 1566 1567
				    int start __attribute__((unused)),
				    int end __attribute__((unused)))
{
  if (!status.batch && !quick)
1568
#if defined(USE_NEW_READLINE_INTERFACE)
unknown's avatar
unknown committed
1569
    return rl_completion_matches(text, new_command_generator);
1570 1571 1572
#else
    return completion_matches((char *)text, (CPFunction *)new_command_generator);
#endif
unknown's avatar
unknown committed
1573 1574 1575 1576
  else
    return (char**) 0;
}

unknown's avatar
unknown committed
1577
static char *new_command_generator(const char *text,int state)
unknown's avatar
unknown committed
1578 1579 1580 1581 1582 1583 1584
{
  static int textlen;
  char *ptr;
  static Bucket *b;
  static entry *e;
  static uint i;

1585
  if (!state)
unknown's avatar
unknown committed
1586
    textlen=(uint) strlen(text);
unknown's avatar
unknown committed
1587

1588 1589 1590 1591
  if (textlen>0)
  {						/* lookup in the hash */
    if (!state)
    {
unknown's avatar
unknown committed
1592 1593
      uint len;

unknown's avatar
unknown committed
1594
      b = find_all_matches(&ht,text,(uint) strlen(text),&len);
1595
      if (!b)
unknown's avatar
unknown committed
1596 1597 1598 1599
	return NullS;
      e = b->pData;
    }

1600 1601
    if (e)
    {
unknown's avatar
unknown committed
1602 1603 1604 1605
      ptr= strdup(e->str);
      e = e->pNext;
      return ptr;
    }
1606 1607 1608
  }
  else
  { /* traverse the entire hash, ugly but works */
unknown's avatar
unknown committed
1609

1610 1611
    if (!state)
    {
unknown's avatar
unknown committed
1612
      /* find the first used bucket */
1613 1614 1615 1616
      for (i=0 ; i < ht.nTableSize ; i++)
      {
	if (ht.arBuckets[i])
	{
unknown's avatar
unknown committed
1617 1618 1619 1620 1621 1622 1623
	  b = ht.arBuckets[i];
	  e = b->pData;
	  break;
	}
      }
    }
    ptr= NullS;
1624 1625 1626
    while (e && !ptr)
    {					/* find valid entry in bucket */
      if ((uint) strlen(e->str) == b->nKeyLength)
unknown's avatar
unknown committed
1627 1628 1629
	ptr = strdup(e->str);
      /* find the next used entry */
      e = e->pNext;
1630 1631
      if (!e)
      { /* find the next used bucket */
unknown's avatar
unknown committed
1632
	b = b->pNext;
1633 1634 1635 1636 1637 1638
	if (!b)
	{
	  for (i++ ; i<ht.nTableSize; i++)
	  {
	    if (ht.arBuckets[i])
	    {
unknown's avatar
unknown committed
1639 1640 1641 1642 1643 1644
	      b = ht.arBuckets[i];
	      e = b->pData;
	      break;
	    }
	  }
	}
1645 1646
	else
	  e = b->pData;
unknown's avatar
unknown committed
1647 1648
      }
    }
1649
    if (ptr)
unknown's avatar
unknown committed
1650 1651 1652 1653 1654 1655 1656 1657
      return ptr;
  }
  return NullS;
}


/* Build up the completion hash */

unknown's avatar
unknown committed
1658
static void build_completion_hash(bool rehash, bool write_info)
unknown's avatar
unknown committed
1659 1660
{
  COMMANDS *cmd=commands;
1661 1662
  MYSQL_RES *databases=0,*tables=0;
  MYSQL_RES *fields;
unknown's avatar
unknown committed
1663 1664 1665 1666 1667 1668 1669
  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");

1670
  if (status.batch || quick || !current_db)
unknown's avatar
unknown committed
1671 1672 1673 1674 1675 1676 1677
    DBUG_VOID_RETURN;			// We don't need completion in batches

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

1681 1682 1683 1684 1685 1686
  /* 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
1687 1688 1689
  /* hash MySQL functions (to be implemented) */

  /* hash all database names */
1690 1691
  if (mysql_query(&mysql,"show databases") == 0)
  {
unknown's avatar
unknown committed
1692 1693 1694 1695 1696
    if (!(databases = mysql_store_result(&mysql)))
      put_info(mysql_error(&mysql),INFO_INFO);
    else
    {
      while ((database_row=mysql_fetch_row(databases)))
1697 1698 1699 1700 1701 1702
      {
	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
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713
    }
  }
  /* 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
1714
	tee_fprintf(stdout, "\
unknown's avatar
unknown committed
1715 1716 1717 1718 1719
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)))
      {
1720 1721 1722 1723
	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
1724 1725 1726 1727 1728
      }
    }
  }

  /* hash all field names, both with the table prefix and without it */
unknown's avatar
unknown committed
1729 1730
  if (!tables)					/* no tables */
  {
unknown's avatar
unknown committed
1731 1732 1733
    DBUG_VOID_RETURN;
  }
  mysql_data_seek(tables,0);
1734 1735 1736 1737
  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
1738
    DBUG_VOID_RETURN;
1739
  }
unknown's avatar
unknown committed
1740 1741 1742 1743 1744 1745
  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);
1746 1747 1748
      if (!(field_names[i] = (char **) alloc_root(&hash_mem_root,
						  sizeof(char *) *
						  (num_fields*2+1))))
1749 1750 1751 1752
      {
        mysql_free_result(fields);
        break;
      }
1753
      field_names[i][num_fields*2]= '\0';
unknown's avatar
unknown committed
1754 1755 1756
      j=0;
      while ((sql_field=mysql_fetch_field(fields)))
      {
1757
	sprintf(buf,"%.64s.%.64s",table_row[0],sql_field->name);
1758
	field_names[i][j] = strdup_root(&hash_mem_root,buf);
unknown's avatar
unknown committed
1759
	add_word(&ht,field_names[i][j]);
1760 1761
	field_names[i][num_fields+j] = strdup_root(&hash_mem_root,
						   sql_field->name);
unknown's avatar
unknown committed
1762
	if (!completion_hash_exists(&ht,field_names[i][num_fields+j],
unknown's avatar
unknown committed
1763
				    (uint) strlen(field_names[i][num_fields+j])))
unknown's avatar
unknown committed
1764 1765 1766
	  add_word(&ht,field_names[i][num_fields+j]);
	j++;
      }
1767
      mysql_free_result(fields);
unknown's avatar
unknown committed
1768 1769
    }
    else
1770
      field_names[i]= 0;
unknown's avatar
unknown committed
1771

unknown's avatar
unknown committed
1772 1773
    i++;
  }
1774
  mysql_free_result(tables);
unknown's avatar
unknown committed
1775
  field_names[i]=0;				// End pointer
unknown's avatar
unknown committed
1776 1777 1778 1779 1780 1781 1782
  DBUG_VOID_RETURN;
}

	/* for gnu readline */

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

1785
char *index(const char *s,int c)
unknown's avatar
unknown committed
1786 1787 1788 1789 1790 1791 1792 1793
{
  for (;;)
  {
     if (*s == (char) c) return (char*) s;
     if (!*s++) return NullS;
  }
}

1794
char *rindex(const char *s,int c)
unknown's avatar
unknown committed
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805
{
  reg3 char *t;

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

1806

unknown's avatar
unknown committed
1807 1808
static int reconnect(void)
{
1809
  /* purecov: begin tested */
1810
  if (opt_reconnect)
unknown's avatar
unknown committed
1811 1812 1813
  {
    put_info("No connection. Trying to reconnect...",INFO_INFO);
    (void) com_connect((String *) 0, 0);
1814
    if (opt_rehash)
1815
      com_rehash(NULL, NULL);
unknown's avatar
unknown committed
1816 1817 1818
  }
  if (!connected)
    return put_info("Can't connect to the server\n",INFO_ERROR);
1819
  /* purecov: end */
unknown's avatar
unknown committed
1820 1821 1822
  return 0;
}

1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838
static void get_current_db()
{
  MYSQL_RES *res;

  my_free(current_db, MYF(MY_ALLOW_ZERO_PTR));
  current_db= NULL;
  /* In case of error below current_db will be NULL */
  if (!mysql_query(&mysql, "SELECT DATABASE()") &&
      (res= mysql_use_result(&mysql)))
  {
    MYSQL_ROW row= mysql_fetch_row(res);
    if (row[0])
      current_db= my_strdup(row[0], MYF(MY_WME));
    mysql_free_result(res);
  }
}
unknown's avatar
unknown committed
1839 1840 1841 1842 1843

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

unknown's avatar
unknown committed
1844 1845 1846 1847
int mysql_real_query_for_lazy(const char *buf, int length)
{
  for (uint retry=0;; retry++)
  {
unknown's avatar
unknown committed
1848
    int error;
unknown's avatar
unknown committed
1849
    if (!mysql_real_query(&mysql,buf,length))
1850
      return 0;
unknown's avatar
unknown committed
1851
    error= put_error(&mysql);
1852
    if (mysql_errno(&mysql) != CR_SERVER_GONE_ERROR || retry > 1 ||
unknown's avatar
unknown committed
1853
        !opt_reconnect)
unknown's avatar
unknown committed
1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865
      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])
1866
    return put_error(&mysql);
unknown's avatar
unknown committed
1867 1868 1869
  return 0;
}

unknown's avatar
unknown committed
1870 1871 1872 1873 1874
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)
  {
unknown's avatar
unknown committed
1875
    put_info(ccat == 'Y' ? "categories:" : "topics:", INFO_INFO);
unknown's avatar
unknown committed
1876 1877 1878 1879
    *last_char= ccat;
  }
  tee_fprintf(PAGER, "   %s\n", (*cur)[num_name]);
}
1880

1881

unknown's avatar
unknown committed
1882
static int com_server_help(String *buffer __attribute__((unused)),
1883
			   char *line __attribute__((unused)), char *help_arg)
unknown's avatar
unknown committed
1884 1885 1886 1887
{
  MYSQL_ROW cur;
  const char *server_cmd= buffer->ptr();
  char cmd_buf[100];
1888 1889
  MYSQL_RES *result;
  int error;
unknown's avatar
unknown committed
1890
  
1891
  if (help_arg[0] != '\'')
unknown's avatar
unknown committed
1892
  {
1893 1894 1895 1896 1897 1898 1899 1900
	char *end_arg= strend(help_arg);
	if(--end_arg)
	{
		while (my_isspace(charset_info,*end_arg))
          end_arg--;
		*++end_arg= '\0';
	}
	(void) strxnmov(cmd_buf, sizeof(cmd_buf), "help '", help_arg, "'", NullS);
unknown's avatar
unknown committed
1901 1902
    server_cmd= cmd_buf;
  }
unknown's avatar
unknown committed
1903
  
unknown's avatar
unknown committed
1904 1905 1906 1907 1908 1909 1910 1911 1912
  if (!status.batch)
  {
    old_buffer= *buffer;
    old_buffer.copy();
  }

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

1913
  if ((error= mysql_real_query_for_lazy(server_cmd,(int)strlen(server_cmd))) ||
unknown's avatar
unknown committed
1914
      (error= mysql_store_result_for_lazy(&result)))
unknown's avatar
unknown committed
1915 1916 1917 1918
    return error;

  if (result)
  {
unknown's avatar
unknown committed
1919 1920
    unsigned int num_fields= mysql_num_fields(result);
    my_ulonglong num_rows= mysql_num_rows(result);
unknown's avatar
unknown committed
1921
    mysql_fetch_fields(result);
unknown's avatar
unknown committed
1922
    if (num_fields==3 && num_rows==1)
unknown's avatar
unknown committed
1923 1924
    {
      if (!(cur= mysql_fetch_row(result)))
1925 1926 1927 1928
      {
	error= -1;
	goto err;
      }
unknown's avatar
unknown committed
1929 1930

      init_pager();
unknown's avatar
unknown committed
1931 1932 1933 1934 1935
      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
1936 1937
      end_pager();
    }
unknown's avatar
unknown committed
1938
    else if (num_fields >= 2 && num_rows)
unknown's avatar
unknown committed
1939 1940
    {
      init_pager();
1941 1942
      char last_char= 0;

1943
      int num_name= 0, num_cat= 0;
1944 1945 1946
      LINT_INIT(num_name);
      LINT_INIT(num_cat);

unknown's avatar
unknown committed
1947
      if (num_fields == 2)
1948
      {
unknown's avatar
unknown committed
1949
	put_info("Many help items for your request exist.", INFO_INFO);
unknown's avatar
unknown committed
1950
	put_info("To make a more specific request, please type 'help <item>',\nwhere <item> is one of the following", INFO_INFO);
unknown's avatar
unknown committed
1951 1952
	num_name= 0;
	num_cat= 1;
unknown's avatar
unknown committed
1953
      }
unknown's avatar
unknown committed
1954 1955
      else if ((cur= mysql_fetch_row(result)))
      {
unknown's avatar
unknown committed
1956
	tee_fprintf(PAGER, "You asked for help about help category: \"%s\"\n", cur[0]);
unknown's avatar
unknown committed
1957
	put_info("For more information, type 'help <item>', where <item> is one of the following", INFO_INFO);
unknown's avatar
unknown committed
1958 1959 1960 1961
	num_name= 1;
	num_cat= 2;
	print_help_item(&cur,1,2,&last_char);
      }
1962

unknown's avatar
unknown committed
1963 1964
      while ((cur= mysql_fetch_row(result)))
	print_help_item(&cur,num_name,num_cat,&last_char);
unknown's avatar
unknown committed
1965 1966 1967 1968 1969
      tee_fprintf(PAGER, "\n");
      end_pager();
    }
    else
    {
unknown's avatar
unknown committed
1970
      put_info("\nNothing found", INFO_INFO);
unknown's avatar
unknown committed
1971
      put_info("Please try to run 'help contents' for a list of all accessible topics\n", INFO_INFO);
unknown's avatar
unknown committed
1972 1973 1974
    }
  }

1975
err:
unknown's avatar
unknown committed
1976 1977 1978 1979
  mysql_free_result(result);
  return error;
}

unknown's avatar
unknown committed
1980
static int
1981 1982
com_help(String *buffer __attribute__((unused)),
	 char *line __attribute__((unused)))
unknown's avatar
unknown committed
1983
{
1984 1985
  reg1 int i, j;
  char * help_arg= strchr(line,' '), buff[32], *end;
unknown's avatar
unknown committed
1986
  if (help_arg)
1987 1988 1989 1990 1991 1992
  {
    while (my_isspace(charset_info,*help_arg))
      help_arg++;
	if (*help_arg)	  
	  return com_server_help(buffer,line,help_arg);
  }
1993

1994 1995 1996 1997 1998 1999 2000
  put_info("\nFor information about MySQL products and services, visit:\n"
           "   http://www.mysql.com/\n"
           "For developer information, including the MySQL Reference Manual, "
           "visit:\n"
           "   http://dev.mysql.com/\n"
           "To buy MySQL Network Support, training, or other products, visit:\n"
           "   https://shop.mysql.com/\n", INFO_INFO);
2001 2002 2003 2004
  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++)
unknown's avatar
unknown committed
2005
  {
2006
    end= strmov(buff, commands[i].name);
2007
    for (j= (int)strlen(commands[i].name); j < 10; j++)
2008
      end= strmov(end, " ");
2009
    if (commands[i].func)
2010
      tee_fprintf(stdout, "%s(\\%c) %s\n", buff,
2011
		  commands[i].cmd_char, commands[i].doc);
unknown's avatar
unknown committed
2012
  }
2013
  if (connected && mysql_get_server_version(&mysql) >= 40100)
unknown's avatar
unknown committed
2014
    put_info("\nFor server side help, type 'help contents'\n", INFO_INFO);
unknown's avatar
unknown committed
2015 2016 2017 2018 2019 2020 2021 2022
  return 0;
}


	/* ARGSUSED */
static int
com_clear(String *buffer,char *line __attribute__((unused)))
{
2023 2024 2025 2026
#ifdef HAVE_READLINE
  if (status.add_to_history)
    fix_history(buffer);
#endif
unknown's avatar
unknown committed
2027 2028 2029 2030
  buffer->length(0);
  return 0;
}

2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
	/* ARGSUSED */
static int
com_charset(String *buffer __attribute__((unused)), char *line)
{
  char buff[256], *param;
  CHARSET_INFO * new_cs;
  strmake(buff, line, sizeof(buff) - 1);
  param= get_arg(buff, 0);
  if (!param || !*param)
  {
    return put_info("Usage: \\C char_setname | charset charset_name", 
		    INFO_ERROR, 0);
  }
  new_cs= get_charset_by_csname(param, MY_CS_PRIMARY, MYF(MY_WME));
  if (new_cs)
  {
    charset_info= new_cs;
2048 2049 2050
    mysql_set_character_set(&mysql, charset_info->csname);
    default_charset= (char *)charset_info->csname;
    default_charset_used= 1;
2051 2052 2053 2054 2055
    put_info("Charset changed", INFO_INFO);
  }
  else put_info("Charset is not found", INFO_INFO);
  return 0;
}
unknown's avatar
unknown committed
2056 2057

/*
2058 2059 2060 2061
  Execute command
  Returns: 0  if ok
          -1 if not fatal error
	  1  if fatal error
unknown's avatar
unknown committed
2062 2063 2064 2065 2066 2067
*/


static int
com_go(String *buffer,char *line __attribute__((unused)))
{
2068
  char		buff[200], time_buff[32], *pos;
unknown's avatar
unknown committed
2069
  MYSQL_RES	*result;
2070
  ulong		timer, warnings;
2071 2072
  uint		error= 0;
  int           err= 0;
unknown's avatar
unknown committed
2073

2074
  interrupted_query= 0;
unknown's avatar
unknown committed
2075 2076 2077 2078 2079 2080
  if (!status.batch)
  {
    old_buffer= *buffer;			// Save for edit command
    old_buffer.copy();
  }

2081
  /* Remove garbage for nicer messages */
unknown's avatar
unknown committed
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
  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
2095
    return opt_reconnect ? -1 : 1;          // Fatal error
unknown's avatar
unknown committed
2096 2097 2098 2099 2100
  }
  if (verbose)
    (void) com_print(buffer,0);

  if (skip_updates &&
2101
      (buffer->length() < 4 || my_strnncoll(charset_info,
unknown's avatar
unknown committed
2102 2103
					    (const uchar*)buffer->ptr(),4,
					    (const uchar*)"SET ",4)))
unknown's avatar
unknown committed
2104 2105 2106 2107 2108 2109
  {
    (void) put_info("Ignoring query to other database",INFO_INFO);
    return 0;
  }

  timer=start_timer();
2110
  executing_query= 1;
unknown's avatar
unknown committed
2111
  error= mysql_real_query_for_lazy(buffer->ptr(),buffer->length());
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121

#ifdef HAVE_READLINE
  if (status.add_to_history) 
  {  
    buffer->append(vertical ? "\\G" : delimiter);
    /* Append final command onto history */
    fix_history(buffer);
  }
#endif

unknown's avatar
unknown committed
2122
  if (error)
unknown's avatar
unknown committed
2123
  {
2124
    executing_query= 0;
unknown's avatar
unknown committed
2125 2126
    buffer->length(0); // Remove query on error
    return error;
unknown's avatar
unknown committed
2127 2128 2129 2130
  }
  error=0;
  buffer->length(0);

2131
  do
unknown's avatar
unknown committed
2132
  {
2133
    if (quick)
unknown's avatar
unknown committed
2134
    {
2135
      if (!(result=mysql_use_result(&mysql)) && mysql_field_count(&mysql))
2136 2137 2138 2139
      {
        executing_query= 0;
        return put_error(&mysql);
      }
unknown's avatar
unknown committed
2140 2141 2142
    }
    else
    {
2143 2144
      error= mysql_store_result_for_lazy(&result);
      if (error)
2145 2146 2147 2148
      {
        executing_query= 0;
        return error;
      }
2149 2150 2151 2152 2153 2154 2155 2156
    }

    if (verbose >= 3 || !opt_silent)
      mysql_end_timer(timer,time_buff);
    else
      time_buff[0]=0;
    if (result)
    {
2157
      if (!mysql_num_rows(result) && ! quick && !column_types_flag)
2158 2159
      {
	strmov(buff, "Empty set");
2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170
        if (opt_xml)
        { 
          /*
            We must print XML header and footer
            to produce a well-formed XML even if
            the result set is empty (Bug#27608).
          */
          init_pager();
          print_table_data_xml(result);
          end_pager();
        }
2171
      }
unknown's avatar
unknown committed
2172
      else
2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188
      {
	init_pager();
	if (opt_html)
	  print_table_data_html(result);
	else if (opt_xml)
	  print_table_data_xml(result);
	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);
	sprintf(buff,"%ld %s in set",
		(long) mysql_num_rows(result),
		(long) mysql_num_rows(result) == 1 ? "row" : "rows");
	end_pager();
2189 2190
        if (mysql_errno(&mysql))
          error= put_error(&mysql);
2191
      }
unknown's avatar
unknown committed
2192
    }
2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
    else if (mysql_affected_rows(&mysql) == ~(ulonglong) 0)
      strmov(buff,"Query OK");
    else
      sprintf(buff,"Query OK, %ld %s affected",
	      (long) mysql_affected_rows(&mysql),
	      (long) mysql_affected_rows(&mysql) == 1 ? "row" : "rows");

    pos=strend(buff);
    if ((warnings= mysql_warning_count(&mysql)))
    {
      *pos++= ',';
      *pos++= ' ';
2205
      pos=int10_to_str(warnings, pos, 10);
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220
      pos=strmov(pos, " warning");
      if (warnings != 1)
	*pos++= 's';
    }
    strmov(pos, time_buff);
    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 */
      error= put_error(&mysql);
    else if (unbuffered)
      fflush(stdout);
    mysql_free_result(result);
2221 2222 2223
  } while (!(err= mysql_next_result(&mysql)));
  if (err >= 1)
    error= put_error(&mysql);
2224

2225
  if (show_warnings == 1 && warnings >= 1) /* Show warnings if any */
2226 2227 2228 2229 2230 2231
  {
    init_pager();
    print_warnings();
    end_pager();
  }

unknown's avatar
unknown committed
2232 2233
  if (!error && !status.batch && 
      (mysql.server_status & SERVER_STATUS_DB_DROPPED))
2234 2235
    get_current_db();

2236
  executing_query= 0;
unknown's avatar
unknown committed
2237 2238 2239
  return error;				/* New command follows */
}

unknown's avatar
unknown committed
2240 2241 2242

static void init_pager()
{
unknown's avatar
unknown committed
2243
#ifdef USE_POPEN
unknown's avatar
unknown committed
2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258
  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
2259
#ifdef USE_POPEN
unknown's avatar
unknown committed
2260 2261 2262 2263 2264
  if (!opt_nopager)
    pclose(PAGER);
#endif
}

2265

unknown's avatar
unknown committed
2266
static void init_tee(const char *file_name)
unknown's avatar
unknown committed
2267
{
2268
  FILE* new_outfile;
unknown's avatar
unknown committed
2269
  if (opt_outfile)
2270
    end_tee();
unknown's avatar
unknown committed
2271 2272 2273 2274 2275
  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;
  }
2276
  OUTFILE = new_outfile;
unknown's avatar
unknown committed
2277 2278 2279 2280
  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
2281 2282
}

2283

unknown's avatar
unknown committed
2284 2285 2286
static void end_tee()
{
  my_fclose(OUTFILE, MYF(0));
unknown's avatar
unknown committed
2287
  OUTFILE= 0;
unknown's avatar
unknown committed
2288
  opt_outfile= 0;
unknown's avatar
unknown committed
2289 2290 2291
  return;
}

unknown's avatar
unknown committed
2292

unknown's avatar
unknown committed
2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
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
2304 2305 2306 2307

static const char *fieldtype2str(enum enum_field_types type)
{
  switch (type) {
2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333
    case MYSQL_TYPE_BIT:         return "BIT";
    case MYSQL_TYPE_BLOB:        return "BLOB";
    case MYSQL_TYPE_DATE:        return "DATE";
    case MYSQL_TYPE_DATETIME:    return "DATETIME";
    case MYSQL_TYPE_NEWDECIMAL:  return "NEWDECIMAL";
    case MYSQL_TYPE_DECIMAL:     return "DECIMAL";
    case MYSQL_TYPE_DOUBLE:      return "DOUBLE";
    case MYSQL_TYPE_ENUM:        return "ENUM";
    case MYSQL_TYPE_FLOAT:       return "FLOAT";
    case MYSQL_TYPE_GEOMETRY:    return "GEOMETRY";
    case MYSQL_TYPE_INT24:       return "INT24";
    case MYSQL_TYPE_LONG:        return "LONG";
    case MYSQL_TYPE_LONGLONG:    return "LONGLONG";
    case MYSQL_TYPE_LONG_BLOB:   return "LONG_BLOB";
    case MYSQL_TYPE_MEDIUM_BLOB: return "MEDIUM_BLOB";
    case MYSQL_TYPE_NEWDATE:     return "NEWDATE";
    case MYSQL_TYPE_NULL:        return "NULL";
    case MYSQL_TYPE_SET:         return "SET";
    case MYSQL_TYPE_SHORT:       return "SHORT";
    case MYSQL_TYPE_STRING:      return "STRING";
    case MYSQL_TYPE_TIME:        return "TIME";
    case MYSQL_TYPE_TIMESTAMP:   return "TIMESTAMP";
    case MYSQL_TYPE_TINY:        return "TINY";
    case MYSQL_TYPE_TINY_BLOB:   return "TINY_BLOB";
    case MYSQL_TYPE_VAR_STRING:  return "VAR_STRING";
    case MYSQL_TYPE_YEAR:        return "YEAR";
unknown's avatar
unknown committed
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367
    default:                     return "?-unknown-?";
  }
}

static char *fieldflags2str(uint f) {
  static char buf[1024];
  char *s=buf;
  *s=0;
#define ff2s_check_flag(X) \
                if (f & X ## _FLAG) { s=strmov(s, # X " "); f &= ~ X ## _FLAG; }
  ff2s_check_flag(NOT_NULL);
  ff2s_check_flag(PRI_KEY);
  ff2s_check_flag(UNIQUE_KEY);
  ff2s_check_flag(MULTIPLE_KEY);
  ff2s_check_flag(BLOB);
  ff2s_check_flag(UNSIGNED);
  ff2s_check_flag(ZEROFILL);
  ff2s_check_flag(BINARY);
  ff2s_check_flag(ENUM);
  ff2s_check_flag(AUTO_INCREMENT);
  ff2s_check_flag(TIMESTAMP);
  ff2s_check_flag(SET);
  ff2s_check_flag(NO_DEFAULT_VALUE);
  ff2s_check_flag(NUM);
  ff2s_check_flag(PART_KEY);
  ff2s_check_flag(GROUP);
  ff2s_check_flag(UNIQUE);
  ff2s_check_flag(BINCMP);
#undef ff2s_check_flag
  if (f)
    sprintf(s, " unknows=0x%04x", f);
  return buf;
}

unknown's avatar
unknown committed
2368 2369 2370
static void
print_field_types(MYSQL_RES *result)
{
unknown's avatar
unknown committed
2371 2372 2373
  MYSQL_FIELD   *field;
  uint i=0;

unknown's avatar
unknown committed
2374 2375
  while ((field = mysql_fetch_field(result)))
  {
unknown's avatar
unknown committed
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392
    tee_fprintf(PAGER, "Field %3u:  `%s`\n"
                       "Catalog:    `%s`\n"
                       "Database:   `%s`\n"
                       "Table:      `%s`\n"
                       "Org_table:  `%s`\n"
                       "Type:       %s\n"
                       "Collation:  %s (%u)\n"
                       "Length:     %lu\n"
                       "Max_length: %lu\n"
                       "Decimals:   %u\n"
                       "Flags:      %s\n\n",
                ++i,
                field->name, field->catalog, field->db, field->table,
                field->org_table, fieldtype2str(field->type),
                get_charset_name(field->charsetnr), field->charsetnr,
                field->length, field->max_length, field->decimals,
                fieldflags2str(field->flags));
unknown's avatar
unknown committed
2393 2394 2395 2396
  }
  tee_puts("", PAGER);
}

unknown's avatar
unknown committed
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406

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));
2407
  if (column_types_flag)
unknown's avatar
unknown committed
2408 2409
  {
    print_field_types(result);
unknown's avatar
unknown committed
2410 2411
    if (!mysql_num_rows(result))
      return;
unknown's avatar
unknown committed
2412 2413
    mysql_field_seek(result,0);
  }
2414
  separator.copy("+",1,charset_info);
unknown's avatar
unknown committed
2415 2416
  while ((field = mysql_fetch_field(result)))
  {
2417
    uint length= column_names ? field->name_length : 0;
unknown's avatar
unknown committed
2418 2419 2420 2421 2422 2423
    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"
2424
    field->max_length=length;
unknown's avatar
unknown committed
2425 2426 2427
    separator.fill(separator.length()+length+2,'-');
    separator.append('+');
  }
unknown's avatar
unknown committed
2428 2429
  separator.append('\0');                       // End marker for \0
  tee_puts((char*) separator.ptr(), PAGER);
2430
  if (column_names)
unknown's avatar
unknown committed
2431 2432
  {
    mysql_field_seek(result,0);
unknown's avatar
unknown committed
2433
    (void) tee_fputs("|", PAGER);
unknown's avatar
unknown committed
2434 2435
    for (uint off=0; (field = mysql_fetch_field(result)) ; off++)
    {
2436 2437 2438 2439 2440
      uint name_length= (uint) strlen(field->name);
      uint numcells= charset_info->cset->numcells(charset_info,
                                                  field->name,
                                                  field->name + name_length);
      uint display_length= field->max_length + name_length - numcells;
2441
      tee_fprintf(PAGER, " %-*s |",(int) min(display_length,
2442
                                            MAX_COLUMN_LENGTH),
2443
                  field->name);
unknown's avatar
unknown committed
2444 2445
      num_flag[off]= IS_NUM(field->type);
    }
unknown's avatar
unknown committed
2446
    (void) tee_fputs("\n", PAGER);
unknown's avatar
unknown committed
2447
    tee_puts((char*) separator.ptr(), PAGER);
unknown's avatar
unknown committed
2448 2449
  }

unknown's avatar
unknown committed
2450
  while ((cur= mysql_fetch_row(result)))
unknown's avatar
unknown committed
2451
  {
2452 2453
    if (interrupted_query)
      break;
unknown's avatar
unknown committed
2454
    ulong *lengths= mysql_fetch_lengths(result);
2455
    (void) tee_fputs("| ", PAGER);
unknown's avatar
unknown committed
2456 2457
    mysql_field_seek(result, 0);
    for (uint off= 0; off < mysql_num_fields(result); off++)
unknown's avatar
unknown committed
2458
    {
2459 2460 2461 2462 2463 2464
      const char *buffer;
      uint data_length;
      uint field_max_length;
      uint visible_length;
      uint extra_padding;

2465
      if (cur[off] == NULL)
2466 2467 2468 2469 2470
      {
        buffer= "NULL";
        data_length= 4;
      } 
      else 
unknown's avatar
unknown committed
2471
      {
2472 2473
        buffer= cur[off];
        data_length= (uint) lengths[off];
unknown's avatar
unknown committed
2474
      }
2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491

      field= mysql_fetch_field(result);
      field_max_length= field->max_length;

      /* 
       How many text cells on the screen will this string span?  If it contains
       multibyte characters, then the number of characters we occupy on screen
       will be fewer than the number of bytes we occupy in memory.

       We need to find how much screen real-estate we will occupy to know how 
       many extra padding-characters we should send with the printing function.
      */
      visible_length= charset_info->cset->numcells(charset_info, buffer, buffer + data_length);
      extra_padding= data_length - visible_length;

      if (field_max_length > MAX_COLUMN_LENGTH)
        tee_print_sized_data(buffer, data_length, MAX_COLUMN_LENGTH+extra_padding, FALSE);
unknown's avatar
unknown committed
2492
      else
unknown's avatar
unknown committed
2493
      {
2494 2495
        if (num_flag[off] != 0) /* if it is numeric, we right-justify it */
          tee_print_sized_data(buffer, data_length, field_max_length+extra_padding, TRUE);
2496
        else 
2497
          tee_print_sized_data(buffer, data_length, field_max_length+extra_padding, FALSE);
unknown's avatar
unknown committed
2498
      }
2499
      tee_fputs(" | ", PAGER);
unknown's avatar
unknown committed
2500
    }
unknown's avatar
unknown committed
2501
    (void) tee_fputs("\n", PAGER);
unknown's avatar
unknown committed
2502
  }
unknown's avatar
unknown committed
2503
  tee_puts((char*) separator.ptr(), PAGER);
2504
  my_afree((uchar*) num_flag);
unknown's avatar
unknown committed
2505 2506
}

unknown's avatar
unknown committed
2507

2508
static void
2509
tee_print_sized_data(const char *data, unsigned int data_length, unsigned int total_bytes_to_send, bool right_justified)
2510 2511 2512 2513 2514 2515 2516 2517 2518
{
  /* 
    For '\0's print ASCII spaces instead, as '\0' is eaten by (at
    least my) console driver, and that messes up the pretty table
    grid.  (The \0 is also the reason we can't use fprintf() .) 
  */
  unsigned int i;
  const char *p;

2519
  if (right_justified) 
2520
    for (i= data_length; i < total_bytes_to_send; i++)
2521
      tee_putc((int)' ', PAGER);
2522

2523
  for (i= 0, p= data; i < data_length; i+= 1, p+= 1)
2524 2525 2526 2527 2528 2529 2530
  {
    if (*p == '\0')
      tee_putc((int)' ', PAGER);
    else
      tee_putc((int)*p, PAGER);
  }

2531
  if (! right_justified) 
2532
    for (i= data_length; i < total_bytes_to_send; i++)
2533
      tee_putc((int)' ', PAGER);
2534 2535 2536 2537
}



unknown's avatar
unknown committed
2538 2539 2540
static void
print_table_data_html(MYSQL_RES *result)
{
unknown's avatar
unknown committed
2541 2542
  MYSQL_ROW	cur;
  MYSQL_FIELD	*field;
unknown's avatar
unknown committed
2543 2544

  mysql_field_seek(result,0);
unknown's avatar
unknown committed
2545
  (void) tee_fputs("<TABLE BORDER=1><TR>", PAGER);
2546
  if (column_names)
unknown's avatar
unknown committed
2547 2548 2549
  {
    while((field = mysql_fetch_field(result)))
    {
unknown's avatar
unknown committed
2550 2551 2552
      tee_fprintf(PAGER, "<TH>%s</TH>", (field->name ? 
					 (field->name[0] ? field->name : 
					  " &nbsp; ") : "NULL"));
unknown's avatar
unknown committed
2553
    }
unknown's avatar
unknown committed
2554
    (void) tee_fputs("</TR>", PAGER);
unknown's avatar
unknown committed
2555 2556 2557
  }
  while ((cur = mysql_fetch_row(result)))
  {
2558 2559
    if (interrupted_query)
      break;
2560
    ulong *lengths=mysql_fetch_lengths(result);
unknown's avatar
unknown committed
2561
    (void) tee_fputs("<TR>", PAGER);
unknown's avatar
unknown committed
2562 2563
    for (uint i=0; i < mysql_num_fields(result); i++)
    {
unknown's avatar
unknown committed
2564
      (void) tee_fputs("<TD>", PAGER);
unknown's avatar
unknown committed
2565
      safe_put_field(cur[i],lengths[i]);
unknown's avatar
unknown committed
2566
      (void) tee_fputs("</TD>", PAGER);
unknown's avatar
unknown committed
2567
    }
unknown's avatar
unknown committed
2568
    (void) tee_fputs("</TR>", PAGER);
unknown's avatar
unknown committed
2569
  }
unknown's avatar
unknown committed
2570
  (void) tee_fputs("</TABLE>", PAGER);
unknown's avatar
unknown committed
2571 2572 2573
}


2574 2575 2576 2577 2578 2579 2580 2581
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
2582
  tee_fputs("<?xml version=\"1.0\"?>\n\n<resultset statement=\"", PAGER);
2583
  xmlencode_print(glob_buffer.ptr(), (int)strlen(glob_buffer.ptr()));
2584 2585
  tee_fputs("\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">",
            PAGER);
2586 2587 2588 2589

  fields = mysql_fetch_fields(result);
  while ((cur = mysql_fetch_row(result)))
  {
2590 2591
    if (interrupted_query)
      break;
2592
    ulong *lengths=mysql_fetch_lengths(result);
2593 2594 2595
    (void) tee_fputs("\n  <row>\n", PAGER);
    for (uint i=0; i < mysql_num_fields(result); i++)
    {
2596
      tee_fprintf(PAGER, "\t<field name=\"");
2597
      xmlencode_print(fields[i].name, (uint) strlen(fields[i].name));
2598 2599 2600 2601 2602 2603 2604 2605
      if (cur[i])
      {
        tee_fprintf(PAGER, "\">");
        xmlencode_print(cur[i], lengths[i]);
        tee_fprintf(PAGER, "</field>\n");
      }
      else
        tee_fprintf(PAGER, "\" xsi:nil=\"true\" />\n");
2606 2607 2608 2609 2610 2611
    }
    (void) tee_fputs("  </row>\n", PAGER);
  }
  (void) tee_fputs("</resultset>\n", PAGER);
}

unknown's avatar
unknown committed
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621

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)))
  {
2622
    uint length= field->name_length;
unknown's avatar
unknown committed
2623 2624 2625 2626 2627 2628 2629 2630
    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++)
  {
2631 2632
    if (interrupted_query)
      break;
unknown's avatar
unknown committed
2633
    mysql_field_seek(result,0);
unknown's avatar
unknown committed
2634 2635
    tee_fprintf(PAGER, 
		"*************************** %d. row ***************************\n", row_count);
unknown's avatar
unknown committed
2636 2637 2638
    for (uint off=0; off < mysql_num_fields(result); off++)
    {
      field= mysql_fetch_field(result);
unknown's avatar
unknown committed
2639 2640
      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
2641 2642 2643 2644
    }
  }
}

unknown's avatar
unknown committed
2645

2646
/* print_warnings should be called right after executing a statement */
unknown's avatar
unknown committed
2647 2648

static void print_warnings()
2649
{
unknown's avatar
unknown committed
2650
  const char   *query;
2651 2652
  MYSQL_RES    *result;
  MYSQL_ROW    cur;
unknown's avatar
unknown committed
2653
  my_ulonglong num_rows;
2654 2655

  /* Get the warnings */
unknown's avatar
unknown committed
2656 2657
  query= "show warnings";
  mysql_real_query_for_lazy(query, strlen(query));
2658 2659 2660
  mysql_store_result_for_lazy(&result);

  /* Bail out when no warnings */
unknown's avatar
unknown committed
2661
  if (!(num_rows= mysql_num_rows(result)))
2662 2663 2664 2665 2666 2667 2668 2669
  {
    mysql_free_result(result);
    return;
  }

  /* Print the warnings */
  while ((cur= mysql_fetch_row(result)))
  {
2670
    tee_fprintf(PAGER, "%s (Code %s): %s\n", cur[0], cur[1], cur[2]);
2671 2672 2673
  }
  mysql_free_result(result);
}
unknown's avatar
unknown committed
2674

unknown's avatar
unknown committed
2675 2676

static const char *array_value(const char **array, char key)
unknown's avatar
unknown committed
2677
{
unknown's avatar
unknown committed
2678 2679 2680
  for (; *array; array+= 2)
    if (**array == key)
      return array[1];
2681 2682 2683
  return 0;
}

unknown's avatar
unknown committed
2684

unknown's avatar
unknown committed
2685
static void
unknown's avatar
unknown committed
2686
xmlencode_print(const char *src, uint length)
unknown's avatar
unknown committed
2687
{
unknown's avatar
unknown committed
2688 2689 2690
  if (!src)
    tee_fputs("NULL", PAGER);
  else
unknown's avatar
unknown committed
2691
  {
unknown's avatar
unknown committed
2692 2693 2694 2695 2696 2697 2698 2699 2700
    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);
    }
  }
2701
}
unknown's avatar
unknown committed
2702

unknown's avatar
unknown committed
2703 2704 2705 2706 2707

static void
safe_put_field(const char *pos,ulong length)
{
  if (!pos)
unknown's avatar
unknown committed
2708
    tee_fputs("NULL", PAGER);
unknown's avatar
unknown committed
2709 2710 2711
  else
  {
    if (opt_raw_data)
unknown's avatar
unknown committed
2712
      tee_fputs(pos, PAGER);
unknown's avatar
unknown committed
2713 2714 2715 2716
    else for (const char *end=pos+length ; pos != end ; pos++)
    {
#ifdef USE_MB
      int l;
2717 2718
      if (use_mb(charset_info) &&
          (l = my_ismbchar(charset_info, pos, end)))
unknown's avatar
unknown committed
2719
      {
unknown's avatar
unknown committed
2720
	  while (l--)
2721
	    tee_putc(*pos++, PAGER);
unknown's avatar
unknown committed
2722 2723 2724 2725 2726
	  pos--;
	  continue;
      }
#endif
      if (!*pos)
unknown's avatar
unknown committed
2727
	tee_fputs("\\0", PAGER); // This makes everything hard
unknown's avatar
unknown committed
2728
      else if (*pos == '\t')
unknown's avatar
unknown committed
2729
	tee_fputs("\\t", PAGER); // This would destroy tab format
unknown's avatar
unknown committed
2730
      else if (*pos == '\n')
unknown's avatar
unknown committed
2731
	tee_fputs("\\n", PAGER); // This too
unknown's avatar
unknown committed
2732
      else if (*pos == '\\')
unknown's avatar
unknown committed
2733
	tee_fputs("\\\\", PAGER);
2734
	else
2735
	tee_putc(*pos, PAGER);
unknown's avatar
unknown committed
2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747
    }
  }
}


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

2748
  if (opt_silent < 2 && column_names)
unknown's avatar
unknown committed
2749 2750 2751 2752 2753
  {
    int first=0;
    while ((field = mysql_fetch_field(result)))
    {
      if (first++)
unknown's avatar
unknown committed
2754 2755
	(void) tee_fputs("\t", PAGER);
      (void) tee_fputs(field->name, PAGER);
unknown's avatar
unknown committed
2756
    }
unknown's avatar
unknown committed
2757
    (void) tee_fputs("\n", PAGER);
unknown's avatar
unknown committed
2758 2759 2760 2761 2762 2763 2764
  }
  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
2765
      (void) tee_fputs("\t", PAGER);
unknown's avatar
unknown committed
2766
      safe_put_field(cur[off], lengths[off]);
unknown's avatar
unknown committed
2767
    }
unknown's avatar
unknown committed
2768
    (void) tee_fputs("\n", PAGER);
unknown's avatar
unknown committed
2769 2770 2771
  }
}

unknown's avatar
unknown committed
2772 2773 2774 2775 2776 2777 2778
static int
com_tee(String *buffer, char *line __attribute__((unused)))
{
  char file_name[FN_REFLEN], *end, *param;

  if (status.batch)
    return 0;
2779
  while (my_isspace(charset_info,*line))
unknown's avatar
unknown committed
2780 2781 2782 2783 2784
    line++;
  if (!(param = strchr(line, ' '))) // if outfile wasn't given, use the default
  {
    if (!strlen(outfile))
    {
unknown's avatar
unknown committed
2785
      printf("No previous outfile available, you must give a filename!\n");
unknown's avatar
unknown committed
2786 2787
      return 0;
    }
2788 2789 2790 2791 2792 2793 2794
    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
2795
  }
2796 2797

  /* eliminate the spaces before the parameters */
2798
  while (my_isspace(charset_info,*param))
2799 2800 2801
    param++;
  end= strmake(file_name, param, sizeof(file_name) - 1);
  /* remove end space from command line */
2802 2803
  while (end > file_name && (my_isspace(charset_info,end[-1]) || 
			     my_iscntrl(charset_info,end[-1])))
2804 2805
    end--;
  end[0]= 0;
unknown's avatar
unknown committed
2806
  if (end == file_name)
unknown's avatar
unknown committed
2807 2808 2809 2810
  {
    printf("No outfile specified!\n");
    return 0;
  }
unknown's avatar
unknown committed
2811
  init_tee(file_name);
unknown's avatar
unknown committed
2812 2813 2814
  return 0;
}

2815

unknown's avatar
unknown committed
2816 2817 2818 2819 2820 2821 2822 2823 2824 2825
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;
}

2826
/*
2827
  Sorry, this command is not available in Windows.
2828 2829
*/

unknown's avatar
unknown committed
2830
#ifdef USE_POPEN
unknown's avatar
unknown committed
2831 2832 2833 2834 2835 2836 2837
static int
com_pager(String *buffer, char *line __attribute__((unused)))
{
  char pager_name[FN_REFLEN], *end, *param;

  if (status.batch)
    return 0;
2838 2839
  /* Skip spaces in front of the pager command */
  while (my_isspace(charset_info, *line))
unknown's avatar
unknown committed
2840
    line++;
2841 2842 2843 2844 2845 2846
  /* Skip the pager command */
  param= strchr(line, ' ');
  /* Skip the spaces between the command and the argument */
  while (param && my_isspace(charset_info, *param))
    param++;
  if (!param || !strlen(param)) // if pager was not given, use the default
unknown's avatar
unknown committed
2847
  {
2848
    if (!default_pager_set)
unknown's avatar
unknown committed
2849
    {
unknown's avatar
unknown committed
2850
      tee_fprintf(stdout, "Default pager wasn't set, using stdout.\n");
unknown's avatar
unknown committed
2851 2852 2853 2854 2855 2856 2857 2858 2859
      opt_nopager=1;
      strmov(pager, "stdout");
      PAGER= stdout;
      return 0;
    }
    strmov(pager, default_pager);
  }
  else
  {
2860
    end= strmake(pager_name, param, sizeof(pager_name)-1);
2861 2862
    while (end > pager_name && (my_isspace(charset_info,end[-1]) || 
                                my_iscntrl(charset_info,end[-1])))
unknown's avatar
unknown committed
2863 2864 2865
      end--;
    end[0]=0;
    strmov(pager, pager_name);
2866
    strmov(default_pager, pager_name);
unknown's avatar
unknown committed
2867 2868
  }
  opt_nopager=0;
2869
  tee_fprintf(stdout, "PAGER set to '%s'\n", pager);
unknown's avatar
unknown committed
2870 2871 2872
  return 0;
}

2873

unknown's avatar
unknown committed
2874 2875 2876 2877 2878 2879
static int
com_nopager(String *buffer __attribute__((unused)),
	    char *line __attribute__((unused)))
{
  strmov(pager, "stdout");
  opt_nopager=1;
2880
  PAGER= stdout;
unknown's avatar
unknown committed
2881 2882 2883
  tee_fprintf(stdout, "PAGER set to stdout\n");
  return 0;
}
2884
#endif
unknown's avatar
unknown committed
2885

unknown's avatar
unknown committed
2886

2887
/*
2888
  Sorry, you can't send the result to an editor in Win32
2889 2890
*/

unknown's avatar
unknown committed
2891
#ifdef USE_POPEN
unknown's avatar
unknown committed
2892 2893 2894
static int
com_edit(String *buffer,char *line __attribute__((unused)))
{
2895
  char	filename[FN_REFLEN],buff[160];
unknown's avatar
unknown committed
2896 2897 2898
  int	fd,tmp;
  const char *editor;

2899 2900
  if ((fd=create_temp_file(filename,NullS,"sql", O_CREAT | O_WRONLY,
			   MYF(MY_WME))) < 0)
unknown's avatar
unknown committed
2901 2902
    goto err;
  if (buffer->is_empty() && !old_buffer.is_empty())
2903
    (void) my_write(fd,(uchar*) old_buffer.ptr(),old_buffer.length(),
unknown's avatar
unknown committed
2904 2905
		    MYF(MY_WME));
  else
2906
    (void) my_write(fd,(uchar*) buffer->ptr(),buffer->length(),MYF(MY_WME));
unknown's avatar
unknown committed
2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929
  (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;
}
2930 2931
#endif

unknown's avatar
unknown committed
2932 2933 2934 2935 2936 2937 2938

/* 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
2939 2940
  /* let the screen auto close on a normal shutdown */
  NETWARE_SET_SCREEN_MODE(SCR_AUTOCLOSE_ON_EXIT);
unknown's avatar
unknown committed
2941 2942 2943 2944 2945 2946 2947 2948 2949
  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
2950
  build_completion_hash(1, 0);
unknown's avatar
unknown committed
2951 2952 2953 2954
#endif
  return 0;
}

2955

unknown's avatar
unknown committed
2956
#ifdef USE_POPEN
2957 2958 2959 2960
static int
com_shell(String *buffer, char *line __attribute__((unused)))
{
  char *shell_cmd;
2961 2962

  /* Skip space from line begin */
unknown's avatar
unknown committed
2963
  while (my_isspace(charset_info, *line))
2964
    line++;
2965 2966 2967 2968 2969
  if (!(shell_cmd = strchr(line, ' ')))
  {
    put_info("Usage: \\! shell-command", INFO_ERROR);
    return -1;
  }
2970 2971 2972 2973 2974
  /*
    The output of the shell command does not
    get directed to the pager or the outfile
  */
  if (system(shell_cmd) == -1)
2975 2976 2977 2978 2979 2980 2981 2982 2983
  {
    put_info(strerror(errno), INFO_ERROR, errno);
    return -1;
  }
  return 0;
}
#endif


unknown's avatar
unknown committed
2984 2985 2986
static int
com_print(String *buffer,char *line __attribute__((unused)))
{
unknown's avatar
unknown committed
2987 2988
  tee_puts("--------------", stdout);
  (void) tee_fputs(buffer->c_ptr(), stdout);
unknown's avatar
unknown committed
2989
  if (!buffer->length() || (*buffer)[buffer->length()-1] != '\n')
2990
    tee_putc('\n', stdout);
unknown's avatar
unknown committed
2991
  tee_puts("--------------\n", stdout);
unknown's avatar
unknown committed
2992 2993 2994 2995 2996 2997 2998
  return 0;					/* If empty buffer */
}

	/* ARGSUSED */
static int
com_connect(String *buffer, char *line)
{
2999
  char *tmp, buff[256];
3000
  bool save_rehash= opt_rehash;
unknown's avatar
unknown committed
3001 3002
  int error;

3003
  bzero(buff, sizeof(buff));
unknown's avatar
unknown committed
3004 3005
  if (buffer)
  {
3006 3007 3008 3009 3010
    /*
      Two null bytes are needed in the end of buff to allow
      get_arg to find end of string the second time it's called.
    */
    strmake(buff, line, sizeof(buff)-2);
3011 3012
    tmp= get_arg(buff, 0);
    if (tmp && *tmp)
unknown's avatar
unknown committed
3013
    {
3014 3015 3016 3017
      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
3018 3019 3020 3021 3022 3023
      {
	my_free(current_host,MYF(MY_ALLOW_ZERO_PTR));
	current_host=my_strdup(tmp,MYF(MY_WME));
      }
    }
    else
3024 3025 3026 3027
    {
      /* Quick re-connect */
      opt_rehash= 0;                            /* purecov: tested */
    }
unknown's avatar
unknown committed
3028 3029 3030
    buffer->length(0);				// command used
  }
  else
3031
    opt_rehash= 0;
unknown's avatar
unknown committed
3032
  error=sql_connect(current_host,current_db,current_user,opt_password,0);
3033
  opt_rehash= save_rehash;
unknown's avatar
unknown committed
3034 3035 3036

  if (connected)
  {
3037
    sprintf(buff,"Connection id:    %lu",mysql_thread_id(&mysql));
unknown's avatar
unknown committed
3038
    put_info(buff,INFO_INFO);
3039
    sprintf(buff,"Current database: %.128s\n",
unknown's avatar
unknown committed
3040
	    current_db ? current_db : "*** NONE ***");
unknown's avatar
unknown committed
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055
    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 */
3056
  while (my_isspace(charset_info,*line))
unknown's avatar
unknown committed
3057
    line++;
unknown's avatar
unknown committed
3058 3059 3060
  if (!(param = strchr(line, ' ')))		// Skip command name
    return put_info("Usage: \\. <filename> | source <filename>", 
		    INFO_ERROR, 0);
3061
  while (my_isspace(charset_info,*param))
unknown's avatar
unknown committed
3062 3063
    param++;
  end=strmake(source_name,param,sizeof(source_name)-1);
3064 3065
  while (end > source_name && (my_isspace(charset_info,end[-1]) || 
                               my_iscntrl(charset_info,end[-1])))
unknown's avatar
unknown committed
3066 3067
    end--;
  end[0]=0;
unknown's avatar
unknown committed
3068
  unpack_filename(source_name,source_name);
unknown's avatar
unknown committed
3069
  /* open file name */
unknown's avatar
unknown committed
3070
  if (!(sql_file = my_fopen(source_name, O_RDONLY | O_BINARY,MYF(0))))
unknown's avatar
unknown committed
3071 3072 3073 3074 3075 3076
  {
    char buff[FN_REFLEN+60];
    sprintf(buff,"Failed to open file '%s', error: %d", source_name,errno);
    return put_info(buff, INFO_ERROR, 0);
  }

3077
  if (!(line_buff=batch_readline_init(opt_max_allowed_packet+512,sql_file)))
unknown's avatar
unknown committed
3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090
  {
    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
3091
  error= read_and_execute(false);
unknown's avatar
unknown committed
3092 3093 3094 3095 3096 3097 3098
  status=old_status;				// Continue as before
  my_fclose(sql_file,MYF(0));
  batch_readline_end(line_buff);
  return error;
}


unknown's avatar
unknown committed
3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113
	/* 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;
  }
3114 3115 3116 3117 3118 3119 3120 3121
  else
  {
    if (strstr(tmp, "\\")) 
    {
      put_info("DELIMITER cannot contain a backslash character", INFO_ERROR);
      return 0;
    }
  }
unknown's avatar
unknown committed
3122
  strmake(delimiter, tmp, sizeof(delimiter) - 1);
3123
  delimiter_length= (int)strlen(delimiter);
3124
  delimiter_str= delimiter;
unknown's avatar
unknown committed
3125 3126 3127
  return 0;
}

unknown's avatar
unknown committed
3128 3129 3130 3131
	/* ARGSUSED */
static int
com_use(String *buffer __attribute__((unused)), char *line)
{
unknown's avatar
unknown committed
3132
  char *tmp, buff[FN_REFLEN + 1];
3133
  int select_db;
unknown's avatar
unknown committed
3134

3135
  bzero(buff, sizeof(buff));
3136
  strmake(buff, line, sizeof(buff) - 1);
3137
  tmp= get_arg(buff, 0);
3138
  if (!tmp || !*tmp)
unknown's avatar
unknown committed
3139
  {
3140
    put_info("USE must be followed by a database name", INFO_ERROR);
unknown's avatar
unknown committed
3141 3142
    return 0;
  }
3143 3144 3145 3146
  /*
    We need to recheck the current database, because it may change
    under our feet, for example if DROP DATABASE or RENAME DATABASE
    (latter one not yet available by the time the comment was written)
unknown's avatar
unknown committed
3147
  */
3148
  get_current_db();
3149

unknown's avatar
unknown committed
3150
  if (!current_db || cmp_database(charset_info, current_db,tmp))
unknown's avatar
unknown committed
3151 3152
  {
    if (one_database)
3153
    {
3154
      skip_updates= 1;
3155 3156
      select_db= 0;    // don't do mysql_select_db()
    }
unknown's avatar
unknown committed
3157
    else
3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179
      select_db= 2;    // do mysql_select_db() and build_completion_hash()
  }
  else
  {
    /*
      USE to the current db specified.
      We do need to send mysql_select_db() to make server
      update database level privileges, which might
      change since last USE (see bug#10979).
      For performance purposes, we'll skip rebuilding of completion hash.
    */
    skip_updates= 0;
    select_db= 1;      // do only mysql_select_db(), without completion
  }

  if (select_db)
  {
    /*
      reconnect once if connection is down or if connection was found to
      be down during query
    */
    if (!connected && reconnect())
3180
      return opt_reconnect ? -1 : 1;                        // Fatal error
3181 3182 3183 3184
    if (mysql_select_db(&mysql,tmp))
    {
      if (mysql_errno(&mysql) != CR_SERVER_GONE_ERROR)
        return put_error(&mysql);
unknown's avatar
unknown committed
3185

3186
      if (reconnect())
3187
        return opt_reconnect ? -1 : 1;                      // Fatal error
3188 3189 3190 3191 3192
      if (mysql_select_db(&mysql,tmp))
        return put_error(&mysql);
    }
    my_free(current_db,MYF(MY_ALLOW_ZERO_PTR));
    current_db=my_strdup(tmp,MYF(MY_WME));
unknown's avatar
unknown committed
3193
#ifdef HAVE_READLINE
3194
    if (select_db > 1)
3195
      build_completion_hash(opt_rehash, 1);
unknown's avatar
unknown committed
3196 3197
#endif
  }
3198

unknown's avatar
unknown committed
3199 3200 3201 3202
  put_info("Database changed",INFO_INFO);
  return 0;
}

3203 3204 3205 3206 3207
static int
com_warnings(String *buffer __attribute__((unused)),
   char *line __attribute__((unused)))
{
  show_warnings = 1;
3208
  put_info("Show warnings enabled.",INFO_INFO);
3209 3210 3211 3212 3213 3214 3215 3216
  return 0;
}

static int
com_nowarnings(String *buffer __attribute__((unused)),
   char *line __attribute__((unused)))
{
  show_warnings = 0;
3217
  put_info("Show warnings disabled.",INFO_INFO);
3218 3219
  return 0;
}
unknown's avatar
unknown committed
3220

3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231
/*
  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)
3232
{
unknown's avatar
unknown committed
3233
  char *ptr, *start;
3234
  my_bool quoted= 0, valid_arg= 0;
3235
  char qtype= 0;
3236 3237

  ptr= line;
3238 3239
  if (get_next_arg)
  {
unknown's avatar
unknown committed
3240 3241
    for (; *ptr; ptr++) ;
    if (*(ptr + 1))
3242 3243 3244 3245 3246
      ptr++;
  }
  else
  {
    /* skip leading white spaces */
3247
    while (my_isspace(charset_info, *ptr))
3248 3249 3250
      ptr++;
    if (*ptr == '\\') // short command was used
      ptr+= 2;
3251 3252 3253
    else
      while (*ptr &&!my_isspace(charset_info, *ptr)) // skip command
        ptr++;
3254
  }
3255 3256
  if (!*ptr)
    return NullS;
3257
  while (my_isspace(charset_info, *ptr))
3258
    ptr++;
3259
  if (*ptr == '\'' || *ptr == '\"' || *ptr == '`')
3260
  {
3261
    qtype= *ptr;
3262 3263 3264
    quoted= 1;
    ptr++;
  }
unknown's avatar
unknown committed
3265
  for (start=ptr ; *ptr; ptr++)
3266
  {
unknown's avatar
unknown committed
3267
    if (*ptr == '\\' && ptr[1]) // escaped character
3268
    {
unknown's avatar
unknown committed
3269 3270
      // Remove the backslash
      strmov(ptr, ptr+1);
3271
    }
3272
    else if ((!quoted && *ptr == ' ') || (quoted && *ptr == qtype))
3273 3274 3275 3276 3277
    {
      *ptr= 0;
      break;
    }
  }
unknown's avatar
unknown committed
3278 3279
  valid_arg= ptr != start;
  return valid_arg ? start : NullS;
3280 3281 3282
}


unknown's avatar
unknown committed
3283 3284 3285 3286
static int
sql_real_connect(char *host,char *database,char *user,char *password,
		 uint silent)
{
unknown's avatar
unknown committed
3287 3288 3289 3290 3291
  if (connected)
  {
    connected= 0;
    mysql_close(&mysql);
  }
unknown's avatar
unknown committed
3292
  mysql_init(&mysql);
unknown's avatar
unknown committed
3293
  if (opt_connect_timeout)
3294 3295
  {
    uint timeout=opt_connect_timeout;
unknown's avatar
unknown committed
3296
    mysql_options(&mysql,MYSQL_OPT_CONNECT_TIMEOUT,
3297 3298
		  (char*) &timeout);
  }
unknown's avatar
unknown committed
3299 3300
  if (opt_compress)
    mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);
unknown's avatar
unknown committed
3301 3302
  if (opt_secure_auth)
    mysql_options(&mysql, MYSQL_SECURE_AUTH, (char *) &opt_secure_auth);
unknown's avatar
merge  
unknown committed
3303 3304
  if (using_opt_local_infile)
    mysql_options(&mysql,MYSQL_OPT_LOCAL_INFILE, (char*) &opt_local_infile);
unknown's avatar
unknown committed
3305 3306 3307
#ifdef HAVE_OPENSSL
  if (opt_use_ssl)
    mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
3308
		  opt_ssl_capath, opt_ssl_cipher);
3309 3310
  mysql_options(&mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
                (char*)&opt_ssl_verify_server_cert);
3311 3312 3313 3314 3315 3316
#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
3317 3318 3319 3320 3321 3322 3323 3324 3325
#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);
  }
unknown's avatar
unknown committed
3326 3327
  if (default_charset_used)
    mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset);
3328 3329
  if (!mysql_real_connect(&mysql, host, user, password,
			  database, opt_mysql_port, opt_mysql_unix_port,
3330
			  connect_flag | CLIENT_MULTI_STATEMENTS))
unknown's avatar
unknown committed
3331 3332 3333 3334 3335
  {
    if (!silent ||
	(mysql_errno(&mysql) != CR_CONN_HOST_ERROR &&
	 mysql_errno(&mysql) != CR_CONNECTION_ERROR))
    {
3336
      (void) put_error(&mysql);
unknown's avatar
unknown committed
3337 3338 3339 3340 3341 3342
      (void) fflush(stdout);
      return ignore_errors ? -1 : 1;		// Abort
    }
    return -1;					// Retryable
  }
  connected=1;
3343
#ifndef EMBEDDED_LIBRARY
3344
  mysql.reconnect= debug_info_flag; // We want to know if this happens
3345 3346
#else
  mysql.reconnect= 1;
3347
#endif
unknown's avatar
unknown committed
3348
#ifdef HAVE_READLINE
3349
  build_completion_hash(opt_rehash, 1);
unknown's avatar
unknown committed
3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366
#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
3367
	tee_fputs("\n", stderr);
unknown's avatar
unknown committed
3368 3369 3370 3371 3372 3373 3374 3375 3376
	(void) fflush(stderr);
      }
      return error;
    }
    if (!wait_flag)
      return ignore_errors ? -1 : 1;
    if (!message && !silent)
    {
      message=1;
unknown's avatar
unknown committed
3377
      tee_fputs("Waiting",stderr); (void) fflush(stderr);
unknown's avatar
unknown committed
3378
    }
unknown's avatar
unknown committed
3379
    (void) sleep(wait_time);
unknown's avatar
unknown committed
3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393
    if (!silent)
    {
      putc('.',stderr); (void) fflush(stderr);
      count++;
    }
  }
}



static int
com_status(String *buffer __attribute__((unused)),
	   char *line __attribute__((unused)))
{
3394 3395
  const char *status_str;
  char buff[40];
3396
  ulonglong id;
unknown's avatar
unknown committed
3397 3398
  MYSQL_RES *result;
  LINT_INIT(result);
3399

unknown's avatar
unknown committed
3400
  tee_puts("--------------", stdout);
unknown's avatar
unknown committed
3401 3402 3403
  usage(1);					/* Print version */
  if (connected)
  {
3404
    tee_fprintf(stdout, "\nConnection id:\t\t%lu\n",mysql_thread_id(&mysql));
unknown's avatar
unknown committed
3405 3406 3407 3408
    /* 
      Don't remove "limit 1", 
      it is protection againts SQL_SELECT_LIMIT=0
    */
3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419
    if (!mysql_query(&mysql,"select DATABASE(), USER() limit 1") &&
	(result=mysql_use_result(&mysql)))
    {
      MYSQL_ROW cur=mysql_fetch_row(result);
      if (cur)
      {
        tee_fprintf(stdout, "Current database:\t%s\n", cur[0] ? cur[0] : "");
        tee_fprintf(stdout, "Current user:\t\t%s\n", cur[1]);
      }
      mysql_free_result(result);
    } 
3420
#ifdef HAVE_OPENSSL
3421
    if ((status_str= mysql_get_ssl_cipher(&mysql)))
unknown's avatar
unknown committed
3422
      tee_fprintf(stdout, "SSL:\t\t\tCipher in use is %s\n",
3423
		  status_str);
3424 3425
    else
#endif /* HAVE_OPENSSL */
unknown's avatar
unknown committed
3426
      tee_puts("SSL:\t\t\tNot in use", stdout);
unknown's avatar
unknown committed
3427 3428 3429 3430
  }
  else
  {
    vidattr(A_BOLD);
unknown's avatar
unknown committed
3431
    tee_fprintf(stdout, "\nNo connection\n");
unknown's avatar
unknown committed
3432 3433 3434 3435 3436 3437
    vidattr(A_NORMAL);
    return 0;
  }
  if (skip_updates)
  {
    vidattr(A_BOLD);
unknown's avatar
unknown committed
3438
    tee_fprintf(stdout, "\nAll updates ignored to this database\n");
unknown's avatar
unknown committed
3439 3440
    vidattr(A_NORMAL);
  }
unknown's avatar
unknown committed
3441
#ifdef USE_POPEN
unknown's avatar
unknown committed
3442
  tee_fprintf(stdout, "Current pager:\t\t%s\n", pager);
3443
  tee_fprintf(stdout, "Using outfile:\t\t'%s'\n", opt_outfile ? outfile : "");
unknown's avatar
unknown committed
3444
#endif
unknown's avatar
unknown committed
3445
  tee_fprintf(stdout, "Using delimiter:\t%s\n", delimiter);
3446
  tee_fprintf(stdout, "Server version:\t\t%s\n", server_version_string(&mysql));
unknown's avatar
unknown committed
3447 3448
  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));
3449 3450 3451
  if ((id= mysql_insert_id(&mysql)))
    tee_fprintf(stdout, "Insert id:\t\t%s\n", llstr(id, buff));

3452
  /* "limit 1" is protection against SQL_SELECT_LIMIT=0 */
unknown's avatar
unknown committed
3453
  if (!mysql_query(&mysql,"select @@character_set_client, @@character_set_connection, @@character_set_server, @@character_set_database limit 1") &&
unknown's avatar
unknown committed
3454 3455 3456 3457 3458
      (result=mysql_use_result(&mysql)))
  {
    MYSQL_ROW cur=mysql_fetch_row(result);
    if (cur)
    {
unknown's avatar
unknown committed
3459
      tee_fprintf(stdout, "Server characterset:\t%s\n", cur[2] ? cur[2] : "");
unknown's avatar
unknown committed
3460
      tee_fprintf(stdout, "Db     characterset:\t%s\n", cur[3] ? cur[3] : "");
unknown's avatar
unknown committed
3461
      tee_fprintf(stdout, "Client characterset:\t%s\n", cur[0] ? cur[0] : "");
unknown's avatar
unknown committed
3462 3463 3464 3465
      tee_fprintf(stdout, "Conn.  characterset:\t%s\n", cur[1] ? cur[1] : "");
    }
    mysql_free_result(result);
  }
3466 3467 3468 3469 3470 3471
  else
  {
    /* Probably pre-4.1 server */
    tee_fprintf(stdout, "Client characterset:\t%s\n", charset_info->csname);
    tee_fprintf(stdout, "Server characterset:\t%s\n", mysql.charset->csname);
  }
unknown's avatar
unknown committed
3472

3473
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
3474
  if (strstr(mysql_get_host_info(&mysql),"TCP/IP") || ! mysql.unix_socket)
unknown's avatar
unknown committed
3475
    tee_fprintf(stdout, "TCP port:\t\t%d\n", mysql.port);
unknown's avatar
unknown committed
3476
  else
unknown's avatar
unknown committed
3477
    tee_fprintf(stdout, "UNIX socket:\t\t%s\n", mysql.unix_socket);
3478 3479
  if (mysql.net.compress)
    tee_fprintf(stdout, "Protocol:\t\tCompressed\n");
3480
#endif
3481

3482
  if ((status_str= mysql_stat(&mysql)) && !mysql_error(&mysql)[0])
unknown's avatar
unknown committed
3483 3484
  {
    ulong sec;
3485
    const char *pos= strchr(status_str,' ');
unknown's avatar
unknown committed
3486
    /* print label */
3487 3488
    tee_fprintf(stdout, "%.*s\t\t\t", (int) (pos-status_str), status_str);
    if ((status_str= str2int(pos,10,0,LONG_MAX,(long*) &sec)))
unknown's avatar
unknown committed
3489 3490
    {
      nice_time((double) sec,buff,0);
unknown's avatar
unknown committed
3491
      tee_puts(buff, stdout);			/* print nice time */
3492 3493
      while (*status_str == ' ')
        status_str++;  /* to next info */
3494
      tee_putc('\n', stdout);
3495
      tee_puts(status_str, stdout);
unknown's avatar
unknown committed
3496 3497 3498 3499 3500
    }
  }
  if (safe_updates)
  {
    vidattr(A_BOLD);
unknown's avatar
unknown committed
3501
    tee_fprintf(stdout, "\nNote that you are running in safe_update_mode:\n");
unknown's avatar
unknown committed
3502
    vidattr(A_NORMAL);
unknown's avatar
unknown committed
3503
    tee_fprintf(stdout, "\
unknown's avatar
unknown committed
3504 3505 3506
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
3507
Max number of examined row combination in a join is set to: %lu\n\n",
unknown's avatar
unknown committed
3508
select_limit, max_join_size);
unknown's avatar
unknown committed
3509
  }
unknown's avatar
unknown committed
3510
  tee_puts("--------------\n", stdout);
unknown's avatar
unknown committed
3511 3512 3513
  return 0;
}

3514
static const char *
3515
server_version_string(MYSQL *con)
3516 3517 3518 3519 3520 3521 3522 3523 3524
{
  static char buf[MAX_SERVER_VERSION_LENGTH] = "";

  /* Only one thread calls this, so no synchronization is needed */
  if (buf[0] == '\0')
  {
    char *bufp = buf;
    MYSQL_RES *result;

3525
    bufp= strnmov(buf, mysql_get_server_info(con), sizeof buf);
3526 3527

    /* "limit 1" is protection against SQL_SELECT_LIMIT=0 */
3528 3529
    if (!mysql_query(con, "select @@version_comment limit 1") &&
        (result = mysql_use_result(con)))
3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545
    {
      MYSQL_ROW cur = mysql_fetch_row(result);
      if (cur && cur[0])
      {
        bufp = strxnmov(bufp, sizeof buf - (bufp - buf), " ", cur[0], NullS);
      }
      mysql_free_result(result);
    }

    /* str*nmov doesn't guarantee NUL-termination */
    if (bufp == buf + sizeof buf)
      buf[sizeof buf - 1] = '\0';
  }

  return buf;
}
unknown's avatar
unknown committed
3546 3547

static int
3548
put_info(const char *str,INFO_TYPE info_type, uint error, const char *sqlstate)
unknown's avatar
unknown committed
3549
{
3550
  FILE *file= (info_type == INFO_ERROR ? stderr : stdout);
unknown's avatar
unknown committed
3551
  static int inited=0;
unknown's avatar
unknown committed
3552

unknown's avatar
unknown committed
3553 3554 3555 3556
  if (status.batch)
  {
    if (info_type == INFO_ERROR)
    {
3557 3558
      (void) fflush(file);
      fprintf(file,"ERROR");
unknown's avatar
unknown committed
3559
      if (error)
unknown's avatar
unknown committed
3560 3561 3562 3563 3564 3565
      {
	if (sqlstate)
	  (void) fprintf(file," %d (%s)",error, sqlstate);
        else
	  (void) fprintf(file," %d",error);
      }
3566
      if (status.query_start_line && line_numbers)
unknown's avatar
unknown committed
3567
      {
3568
	(void) fprintf(file," at line %lu",status.query_start_line);
unknown's avatar
unknown committed
3569
	if (status.file_name)
3570
	  (void) fprintf(file," in file: '%s'", status.file_name);
unknown's avatar
unknown committed
3571
      }
3572 3573
      (void) fprintf(file,": %s\n",str);
      (void) fflush(file);
unknown's avatar
unknown committed
3574 3575 3576 3577
      if (!ignore_errors)
	return 1;
    }
    else if (info_type == INFO_RESULT && verbose > 1)
3578
      tee_puts(str, file);
unknown's avatar
unknown committed
3579
    if (unbuffered)
3580
      fflush(file);
unknown's avatar
unknown committed
3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593
    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)
    {
3594
      if (!opt_nobeep)
3595
        putchar('\a');		      	/* This should make a bell */
unknown's avatar
unknown committed
3596 3597
      vidattr(A_STANDOUT);
      if (error)
3598 3599 3600 3601 3602 3603
      {
	if (sqlstate)
          (void) tee_fprintf(file, "ERROR %d (%s): ", error, sqlstate);
        else
          (void) tee_fprintf(file, "ERROR %d: ", error);
      }
unknown's avatar
unknown committed
3604
      else
3605
        tee_puts("ERROR: ", file);
unknown's avatar
unknown committed
3606 3607 3608
    }
    else
      vidattr(A_BOLD);
3609
    (void) tee_puts(str, file);
unknown's avatar
unknown committed
3610 3611 3612
    vidattr(A_NORMAL);
  }
  if (unbuffered)
3613
    fflush(file);
unknown's avatar
unknown committed
3614 3615 3616
  return info_type == INFO_ERROR ? -1 : 0;
}

unknown's avatar
unknown committed
3617

3618
static int
3619
put_error(MYSQL *con)
3620
{
3621 3622
  return put_info(mysql_error(con), INFO_ERROR, mysql_errno(con),
		  mysql_sqlstate(con));
3623 3624 3625
}  


unknown's avatar
unknown committed
3626 3627 3628 3629
static void remove_cntrl(String &buffer)
{
  char *start,*end;
  end=(start=(char*) buffer.ptr())+buffer.length();
3630
  while (start < end && !my_isgraph(charset_info,end[-1]))
unknown's avatar
unknown committed
3631 3632 3633 3634 3635
    end--;
  buffer.length((uint) (end-start));
}


unknown's avatar
unknown committed
3636 3637 3638 3639
void tee_fprintf(FILE *file, const char *fmt, ...)
{
  va_list args;

unknown's avatar
unknown committed
3640
  NETWARE_YIELD;
unknown's avatar
unknown committed
3641
  va_start(args, fmt);
unknown's avatar
unknown committed
3642
  (void) vfprintf(file, fmt, args);
3643 3644
  va_end(args);

unknown's avatar
unknown committed
3645
  if (opt_outfile)
3646 3647
  {
    va_start(args, fmt);
unknown's avatar
unknown committed
3648
    (void) vfprintf(OUTFILE, fmt, args);
3649 3650
    va_end(args);
  }
unknown's avatar
unknown committed
3651 3652 3653 3654 3655
}


void tee_fputs(const char *s, FILE *file)
{
unknown's avatar
unknown committed
3656
  NETWARE_YIELD;
unknown's avatar
unknown committed
3657 3658 3659 3660 3661 3662 3663 3664
  fputs(s, file);
  if (opt_outfile)
    fputs(s, OUTFILE);
}


void tee_puts(const char *s, FILE *file)
{
unknown's avatar
unknown committed
3665
  NETWARE_YIELD;
unknown's avatar
unknown committed
3666
  fputs(s, file);
3667
  fputc('\n', file);
unknown's avatar
unknown committed
3668 3669 3670
  if (opt_outfile)
  {
    fputs(s, OUTFILE);
3671
    fputc('\n', OUTFILE);
unknown's avatar
unknown committed
3672 3673 3674
  }
}

3675 3676 3677 3678 3679 3680 3681
void tee_putc(int c, FILE *file)
{
  putc(c, file);
  if (opt_outfile)
    putc(c, OUTFILE);
}

3682
#if defined( __WIN__) || defined(__NETWARE__)
unknown's avatar
unknown committed
3683 3684 3685
#include <time.h>
#else
#include <sys/times.h>
3686
#ifdef _SC_CLK_TCK				// For mit-pthreads
unknown's avatar
unknown committed
3687 3688 3689
#undef CLOCKS_PER_SEC
#define CLOCKS_PER_SEC (sysconf(_SC_CLK_TCK))
#endif
3690
#endif
unknown's avatar
unknown committed
3691 3692 3693

static ulong start_timer(void)
{
3694
#if defined( __WIN__) || defined(__NETWARE__)
unknown's avatar
unknown committed
3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709
 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;
3710
    buff=int10_to_str((long) tmp, buff, 10);
unknown's avatar
unknown committed
3711 3712 3713 3714 3715 3716
    buff=strmov(buff,tmp > 1 ? " days " : " day ");
  }
  if (sec >= 3600.0)
  {
    tmp=(ulong) floor(sec/3600.0);
    sec-=3600.0*tmp;
3717
    buff=int10_to_str((long) tmp, buff, 10);
unknown's avatar
unknown committed
3718 3719 3720 3721 3722 3723
    buff=strmov(buff,tmp > 1 ? " hours " : " hour ");
  }
  if (sec >= 60.0)
  {
    tmp=(ulong) floor(sec/60.0);
    sec-=60.0*tmp;
3724
    buff=int10_to_str((long) tmp, buff, 10);
unknown's avatar
unknown committed
3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748
    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),")");
}

3749 3750
static const char* construct_prompt()
{
3751 3752
  processed_prompt.free();			// Erase the old prompt
  time_t  lclock = time(NULL);			// Get the date struct
unknown's avatar
merge  
unknown committed
3753
  struct tm *t = localtime(&lclock);
3754 3755

  /* parse thru the settings for the prompt */
3756 3757 3758
  for (char *c = current_prompt; *c ; *c++)
  {
    if (*c != PROMPT_CHAR)
unknown's avatar
merge  
unknown committed
3759
	processed_prompt.append(*c);
3760 3761
    else
    {
unknown's avatar
merge  
unknown committed
3762 3763
      switch (*++c) {
      case '\0':
3764
	c--;			// stop it from going beyond if ends with %
unknown's avatar
merge  
unknown committed
3765 3766 3767 3768 3769
	break;
      case 'c':
	add_int_to_prompt(++prompt_counter);
	break;
      case 'v':
3770 3771 3772 3773
	if (connected)
	  processed_prompt.append(mysql_get_server_info(&mysql));
	else
	  processed_prompt.append("not_connected");
unknown's avatar
merge  
unknown committed
3774 3775 3776 3777 3778 3779
	break;
      case 'd':
	processed_prompt.append(current_db ? current_db : "(none)");
	break;
      case 'h':
      {
3780 3781
	const char *prompt;
	prompt= connected ? mysql_get_host_info(&mysql) : "not_connected";
unknown's avatar
merge  
unknown committed
3782 3783 3784 3785 3786 3787 3788 3789 3790 3791
	if (strstr(prompt, "Localhost"))
	  processed_prompt.append("localhost");
	else
	{
	  const char *end=strcend(prompt,' ');
	  processed_prompt.append(prompt, (uint) (end-prompt));
	}
	break;
      }
      case 'p':
3792
      {
3793
#ifndef EMBEDDED_LIBRARY
3794 3795 3796 3797 3798
	if (!connected)
	{
	  processed_prompt.append("not_connected");
	  break;
	}
3799 3800 3801 3802 3803 3804 3805

	const char *host_info = mysql_get_host_info(&mysql);
	if (strstr(host_info, "memory")) 
	{
		processed_prompt.append( mysql.host );
	}
	else if (strstr(host_info,"TCP/IP") ||
unknown's avatar
unknown committed
3806
	    !mysql.unix_socket)
unknown's avatar
merge  
unknown committed
3807 3808
	  add_int_to_prompt(mysql.port);
	else
3809 3810
	{
	  char *pos=strrchr(mysql.unix_socket,'/');
unknown's avatar
unknown committed
3811
 	  processed_prompt.append(pos ? pos+1 : mysql.unix_socket);
3812
	}
3813
#endif
3814
      }
unknown's avatar
merge  
unknown committed
3815 3816 3817 3818
	break;
      case 'U':
	if (!full_username)
	  init_username();
3819 3820
        processed_prompt.append(full_username ? full_username :
                                (current_user ?  current_user : "(unknown)"));
unknown's avatar
merge  
unknown committed
3821 3822 3823 3824
	break;
      case 'u':
	if (!full_username)
	  init_username();
3825 3826
        processed_prompt.append(part_username ? part_username :
                                (current_user ?  current_user : "(unknown)"));
unknown's avatar
merge  
unknown committed
3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838
	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':
3839 3840
	if (t->tm_hour < 10)
	  processed_prompt.append('0');
unknown's avatar
merge  
unknown committed
3841 3842 3843 3844 3845 3846 3847
	add_int_to_prompt(t->tm_hour);
	break;
      case 'r':
	int getHour;
	getHour = t->tm_hour % 12;
	if (getHour == 0)
	  getHour=12;
3848 3849
	if (getHour < 10)
	  processed_prompt.append('0');
unknown's avatar
merge  
unknown committed
3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872
	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;
	dateTime = ctime(&lclock);
	processed_prompt.append(strtok(dateTime,"\n"));
	break;
      case 's':
3873 3874
	if (t->tm_sec < 10)
	  processed_prompt.append('0');
unknown's avatar
merge  
unknown committed
3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900
	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;
unknown's avatar
unknown committed
3901 3902 3903
      case 'l':
	processed_prompt.append(delimiter_str);
	break;
unknown's avatar
merge  
unknown committed
3904 3905 3906 3907 3908 3909 3910 3911 3912
      default:
	processed_prompt.append(c);
      }
    }
  }
  processed_prompt.append('\0');
  return processed_prompt.ptr();
}

3913 3914 3915

static void add_int_to_prompt(int toadd)
{
unknown's avatar
merge  
unknown committed
3916 3917 3918 3919 3920
  char buffer[16];
  int10_to_str(toadd,buffer,10);
  processed_prompt.append(buffer);
}

3921 3922
static void init_username()
{
unknown's avatar
merge  
unknown committed
3923 3924 3925 3926 3927 3928 3929
  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)))
3930 3931 3932 3933 3934 3935
  {
    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
3936 3937
}

3938 3939 3940
static int com_prompt(String *buffer, char *line)
{
  char *ptr=strchr(line, ' ');
unknown's avatar
merge  
unknown committed
3941 3942
  prompt_counter = 0;
  my_free(current_prompt,MYF(MY_ALLOW_ZERO_PTR));
3943 3944
  current_prompt=my_strdup(ptr ? ptr+1 : default_prompt,MYF(MY_WME));
  if (!ptr)
unknown's avatar
merge  
unknown committed
3945 3946 3947 3948 3949 3950
    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;
}

3951
#ifndef EMBEDDED_LIBRARY
unknown's avatar
unknown committed
3952 3953
/* Keep sql_string library happy */

3954
void *sql_alloc(size_t Size)
unknown's avatar
unknown committed
3955 3956 3957 3958 3959 3960
{
  return my_malloc(Size,MYF(MY_WME));
}

void sql_element_free(void *ptr)
{
3961
  my_free(ptr,MYF(0));
unknown's avatar
unknown committed
3962
}
3963
#endif /* EMBEDDED_LIBRARY */