mysql.cc 66.5 KB
Newer Older
unknown's avatar
unknown committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/* Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
   
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.
   
   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.
   
   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
22
 *   Andi Gutmans <andi@zend.com>
unknown's avatar
unknown committed
23
 *   Zeev Suraski <zeev@zend.com>
unknown's avatar
unknown committed
24
 *   Jani Tolonen <jani@mysql.com>
25 26
 *   Matt Wagner  <mwagner@mysql.com>
 *   Jeremy Cole  <jcole@mysql.com>
unknown's avatar
unknown committed
27 28 29
 *
 **/

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

unknown's avatar
unknown committed
40
const char *VER="11.16";
41

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

unknown's avatar
unknown committed
45
gptr sql_alloc(unsigned size);	     // Don't use mysqld alloc for these
unknown's avatar
unknown committed
46 47 48 49 50 51 52 53 54 55 56 57 58 59
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
60
#include <asm/termbits.h>		// Standard linux
unknown's avatar
unknown committed
61 62 63 64 65 66 67 68
#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
69
#undef SYSV				// hack to avoid syntax error
unknown's avatar
unknown committed
70 71 72 73 74 75
#ifdef HAVE_TERM_H
#include <term.h>
#endif
#endif
#endif

unknown's avatar
unknown committed
76
#undef bcmp				// Fix problem with new readline
unknown's avatar
unknown committed
77
#undef bzero
unknown's avatar
unknown committed
78
#if defined( __WIN__) || defined(OS2)
unknown's avatar
unknown committed
79 80 81 82 83 84 85 86 87 88
#include <conio.h>
#else
#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
89
#define vidattr(A) {}			// Can't get this to work
unknown's avatar
unknown committed
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
#endif

#ifdef __WIN__
#define cmp_database(A,B) my_strcasecmp((A),(B))
#else
#define cmp_database(A,B) strcmp((A),(B))
#endif

#include "completion_hash.h"

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;

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

static MYSQL mysql;			/* The connection */
static bool info_flag=0,ignore_errors=0,wait_flag=0,quick=0,
	    connected=0,opt_raw_data=0,unbuffered=0,output_tables=0,
	    no_rehash=0,skip_updates=0,safe_updates=0,one_database=0,
	    opt_compress=0,
	    vertical=0,skip_line_numbers=0,skip_column_names=0,opt_html=0,
121
            opt_xml=0,opt_nopager=1, opt_outfile=0, no_named_cmds=1;
122
static uint verbose=0,opt_silent=0,opt_mysql_port=0;
unknown's avatar
unknown committed
123 124 125 126 127 128
static my_string opt_mysql_unix_port=0;
static int connect_flag=CLIENT_INTERACTIVE;
static char *current_host,*current_db,*current_user=0,*opt_password=0,
            *default_charset;
static char *histfile;
static String glob_buffer,old_buffer;
unknown's avatar
unknown committed
129
static int wait_time = 5;
unknown's avatar
unknown committed
130
static STATUS status;
131
static ulong select_limit,max_join_size,opt_connect_timeout=0;
unknown's avatar
unknown committed
132
static const char *xmlmeta[] = {
133 134 135 136
  "&", "&amp;",
  "<", "&lt;",
  0, 0
};
unknown's avatar
unknown committed
137 138 139
static char default_pager[FN_REFLEN];
char pager[FN_REFLEN], outfile[FN_REFLEN];
FILE *PAGER, *OUTFILE;
unknown's avatar
unknown committed
140 141 142 143 144 145 146

#include "sslopt-vars.h"

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

unknown's avatar
unknown committed
147 148 149
void tee_fprintf(FILE *file, const char *fmt, ...);
void tee_fputs(const char *s, FILE *file);
void tee_puts(const char *s, FILE *file);
150
void tee_putc(int c, FILE *file);
unknown's avatar
unknown committed
151 152 153 154
/* 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*),
155
	   com_print(String *str,char*),
unknown's avatar
unknown committed
156 157 158
	   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*),
159
	   com_rehash(String *str, char*), com_tee(String *str, char*),
unknown's avatar
unknown committed
160
           com_notee(String *str, char*);
unknown's avatar
unknown committed
161

162 163 164 165 166
#ifndef __WIN__
static int com_nopager(String *str, char*), com_pager(String *str, char*),
	   com_edit(String *str,char*);
#endif

unknown's avatar
unknown committed
167 168 169 170 171
static int read_lines(bool execute_commands);
static int sql_connect(char *host,char *database,char *user,char *password,
		       uint silent);
static int put_info(const char *str,INFO_TYPE info,uint error=0);
static void safe_put_field(const char *pos,ulong length);
unknown's avatar
unknown committed
172 173
static const char *array_value(const char **array, char *key);
static void xmlencode(char *dest, char *src);
174
static void my_chomp(char *end);
unknown's avatar
unknown committed
175 176 177 178
static void init_pager();
static void end_pager();
static void init_tee();
static void end_tee();
unknown's avatar
unknown committed
179 180 181 182 183 184 185 186 187 188 189 190 191

/* 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
192 193 194
  { "help",   'h', com_help,   0, "Display this help." },
  { "?",      '?', com_help,   0, "Synonym for `help'." },
  { "clear",  'c', com_clear,  0, "Clear command."},
unknown's avatar
unknown committed
195
  { "connect",'r', com_connect,1,
unknown's avatar
unknown committed
196
    "Reconnect to the server. Optional arguments are db and host." },
197
#ifndef __WIN__
unknown's avatar
unknown committed
198
  { "edit",   'e', com_edit,   0, "Edit command with $EDITOR."},
199
#endif
unknown's avatar
unknown committed
200
  { "ego",    'G', com_ego,    0,
unknown's avatar
unknown committed
201 202 203 204 205 206 207 208 209 210 211 212 213 214
    "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." },
#ifndef __WIN__
  { "nopager",'n', com_nopager,0, "Disable pager, print to stdout." },
#endif
  { "notee",  't', com_notee,  0, "Don't write into outfile." },
#ifndef __WIN__
  { "pager",  'P', com_pager,  1, 
    "Set PAGER [to_pager]. Print the query results via PAGER." },
#endif
  { "print",  'p', com_print,  0, "Print current command." },
  { "quit",   'q', com_quit,   0, "Quit mysql." },
  { "rehash", '#', com_rehash, 0, "Rebuild completion hash." },
unknown's avatar
unknown committed
215
  { "source", '.', com_source, 1,
unknown's avatar
unknown committed
216 217 218 219
    "Execute a SQL script file. Takes a file name as an argument."},
  { "status", 's', com_status, 0, "Get status information from the server."},
  { "tee",    'T', com_tee,    1, 
    "Set outfile [to_outfile]. Append everything into given outfile." },
unknown's avatar
unknown committed
220
  { "use",    'u', com_use,    1,
unknown's avatar
unknown committed
221
    "Use another database. Takes database name as argument." },
unknown's avatar
unknown committed
222

unknown's avatar
unknown committed
223
  /* Get bash-like expansion for some commands */
unknown's avatar
unknown committed
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
  { "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
243 244 245
};

static const char *load_default_groups[]= { "mysql","client",0 };
246
static const char *server_default_groups[]= { "server", "mysql_SERVER", 0 };
unknown's avatar
unknown committed
247 248 249 250 251 252 253 254 255 256 257 258 259

#ifdef HAVE_READLINE
extern "C" void add_history(char *command); /* From readline directory */
extern "C" int read_history(char *command);
extern "C" int write_history(char *command);
static void initialize_readline (char *name);
#endif

static COMMANDS *find_command (char *name,char cmd_name);
static bool add_line(String &buffer,char *line,char *in_string);
static void remove_cntrl(String &buffer);
static void print_table_data(MYSQL_RES *result);
static void print_table_data_html(MYSQL_RES *result);
260
static void print_table_data_xml(MYSQL_RES *result);
unknown's avatar
unknown committed
261 262 263 264 265 266 267 268 269 270 271 272 273
static void print_tab_data(MYSQL_RES *result);
static void print_table_data_vertically(MYSQL_RES *result);
static ulong start_timer(void);
static void end_timer(ulong start_time,char *buff);
static void mysql_end_timer(ulong start_time,char *buff);
static void nice_time(double sec,char *buff,bool part_second);
static sig_handler mysql_end(int sig);


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

274
  mysql_server_init(0, NULL, server_default_groups);
unknown's avatar
unknown committed
275 276 277 278
  MY_INIT(argv[0]);
  DBUG_ENTER("main");
  DBUG_PROCESS(argv[0]);

unknown's avatar
unknown committed
279 280
  strmov(outfile, "\0");   // no (default) outfile, unless given at least once
  strmov(pager, "stdout"); // the default, if --pager wasn't given
281 282 283 284 285
  {
    char *tmp=getenv("PAGER");
    if (tmp)
      strmov(default_pager,tmp);
  }
unknown's avatar
unknown committed
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
  if (!isatty(0) || !isatty(1))
  {
    status.batch=1; opt_silent=1;
    ignore_errors=0;
  }
  else
    status.add_to_history=1;
  status.exit_status=1;
  load_defaults("my",load_default_groups,&argc,&argv);
  if (get_options(argc,(char **) argv))
  {
    my_end(0);
    exit(1);
  }
  free_defaults(argv);
  if (status.batch && !status.line_buff &&
      !(status.line_buff=batch_readline_init(max_allowed_packet+512,stdin)))
    exit(1);
  glob_buffer.realloc(512);
  completion_hash_init(&ht,50);
  if (sql_connect(current_host,current_db,current_user,opt_password,
		  opt_silent))
  {
309 310 311
    quick=1;					// Avoid history
    status.exit_status=1;
    mysql_end(-1);
unknown's avatar
unknown committed
312 313 314 315 316
  }
  if (!status.batch)
    ignore_errors=1;				// Don't abort monitor
  signal(SIGINT, mysql_end);			// Catch SIGINT to clean up

unknown's avatar
unknown committed
317
  /*
unknown's avatar
unknown committed
318 319 320 321 322 323 324 325 326 327
  **  Run in interactive mode like the ingres/postgres monitor
  */

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

unknown's avatar
unknown committed
328
#ifdef HAVE_OPENSSL
unknown's avatar
unknown committed
329
  if(mysql.net.vio->ssl_ && SSL_get_cipher(mysql.net.vio->ssl_)) {
unknown's avatar
unknown committed
330 331 332 333 334 335 336 337
    sprintf((char*) glob_buffer.ptr(),
  	  "SSL cipher in use is %s\n", SSL_get_cipher(mysql.net.vio->ssl_));
    put_info((char*) glob_buffer.ptr(),INFO_INFO);
  } else
    put_info("SSL is not in use\n",INFO_INFO);
#endif /* HAVE_OPENSSL */


unknown's avatar
unknown committed
338 339
#ifdef HAVE_READLINE
  initialize_readline(my_progname);
340
  if (!status.batch && !quick && !opt_html && !opt_xml)
unknown's avatar
unknown committed
341 342 343 344 345 346
  {
    /*read-history from file, default ~/.mysql_history*/
    if (getenv("MYSQL_HISTFILE"))
      histfile=my_strdup(getenv("MYSQL_HISTFILE"),MYF(MY_WME));
    else if (getenv("HOME"))
    {
unknown's avatar
unknown committed
347 348
      histfile=(char*) my_malloc((uint) strlen(getenv("HOME"))
				 + (uint) strlen("/.mysql_history")+2,
unknown's avatar
unknown committed
349 350 351 352 353 354 355
				 MYF(MY_WME));
      if (histfile)
	sprintf(histfile,"%s/.mysql_history",getenv("HOME"));
    }
    if (histfile)
    {
      if (verbose)
unknown's avatar
unknown committed
356
	tee_fprintf(stdout, "Reading history-file %s\n",histfile);
unknown's avatar
unknown committed
357 358 359 360
      read_history(histfile);
    }
  }
#endif
unknown's avatar
unknown committed
361
  sprintf(buff, 
362
	  "Type 'help;' or '\\h' for help. Type '\\c' to clear the buffer.\n");
unknown's avatar
unknown committed
363 364
  put_info(buff,INFO_INFO);
  status.exit_status=read_lines(1);		// read lines and execute them
unknown's avatar
unknown committed
365 366
  if (opt_outfile)
    end_tee();
unknown's avatar
unknown committed
367
  mysql_end(0);
368
  mysql_server_end();
unknown's avatar
unknown committed
369 370 371 372 373 374 375 376 377
#ifndef _lint
  DBUG_RETURN(0);				// Keep compiler happy
#endif
}

sig_handler mysql_end(int sig)
{
  if (connected)
    mysql_close(&mysql);
378
#ifdef HAVE_OPENSSL
379 380 381
  else
    mysql_ssl_clear(&mysql); /* SSL data structres should be freed 
				even if connection was not made */
382
#endif
unknown's avatar
unknown committed
383
#ifdef HAVE_READLINE
384
  if (!status.batch && !quick && !opt_html && !opt_xml)
unknown's avatar
unknown committed
385 386 387
  {
    /* write-history */
    if (verbose)
unknown's avatar
unknown committed
388
      tee_fprintf(stdout, "Writing history-file %s\n",histfile);
unknown's avatar
unknown committed
389 390 391 392 393
    write_history(histfile);
  }
  batch_readline_end(status.line_buff);
  completion_hash_free(&ht);
#endif
394 395
  if (sig >= 0)
    put_info(sig ? "Aborted" : "Bye", INFO_RESULT);
unknown's avatar
unknown committed
396 397 398 399 400 401 402 403 404 405 406 407 408 409
  glob_buffer.free();
  old_buffer.free();
  my_free(opt_password,MYF(MY_ALLOW_ZERO_PTR));
  my_free(opt_mysql_unix_port,MYF(MY_ALLOW_ZERO_PTR));
  my_free(histfile,MYF(MY_ALLOW_ZERO_PTR));
  my_free(current_db,MYF(MY_ALLOW_ZERO_PTR));
  my_free(current_host,MYF(MY_ALLOW_ZERO_PTR));
  my_free(current_user,MYF(MY_ALLOW_ZERO_PTR));
  my_end(info_flag ? MY_CHECK_ERROR | MY_GIVE_INFO : 0);
  exit(status.exit_status);
}

static struct option long_options[] =
{
410
  {"i-am-a-dummy",  optional_argument,	   0, 'U'},
unknown's avatar
unknown committed
411
  {"batch",	    no_argument,	   0, 'B'},
unknown's avatar
unknown committed
412
  {"character-sets-dir",required_argument, 0, OPT_CHARSETS_DIR},
unknown's avatar
unknown committed
413 414 415 416 417 418
  {"compress",	    no_argument,	   0, 'C'},
#ifndef DBUG_OFF
  {"debug",	    optional_argument,	   0, '#'},
#endif
  {"database",	    required_argument,     0, 'D'},
  {"debug-info",    no_argument,	   0, 'T'},
unknown's avatar
unknown committed
419
  {"default-character-set", required_argument,0, OPT_DEFAULT_CHARSET},
unknown's avatar
unknown committed
420
  {"enable-named-commands", no_argument,   0, 'G'},
unknown's avatar
unknown committed
421 422 423 424
  {"execute",	    required_argument,	   0, 'e'},
  {"force",	    no_argument,	   0, 'f'},
  {"help",	    no_argument,	   0, '?'},
  {"html",	    no_argument,	   0, 'H'},
425
  {"xml",           no_argument,           0, 'X'},
unknown's avatar
unknown committed
426 427 428 429
  {"host",	    required_argument,	   0, 'h'},
  {"ignore-spaces", no_argument,	   0, 'i'},
  {"no-auto-rehash",no_argument,	   0, 'A'},
  {"no-named-commands", no_argument,       0, 'g'},
unknown's avatar
unknown committed
430 431 432 433 434 435 436 437
  {"no-tee",        no_argument,           0, OPT_NOTEE},
#ifndef __WIN__
  {"no-pager",      no_argument,           0, OPT_NOPAGER},
  {"nopager",       no_argument,           0, OPT_NOPAGER},  /* we are kind */
  {"pager",         optional_argument,     0, OPT_PAGER},
#endif
  {"notee",         no_argument,           0, OPT_NOTEE},    /* we are kind */
  {"tee",           required_argument,     0, OPT_TEE},
unknown's avatar
unknown committed
438 439 440 441 442 443 444 445 446
  {"one-database",  no_argument,	   0, 'o'},
  {"password",	    optional_argument,	   0, 'p'},
#ifdef __WIN__
  {"pipe",	    no_argument,	   0, 'W'},
#endif
  {"port",	    required_argument,	   0, 'P'},
  {"quick",	    no_argument,	   0, 'q'},
  {"set-variable",  required_argument,	   0, 'O'},
  {"raw",	    no_argument,	   0, 'r'},
447
  {"safe-updates",  optional_argument,	   0, 'U'},
unknown's avatar
unknown committed
448 449 450 451 452 453 454 455 456 457 458 459 460
  {"silent",	    no_argument,	   0, 's'},
  {"skip-column-names",no_argument,	   0, 'N'},
  {"skip-line-numbers",no_argument,	   0, 'L'},
  {"socket",	    required_argument,	   0, 'S'},
#include "sslopt-longopts.h"
  {"table",	    no_argument,	   0, 't'},
#ifndef DONT_ALLOW_USER_CHANGE
  {"user",	    required_argument,	   0, 'u'},
#endif
  {"unbuffered",    no_argument,	   0, 'n'},
  {"verbose",	    no_argument,	   0, 'v'},
  {"version",	    no_argument,	   0, 'V'},
  {"vertical",	    no_argument,	   0, 'E'},
unknown's avatar
unknown committed
461
  {"wait",	    optional_argument,	   0, 'w'},
unknown's avatar
unknown committed
462 463 464 465 466
  {0, 0, 0, 0}
};


CHANGEABLE_VAR changeable_vars[] = {
467
  { "connect_timeout", (long*) &opt_connect_timeout, 0, 0, 3600*12, 0, 1},
unknown's avatar
unknown committed
468
  { "max_allowed_packet", (long*) &max_allowed_packet,16*1024L*1024L,4096,
unknown's avatar
unknown committed
469 470 471 472 473 474 475 476 477 478 479
    24*1024L*1024L, MALLOC_OVERHEAD,1024},
  { "net_buffer_length",(long*) &net_buffer_length,16384,1024,24*1024*1024L,
    MALLOC_OVERHEAD,1024},
  { "select_limit", (long*) &select_limit, 1000L, 1, ~0L, 0, 1},
  { "max_join_size", (long*) &max_join_size, 1000000L, 1, ~0L, 0, 1},
  { 0, 0, 0, 0, 0, 0, 0}
};


static void usage(int version)
{
480 481
  printf("%s  Ver %s Distrib %s, for %s (%s)\n",
	 my_progname, VER, MYSQL_SERVER_VERSION, SYSTEM_TYPE, MACHINE_TYPE);
unknown's avatar
unknown committed
482 483 484 485 486 487
  if (version)
    return;
  puts("Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB");
  puts("This software comes with ABSOLUTELY NO WARRANTY. This is free software,\nand you are welcome to modify and redistribute it under the GPL license\n");
  printf("Usage: %s [OPTIONS] [database]\n", my_progname);
  printf("\n\
unknown's avatar
unknown committed
488
  -?, --help		Display this help and exit.\n\
unknown's avatar
unknown committed
489 490 491 492
  -A, --no-auto-rehash  No automatic rehashing. One has to use 'rehash' to\n\
			get table and field completion. This gives a quicker\n\
			start of mysql and disables rehashing on reconnect.\n\
  -B, --batch		Print results with a tab as separator, each row on\n\
unknown's avatar
unknown committed
493
			a new line. Doesn't use history file.\n\
unknown's avatar
unknown committed
494
  --character-sets-dir=...\n\
unknown's avatar
unknown committed
495 496
                        Directory where character sets are located.\n\
  -C, --compress	Use compression in server/client protocol.\n");
unknown's avatar
unknown committed
497 498
#ifndef DBUG_OFF
  printf("\
unknown's avatar
unknown committed
499
  -#, --debug[=...]     Debug log. Default is '%s'.\n",default_dbug_option);
unknown's avatar
unknown committed
500 501
#endif
  printf("\
unknown's avatar
unknown committed
502
  -D, --database=..	Database to use.\n\
unknown's avatar
unknown committed
503
  --default-character-set=...\n\
unknown's avatar
unknown committed
504 505 506 507
                        Set the default character set.\n\
  -e, --execute=...     Execute command and quit. (Output like with --batch)\n\
  -E, --vertical        Print the output of a query (rows) vertically.\n\
  -f, --force           Continue even if we get an sql error.\n\
unknown's avatar
unknown committed
508
  -g, --no-named-commands\n\
unknown's avatar
unknown committed
509 510
			Named commands are disabled. Use \\* form only, or\n\
                        use named commands only in the beginning of a line\n\
unknown's avatar
unknown committed
511 512 513 514
                        ending with a semicolon (;) Since version 10.9 the\n\
                        client now starts with this option ENABLED by\n\
                        default! Disable with '-G'. Long format commands\n\
                        still work from the first line.\n\
515 516
  -G, --enable-named-commands\n\
                        Named commands are enabled. Opposite to -g.\n\
unknown's avatar
unknown committed
517 518 519
  -i, --ignore-space	Ignore space after function names.\n\
  -h, --host=...	Connect to host.\n\
  -H, --html		Produce HTML output.\n\
520
  -X, --xml		Produce XML output.\n\
unknown's avatar
unknown committed
521 522 523 524 525 526 527 528 529
  -L, --skip-line-numbers\n\
                        Don't write line number for errors.\n");
#ifndef __WIN__
  printf("\
  --no-pager            Disable pager and print to stdout. See interactive\n\
                        help (\\h) also.\n");
#endif
  printf("\
  --no-tee              Disable outfile. See interactive help (\\h) also.\n\
unknown's avatar
unknown committed
530
  -n, --unbuffered	Flush buffer after each query.\n\
unknown's avatar
unknown committed
531 532
  -N, --skip-column-names\n\
                        Don't write column names in results.\n\
unknown's avatar
unknown committed
533
  -O, --set-variable var=option\n\
unknown's avatar
unknown committed
534
			Give a variable an value. --help lists variables.\n\
unknown's avatar
unknown committed
535 536
  -o, --one-database	Only update the default database. This is useful\n\
			for skipping updates to other database in the update\n\
unknown's avatar
unknown committed
537
			log.\n");
unknown's avatar
unknown committed
538 539
#ifndef __WIN__
  printf("\
unknown's avatar
unknown committed
540 541 542
  --pager[=...]         Pager to use to display results. If you don't supply\n\
                        an option the default pager is taken from your ENV\n\
                        variable PAGER (%s).\n\
unknown's avatar
unknown committed
543
                        Valid pagers are less, more, cat [> filename], etc.\n\
unknown's avatar
unknown committed
544
                        See interactive help (\\h) also. This option does\n\
unknown's avatar
unknown committed
545
                        not work in batch mode.\n", getenv("PAGER") ? getenv("PAGER") : "");
unknown's avatar
unknown committed
546 547
#endif
  printf("\
unknown's avatar
unknown committed
548 549 550 551 552 553 554
  -p[password], --password[=...]\n\
			Password to use when connecting to server\n\
			If password is not given it's asked from the tty.\n");
#ifdef __WIN__
  puts("  -W, --pipe		Use named pipes to connect to server");
#endif
  printf("\n\
555
  -P, --port=...	Port number to use for connection.\n\
unknown's avatar
unknown committed
556 557
  -q, --quick		Don't cache result, print it row by row. This may\n\
			slow down the server if the output is suspended.\n\
unknown's avatar
unknown committed
558
			Doesn't use history file.\n\
unknown's avatar
unknown committed
559 560
  -r, --raw		Write fields without conversion. Used with --batch\n\
  -s, --silent		Be more silent.\n\
unknown's avatar
unknown committed
561
  -S  --socket=...	Socket file to use for connection.\n");
unknown's avatar
unknown committed
562 563
#include "sslopt-usage.h"
  printf("\
564
  -t, --table		Output in table format.\n\
unknown's avatar
unknown committed
565 566 567
  -T, --debug-info	Print some debug info at exit.\n\
  --tee=...             Append everything into outfile. See interactive help\n\
                        (\\h) also. Does not work in batch mode.\n");
unknown's avatar
unknown committed
568 569
#ifndef DONT_ALLOW_USER_CHANGE
  printf("\
unknown's avatar
unknown committed
570
  -u, --user=#		User for login if not current user.\n");
unknown's avatar
unknown committed
571 572 573
#endif
  printf("\
  -U, --safe-updates[=#], --i-am-a-dummy[=#]\n\
unknown's avatar
unknown committed
574 575 576 577
		        Only allow UPDATE and DELETE that uses keys.\n\
  -v, --verbose		Write more. (-v -v -v gives the table output format)\n\
  -V, --version		Output version information and exit.\n\
  -w, --wait		Wait and retry if connection is down.\n");
unknown's avatar
unknown committed
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
  print_defaults("my",load_default_groups);

  printf("\nPossible variables for option --set-variable (-O) are:\n");
  for (uint i=0 ; changeable_vars[i].name ; i++)
    printf("%-20s  current value: %lu\n",
	   changeable_vars[i].name,
	   (ulong) *changeable_vars[i].varptr);
}


static int get_options(int argc, char **argv)
{
  int c,option_index=0;
  bool tty_password=0;

  set_all_changeable_vars(changeable_vars);
unknown's avatar
unknown committed
594
  while ((c=getopt_long(argc,argv,
unknown's avatar
unknown committed
595
			(char*) "?ABCD:LfgGHXinNoqrstTU::vVw::WEe:h:O:P:S:u:#::p::",
unknown's avatar
unknown committed
596 597 598 599 600 601 602 603 604
			long_options, &option_index)) != EOF)
  {
    switch(c) {
    case OPT_DEFAULT_CHARSET:
      default_charset= optarg;
      break;
    case OPT_CHARSETS_DIR:
      charsets_dir= optarg;
      break;
unknown's avatar
unknown committed
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
    case OPT_TEE:
      if (!opt_outfile && strlen(optarg))
      {
	strmov(outfile, optarg);
	opt_outfile=1;
	init_tee();
      }
      break;
    case OPT_NOTEE:
      if (opt_outfile)
	end_tee();
      opt_outfile=0;
      break;
    case OPT_PAGER:
      opt_nopager=0;
      if (optarg)
	strmov(pager, optarg);
      else
623 624 625 626 627 628 629 630 631 632
      {
	char *pagpoint = getenv("PAGER");
	if (!((char*) (pagpoint)))
	{
	  strmov(pager, "stdout");
	  opt_nopager=1;
	}
	else
	  strmov(pager, pagpoint);
      }
unknown's avatar
unknown committed
633 634 635 636 637
      strmov(default_pager, pager);
      break;
    case OPT_NOPAGER:
      opt_nopager=1;
      break;
unknown's avatar
unknown committed
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
    case 'D':
      my_free(current_db,MYF(MY_ALLOW_ZERO_PTR));      
      current_db=my_strdup(optarg,MYF(MY_WME));
      break;
    case 'e':
      status.batch=1;
      status.add_to_history=0;
      batch_readline_end(status.line_buff);	// If multiple -e
      if (!(status.line_buff=batch_readline_command(optarg)))
	return 1;
      ignore_errors=0;
      break;
    case 'f':
      ignore_errors=1;
      break;
    case 'h':
      my_free(current_host,MYF(MY_ALLOW_ZERO_PTR));
      current_host=my_strdup(optarg,MYF(MY_WME));
      break;
#ifndef DONT_ALLOW_USER_CHANGE
    case 'u':
      my_free(current_user,MYF(MY_ALLOW_ZERO_PTR));
      current_user= my_strdup(optarg,MYF(MY_WME));
      break;
#endif
    case 'U':
      if (!optarg)
	safe_updates=1;
      else
	safe_updates=atoi(optarg) != 0;
      break;
    case 'o':
      one_database=skip_updates=1;
      break;
    case 'O':
      if (set_changeable_var(optarg, changeable_vars))
      {
	usage(0);
	return(1);
      }
      break;
    case 'p':
      if (optarg)
      {
unknown's avatar
unknown committed
682
	char *start=optarg;
unknown's avatar
unknown committed
683 684 685
	my_free(opt_password,MYF(MY_ALLOW_ZERO_PTR));
	opt_password=my_strdup(optarg,MYF(MY_FAE));
	while (*optarg) *optarg++= 'x';		// Destroy argument
unknown's avatar
unknown committed
686 687
	if (*start)
	  start[1]=0;
unknown's avatar
unknown committed
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707
      }
      else
	tty_password=1;
      break;
    case 't':
      output_tables=1;
      break;
    case 'r':
      opt_raw_data=1;
      break;
    case '#':
      DBUG_PUSH(optarg ? optarg : default_dbug_option);
      info_flag=1;
      break;
    case 'q': quick=1; break;
    case 's': opt_silent++; break;
    case 'T': info_flag=1; break;
    case 'n': unbuffered=1; break;
    case 'v': verbose++; break;
    case 'E': vertical=1; break;
unknown's avatar
unknown committed
708 709 710 711
    case 'w':
      wait_flag=1;
      if(optarg) wait_time = atoi(optarg) ;
      break;
unknown's avatar
unknown committed
712
    case 'A': no_rehash=1; break;
unknown's avatar
unknown committed
713
    case 'G': no_named_cmds=0; break;
unknown's avatar
unknown committed
714 715
    case 'g': no_named_cmds=1; break;
    case 'H': opt_html=1; break;
716
    case 'X': opt_xml=1; break;
unknown's avatar
unknown committed
717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
    case 'i': connect_flag|= CLIENT_IGNORE_SPACE; break;
    case 'B':
      if (!status.batch)
      {
	status.batch=1;
	status.add_to_history=0;
	opt_silent++;				// more silent
      }
      break;
    case 'C':
      opt_compress=1;
      break;
    case 'L':
      skip_line_numbers=1;
      break;
    case 'N':
      skip_column_names=1;
      break;
    case 'P':
      opt_mysql_port= (unsigned int) atoi(optarg);
      break;
    case 'S':
      my_free(opt_mysql_unix_port,MYF(MY_ALLOW_ZERO_PTR));
      opt_mysql_unix_port= my_strdup(optarg,MYF(0));
      break;
    case 'W':
#ifdef __WIN__
744
      opt_mysql_unix_port=my_strdup(MYSQL_NAMEDPIPE,MYF(0));
unknown's avatar
unknown committed
745 746 747 748 749 750 751 752 753
#endif
      break;
    case 'V': usage(1); exit(0);
    case 'I':
    case '?':
      usage(0);
      exit(0);
#include "sslopt-case.h"
    default:
unknown's avatar
unknown committed
754
      tee_fprintf(stderr,"illegal option: -%c\n",opterr);
unknown's avatar
unknown committed
755 756 757 758
      usage(0);
      exit(1);
    }
  }
unknown's avatar
unknown committed
759 760 761 762 763 764 765
  if (status.batch) /* disable pager and outfile in this case */
  {
    strmov(default_pager, "stdout");
    strmov(pager, "stdout");
    opt_nopager=1;
    opt_outfile=0;
  }
unknown's avatar
unknown committed
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
  if (default_charset)
  {
    if (set_default_charset_by_name(default_charset, MYF(MY_WME)))
      exit(1);
  }
  argc-=optind;
  argv+=optind;
  if (argc > 1)
  {
    usage(0);
    exit(1);
  }
  if (argc == 1)
  {
    my_free(current_db,MYF(MY_ALLOW_ZERO_PTR));
    current_db= my_strdup(*argv,MYF(MY_WME));
  }
  if (!current_host)
  {	/* If we don't have a hostname have a look at MYSQL_HOST */
    char *tmp=(char *) getenv("MYSQL_HOST");
    if (tmp)
      current_host = my_strdup(tmp,MYF(MY_WME));
  }
  if (tty_password)
    opt_password=get_tty_password(NullS);
  return(0);
}

unknown's avatar
unknown committed
794 795 796 797 798 799 800 801 802 803
#if  defined(OS2)
static char* readline( char* prompt)
{
#if defined(OS2)
   static char linebuffer[254];
#endif
   puts( prompt);
   return gets( linebuffer);
}
#endif
unknown's avatar
unknown committed
804 805 806

static int read_lines(bool execute_commands)
{
unknown's avatar
unknown committed
807
#if defined( __WIN__) || defined(OS2)
unknown's avatar
unknown committed
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
  char linebuffer[254];
#endif
  char	*line;
  char	in_string=0;
  ulong line_number=0;
  COMMANDS *com;
  status.exit_status=1;

  for (;;)
  {
    if (status.batch || !execute_commands)
    {
      line=batch_readline(status.line_buff);
      line_number++;
      if (!glob_buffer.length())
	status.query_start_line=line_number;
    }
    else
unknown's avatar
unknown committed
826
    {
unknown's avatar
unknown committed
827
#if defined( __WIN__) || defined(OS2)
828 829 830 831 832 833 834 835 836
      if (opt_outfile && glob_buffer.is_empty())
	fflush(OUTFILE);
      tee_fputs(glob_buffer.is_empty() ? "mysql> " :
		!in_string ? "    -> " :
		in_string == '\'' ?
		"    '> " : "    \"> ",stdout);
      linebuffer[0]=(char) sizeof(linebuffer);
      line=_cgets(linebuffer);
#else
unknown's avatar
unknown committed
837 838 839 840 841 842 843 844 845 846 847 848 849
      if (opt_outfile)
      {
	if (glob_buffer.is_empty())
	  fflush(OUTFILE);
	fputs(glob_buffer.is_empty() ? "mysql> " :
	      !in_string ? "    -> " :
	      in_string == '\'' ?
	      "    '> " : "    \"> ", OUTFILE);
      }
      line=readline((char*) (glob_buffer.is_empty() ? "mysql> " :
			     !in_string ? "    -> " :
			     in_string == '\'' ?
			     "    '> " : "    \"> "));
unknown's avatar
unknown committed
850
#endif
unknown's avatar
unknown committed
851 852
      if (opt_outfile)
	fprintf(OUTFILE, "%s\n", line);
853
    }
unknown's avatar
unknown committed
854 855 856 857 858 859 860 861
    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
862
      continue;					// Skip comment lines
unknown's avatar
unknown committed
863 864 865

    /* Check if line is a mysql command line */
    /* (We want to allow help, print and clear anywhere at line start */
unknown's avatar
unknown committed
866 867
    if (execute_commands && (!no_named_cmds || glob_buffer.is_empty()) 
	&& !in_string && (com=find_command(line,0)))
unknown's avatar
unknown committed
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
    {
      if ((*com->func)(&glob_buffer,line) > 0)
	break;
      if (glob_buffer.is_empty())		// If buffer was emptied
	in_string=0;
#ifdef HAVE_READLINE
      if (status.add_to_history)
	add_history(line);
#endif
      continue;
    }
    if (add_line(glob_buffer,line,&in_string))
      break;
  }
  /* if in batch mode, send last query even if it doesn't end with \g or go */

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


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

  if (!name)
  {
    len=0;
    end=0;
  }
  else
  {
    while (isspace(*name))
      name++;
    if (strchr(name,';') || strstr(name,"\\g"))
      return ((COMMANDS *) 0);
    if ((end=strcont(name," \t")))
    {
      len=(uint) (end - name);
      while (isspace(*end))
	end++;
      if (!*end)
	end=0;					// no arguments to function
    }
    else
unknown's avatar
unknown committed
923
      len=(uint) strlen(name);
unknown's avatar
unknown committed
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
  }

  for (uint i= 0; commands[i].name; i++)
  {
    if (commands[i].func &&
	((name && !my_casecmp(name,commands[i].name,len) &&
	  !commands[i].name[len] &&
	  (!end || (end && commands[i].takes_params))) ||
	 !name && commands[i].cmd_char == cmd_char))
      return (&commands[i]);
  }
  return ((COMMANDS *) 0);
}


static bool add_line(String &buffer,char *line,char *in_string)
{
  uchar inchar;
  char buff[80],*pos,*out;
  COMMANDS *com;

  if (!line[0] && buffer.is_empty())
    return 0;
#ifdef HAVE_READLINE
  if (status.add_to_history && line[0])
    add_history(line);
#endif
#ifdef USE_MB
unknown's avatar
unknown committed
952
  char *strend=line+(uint) strlen(line);
unknown's avatar
unknown committed
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
#endif

  for (pos=out=line ; (inchar= (uchar) *pos) ; pos++)
  {
    if (isspace(inchar) && out == line && buffer.is_empty())
      continue;
#ifdef USE_MB
    int l;
    if (use_mb(default_charset_info) &&
        (l = my_ismbchar(default_charset_info, pos, strend))) {
	while (l--)
	    *out++ = *pos++;
	pos--;
	continue;
    }
#endif
    if (inchar == '\\')
    {					// mSQL or postgreSQL style command ?
      if (!(inchar = (uchar) *++pos))
	break;				// readline adds one '\'
      if (*in_string || inchar == 'N')
      {					// Don't allow commands in string
	*out++='\\';
	*out++= (char) inchar;
	continue;
      }
      if ((com=find_command(NullS,(char) inchar)))
      {
	const String tmp(line,(uint) (out-line));
	buffer.append(tmp);
	if ((*com->func)(&buffer,pos-1) > 0)
	  return 1;				// Quit
	if (com->takes_params)
	{
	  for (pos++ ; *pos && *pos != ';' ; pos++) ;	// Remove parameters
	  if (!*pos)
	    pos--;
	}
	out=line;
      }
      else
      {
	sprintf(buff,"Unknown command '\\%c'.",inchar);
	if (put_info(buff,INFO_ERROR) > 0)
	  return 1;
	*out++='\\';
	*out++=(char) inchar;
	continue;
      }
    }
    else if (inchar == ';' && !*in_string)
    {						// ';' is end of command
      if (out != line)
	buffer.append(line,(uint) (out-line));	// Add this line
      if ((com=find_command(buffer.c_ptr(),0)))
      {
	if ((*com->func)(&buffer,buffer.c_ptr()) > 0)
	  return 1;				// Quit
      }
      else
      {
	int error=com_go(&buffer,0);
	if (error)
	{
	  return error < 0 ? 0 : 1;		// < 0 is not fatal
	}
      }
      buffer.length(0);
      out=line;
    }
    else if (!*in_string && (inchar == '#' ||
			     inchar == '-' && pos[1] == '-' &&
			     isspace(pos[2])))
      break;					// comment to end of line
    else
    {						// Add found char to buffer
      if (inchar == *in_string)
	*in_string=0;
      else if (!*in_string && (inchar == '\'' || inchar == '"'))
	*in_string=(char) inchar;
      *out++ = (char) inchar;
    }
  }
  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);
    if (buffer.append(line,length))
      return 1;
  }
  return 0;
}

/* **************************************************************** */
/*								    */
/*		    Interface to Readline Completion		    */
/*								    */
/* **************************************************************** */

#ifdef HAVE_READLINE

static char *new_command_generator(char *text, int);
static char **new_mysql_completion (char *text, int start, int end);

/* 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. */

char **no_completion (char *text __attribute__ ((unused)),
		      char *word __attribute__ ((unused)))
{
  return 0;					/* No filename completion */
}

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

  /* Tell the completer that we want a crack first. */
  /* rl_attempted_completion_function = (CPPFunction *)mysql_completion;*/
  rl_attempted_completion_function = (CPPFunction *) new_mysql_completion;
  rl_completion_entry_function=(Function *) no_completion;
}

/* 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. */


static char **new_mysql_completion (char *text,
				    int start __attribute__((unused)),
				    int end __attribute__((unused)))
{
  if (!status.batch && !quick)
    return completion_matches(text, (CPFunction*) new_command_generator);
  else
    return (char**) 0;
}

static char *new_command_generator(char *text,int state)
{
  static int textlen;
  char *ptr;
  static Bucket *b;
  static entry *e;
  static uint i;

  if (!state) {
unknown's avatar
unknown committed
1105
    textlen=(uint) strlen(text);
unknown's avatar
unknown committed
1106 1107 1108 1109 1110 1111
  }

  if (textlen>0) { /* lookup in the hash */
    if (!state) {
      uint len;

unknown's avatar
unknown committed
1112
      b = find_all_matches(&ht,text,(uint) strlen(text),&len);
unknown's avatar
unknown committed
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
      if (!b) {
	return NullS;
      }
      e = b->pData;
    }

    while (e) {
      ptr= strdup(e->str);
      e = e->pNext;
      return ptr;
    }
  } else { /* traverse the entire hash, ugly but works */

    if (!state) {
      i=0;
      /* find the first used bucket */
      while (i<ht.nTableSize) {
	if (ht.arBuckets[i]) {
	  b = ht.arBuckets[i];
	  e = b->pData;
	  break;
	}
	i++;
      }
    }
    ptr= NullS;
    while (e && !ptr) { /* find valid entry in bucket */
unknown's avatar
unknown committed
1140
      if ((uint) strlen(e->str)==b->nKeyLength) {
unknown's avatar
unknown committed
1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
	ptr = strdup(e->str);
      }
      /* find the next used entry */
      e = e->pNext;
      if (!e) { /* find the next used bucket */
	b = b->pNext;
	if (!b) {
	  i++;
	  while (i<ht.nTableSize) {
	    if (ht.arBuckets[i]) {
	      b = ht.arBuckets[i];
	      e = b->pData;
	      break;
	    }
	    i++;
	  }
	} else {
	  e = b->pData;
	}
      }
    }
    if (ptr) {
      return ptr;
    }
  }
  return NullS;
}


/* Build up the completion hash */

static void build_completion_hash(bool skip_rehash,bool write_info)
{
  COMMANDS *cmd=commands;
  static MYSQL_RES *databases=0,*tables=0,*fields;
  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");

1183
  if (status.batch || quick || !current_db)
unknown's avatar
unknown committed
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
    DBUG_VOID_RETURN;			// We don't need completion in batches

  completion_hash_clean(&ht);
  if (tables)
  {
    mysql_free_result(tables);
    tables=0;
  }
  if (databases) {
    mysql_free_result(databases);
    databases=0;
  }

  /* hash SQL commands */
  while (cmd->name) {
    add_word(&ht,(char*) cmd->name);
    cmd++;
  }
  if (skip_rehash)
    DBUG_VOID_RETURN;

  /* hash MySQL functions (to be implemented) */

  /* hash all database names */
  if (mysql_query(&mysql,"show databases")==0) {
    if (!(databases = mysql_store_result(&mysql)))
      put_info(mysql_error(&mysql),INFO_INFO);
    else
    {
      while ((database_row=mysql_fetch_row(databases)))
	add_word(&ht,(char*) database_row[0]);
    }
  }
  /* 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
1226
	tee_fprintf(stdout, "\
unknown's avatar
unknown committed
1227 1228 1229 1230 1231 1232
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)))
      {
	if (!completion_hash_exists(&ht,(char*) table_row[0],
unknown's avatar
unknown committed
1233
				    (uint) strlen((const char*) table_row[0])))
unknown's avatar
unknown committed
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
	  add_word(&ht,table_row[0]);
      }
    }
  }
  if (field_names) {
    for (i=0; field_names[i]; i++) {
      for (j=0; field_names[i][j]; j++) {
	my_free(field_names[i][j],MYF(0));
      }
      my_free((gptr) field_names[i],MYF(0));
    }
    my_free((gptr) field_names,MYF(0));
  }
  field_names=0;

  /* hash all field names, both with the table prefix and without it */
unknown's avatar
unknown committed
1250 1251
  if (!tables)					/* no tables */
  {
unknown's avatar
unknown committed
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
    DBUG_VOID_RETURN;
  }
  mysql_data_seek(tables,0);
  field_names = (char ***) my_malloc(sizeof(char **) *
				     (uint) (mysql_num_rows(tables)+1),
				     MYF(MY_WME));
  if (!field_names)
    DBUG_VOID_RETURN;
  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);
      field_names[i] = (char **) my_malloc(sizeof(char *)*(num_fields*2+1),
					   MYF(0));
      if (!field_names[i])
      {
	continue;
      }
      field_names[i][num_fields*2]='\0';
      j=0;
      while ((sql_field=mysql_fetch_field(fields)))
      {
	sprintf(buf,"%s.%s",table_row[0],sql_field->name);
	field_names[i][j] = my_strdup(buf,MYF(0));
	add_word(&ht,field_names[i][j]);
	field_names[i][num_fields+j] = my_strdup(sql_field->name,MYF(0));
	if (!completion_hash_exists(&ht,field_names[i][num_fields+j],
unknown's avatar
unknown committed
1281
				    (uint) strlen(field_names[i][num_fields+j])))
unknown's avatar
unknown committed
1282 1283 1284 1285 1286
	  add_word(&ht,field_names[i][num_fields+j]);
	j++;
      }
    }
    else
unknown's avatar
unknown committed
1287
    {
unknown's avatar
unknown committed
1288 1289
      tee_fprintf(stdout,
		  "Didn't find any fields in table '%s'\n",table_row[0]);
unknown's avatar
unknown committed
1290 1291
      field_names[i]=0;
    }
unknown's avatar
unknown committed
1292 1293
    i++;
  }
unknown's avatar
unknown committed
1294
  field_names[i]=0;				// End pointer
unknown's avatar
unknown committed
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 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 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
  DBUG_VOID_RETURN;
}


	/* for gnu readline */

#ifndef HAVE_INDEX
#ifdef	__cplusplus
extern "C" {
#endif
extern char *index(const char *,pchar c),*rindex(const char *,pchar);

char *index(const char *s,pchar c)
{
  for (;;)
  {
     if (*s == (char) c) return (char*) s;
     if (!*s++) return NullS;
  }
}

char *rindex(const char *s,pchar c)
{
  reg3 char *t;

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

static int reconnect(void)
{
  if (!status.batch)
  {
    put_info("No connection. Trying to reconnect...",INFO_INFO);
    (void) com_connect((String *) 0, 0);
    if(!no_rehash) com_rehash(NULL, NULL);
  }
  if (!connected)
    return put_info("Can't connect to the server\n",INFO_ERROR);
  return 0;
}


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

static int
com_help (String *buffer __attribute__((unused)),
	  char *line __attribute__((unused)))
{
  reg1 int i;

  put_info("\nMySQL commands:",INFO_INFO);
unknown's avatar
unknown committed
1355 1356
  if (no_named_cmds)
    put_info("Note that all text commands must be first on line and end with ';'",INFO_INFO);
unknown's avatar
unknown committed
1357 1358 1359
  for (i = 0; commands[i].name; i++)
  {
    if (commands[i].func)
unknown's avatar
unknown committed
1360 1361
      tee_fprintf(stdout, "%s\t(\\%c)\t%s\n", commands[i].name,
		  commands[i].cmd_char, commands[i].doc);
unknown's avatar
unknown committed
1362 1363
  }
  if (connected)
unknown's avatar
unknown committed
1364 1365 1366
    tee_fprintf(stdout,
		"\nConnection id: %ld  (Can be used with mysqladmin kill)\n\n",
		mysql_thread_id(&mysql));
unknown's avatar
unknown committed
1367
  else
unknown's avatar
unknown committed
1368
    tee_fprintf(stdout, "Not connected!  Reconnect with 'connect'!\n\n");
unknown's avatar
unknown committed
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
  return 0;
}


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


/*
** Execute command
** Returns: 0  if ok
**	    -1 if not fatal error
**	    1  if fatal error
*/


static int
com_go(String *buffer,char *line __attribute__((unused)))
{
  char		buff[160],time_buff[32];
  MYSQL_RES	*result;
  ulong		timer;
  uint		error=0;

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

	/* Remove garbage for nicer messages */
  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
    return status.batch ? 1 : -1;		// Fatal error
  }
  if (verbose)
    (void) com_print(buffer,0);

  if (skip_updates &&
      (buffer->length() < 4 || my_sortcmp(buffer->ptr(),"SET ",4)))
  {
    (void) put_info("Ignoring query to other database",INFO_INFO);
    return 0;
  }

  timer=start_timer();
  for (uint retry=0;; retry++)
  {
    if (!mysql_real_query(&mysql,buffer->ptr(),buffer->length()))
      break;
    error=put_info(mysql_error(&mysql),INFO_ERROR, mysql_errno(&mysql));
unknown's avatar
unknown committed
1436 1437
    if (mysql_errno(&mysql) != CR_SERVER_GONE_ERROR || retry > 1 
	|| status.batch)
unknown's avatar
unknown committed
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480
    {
      buffer->length(0);			// Remove query on error
      return error;
    }
    if (reconnect())
    {
      buffer->length(0);			// Remove query on error
      return error;
    }
  }
  error=0;
  buffer->length(0);

  if (quick)
  {
    if (!(result=mysql_use_result(&mysql)) && mysql_field_count(&mysql))
    {
      return put_info(mysql_error(&mysql),INFO_ERROR,mysql_errno(&mysql));
    }
  }
  else
  {
    if (!(result=mysql_store_result(&mysql)))
    {
      if (mysql_error(&mysql)[0])
      {
	return put_info(mysql_error(&mysql),INFO_ERROR,mysql_errno(&mysql));
      }
    }
  }

  if (verbose >= 3 || !opt_silent)
    mysql_end_timer(timer,time_buff);
  else
    time_buff[0]=0;
  if (result)
  {
    if (!mysql_num_rows(result) && ! quick)
    {
      sprintf(buff,"Empty set%s",time_buff);
    }
    else
    {
unknown's avatar
unknown committed
1481
      init_pager();
unknown's avatar
unknown committed
1482 1483
      if (opt_html)
	print_table_data_html(result);
1484 1485
      else if (opt_xml)
	print_table_data_xml(result);
unknown's avatar
unknown committed
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495
      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%s",
	      (long) mysql_num_rows(result),
	      (long) mysql_num_rows(result) == 1 ? "row" : "rows",
	      time_buff);
unknown's avatar
unknown committed
1496
      end_pager();
unknown's avatar
unknown committed
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
    }
  }
  else if (mysql_affected_rows(&mysql) == ~(ulonglong) 0)
    sprintf(buff,"Query OK%s",time_buff);
  else
    sprintf(buff,"Query OK, %ld %s affected%s",
	    (long) mysql_affected_rows(&mysql),
	    (long) mysql_affected_rows(&mysql) == 1 ? "row" : "rows",
	    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_info(mysql_error(&mysql),INFO_ERROR,mysql_errno(&mysql));
  else if (unbuffered)
    fflush(stdout);
  mysql_free_result(result);
  return error;				/* New command follows */
}

unknown's avatar
unknown committed
1519 1520 1521

static void init_pager()
{
unknown's avatar
unknown committed
1522
#if !defined( __WIN__) && !defined( OS2)
unknown's avatar
unknown committed
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
  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
1538
#if !defined( __WIN__) && !defined( OS2)
unknown's avatar
unknown committed
1539 1540 1541 1542 1543 1544 1545
  if (!opt_nopager)
    pclose(PAGER);
#endif
}

static void init_tee()
{
1546
  if (!(OUTFILE= my_fopen(outfile, O_APPEND | O_WRONLY, MYF(MY_WME))))
unknown's avatar
unknown committed
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559
  {
    opt_outfile=0;
    init_pager();
    return;
  }
}

static void end_tee()
{
  my_fclose(OUTFILE, MYF(0));
  return;
}

unknown's avatar
unknown committed
1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
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
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
static void
print_field_types(MYSQL_RES *result)
{
  MYSQL_FIELD	*field;  
  while ((field = mysql_fetch_field(result)))
  {
    tee_fprintf(PAGER,"%s '%s' %d %d %d %d %d\n",
		field->name,
		field->table ? "" : field->table,
		(int) field->type,
		field->length, field->max_length, 
		field->flags, field->decimals);
  }
  tee_puts("", PAGER);
}

unknown's avatar
unknown committed
1587 1588 1589 1590 1591 1592 1593 1594 1595 1596

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

  num_flag=(bool*) my_alloca(sizeof(bool)*mysql_num_fields(result));
unknown's avatar
unknown committed
1597 1598 1599 1600 1601
  if (info_flag)
  {
    print_field_types(result);
    mysql_field_seek(result,0);
  }
unknown's avatar
unknown committed
1602 1603 1604
  separator.copy("+",1);
  while ((field = mysql_fetch_field(result)))
  {
unknown's avatar
unknown committed
1605
    uint length=skip_column_names ? 0 : (uint) strlen(field->name);
unknown's avatar
unknown committed
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615
    if (quick)
      length=max(length,field->length);
    else
      length=max(length,field->max_length);
    if (length < 4 && !IS_NOT_NULL(field->flags))
      length=4;					// Room for "NULL"
    field->max_length=length+1;
    separator.fill(separator.length()+length+2,'-');
    separator.append('+');
  }
unknown's avatar
unknown committed
1616
  tee_puts(separator.c_ptr(), PAGER);
unknown's avatar
unknown committed
1617 1618 1619
  if (!skip_column_names)
  {
    mysql_field_seek(result,0);
unknown's avatar
unknown committed
1620
    (void) tee_fputs("|", PAGER);
unknown's avatar
unknown committed
1621 1622
    for (uint off=0; (field = mysql_fetch_field(result)) ; off++)
    {
unknown's avatar
unknown committed
1623 1624
      tee_fprintf(PAGER, " %-*s|",min(field->max_length,MAX_COLUMN_LENGTH),
		  field->name);
unknown's avatar
unknown committed
1625 1626
      num_flag[off]= IS_NUM(field->type);
    }
unknown's avatar
unknown committed
1627 1628
    (void) tee_fputs("\n", PAGER);
    tee_puts(separator.c_ptr(), PAGER);
unknown's avatar
unknown committed
1629 1630 1631 1632
  }

  while ((cur = mysql_fetch_row(result)))
  {
unknown's avatar
unknown committed
1633
    (void) tee_fputs("|", PAGER);
unknown's avatar
unknown committed
1634 1635 1636
    mysql_field_seek(result,0);
    for (uint off=0 ; off < mysql_num_fields(result); off++)
    {
unknown's avatar
unknown committed
1637
      const char *str=cur[off] ? cur[off] : "NULL";
unknown's avatar
unknown committed
1638 1639
      field = mysql_fetch_field(result);
      uint length=field->max_length;
unknown's avatar
unknown committed
1640 1641 1642 1643 1644
      if (length > MAX_COLUMN_LENGTH)
      {
	tee_fputs(str,PAGER); tee_fputs(" |",PAGER);
      }
      else
unknown's avatar
unknown committed
1645
      tee_fprintf(PAGER, num_flag[off] ? "%*s |" : " %-*s|",
unknown's avatar
unknown committed
1646
		  length, str);
unknown's avatar
unknown committed
1647
    }
unknown's avatar
unknown committed
1648
    (void) tee_fputs("\n", PAGER);
unknown's avatar
unknown committed
1649
  }
unknown's avatar
unknown committed
1650
  tee_puts(separator.c_ptr(), PAGER);
unknown's avatar
unknown committed
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660
  my_afree((gptr) num_flag);
}

static void
print_table_data_html(MYSQL_RES *result)
{
  MYSQL_ROW   cur;
  MYSQL_FIELD *field;

  mysql_field_seek(result,0);
unknown's avatar
unknown committed
1661
  (void) tee_fputs("<TABLE BORDER=1><TR>", PAGER);
unknown's avatar
unknown committed
1662 1663 1664 1665
  if (!skip_column_names)
  {
    while((field = mysql_fetch_field(result)))
    {
unknown's avatar
unknown committed
1666 1667 1668
      tee_fprintf(PAGER, "<TH>%s</TH>", (field->name ? 
					 (field->name[0] ? field->name : 
					  " &nbsp; ") : "NULL"));
unknown's avatar
unknown committed
1669
    }
unknown's avatar
unknown committed
1670
    (void) tee_fputs("</TR>", PAGER);
unknown's avatar
unknown committed
1671 1672 1673
  }
  while ((cur = mysql_fetch_row(result)))
  {
unknown's avatar
unknown committed
1674
    (void) tee_fputs("<TR>", PAGER);
unknown's avatar
unknown committed
1675 1676 1677
    for (uint i=0; i < mysql_num_fields(result); i++)
    {
      ulong *lengths=mysql_fetch_lengths(result);
unknown's avatar
unknown committed
1678
      (void) tee_fputs("<TD>", PAGER);
unknown's avatar
unknown committed
1679
      safe_put_field(cur[i],lengths[i]);
unknown's avatar
unknown committed
1680
      (void) tee_fputs("</TD>", PAGER);
unknown's avatar
unknown committed
1681
    }
unknown's avatar
unknown committed
1682
    (void) tee_fputs("</TR>", PAGER);
unknown's avatar
unknown committed
1683
  }
unknown's avatar
unknown committed
1684
  (void) tee_fputs("</TABLE>", PAGER);
unknown's avatar
unknown committed
1685 1686 1687
}


1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730
static void
print_table_data_xml(MYSQL_RES *result)
{
  MYSQL_ROW   cur;
  MYSQL_FIELD *fields;

  mysql_field_seek(result,0);

  char *statement;
  statement=(char*) my_malloc(strlen(glob_buffer.ptr())*5+1, MYF(MY_WME));
  xmlencode(statement, (char*) glob_buffer.ptr());

  (void) my_chomp(strend(statement));

  tee_fprintf(PAGER,"<?xml version=\"1.0\"?>\n\n<resultset statement=\"%s\">", statement);

  my_free(statement,MYF(MY_ALLOW_ZERO_PTR));

  fields = mysql_fetch_fields(result);

  while ((cur = mysql_fetch_row(result)))
  {
    (void) tee_fputs("\n  <row>\n", PAGER);
    for (uint i=0; i < mysql_num_fields(result); i++)
    {
      char *data;
      ulong *lengths=mysql_fetch_lengths(result);
      data=(char*) my_malloc(lengths[i]*5+1, MYF(MY_WME));
      tee_fprintf(PAGER, "\t<%s>", (fields[i].name ?
				  (fields[i].name[0] ? fields[i].name :
				   " &nbsp; ") : "NULL"));
      xmlencode(data, cur[i]);
      safe_put_field(data, strlen(data));
      tee_fprintf(PAGER, "</%s>\n", (fields[i].name ?
				     (fields[i].name[0] ? fields[i].name :
				      " &nbsp; ") : "NULL"));
      my_free(data,MYF(MY_ALLOW_ZERO_PTR));
    }
    (void) tee_fputs("  </row>\n", PAGER);
  }
  (void) tee_fputs("</resultset>\n", PAGER);
}

unknown's avatar
unknown committed
1731 1732 1733 1734 1735 1736 1737 1738 1739 1740

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)))
  {
unknown's avatar
unknown committed
1741
    uint length=(uint) strlen(field->name);
unknown's avatar
unknown committed
1742 1743 1744 1745 1746 1747 1748 1749 1750
    if (length > max_length)
      max_length= length;
    field->max_length=length;
  }

  mysql_field_seek(result,0);
  for (uint row_count=1; (cur= mysql_fetch_row(result)); row_count++)
  {
    mysql_field_seek(result,0);
unknown's avatar
unknown committed
1751 1752
    tee_fprintf(PAGER, 
		"*************************** %d. row ***************************\n", row_count);
unknown's avatar
unknown committed
1753 1754 1755
    for (uint off=0; off < mysql_num_fields(result); off++)
    {
      field= mysql_fetch_field(result);
unknown's avatar
unknown committed
1756 1757
      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
1758 1759 1760 1761
    }
  }
}

unknown's avatar
unknown committed
1762 1763
static const char
*array_value(const char **array, char *key) {
1764 1765 1766 1767 1768 1769 1770
  int x;
  for(x=0; array[x]; x+=2)
    if(!strcmp(array[x], key))
      return array[x+1];
  return 0;
}

unknown's avatar
unknown committed
1771 1772 1773
static void
xmlencode(char *dest, char *src)
{
1774
  char *p = src;
unknown's avatar
unknown committed
1775
  const char *t;
1776 1777 1778
  char s[2] = { 0, 0 };
  *dest = 0;
  
unknown's avatar
unknown committed
1779 1780
  do
  {
1781
    s[0] = *p;
unknown's avatar
unknown committed
1782 1783 1784
    if (!(t=array_value(xmlmeta, s)))
      t = s;
    dest=strmov(dest, t);
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
  } while(*p++);
}

static void
my_chomp(char *end) {
  char *mend;
  mend = end;

  do {
    if (isspace(*mend)) {
      *mend = '\0';
    } else
      mend--;
  } while (mend && *mend);
}
    
unknown's avatar
unknown committed
1801 1802 1803 1804 1805

static void
safe_put_field(const char *pos,ulong length)
{
  if (!pos)
unknown's avatar
unknown committed
1806
    tee_fputs("NULL", PAGER);
unknown's avatar
unknown committed
1807 1808 1809
  else
  {
    if (opt_raw_data)
unknown's avatar
unknown committed
1810
      tee_fputs(pos, PAGER);
unknown's avatar
unknown committed
1811 1812 1813 1814 1815 1816 1817
    else for (const char *end=pos+length ; pos != end ; pos++)
    {
#ifdef USE_MB
      int l;
      if (use_mb(default_charset_info) &&
          (l = my_ismbchar(default_charset_info, pos, end))) {
	  while (l--)
1818
	    tee_putc(*pos++, PAGER);
unknown's avatar
unknown committed
1819 1820 1821 1822 1823
	  pos--;
	  continue;
      }
#endif
      if (!*pos)
unknown's avatar
unknown committed
1824
	tee_fputs("\\0", PAGER); // This makes everything hard
unknown's avatar
unknown committed
1825
      else if (*pos == '\t')
unknown's avatar
unknown committed
1826
	tee_fputs("\\t", PAGER); // This would destroy tab format
unknown's avatar
unknown committed
1827
      else if (*pos == '\n')
unknown's avatar
unknown committed
1828
	tee_fputs("\\n", PAGER); // This too
unknown's avatar
unknown committed
1829
      else if (*pos == '\\')
unknown's avatar
unknown committed
1830
	tee_fputs("\\\\", PAGER);
1831
	else
1832
	tee_putc(*pos, PAGER);
unknown's avatar
unknown committed
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
    }
  }
}


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

  if (opt_silent < 2 && !skip_column_names)
  {
    int first=0;
    while ((field = mysql_fetch_field(result)))
    {
      if (first++)
unknown's avatar
unknown committed
1851 1852
	(void) tee_fputs("\t", PAGER);
      (void) tee_fputs(field->name, PAGER);
unknown's avatar
unknown committed
1853
    }
unknown's avatar
unknown committed
1854
    (void) tee_fputs("\n", PAGER);
unknown's avatar
unknown committed
1855 1856 1857 1858 1859 1860 1861
  }
  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
1862
      (void) tee_fputs("\t", PAGER);
unknown's avatar
unknown committed
1863 1864
      safe_put_field(cur[off],lengths[off]);
    }
unknown's avatar
unknown committed
1865
    (void) tee_fputs("\n", PAGER);
unknown's avatar
unknown committed
1866 1867 1868
  }
}

unknown's avatar
unknown committed
1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906
static int
com_tee(String *buffer, char *line __attribute__((unused)))
{
  char file_name[FN_REFLEN], *end, *param;

  if (status.batch)
    return 0;
  while (isspace(*line))
    line++;
  if (!(param = strchr(line, ' '))) // if outfile wasn't given, use the default
  {
    if (!strlen(outfile))
    {
      printf("No previous outfile available, you must give the filename!\n");
      opt_outfile=0;
      return 0;
    }
  }
  else
  {
    while (isspace(*param))
      param++;
    end=strmake(file_name, param, sizeof(file_name)-1);
    while (end > file_name && (isspace(end[-1]) || iscntrl(end[-1])))
      end--;
    end[0]=0;
    strmov(outfile, file_name);
  }
  if (!strlen(outfile))
  {
    printf("No outfile specified!\n");
    return 0;
  }
  if (!opt_outfile)
  {
    init_tee();
    opt_outfile=1;
  }
1907
  tee_fprintf(stdout, "Logging to file '%s'\n", outfile);
unknown's avatar
unknown committed
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921
  return 0;
}

static int
com_notee(String *buffer __attribute__((unused)),
	  char *line __attribute__((unused)))
{
  if (opt_outfile)
    end_tee();
  opt_outfile=0;
  tee_fprintf(stdout, "Outfile disabled.\n");
  return 0;
}

1922 1923 1924 1925 1926
/*
** Sorry, this command is not available in Windows.
*/

#ifndef __WIN__
unknown's avatar
unknown committed
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
static int
com_pager(String *buffer, char *line __attribute__((unused)))
{
  char pager_name[FN_REFLEN], *end, *param;

  if (status.batch)
    return 0;
  /* Skip space from file name */
  while (isspace(*line))
    line++;
  if (!(param = strchr(line, ' '))) // if pager was not given, use the default
  {
    if (!strlen(default_pager))
    {
unknown's avatar
unknown committed
1941
      tee_fprintf(stdout, "Default pager wasn't set, using stdout.\n");
unknown's avatar
unknown committed
1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957
      opt_nopager=1;
      strmov(pager, "stdout");
      PAGER= stdout;
      return 0;
    }
    strmov(pager, default_pager);
  }
  else
  {
    while (isspace(*param))
      param++;
    end=strmake(pager_name, param, sizeof(pager_name)-1);
    while (end > pager_name && (isspace(end[-1]) || iscntrl(end[-1])))
      end--;
    end[0]=0;
    strmov(pager, pager_name);
1958
    strmov(default_pager, pager_name);
unknown's avatar
unknown committed
1959 1960 1961 1962 1963 1964
  }
  opt_nopager=0;
  tee_fprintf(stdout, "PAGER set to %s\n", pager);
  return 0;
}

1965

unknown's avatar
unknown committed
1966 1967 1968 1969 1970 1971 1972 1973 1974
static int
com_nopager(String *buffer __attribute__((unused)),
	    char *line __attribute__((unused)))
{
  strmov(pager, "stdout");
  opt_nopager=1;
  tee_fprintf(stdout, "PAGER set to stdout\n");
  return 0;
}
1975
#endif
unknown's avatar
unknown committed
1976

unknown's avatar
unknown committed
1977

1978 1979 1980 1981 1982
/*
** Sorry, you can't send the result to an editor in Win32
*/

#ifndef __WIN__
unknown's avatar
unknown committed
1983 1984 1985
static int
com_edit(String *buffer,char *line __attribute__((unused)))
{
1986
  char	filename[FN_REFLEN],buff[160];
unknown's avatar
unknown committed
1987 1988 1989
  int	fd,tmp;
  const char *editor;

1990 1991
  if ((fd=create_temp_file(filename,NullS,"sql", O_CREAT | O_WRONLY,
			   MYF(MY_WME))) < 0)
unknown's avatar
unknown committed
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020
    goto err;
  if (buffer->is_empty() && !old_buffer.is_empty())
    (void) my_write(fd,(byte*) old_buffer.ptr(),old_buffer.length(),
		    MYF(MY_WME));
  else
    (void) my_write(fd,(byte*) buffer->ptr(),buffer->length(),MYF(MY_WME));
  (void) my_close(fd,MYF(0));

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

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

unknown's avatar
unknown committed
2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046

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

static int
com_quit(String *buffer __attribute__((unused)),
	 char *line __attribute__((unused)))
{
  status.exit_status=0;
  return 1;
}

static int
com_rehash(String *buffer __attribute__((unused)),
	 char *line __attribute__((unused)))
{
#ifdef HAVE_READLINE
  build_completion_hash(0,0);
#endif
  return 0;
}

static int
com_print(String *buffer,char *line __attribute__((unused)))
{
unknown's avatar
unknown committed
2047 2048
  tee_puts("--------------", stdout);
  (void) tee_fputs(buffer->c_ptr(), stdout);
unknown's avatar
unknown committed
2049
  if (!buffer->length() || (*buffer)[buffer->length()-1] != '\n')
2050
    tee_putc('\n', stdout);
unknown's avatar
unknown committed
2051
  tee_puts("--------------\n", stdout);
unknown's avatar
unknown committed
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
  return 0;					/* If empty buffer */
}

	/* ARGSUSED */
static int
com_connect(String *buffer, char *line)
{
  char *tmp,buff[256];
  bool save_rehash=no_rehash;
  int error;

  if (buffer)
  {
    while (isspace(*line))
      line++;
    strnmov(buff,line,sizeof(buff)-1);		// Don't destroy history
    if (buff[0] == '\\')			// Short command
      buff[1]=' ';
unknown's avatar
unknown committed
2070
    tmp=(char *) strtok(buff," \t");		// Skip connect command
unknown's avatar
unknown committed
2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
    if (tmp && (tmp=(char *) strtok(NullS," \t;")))
    {
      my_free(current_db,MYF(MY_ALLOW_ZERO_PTR));
      current_db=my_strdup(tmp,MYF(MY_WME));
      if ((tmp=(char *) strtok(NullS," \t;")))
      {
	my_free(current_host,MYF(MY_ALLOW_ZERO_PTR));
	current_host=my_strdup(tmp,MYF(MY_WME));
      }
    }
    else
      no_rehash=1;				// Quick re-connect
    buffer->length(0);				// command used
  }
  else
    no_rehash=1;
  error=sql_connect(current_host,current_db,current_user,opt_password,0);
  no_rehash=save_rehash;

  if (connected)
  {
    sprintf(buff,"Connection id:    %ld",mysql_thread_id(&mysql));
    put_info(buff,INFO_INFO);
    sprintf(buff,"Current database: %s\n",
unknown's avatar
unknown committed
2095
	    current_db ? current_db : "*** NONE ***");
unknown's avatar
unknown committed
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112
    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 */
  while (isspace(*line))
    line++;
unknown's avatar
unknown committed
2113 2114 2115
  if (!(param = strchr(line, ' ')))		// Skip command name
    return put_info("Usage: \\. <filename> | source <filename>", 
		    INFO_ERROR, 0);
unknown's avatar
unknown committed
2116 2117 2118 2119 2120 2121
  while (isspace(*param))
    param++;
  end=strmake(source_name,param,sizeof(source_name)-1);
  while (end > source_name && (isspace(end[-1]) || iscntrl(end[-1])))
    end--;
  end[0]=0;
unknown's avatar
unknown committed
2122
  unpack_filename(source_name,source_name);
unknown's avatar
unknown committed
2123
  /* open file name */
unknown's avatar
unknown committed
2124
  if (!(sql_file = my_fopen(source_name, O_RDONLY | O_BINARY,MYF(0))))
unknown's avatar
unknown committed
2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164
  {
    char buff[FN_REFLEN+60];
    sprintf(buff,"Failed to open file '%s', error: %d", source_name,errno);
    return put_info(buff, INFO_ERROR, 0);
  }

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

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

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


	/* ARGSUSED */
static int
com_use(String *buffer __attribute__((unused)), char *line)
{
  char *tmp;
  char buff[256];

  while (isspace(*line))
    line++;
  strnmov(buff,line,sizeof(buff)-1);		// Don't destroy history
  if (buff[0] == '\\')				// Short command
    buff[1]=' ';
unknown's avatar
unknown committed
2165
  tmp=(char *) strtok(buff," \t;");		// Skip connect command
unknown's avatar
unknown committed
2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192
  if (!tmp || !(tmp=(char *) strtok(NullS," \t;")))
  {
    put_info("USE must be followed by a database name",INFO_ERROR);
    return 0;
  }
  if (!current_db || cmp_database(current_db,tmp))
  {
    if (one_database)
      skip_updates=1;
    else
    {
      /*
	reconnect once if connection is down or if connection was found to
	be down during query
      */
      if (!connected && reconnect())
	return status.batch ? 1 : -1;			// Fatal error
      if (mysql_select_db(&mysql,tmp))
      {
	if (mysql_errno(&mysql) != CR_SERVER_GONE_ERROR)
	  return put_info(mysql_error(&mysql),INFO_ERROR,mysql_errno(&mysql));

	if (reconnect())
	  return status.batch ? 1 : -1;			// Fatal error
	if (mysql_select_db(&mysql,tmp))
	  return put_info(mysql_error(&mysql),INFO_ERROR,mysql_errno(&mysql));
      }
unknown's avatar
unknown committed
2193 2194
      my_free(current_db,MYF(MY_ALLOW_ZERO_PTR));
      current_db=my_strdup(tmp,MYF(MY_WME));
unknown's avatar
unknown committed
2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215
#ifdef HAVE_READLINE
      build_completion_hash(no_rehash,1);
#endif
    }
  }
  else
    skip_updates=0;
  put_info("Database changed",INFO_INFO);
  return 0;
}


static int
sql_real_connect(char *host,char *database,char *user,char *password,
		 uint silent)
{
  if (connected)
  {					/* if old is open, close it first */
    mysql_close(&mysql);
    connected= 0;
  }
2216
#ifdef HAVE_OPENSSL
2217 2218 2219
  else
    mysql_ssl_clear(&mysql); /* SSL data structres should be freed 
				even if connection was not made */
2220
#endif
unknown's avatar
unknown committed
2221
  mysql_init(&mysql);
unknown's avatar
unknown committed
2222
  if (opt_connect_timeout)
2223 2224
  {
    uint timeout=opt_connect_timeout;
unknown's avatar
unknown committed
2225
    mysql_options(&mysql,MYSQL_OPT_CONNECT_TIMEOUT,
2226 2227
		  (char*) &timeout);
  }
unknown's avatar
unknown committed
2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277
  if (opt_compress)
    mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);
#ifdef HAVE_OPENSSL
  if (opt_use_ssl)
    mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
		  opt_ssl_capath);
#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);
  }
  if (!mysql_real_connect(&mysql,host,user,password,
			  database,opt_mysql_port,opt_mysql_unix_port,
			  connect_flag))
  {
    if (!silent ||
	(mysql_errno(&mysql) != CR_CONN_HOST_ERROR &&
	 mysql_errno(&mysql) != CR_CONNECTION_ERROR))
    {
      put_info(mysql_error(&mysql),INFO_ERROR,mysql_errno(&mysql));
      (void) fflush(stdout);
      return ignore_errors ? -1 : 1;		// Abort
    }
    return -1;					// Retryable
  }
  connected=1;
  mysql.reconnect=info_flag ? 1 : 0; // We want to know if this happens
#ifdef HAVE_READLINE
  build_completion_hash(no_rehash,1);
#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
2278
	tee_fputs("\n", stderr);
unknown's avatar
unknown committed
2279 2280 2281 2282 2283 2284 2285 2286 2287
	(void) fflush(stderr);
      }
      return error;
    }
    if (!wait_flag)
      return ignore_errors ? -1 : 1;
    if (!message && !silent)
    {
      message=1;
unknown's avatar
unknown committed
2288
      tee_fputs("Waiting",stderr); (void) fflush(stderr);
unknown's avatar
unknown committed
2289
    }
unknown's avatar
unknown committed
2290
    (void) sleep(wait_time);
unknown's avatar
unknown committed
2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305
    if (!silent)
    {
      putc('.',stderr); (void) fflush(stderr);
      count++;
    }
  }
}



static int
com_status(String *buffer __attribute__((unused)),
	   char *line __attribute__((unused)))
{
  char *status;
unknown's avatar
unknown committed
2306
  tee_puts("--------------", stdout);
unknown's avatar
unknown committed
2307 2308 2309 2310 2311
  usage(1);					/* Print version */
  if (connected)
  {
    MYSQL_RES *result;
    LINT_INIT(result);
unknown's avatar
unknown committed
2312
    tee_fprintf(stdout, "\nConnection id:\t\t%ld\n",mysql_thread_id(&mysql));
unknown's avatar
unknown committed
2313 2314 2315 2316
    if (!mysql_query(&mysql,"select DATABASE(),USER()") &&
	(result=mysql_use_result(&mysql)))
    {
      MYSQL_ROW cur=mysql_fetch_row(result);
unknown's avatar
unknown committed
2317 2318
      tee_fprintf(stdout, "Current database:\t%s\n",cur[0]);
      tee_fprintf(stdout, "Current user:\t\t%s\n",cur[1]);
unknown's avatar
unknown committed
2319 2320 2321 2322 2323 2324
      (void) mysql_fetch_row(result);		// Read eof
    }
  }
  else
  {
    vidattr(A_BOLD);
unknown's avatar
unknown committed
2325
    tee_fprintf(stdout, "\nNo connection\n");
unknown's avatar
unknown committed
2326 2327 2328 2329 2330 2331
    vidattr(A_NORMAL);
    return 0;
  }
  if (skip_updates)
  {
    vidattr(A_BOLD);
unknown's avatar
unknown committed
2332
    tee_fprintf(stdout, "\nAll updates ignored to this database\n");
unknown's avatar
unknown committed
2333 2334
    vidattr(A_NORMAL);
  }
unknown's avatar
unknown committed
2335 2336
#ifndef __WIN__
  tee_fprintf(stdout, "Current pager:\t\t%s\n", pager);
2337
  tee_fprintf(stdout, "Using outfile:\t\t'%s'\n", opt_outfile ? outfile : "");
unknown's avatar
unknown committed
2338 2339 2340 2341
#endif
  tee_fprintf(stdout, "Server version:\t\t%s\n", mysql_get_server_info(&mysql));
  tee_fprintf(stdout, "Protocol version:\t%d\n", mysql_get_proto_info(&mysql));
  tee_fprintf(stdout, "Connection:\t\t%s\n", mysql_get_host_info(&mysql));
unknown's avatar
unknown committed
2342 2343 2344
  tee_fprintf(stdout, "Client characterset:\t%s\n",
	      default_charset_info->name);
  tee_fprintf(stdout, "Server characterset:\t%s\n", mysql.charset->name);
unknown's avatar
unknown committed
2345
  if (strstr(mysql_get_host_info(&mysql),"TCP/IP") || ! mysql.unix_socket)
unknown's avatar
unknown committed
2346
    tee_fprintf(stdout, "TCP port:\t\t%d\n", mysql.port);
unknown's avatar
unknown committed
2347
  else
unknown's avatar
unknown committed
2348
    tee_fprintf(stdout, "UNIX socket:\t\t%s\n", mysql.unix_socket);
2349 2350 2351
  if (mysql.net.compress)
    tee_fprintf(stdout, "Protocol:\t\tCompressed\n");

unknown's avatar
unknown committed
2352 2353 2354 2355 2356 2357
  if ((status=mysql_stat(&mysql)) && !mysql_error(&mysql)[0])
  {
    char *pos,buff[40];
    ulong sec;
    pos=strchr(status,' ');
    *pos++=0;
unknown's avatar
unknown committed
2358
    tee_fprintf(stdout, "%s\t\t\t", status);	/* print label */
unknown's avatar
unknown committed
2359 2360 2361
    if ((status=str2int(pos,10,0,LONG_MAX,(long*) &sec)))
    {
      nice_time((double) sec,buff,0);
unknown's avatar
unknown committed
2362
      tee_puts(buff, stdout);			/* print nice time */
unknown's avatar
unknown committed
2363 2364 2365 2366
      while (*status == ' ') status++;		/* to next info */
    }
    if (status)
    {
2367
      tee_putc('\n', stdout);
unknown's avatar
unknown committed
2368
      tee_puts(status, stdout);
unknown's avatar
unknown committed
2369 2370 2371 2372 2373
    }
  }
  if (safe_updates)
  {
    vidattr(A_BOLD);
unknown's avatar
unknown committed
2374
    tee_fprintf(stdout, "\nNote that you are running in safe_update_mode:\n");
unknown's avatar
unknown committed
2375
    vidattr(A_NORMAL);
unknown's avatar
unknown committed
2376
    tee_fprintf(stdout, "\
unknown's avatar
unknown committed
2377 2378 2379
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
2380
Max number of examined row combination in a join is set to: %lu\n\n",
unknown's avatar
unknown committed
2381
select_limit, max_join_size);
unknown's avatar
unknown committed
2382
  }
unknown's avatar
unknown committed
2383
  tee_puts("--------------\n", stdout);
unknown's avatar
unknown committed
2384 2385 2386 2387 2388 2389 2390 2391
  return 0;
}


static int
put_info(const char *str,INFO_TYPE info_type,uint error)
{
  static int inited=0;
unknown's avatar
unknown committed
2392
  
unknown's avatar
unknown committed
2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
  if (status.batch)
  {
    if (info_type == INFO_ERROR)
    {
      (void) fflush(stdout);
      fprintf(stderr,"ERROR");
      if (error)
	(void) fprintf(stderr," %d",error);
      if (status.query_start_line && ! skip_line_numbers)
      {
	(void) fprintf(stderr," at line %lu",status.query_start_line);
	if (status.file_name)
	  (void) fprintf(stderr," in file: '%s'", status.file_name);
      }
      (void) fprintf(stderr,": %s\n",str);
      (void) fflush(stderr);
      if (!ignore_errors)
	return 1;
    }
    else if (info_type == INFO_RESULT && verbose > 1)
unknown's avatar
unknown committed
2413
      tee_puts(str, stdout);
unknown's avatar
unknown committed
2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431
    if (unbuffered)
      fflush(stdout);
    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)
    {
      putchar('\007');				/* This should make a bell */
      vidattr(A_STANDOUT);
      if (error)
unknown's avatar
unknown committed
2432
        (void) tee_fprintf(stderr, "ERROR %d: ", error);
unknown's avatar
unknown committed
2433
      else
unknown's avatar
unknown committed
2434
        tee_puts("ERROR: ", stdout);
unknown's avatar
unknown committed
2435 2436 2437
    }
    else
      vidattr(A_BOLD);
unknown's avatar
unknown committed
2438
    (void) tee_puts(str, stdout);
unknown's avatar
unknown committed
2439 2440 2441 2442 2443 2444 2445
    vidattr(A_NORMAL);
  }
  if (unbuffered)
    fflush(stdout);
  return info_type == INFO_ERROR ? -1 : 0;
}

unknown's avatar
unknown committed
2446

unknown's avatar
unknown committed
2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
static void remove_cntrl(String &buffer)
{
  char *start,*end;
  end=(start=(char*) buffer.ptr())+buffer.length();
  while (start < end && !isgraph(end[-1]))
    end--;
  buffer.length((uint) (end-start));
}


unknown's avatar
unknown committed
2457 2458 2459 2460 2461
void tee_fprintf(FILE *file, const char *fmt, ...)
{
  va_list args;

  va_start(args, fmt);
unknown's avatar
unknown committed
2462
  (void) vfprintf(file, fmt, args);
unknown's avatar
unknown committed
2463 2464 2465
#ifdef OS2
  fflush( file);
#endif
unknown's avatar
unknown committed
2466
  if (opt_outfile)
unknown's avatar
unknown committed
2467
    (void) vfprintf(OUTFILE, fmt, args);
unknown's avatar
unknown committed
2468 2469 2470 2471 2472 2473 2474
  va_end(args);
}


void tee_fputs(const char *s, FILE *file)
{
  fputs(s, file);
unknown's avatar
unknown committed
2475 2476 2477
#ifdef OS2
  fflush( file);
#endif
unknown's avatar
unknown committed
2478 2479 2480 2481 2482 2483 2484 2485 2486
  if (opt_outfile)
    fputs(s, OUTFILE);
}


void tee_puts(const char *s, FILE *file)
{
  fputs(s, file);
  fputs("\n", file);
unknown's avatar
unknown committed
2487 2488 2489
#ifdef OS2
  fflush( file);
#endif
unknown's avatar
unknown committed
2490 2491 2492 2493 2494 2495 2496
  if (opt_outfile)
  {
    fputs(s, OUTFILE);
    fputs("\n", OUTFILE);
  }
}

2497 2498 2499
void tee_putc(int c, FILE *file)
{
  putc(c, file);
unknown's avatar
unknown committed
2500 2501 2502
#ifdef OS2
  fflush( file);
#endif
2503 2504 2505 2506
  if (opt_outfile)
    putc(c, OUTFILE);
}

unknown's avatar
unknown committed
2507
#if defined( __WIN__) || defined( OS2)
unknown's avatar
unknown committed
2508 2509 2510 2511 2512 2513 2514 2515 2516
#include <time.h>
#else
#include <sys/times.h>
#undef CLOCKS_PER_SEC
#define CLOCKS_PER_SEC (sysconf(_SC_CLK_TCK))
#endif

static ulong start_timer(void)
{
unknown's avatar
unknown committed
2517
#if defined( __WIN__) || defined( OS2)
unknown's avatar
unknown committed
2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571
 return clock();
#else
  struct tms tms_tmp;
  return times(&tms_tmp);
#endif
}


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


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


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

2572
#ifndef EMBEDDED_SERVER
unknown's avatar
unknown committed
2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583
/* Keep sql_string library happy */

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

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