mysql.cc 74.6 KB
Newer Older
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1
/* Copyright (C) 2000-2003 MySQL AB
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2

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

bk@work.mysql.com's avatar
bk@work.mysql.com committed
8 9 10 11
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
12

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

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

monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
32
#include "client_priv.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
33
#include <m_ctype.h>
34
#include <stdarg.h>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
35 36
#include <my_dir.h>
#ifndef __GNU_LIBRARY__
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
37
#define __GNU_LIBRARY__		      // Skip warnings in getopt.h
bk@work.mysql.com's avatar
bk@work.mysql.com committed
38 39 40
#endif
#include "my_readline.h"
#include <signal.h>
tonu@x153.internalnet's avatar
tonu@x153.internalnet committed
41
#include <violite.h>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
42

43
const char *VER= "12.22";
44

monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
45 46 47
/* Don't try to make a nice table if the data is too big */
#define MAX_COLUMN_LENGTH	     1024

jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
48
gptr sql_alloc(unsigned size);	     // Don't use mysqld alloc for these
bk@work.mysql.com's avatar
bk@work.mysql.com committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62
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))
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
63
#include <asm/termbits.h>		// Standard linux
bk@work.mysql.com's avatar
bk@work.mysql.com committed
64 65 66 67 68 69 70 71
#endif
#undef VOID
#if defined(HAVE_TERMCAP_H)
#include <termcap.h>
#else
#ifdef HAVE_CURSES_H
#include <curses.h>
#endif
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
72
#undef SYSV				// hack to avoid syntax error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
73 74 75 76 77 78
#ifdef HAVE_TERM_H
#include <term.h>
#endif
#endif
#endif

jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
79
#undef bcmp				// Fix problem with new readline
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
80
#if defined( __WIN__) || defined(OS2)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
81
#include <conio.h>
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
82
#elif !defined(__NETWARE__)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
83 84 85 86 87 88 89 90
#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
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
91
#define vidattr(A) {}			// Can't get this to work
bk@work.mysql.com's avatar
bk@work.mysql.com committed
92 93
#endif

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
94
#ifdef FN_NO_CASE_SENCE
bk@work.mysql.com's avatar
bk@work.mysql.com committed
95 96 97 98 99
#define cmp_database(A,B) my_strcasecmp((A),(B))
#else
#define cmp_database(A,B) strcmp((A),(B))
#endif

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
100 101 102 103
#if !defined( __WIN__) && !defined( OS2) && !defined(__NETWARE__) && (!defined(HAVE_mit_thread) || !defined(THREAD))
#define USE_POPEN
#endif

bk@work.mysql.com's avatar
bk@work.mysql.com committed
104 105
#include "completion_hash.h"

jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
106 107
#define PROMPT_CHAR '\\'

bk@work.mysql.com's avatar
bk@work.mysql.com committed
108 109 110 111 112 113 114 115 116 117 118
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;
119
static char **defaults_argv;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
120 121 122 123 124

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

static MYSQL mysql;			/* The connection */
125 126
static my_bool info_flag=0,ignore_errors=0,wait_flag=0,quick=0,
               connected=0,opt_raw_data=0,unbuffered=0,output_tables=0,
127
	       rehash=1,skip_updates=0,safe_updates=0,one_database=0,
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
128
	       opt_compress=0, using_opt_local_infile=0,
129 130
	       vertical=0, line_numbers=1, column_names=1,opt_html=0,
               opt_xml=0,opt_nopager=1, opt_outfile=0, named_cmds= 0,
131
               tty_password= 0, opt_nobeep=0;
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
132
static uint verbose=0,opt_silent=0,opt_mysql_port=0, opt_local_infile=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
133 134 135
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,
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
136
            *current_prompt=0, *default_charset;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
137 138
static char *histfile;
static String glob_buffer,old_buffer;
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
139 140
static String processed_prompt;
static char *full_username=0,*part_username=0,*default_prompt=0;
141
static int wait_time = 5;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
142
static STATUS status;
143
static ulong select_limit,max_join_size,opt_connect_timeout=0;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
144
static char mysql_charsets_dir[FN_REFLEN+1];
145
static const char *xmlmeta[] = {
146 147 148 149
  "&", "&amp;",
  "<", "&lt;",
  0, 0
};
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
150 151 152 153 154 155 156 157
static const char *day_names[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
static const char *month_names[]={"Jan","Feb","Mar","Apr","May","Jun","Jul",
			    "Aug","Sep","Oct","Nov","Dec"};
static char default_pager[FN_REFLEN];
static char pager[FN_REFLEN], outfile[FN_REFLEN];
static FILE *PAGER, *OUTFILE;
static MEM_ROOT hash_mem_root;
static uint prompt_counter;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
158 159 160 161 162 163 164

#include "sslopt-vars.h"

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

jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
165 166 167
void tee_fprintf(FILE *file, const char *fmt, ...);
void tee_fputs(const char *s, FILE *file);
void tee_puts(const char *s, FILE *file);
168
void tee_putc(int c, FILE *file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
169 170 171 172
/* 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*),
173
	   com_print(String *str,char*),
bk@work.mysql.com's avatar
bk@work.mysql.com committed
174 175 176
	   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*),
177
	   com_rehash(String *str, char*), com_tee(String *str, char*),
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
178
           com_notee(String *str, char*),
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
179
           com_prompt(String *str, char*);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
180

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
181
#ifdef USE_POPEN
182
static int com_nopager(String *str, char*), com_pager(String *str, char*),
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
183
           com_edit(String *str,char*), com_shell(String *str, char *);
184 185
#endif

bk@work.mysql.com's avatar
bk@work.mysql.com committed
186 187 188 189 190
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);
191
static void xmlencode_print(const char *src, uint length);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
192 193
static void init_pager();
static void end_pager();
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
194
static void init_tee(const char *);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
195
static void end_tee();
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
196 197 198
static const char* construct_prompt();
static void init_username();
static void add_int_to_prompt(int toadd);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
199 200 201 202 203 204 205 206 207 208 209 210 211

/* 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[] = {
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
212 213 214
  { "help",   'h', com_help,   0, "Display this help." },
  { "?",      '?', com_help,   0, "Synonym for `help'." },
  { "clear",  'c', com_clear,  0, "Clear command."},
215
  { "connect",'r', com_connect,1,
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
216
    "Reconnect to the server. Optional arguments are db and host." },
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
217
#ifdef USE_POPEN
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
218
  { "edit",   'e', com_edit,   0, "Edit command with $EDITOR."},
219
#endif
220
  { "ego",    'G', com_ego,    0,
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
221 222 223
    "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." },
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
224
#ifdef USE_POPEN
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
225 226 227
  { "nopager",'n', com_nopager,0, "Disable pager, print to stdout." },
#endif
  { "notee",  't', com_notee,  0, "Don't write into outfile." },
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
228
#ifdef USE_POPEN
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
229 230 231 232
  { "pager",  'P', com_pager,  1, 
    "Set PAGER [to_pager]. Print the query results via PAGER." },
#endif
  { "print",  'p', com_print,  0, "Print current command." },
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
233
  { "prompt", 'R', com_prompt, 1, "Change your mysql prompt."},
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
234 235
  { "quit",   'q', com_quit,   0, "Quit mysql." },
  { "rehash", '#', com_rehash, 0, "Rebuild completion hash." },
bk@work.mysql.com's avatar
bk@work.mysql.com committed
236
  { "source", '.', com_source, 1,
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
237 238
    "Execute a SQL script file. Takes a file name as an argument."},
  { "status", 's', com_status, 0, "Get status information from the server."},
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
239
#ifdef USE_POPEN
240 241
  { "system", '!', com_shell,  1, "Execute a system shell command."},
#endif
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
242 243
  { "tee",    'T', com_tee,    1, 
    "Set outfile [to_outfile]. Append everything into given outfile." },
244
  { "use",    'u', com_use,    1,
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
245
    "Use another database. Takes database name as argument." },
bk@work.mysql.com's avatar
bk@work.mysql.com committed
246

jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
247
  /* Get bash-like expansion for some commands */
248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
  { "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, ""}
bk@work.mysql.com's avatar
bk@work.mysql.com committed
267 268 269
};

static const char *load_default_groups[]= { "mysql","client",0 };
270 271
static const char *server_default_groups[]=
{ "server", "embedded", "mysql_SERVER", 0 };
bk@work.mysql.com's avatar
bk@work.mysql.com committed
272 273 274 275 276 277 278 279 280 281 282 283 284

#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);
285
static void print_table_data_xml(MYSQL_RES *result);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
static void print_tab_data(MYSQL_RES *result);
static void print_table_data_vertically(MYSQL_RES *result);
static ulong start_timer(void);
static void end_timer(ulong start_time,char *buff);
static void mysql_end_timer(ulong start_time,char *buff);
static void nice_time(double sec,char *buff,bool part_second);
static sig_handler mysql_end(int sig);


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

  MY_INIT(argv[0]);
  DBUG_ENTER("main");
  DBUG_PROCESS(argv[0]);

jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
303 304 305 306 307 308
  default_prompt = my_strdup(getenv("MYSQL_PS1") ? 
			     getenv("MYSQL_PS1") : 
			     "mysql> ",MYF(MY_WME));
  current_prompt = my_strdup(default_prompt,MYF(MY_WME));
  prompt_counter=0;

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
309 310
  outfile[0]=0;			// no (default) outfile
  strmov(pager, "stdout");	// the default, if --pager wasn't given
311 312 313 314 315
  {
    char *tmp=getenv("PAGER");
    if (tmp)
      strmov(default_pager,tmp);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
316 317 318 319 320 321 322 323 324
  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);
325
  defaults_argv=argv;
326
  if (get_options(argc, (char **) argv))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
327
  {
328
    free_defaults(defaults_argv);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
329 330 331 332 333
    my_end(0);
    exit(1);
  }
  if (status.batch && !status.line_buff &&
      !(status.line_buff=batch_readline_init(max_allowed_packet+512,stdin)))
334 335
  {
    free_defaults(defaults_argv);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
336
    exit(1);
337
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
338
  glob_buffer.realloc(512);
339 340 341
  mysql_server_init(0, NULL, (char**) server_default_groups);
  completion_hash_init(&ht, 128);
  init_alloc_root(&hash_mem_root, 16384, 0);
342
  bzero((char*) &mysql, sizeof(mysql));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
343 344 345
  if (sql_connect(current_host,current_db,current_user,opt_password,
		  opt_silent))
  {
346 347 348
    quick=1;					// Avoid history
    status.exit_status=1;
    mysql_end(-1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
349 350 351 352 353
  }
  if (!status.batch)
    ignore_errors=1;				// Don't abort monitor
  signal(SIGINT, mysql_end);			// Catch SIGINT to clean up

jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
354
  /*
355
    Run in interactive mode like the ingres/postgres monitor
bk@work.mysql.com's avatar
bk@work.mysql.com committed
356 357 358 359 360
  */

  put_info("Welcome to the MySQL monitor.  Commands end with ; or \\g.",
	   INFO_INFO);
  sprintf((char*) glob_buffer.ptr(),
361
	  "Your MySQL connection id is %lu to server version: %s\n",
bk@work.mysql.com's avatar
bk@work.mysql.com committed
362 363 364 365 366
	  mysql_thread_id(&mysql),mysql_get_server_info(&mysql));
  put_info((char*) glob_buffer.ptr(),INFO_INFO);

#ifdef HAVE_READLINE
  initialize_readline(my_progname);
367
  if (!status.batch && !quick && !opt_html && !opt_xml)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
368
  {
369
    /* read-history from file, default ~/.mysql_history*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
370 371 372 373
    if (getenv("MYSQL_HISTFILE"))
      histfile=my_strdup(getenv("MYSQL_HISTFILE"),MYF(MY_WME));
    else if (getenv("HOME"))
    {
374 375
      histfile=(char*) my_malloc((uint) strlen(getenv("HOME"))
				 + (uint) strlen("/.mysql_history")+2,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
376 377 378 379 380 381 382
				 MYF(MY_WME));
      if (histfile)
	sprintf(histfile,"%s/.mysql_history",getenv("HOME"));
    }
    if (histfile)
    {
      if (verbose)
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
383
	tee_fprintf(stdout, "Reading history-file %s\n",histfile);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
384 385 386 387
      read_history(histfile);
    }
  }
#endif
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
388
  sprintf(buff, 
389
	  "Type 'help;' or '\\h' for help. Type '\\c' to clear the buffer.\n");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
390 391
  put_info(buff,INFO_INFO);
  status.exit_status=read_lines(1);		// read lines and execute them
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
392 393
  if (opt_outfile)
    end_tee();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
394 395 396 397 398 399 400 401
  mysql_end(0);
#ifndef _lint
  DBUG_RETURN(0);				// Keep compiler happy
#endif
}

sig_handler mysql_end(int sig)
{
402
  mysql_close(&mysql);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
403
#ifdef HAVE_READLINE
404
  if (!status.batch && !quick && !opt_html && !opt_xml)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
405 406 407
  {
    /* write-history */
    if (verbose)
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
408
      tee_fprintf(stdout, "Writing history-file %s\n",histfile);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
409 410 411 412
    write_history(histfile);
  }
  batch_readline_end(status.line_buff);
  completion_hash_free(&ht);
413 414
  free_root(&hash_mem_root,MYF(0));

bk@work.mysql.com's avatar
bk@work.mysql.com committed
415
#endif
416 417
  if (sig >= 0)
    put_info(sig ? "Aborted" : "Bye", INFO_RESULT);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
418 419
  glob_buffer.free();
  old_buffer.free();
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
420
  processed_prompt.free();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
421 422 423 424 425 426
  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));
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
427 428 429 430
  my_free(full_username,MYF(MY_ALLOW_ZERO_PTR));
  my_free(part_username,MYF(MY_ALLOW_ZERO_PTR));
  my_free(default_prompt,MYF(MY_ALLOW_ZERO_PTR));
  my_free(current_prompt,MYF(MY_ALLOW_ZERO_PTR));
431
  mysql_server_end();
432
  free_defaults(defaults_argv);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
433 434 435 436
  my_end(info_flag ? MY_CHECK_ERROR | MY_GIVE_INFO : 0);
  exit(status.exit_status);
}

437 438

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


static void usage(int version)
{
593 594
  printf("%s  Ver %s Distrib %s, for %s (%s)\n",
	 my_progname, VER, MYSQL_SERVER_VERSION, SYSTEM_TYPE, MACHINE_TYPE);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
595 596
  if (version)
    return;
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
597
  printf("\
598
Copyright (C) 2002 MySQL AB\n\
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
599 600
This software comes with ABSOLUTELY NO WARRANTY. This is free software,\n\
and you are welcome to modify and redistribute it under the GPL license\n");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
601
  printf("Usage: %s [OPTIONS] [database]\n", my_progname);
602
  my_print_help(my_long_options);
603
  print_defaults("my", load_default_groups);
604
  my_print_variables(my_long_options);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
605 606
}

607 608 609
static my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
	       char *argument)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
610
{
611
  switch(optid) {
612 613 614 615 616 617 618 619 620 621
  case OPT_CHARSETS_DIR:
    strmov(mysql_charsets_dir, argument);
    charsets_dir = mysql_charsets_dir;
    break;
  case OPT_LOCAL_INFILE:
    using_opt_local_infile=1;
    break;
  case OPT_TEE:
    if (argument == disabled_my_option)
    {
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
622 623
      if (opt_outfile)
	end_tee();
624 625
    }
    else
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
626
      init_tee(argument);
627 628
    break;
  case OPT_NOTEE:
629
    printf("WARNING: option deprecated; use --disable-tee instead.\n");
630 631 632 633
    if (opt_outfile)
      end_tee();
    break;
  case OPT_PAGER:
634 635
    if (argument == disabled_my_option)
      opt_nopager= 1;
636
    else
637 638 639 640 641 642 643 644
    {
      opt_nopager= 0;
      if (argument)
	strmov(pager, argument);
      else
	strmov(pager, default_pager);
      strmov(default_pager, pager);
    }
645 646
    break;
  case OPT_NOPAGER:
647
    printf("WARNING: option deprecated; use --disable-pager instead.\n");
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 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
    opt_nopager= 1;
    break;
  case 'A':
    rehash= 0;
    break;
  case 'N':
    column_names= 0;
    break;
  case 'e':
    status.batch= 1;
    status.add_to_history= 0;
    batch_readline_end(status.line_buff);	// If multiple -e
    if (!(status.line_buff= batch_readline_command(argument)))
      return 1;
    ignore_errors= 0;
    break;
  case 'o':
    if (argument == disabled_my_option)
      one_database= 0;
    else
      one_database= skip_updates= 1;
    break;
  case 'p':
    if (argument == disabled_my_option)
      argument= (char*) "";			// Don't require password
    if (argument)
    {
      char *start= argument;
      my_free(opt_password, MYF(MY_ALLOW_ZERO_PTR));
      opt_password= my_strdup(argument, MYF(MY_FAE));
      while (*argument) *argument++= 'x';		// Destroy argument
      if (*start)
	start[1]=0 ;
    }
    else
      tty_password= 1;
    break;
  case '#':
    DBUG_PUSH(argument ? argument : default_dbug_option);
    info_flag= 1;
    break;
  case 's':
    if (argument == disabled_my_option)
      opt_silent= 0;
    else
      opt_silent++;
    break;
  case 'v':
    if (argument == disabled_my_option)
      verbose= 0;
    else
      verbose++;
    break;
  case 'B':
    if (!status.batch)
    {
      status.batch= 1;
      status.add_to_history= 0;
      opt_silent++;				// more silent
    }
    break;
  case 'W':
bk@work.mysql.com's avatar
bk@work.mysql.com committed
710
#ifdef __WIN__
711
    my_free(opt_mysql_unix_port, MYF(MY_ALLOW_ZERO_PTR));
712
    opt_mysql_unix_port= my_strdup(MYSQL_NAMEDPIPE, MYF(0));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
713
#endif
714
    break;
715
#include <sslopt-case.h>
716 717 718 719 720 721 722
  case 'V':
    usage(1);
    exit(0);
  case 'I':
  case '?':
    usage(0);
    exit(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
723
  }
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
  return 0;
}


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

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

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

  if ((ho_error=handle_options(&argc, &argv, my_long_options, get_one_option)))
748
    exit(ho_error);
749

jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
750 751 752 753
  if (status.batch) /* disable pager and outfile in this case */
  {
    strmov(default_pager, "stdout");
    strmov(pager, "stdout");
754 755
    opt_nopager= 1;
    opt_outfile= 0;
756
    connect_flag= 0; /* Not in interactive mode */
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
757
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
758 759 760 761 762 763 764 765 766 767 768 769
  if (default_charset)
  {
    if (set_default_charset_by_name(default_charset, MYF(MY_WME)))
      exit(1);
  }
  if (argc > 1)
  {
    usage(0);
    exit(1);
  }
  if (argc == 1)
  {
770
    skip_updates= 0;
771 772
    my_free(current_db, MYF(MY_ALLOW_ZERO_PTR));
    current_db= my_strdup(*argv, MYF(MY_WME));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
773 774
  }
  if (tty_password)
775
    opt_password= get_tty_password(NullS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
776 777 778 779 780
  return(0);
}

static int read_lines(bool execute_commands)
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
781
#if defined( __WIN__) || defined(OS2) || defined(__NETWARE__)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
  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
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
800
    {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
801 802 803
      char *prompt= (char*) (glob_buffer.is_empty() ? construct_prompt() :
			     !in_string ? "    -> " :
			     in_string == '\'' ?
804 805 806
			     "    '> " : (in_string == '`' ?
			     "    `> " :
			     "    \"> "));
807 808
      if (opt_outfile && glob_buffer.is_empty())
	fflush(OUTFILE);
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
809 810 811 812 813 814

#if defined( __WIN__) || defined(OS2) || defined(__NETWARE__)
      tee_fputs(prompt, stdout);
#ifdef __NETWARE__
      line=fgets(linebuffer, sizeof(linebuffer)-1, stdin);
      /* Remove the '\n' */
815
      {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
816
        char *p = strrchr(line, '\n');
817 818
        if (p != NULL)
          *p = '\0';
819
      }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
820 821 822 823 824 825 826 827 828 829
#else
      linebuffer[0]= (char) sizeof(linebuffer);
      line= _cgets(linebuffer);
#endif /* __NETWARE__ */
#else
      if (opt_outfile)
	fputs(prompt, OUTFILE);
      line= readline(prompt);
#endif /* defined( __WIN__) || defined(OS2) || defined(__NETWARE__) */

830 831
      if (opt_outfile)
	fprintf(OUTFILE, "%s\n", line);
832
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
833 834 835 836 837 838 839 840
    if (!line)					// End of file
    {
      status.exit_status=0;
      break;
    }
    if (!in_string && (line[0] == '#' ||
		       (line[0] == '-' && line[1] == '-') ||
		       line[0] == 0))
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
841
      continue;					// Skip comment lines
bk@work.mysql.com's avatar
bk@work.mysql.com committed
842

843 844 845 846
    /*
      Check if line is a mysql command line
      (We want to allow help, print and clear anywhere at line start
    */
847
    if (execute_commands && (named_cmds || glob_buffer.is_empty()) 
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
848
	&& !in_string && (com=find_command(line,0)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903
    {
      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
904
      len=(uint) strlen(name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
  }

  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;
925
  my_bool in_comment= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
926 927 928 929 930 931 932 933

  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
934
  char *strend=line+(uint) strlen(line);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954
#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 '\'
955
      if (*in_string || inchar == 'N')	// \N is short for NULL
bk@work.mysql.com's avatar
bk@work.mysql.com committed
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
      {					// 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;
      }
    }
985
    else if (inchar == ';' && !*in_string && !in_comment)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
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
    {						// ';' 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;
1013
      else if (!in_comment && !*in_string && (inchar == '\'' || inchar == '"' || inchar == '`'))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1014 1015
	*in_string=(char) inchar;
      *out++ = (char) inchar;
1016 1017 1018 1019 1020 1021 1022
      if (inchar == '*' && !*in_string)
      {
	if (pos != line && pos[-1] == '/')
	  in_comment= 1;
	else if (in_comment && pos[1] == '/')
	  in_comment= 0;
      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
    }
  }
  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;
}

1037 1038 1039
/*****************************************************************
	    Interface to Readline Completion
******************************************************************/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1040 1041 1042 1043 1044 1045

#ifdef HAVE_READLINE

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

1046 1047 1048 1049 1050
/*
  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.
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068

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

1069 1070 1071 1072 1073 1074
/*
  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.
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093

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;

1094
  if (!state)
1095
    textlen=(uint) strlen(text);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1096

1097 1098 1099 1100
  if (textlen>0)
  {						/* lookup in the hash */
    if (!state)
    {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1101 1102
      uint len;

1103
      b = find_all_matches(&ht,text,(uint) strlen(text),&len);
1104
      if (!b)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1105 1106 1107 1108
	return NullS;
      e = b->pData;
    }

1109 1110
    if (e)
    {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1111 1112 1113 1114
      ptr= strdup(e->str);
      e = e->pNext;
      return ptr;
    }
1115 1116 1117
  }
  else
  { /* traverse the entire hash, ugly but works */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1118

1119 1120
    if (!state)
    {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1121
      /* find the first used bucket */
1122 1123 1124 1125
      for (i=0 ; i < ht.nTableSize ; i++)
      {
	if (ht.arBuckets[i])
	{
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1126 1127 1128 1129 1130 1131 1132
	  b = ht.arBuckets[i];
	  e = b->pData;
	  break;
	}
      }
    }
    ptr= NullS;
1133 1134 1135
    while (e && !ptr)
    {					/* find valid entry in bucket */
      if ((uint) strlen(e->str) == b->nKeyLength)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1136 1137 1138
	ptr = strdup(e->str);
      /* find the next used entry */
      e = e->pNext;
1139 1140
      if (!e)
      { /* find the next used bucket */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1141
	b = b->pNext;
1142 1143 1144 1145 1146 1147
	if (!b)
	{
	  for (i++ ; i<ht.nTableSize; i++)
	  {
	    if (ht.arBuckets[i])
	    {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1148 1149 1150 1151 1152 1153
	      b = ht.arBuckets[i];
	      e = b->pData;
	      break;
	    }
	  }
	}
1154 1155
	else
	  e = b->pData;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1156 1157
      }
    }
1158
    if (ptr)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1159 1160 1161 1162 1163 1164 1165 1166
      return ptr;
  }
  return NullS;
}


/* Build up the completion hash */

1167
static void build_completion_hash(bool rehash, bool write_info)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1168 1169
{
  COMMANDS *cmd=commands;
1170 1171
  MYSQL_RES *databases=0,*tables=0;
  MYSQL_RES *fields;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1172 1173 1174 1175 1176 1177 1178
  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");

1179
  if (status.batch || quick || !current_db)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
    DBUG_VOID_RETURN;			// We don't need completion in batches

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

  /* hash SQL commands */
  while (cmd->name) {
    add_word(&ht,(char*) cmd->name);
    cmd++;
  }
1193
  if (!rehash)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1194 1195
    DBUG_VOID_RETURN;

1196 1197 1198 1199 1200 1201
  /* Free old used memory */
  if (field_names)
    field_names=0;
  completion_hash_clean(&ht);
  free_root(&hash_mem_root,MYF(0));

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1202 1203 1204
  /* hash MySQL functions (to be implemented) */

  /* hash all database names */
1205 1206
  if (mysql_query(&mysql,"show databases") == 0)
  {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1207 1208 1209 1210 1211
    if (!(databases = mysql_store_result(&mysql)))
      put_info(mysql_error(&mysql),INFO_INFO);
    else
    {
      while ((database_row=mysql_fetch_row(databases)))
1212 1213 1214 1215 1216 1217
      {
	char *str=strdup_root(&hash_mem_root, (char*) database_row[0]);
	if (str)
	  add_word(&ht,(char*) str);
      }
      mysql_free_result(databases);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
    }
  }
  /* 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)
      {
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1229
	tee_fprintf(stdout, "\
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1230 1231 1232 1233 1234
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)))
      {
1235 1236 1237 1238
	char *str=strdup_root(&hash_mem_root, (char*) table_row[0]);
	if (str &&
	    !completion_hash_exists(&ht,(char*) str, (uint) strlen(str)))
	  add_word(&ht,str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1239 1240 1241 1242 1243
      }
    }
  }

  /* hash all field names, both with the table prefix and without it */
1244 1245
  if (!tables)					/* no tables */
  {
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1246 1247 1248
    DBUG_VOID_RETURN;
  }
  mysql_data_seek(tables,0);
1249 1250 1251 1252
  if (!(field_names= (char ***) alloc_root(&hash_mem_root,sizeof(char **) *
					   (uint) (mysql_num_rows(tables)+1))))
  {
    mysql_free_result(tables);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1253
    DBUG_VOID_RETURN;
1254
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1255 1256 1257 1258 1259 1260
  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);
1261 1262 1263 1264
      if (!(field_names[i] = (char **) alloc_root(&hash_mem_root,
						  sizeof(char *) *
						  (num_fields*2+1))))
	break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1265 1266 1267 1268 1269
      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);
1270
	field_names[i][j] = strdup_root(&hash_mem_root,buf);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1271
	add_word(&ht,field_names[i][j]);
1272 1273
	field_names[i][num_fields+j] = strdup_root(&hash_mem_root,
						   sql_field->name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1274
	if (!completion_hash_exists(&ht,field_names[i][num_fields+j],
1275
				    (uint) strlen(field_names[i][num_fields+j])))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1276 1277 1278
	  add_word(&ht,field_names[i][num_fields+j]);
	j++;
      }
1279
      mysql_free_result(fields);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1280 1281
    }
    else
1282
    {
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1283 1284
      tee_fprintf(stdout,
		  "Didn't find any fields in table '%s'\n",table_row[0]);
1285 1286
      field_names[i]=0;
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1287 1288
    i++;
  }
1289
  mysql_free_result(tables);
1290
  field_names[i]=0;				// End pointer
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1291 1292 1293 1294 1295 1296 1297
  DBUG_VOID_RETURN;
}

	/* for gnu readline */

#ifndef HAVE_INDEX
extern "C" {
1298
extern char *index(const char *,int c),*rindex(const char *,int);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1299

1300
char *index(const char *s,int c)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1301 1302 1303 1304 1305 1306 1307 1308
{
  for (;;)
  {
     if (*s == (char) c) return (char*) s;
     if (!*s++) return NullS;
  }
}

1309
char *rindex(const char *s,int c)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320
{
  reg3 char *t;

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

1321

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1322 1323 1324 1325 1326 1327
static int reconnect(void)
{
  if (!status.batch)
  {
    put_info("No connection. Trying to reconnect...",INFO_INFO);
    (void) com_connect((String *) 0, 0);
1328 1329
    if (rehash)
      com_rehash(NULL, NULL);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
  }
  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;

1347 1348 1349 1350
  put_info("\nFor the complete MySQL Manual online visit:\n   http://www.mysql.com/documentation\n", INFO_INFO);
  put_info("For info on technical support from MySQL developers visit:\n   http://www.mysql.com/support\n", INFO_INFO);
  put_info("For info on MySQL books, utilities, consultants, etc. visit:\n   http://www.mysql.com/portal\n", INFO_INFO);
  put_info("List of all MySQL commands:", INFO_INFO);
1351
  if (!named_cmds)
1352 1353
    put_info("   (Commands must appear first on line and end with ';')\n",
	     INFO_INFO);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1354 1355 1356
  for (i = 0; commands[i].name; i++)
  {
    if (commands[i].func)
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1357 1358
      tee_fprintf(stdout, "%s\t(\\%c)\t%s\n", commands[i].name,
		  commands[i].cmd_char, commands[i].doc);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1359 1360
  }
  if (connected)
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1361
    tee_fprintf(stdout,
1362
		"\nConnection id: %lu  (Can be used with mysqladmin kill)\n\n",
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1363
		mysql_thread_id(&mysql));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1364
  else
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1365
    tee_fprintf(stdout, "Not connected!  Reconnect with 'connect'!\n\n");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
  return 0;
}


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


/*
1380 1381 1382 1383
  Execute command
  Returns: 0  if ok
          -1 if not fatal error
	  1  if fatal error
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400
*/


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

1401
  /* Remove garbage for nicer messages */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
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
  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));
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1433 1434
    if (mysql_errno(&mysql) != CR_SERVER_GONE_ERROR || retry > 1 
	|| status.batch)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1435 1436 1437 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
    {
      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
    {
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1478
      init_pager();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1479 1480
      if (opt_html)
	print_table_data_html(result);
1481 1482
      else if (opt_xml)
	print_table_data_xml(result);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
      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);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1493
      end_pager();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
    }
  }
  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 */
}

jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1516 1517 1518

static void init_pager()
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1519
#ifdef USE_POPEN
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534
  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()
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1535
#ifdef USE_POPEN
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1536 1537 1538 1539 1540
  if (!opt_nopager)
    pclose(PAGER);
#endif
}

1541

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1542
static void init_tee(const char *file_name)
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1543
{
1544
  FILE* new_outfile;
1545
  if (opt_outfile)
1546
    end_tee();
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1547 1548 1549 1550 1551
  if (!(new_outfile= my_fopen(file_name, O_APPEND | O_WRONLY, MYF(MY_WME))))
  {
    tee_fprintf(stdout, "Error logging to file '%s'\n", file_name);
    return;
  }
1552
  OUTFILE = new_outfile;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1553 1554 1555 1556
  strmake(outfile, file_name, FN_REFLEN-1);
  tee_fprintf(stdout, "Logging to file '%s'\n", file_name);
  opt_outfile= 1;
  return;
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1557 1558
}

1559

jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1560 1561 1562
static void end_tee()
{
  my_fclose(OUTFILE, MYF(0));
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1563
  OUTFILE= 0;
1564
  opt_outfile= 0;
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1565 1566 1567
  return;
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
static int
com_ego(String *buffer,char *line)
{
  int result;
  bool oldvertical=vertical;
  vertical=1;
  result=com_go(buffer,line);
  vertical=oldvertical;
  return result;
}

1579 1580 1581 1582 1583 1584
static void
print_field_types(MYSQL_RES *result)
{
  MYSQL_FIELD	*field;  
  while ((field = mysql_fetch_field(result)))
  {
1585
    tee_fprintf(PAGER,"Name:       '%s'\nTable:      '%s'\nType:       %d\nLength:     %d\nMax length: %d\nIs_null:    %d\nFlags:      %d\nDecimals:   %d\n\n",
1586 1587 1588
		field->name,
		field->table ? "" : field->table,
		(int) field->type,
1589 1590
		field->length, field->max_length,
		!IS_NOT_NULL(field->flags),
1591 1592 1593 1594 1595
		field->flags, field->decimals);
  }
  tee_puts("", PAGER);
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605

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));
1606 1607 1608 1609 1610
  if (info_flag)
  {
    print_field_types(result);
    mysql_field_seek(result,0);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1611 1612 1613
  separator.copy("+",1);
  while ((field = mysql_fetch_field(result)))
  {
1614
    uint length= column_names ? (uint) strlen(field->name) : 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1615 1616 1617 1618 1619 1620 1621 1622 1623 1624
    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('+');
  }
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1625
  tee_puts(separator.c_ptr(), PAGER);
1626
  if (column_names)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1627 1628
  {
    mysql_field_seek(result,0);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1629
    (void) tee_fputs("|", PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1630 1631
    for (uint off=0; (field = mysql_fetch_field(result)) ; off++)
    {
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1632 1633
      tee_fprintf(PAGER, " %-*s|",min(field->max_length,MAX_COLUMN_LENGTH),
		  field->name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1634 1635
      num_flag[off]= IS_NUM(field->type);
    }
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1636 1637
    (void) tee_fputs("\n", PAGER);
    tee_puts(separator.c_ptr(), PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1638 1639
  }

1640
  while ((cur= mysql_fetch_row(result)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1641
  {
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1642
    (void) tee_fputs("|", PAGER);
1643 1644
    mysql_field_seek(result, 0);
    for (uint off= 0; off < mysql_num_fields(result); off++)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1645
    {
1646 1647 1648
      const char *str= cur[off] ? cur[off] : "NULL";
      field= mysql_fetch_field(result);
      uint length= field->max_length;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1649 1650
      if (length > MAX_COLUMN_LENGTH)
      {
1651 1652
	tee_fputs(str, PAGER);
	tee_fputs(" |", PAGER);
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1653 1654
      }
      else
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1655
      tee_fprintf(PAGER, num_flag[off] ? "%*s |" : " %-*s|",
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1656
		  length, str);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1657
    }
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1658
    (void) tee_fputs("\n", PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1659
  }
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1660
  tee_puts(separator.c_ptr(), PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1661 1662 1663
  my_afree((gptr) num_flag);
}

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1664

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1665 1666 1667
static void
print_table_data_html(MYSQL_RES *result)
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1668 1669
  MYSQL_ROW	cur;
  MYSQL_FIELD	*field;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1670 1671

  mysql_field_seek(result,0);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1672
  (void) tee_fputs("<TABLE BORDER=1><TR>", PAGER);
1673
  if (column_names)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1674 1675 1676
  {
    while((field = mysql_fetch_field(result)))
    {
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1677 1678 1679
      tee_fprintf(PAGER, "<TH>%s</TH>", (field->name ? 
					 (field->name[0] ? field->name : 
					  " &nbsp; ") : "NULL"));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1680
    }
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1681
    (void) tee_fputs("</TR>", PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1682 1683 1684
  }
  while ((cur = mysql_fetch_row(result)))
  {
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1685
    (void) tee_fputs("<TR>", PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1686 1687 1688
    for (uint i=0; i < mysql_num_fields(result); i++)
    {
      ulong *lengths=mysql_fetch_lengths(result);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1689
      (void) tee_fputs("<TD>", PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1690
      safe_put_field(cur[i],lengths[i]);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1691
      (void) tee_fputs("</TD>", PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1692
    }
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1693
    (void) tee_fputs("</TR>", PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1694
  }
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1695
  (void) tee_fputs("</TABLE>", PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1696 1697 1698
}


1699 1700 1701 1702 1703 1704 1705 1706
static void
print_table_data_xml(MYSQL_RES *result)
{
  MYSQL_ROW   cur;
  MYSQL_FIELD *fields;

  mysql_field_seek(result,0);

1707
  tee_fputs("<?xml version=\"1.0\"?>\n\n<resultset statement=\"", PAGER);
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
1708
  xmlencode_print(glob_buffer.ptr(), strlen(glob_buffer.ptr()));
1709
  tee_fputs("\">", PAGER);
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720

  fields = mysql_fetch_fields(result);
  while ((cur = mysql_fetch_row(result)))
  {
    (void) tee_fputs("\n  <row>\n", PAGER);
    for (uint i=0; i < mysql_num_fields(result); i++)
    {
      ulong *lengths=mysql_fetch_lengths(result);
      tee_fprintf(PAGER, "\t<%s>", (fields[i].name ?
				  (fields[i].name[0] ? fields[i].name :
				   " &nbsp; ") : "NULL"));
1721
      xmlencode_print(cur[i], lengths[i]);
1722 1723 1724 1725 1726 1727 1728 1729 1730
      tee_fprintf(PAGER, "</%s>\n", (fields[i].name ?
				     (fields[i].name[0] ? fields[i].name :
				      " &nbsp; ") : "NULL"));
    }
    (void) tee_fputs("  </row>\n", PAGER);
  }
  (void) tee_fputs("</resultset>\n", PAGER);
}

bk@work.mysql.com's avatar
bk@work.mysql.com 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)))
  {
1741
    uint length=(uint) strlen(field->name);
bk@work.mysql.com's avatar
bk@work.mysql.com 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);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1751 1752
    tee_fprintf(PAGER, 
		"*************************** %d. row ***************************\n", row_count);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1753 1754 1755
    for (uint off=0; off < mysql_num_fields(result); off++)
    {
      field= mysql_fetch_field(result);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1756 1757
      tee_fprintf(PAGER, "%*s: ",(int) max_length,field->name);
      tee_fprintf(PAGER, "%s\n",cur[off] ? (char*) cur[off] : "NULL");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1758 1759 1760 1761
    }
  }
}

1762

1763
static const char
1764 1765
*array_value(const char **array, char key)
{
1766
  int x;
1767 1768 1769
  for (x= 0; array[x]; x+= 2)
    if (*array[x] == key)
      return array[x + 1];
1770 1771 1772
  return 0;
}

1773

1774
static void
1775
xmlencode_print(const char *src, uint length)
1776
{
1777 1778 1779
  if (!src)
    tee_fputs("NULL", PAGER);
  else
1780
  {
1781 1782 1783 1784 1785 1786 1787 1788 1789
    for (const char *p = src; *p && length; *p++, length--)
    {
      const char *t;
      if ((t = array_value(xmlmeta, *p)))
	tee_fputs(t, PAGER);
      else
	tee_putc(*p, PAGER);
    }
  }
1790
}
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1791

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1792 1793 1794 1795 1796

static void
safe_put_field(const char *pos,ulong length)
{
  if (!pos)
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1797
    tee_fputs("NULL", PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1798 1799 1800
  else
  {
    if (opt_raw_data)
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1801
      tee_fputs(pos, PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1802 1803 1804 1805 1806 1807 1808
    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--)
1809
	    tee_putc(*pos++, PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1810 1811 1812 1813 1814
	  pos--;
	  continue;
      }
#endif
      if (!*pos)
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1815
	tee_fputs("\\0", PAGER); // This makes everything hard
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1816
      else if (*pos == '\t')
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1817
	tee_fputs("\\t", PAGER); // This would destroy tab format
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1818
      else if (*pos == '\n')
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1819
	tee_fputs("\\n", PAGER); // This too
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1820
      else if (*pos == '\\')
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1821
	tee_fputs("\\\\", PAGER);
1822
	else
1823
	tee_putc(*pos, PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
    }
  }
}


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

1836
  if (opt_silent < 2 && column_names)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1837 1838 1839 1840 1841
  {
    int first=0;
    while ((field = mysql_fetch_field(result)))
    {
      if (first++)
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1842 1843
	(void) tee_fputs("\t", PAGER);
      (void) tee_fputs(field->name, PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1844
    }
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1845
    (void) tee_fputs("\n", PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1846 1847 1848 1849 1850 1851 1852
  }
  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++)
    {
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1853
      (void) tee_fputs("\t", PAGER);
1854
      safe_put_field(cur[off], lengths[off]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1855
    }
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1856
    (void) tee_fputs("\n", PAGER);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1857 1858 1859
  }
}

jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
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))
    {
1873
      printf("No previous outfile available, you must give a filename!\n");
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1874 1875
      return 0;
    }
1876 1877 1878 1879 1880 1881 1882
    else if (opt_outfile)
    {
      tee_fprintf(stdout, "Currently logging to file '%s'\n", outfile);
      return 0;
    }
    else
      param = outfile;			//resume using the old outfile
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1883
  }
1884 1885 1886 1887 1888 1889 1890 1891 1892

  /* eliminate the spaces before the parameters */
  while (isspace(*param))
    param++;
  end= strmake(file_name, param, sizeof(file_name) - 1);
  /* remove end space from command line */
  while (end > file_name && (isspace(end[-1]) || iscntrl(end[-1])))
    end--;
  end[0]= 0;
1893
  if (end == file_name)
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1894 1895 1896 1897
  {
    printf("No outfile specified!\n");
    return 0;
  }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1898
  init_tee(file_name);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1899 1900 1901
  return 0;
}

1902

jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
static int
com_notee(String *buffer __attribute__((unused)),
	  char *line __attribute__((unused)))
{
  if (opt_outfile)
    end_tee();
  tee_fprintf(stdout, "Outfile disabled.\n");
  return 0;
}

1913
/*
1914
  Sorry, this command is not available in Windows.
1915 1916
*/

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1917
#ifdef USE_POPEN
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927
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++;
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1928
  if (!(param= strchr(line, ' '))) // if pager was not given, use the default
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1929
  {
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1930
    if (!default_pager[0])
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1931
    {
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1932
      tee_fprintf(stdout, "Default pager wasn't set, using stdout.\n");
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948
      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);
1949
    strmov(default_pager, pager_name);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1950 1951 1952 1953 1954 1955
  }
  opt_nopager=0;
  tee_fprintf(stdout, "PAGER set to %s\n", pager);
  return 0;
}

1956

jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1957 1958 1959 1960 1961 1962 1963 1964 1965
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;
}
1966
#endif
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
1967

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1968

1969
/*
1970
  Sorry, you can't send the result to an editor in Win32
1971 1972
*/

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
1973
#ifdef USE_POPEN
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1974 1975 1976
static int
com_edit(String *buffer,char *line __attribute__((unused)))
{
1977
  char	filename[FN_REFLEN],buff[160];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1978 1979 1980
  int	fd,tmp;
  const char *editor;

1981 1982
  if ((fd=create_temp_file(filename,NullS,"sql", O_CREAT | O_WRONLY,
			   MYF(MY_WME))) < 0)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011
    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;
}
2012 2013
#endif

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2014 2015 2016 2017 2018 2019 2020

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

static int
com_quit(String *buffer __attribute__((unused)),
	 char *line __attribute__((unused)))
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2021 2022 2023 2024
#ifdef __NETWARE__
  // let the screen auto close on a normal shutdown
  setscreenmode(SCR_AUTOCLOSE_ON_EXIT);
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2025 2026 2027 2028 2029 2030 2031 2032 2033
  status.exit_status=0;
  return 1;
}

static int
com_rehash(String *buffer __attribute__((unused)),
	 char *line __attribute__((unused)))
{
#ifdef HAVE_READLINE
2034
  build_completion_hash(1, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2035 2036 2037 2038
#endif
  return 0;
}

2039

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2040
#ifdef USE_POPEN
2041 2042 2043 2044
static int
com_shell(String *buffer, char *line __attribute__((unused)))
{
  char *shell_cmd;
2045 2046 2047 2048

  /* Skip space from line begin */
  while (isspace(*line))
    line++;
2049 2050 2051 2052 2053
  if (!(shell_cmd = strchr(line, ' ')))
  {
    put_info("Usage: \\! shell-command", INFO_ERROR);
    return -1;
  }
2054 2055 2056 2057 2058
  /*
    The output of the shell command does not
    get directed to the pager or the outfile
  */
  if (system(shell_cmd) == -1)
2059 2060 2061 2062 2063 2064 2065 2066 2067
  {
    put_info(strerror(errno), INFO_ERROR, errno);
    return -1;
  }
  return 0;
}
#endif


bk@work.mysql.com's avatar
bk@work.mysql.com committed
2068 2069 2070
static int
com_print(String *buffer,char *line __attribute__((unused)))
{
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2071 2072
  tee_puts("--------------", stdout);
  (void) tee_fputs(buffer->c_ptr(), stdout);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2073
  if (!buffer->length() || (*buffer)[buffer->length()-1] != '\n')
2074
    tee_putc('\n', stdout);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2075
  tee_puts("--------------\n", stdout);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2076 2077 2078 2079 2080 2081 2082 2083
  return 0;					/* If empty buffer */
}

	/* ARGSUSED */
static int
com_connect(String *buffer, char *line)
{
  char *tmp,buff[256];
2084
  bool save_rehash= rehash;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2085 2086 2087 2088 2089 2090 2091 2092 2093
  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]=' ';
2094
    tmp=(char *) strtok(buff," \t");		// Skip connect command
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
    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
2106
      rehash= 0;				// Quick re-connect
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2107 2108 2109
    buffer->length(0);				// command used
  }
  else
2110
    rehash= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2111
  error=sql_connect(current_host,current_db,current_user,opt_password,0);
2112
  rehash= save_rehash;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2113 2114 2115

  if (connected)
  {
2116
    sprintf(buff,"Connection id:    %lu",mysql_thread_id(&mysql));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2117 2118
    put_info(buff,INFO_INFO);
    sprintf(buff,"Current database: %s\n",
2119
	    current_db ? current_db : "*** NONE ***");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136
    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++;
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2137 2138 2139
  if (!(param = strchr(line, ' ')))		// Skip command name
    return put_info("Usage: \\. <filename> | source <filename>", 
		    INFO_ERROR, 0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2140 2141 2142 2143 2144 2145
  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;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2146
  unpack_filename(source_name,source_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2147
  /* open file name */
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2148
  if (!(sql_file = my_fopen(source_name, O_RDONLY | O_BINARY,MYF(0))))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188
  {
    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]=' ';
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2189
  tmp=(char *) strtok(buff," \t;");		// Skip connect command
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2190 2191 2192 2193 2194 2195 2196 2197
  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)
2198
      skip_updates= 1;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216
    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));
      }
2217 2218
      my_free(current_db,MYF(MY_ALLOW_ZERO_PTR));
      current_db=my_strdup(tmp,MYF(MY_WME));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2219
#ifdef HAVE_READLINE
2220
      build_completion_hash(rehash, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2221 2222 2223 2224
#endif
    }
  }
  else
2225
    skip_updates= 0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2226 2227 2228 2229 2230 2231 2232 2233 2234
  put_info("Database changed",INFO_INFO);
  return 0;
}


static int
sql_real_connect(char *host,char *database,char *user,char *password,
		 uint silent)
{
monty@mysql.com's avatar
monty@mysql.com committed
2235 2236 2237 2238 2239
  if (connected)
  {
    connected= 0;
    mysql_close(&mysql);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2240
  mysql_init(&mysql);
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2241
  if (opt_connect_timeout)
2242 2243
  {
    uint timeout=opt_connect_timeout;
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2244
    mysql_options(&mysql,MYSQL_OPT_CONNECT_TIMEOUT,
2245 2246
		  (char*) &timeout);
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2247 2248
  if (opt_compress)
    mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS);
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2249 2250
  if (using_opt_local_infile)
    mysql_options(&mysql,MYSQL_OPT_LOCAL_INFILE, (char*) &opt_local_infile);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2251 2252 2253
#ifdef HAVE_OPENSSL
  if (opt_use_ssl)
    mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
2254
		  opt_ssl_capath, opt_ssl_cipher);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2255 2256 2257 2258 2259 2260 2261 2262 2263
#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);
  }
2264 2265
  if (!mysql_real_connect(&mysql, host, user, password,
			  database, opt_mysql_port, opt_mysql_unix_port,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280
			  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
2281
  build_completion_hash(rehash, 1);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298
#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)
      {
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2299
	tee_fputs("\n", stderr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2300 2301 2302 2303 2304 2305 2306 2307 2308
	(void) fflush(stderr);
      }
      return error;
    }
    if (!wait_flag)
      return ignore_errors ? -1 : 1;
    if (!message && !silent)
    {
      message=1;
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2309
      tee_fputs("Waiting",stderr); (void) fflush(stderr);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2310
    }
2311
    (void) sleep(wait_time);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
    if (!silent)
    {
      putc('.',stderr); (void) fflush(stderr);
      count++;
    }
  }
}



static int
com_status(String *buffer __attribute__((unused)),
	   char *line __attribute__((unused)))
{
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2326
  const char *status;
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2327
  tee_puts("--------------", stdout);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2328 2329 2330 2331 2332
  usage(1);					/* Print version */
  if (connected)
  {
    MYSQL_RES *result;
    LINT_INIT(result);
2333
    tee_fprintf(stdout, "\nConnection id:\t\t%lu\n",mysql_thread_id(&mysql));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2334 2335 2336 2337
    if (!mysql_query(&mysql,"select DATABASE(),USER()") &&
	(result=mysql_use_result(&mysql)))
    {
      MYSQL_ROW cur=mysql_fetch_row(result);
2338
      tee_fprintf(stdout, "Current database:\t%s\n", cur[0] ? cur[0] : "");
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2339
      tee_fprintf(stdout, "Current user:\t\t%s\n",cur[1]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2340 2341
      (void) mysql_fetch_row(result);		// Read eof
    }
2342
#ifdef HAVE_OPENSSL
2343 2344
    if (mysql.net.vio && mysql.net.vio->ssl_arg &&
	SSL_get_cipher((SSL*) mysql.net.vio->ssl_arg))
2345
      tee_fprintf(stdout, "SSL:\t\t\tCipher in use is %s\n",
2346
		  SSL_get_cipher((SSL*) mysql.net.vio->ssl_arg));
2347 2348
    else
#endif /* HAVE_OPENSSL */
2349
      tee_puts("SSL:\t\t\tNot in use", stdout);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2350 2351 2352 2353
  }
  else
  {
    vidattr(A_BOLD);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2354
    tee_fprintf(stdout, "\nNo connection\n");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2355 2356 2357 2358 2359 2360
    vidattr(A_NORMAL);
    return 0;
  }
  if (skip_updates)
  {
    vidattr(A_BOLD);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2361
    tee_fprintf(stdout, "\nAll updates ignored to this database\n");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2362 2363
    vidattr(A_NORMAL);
  }
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2364
#ifdef USE_POPEN
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2365
  tee_fprintf(stdout, "Current pager:\t\t%s\n", pager);
2366
  tee_fprintf(stdout, "Using outfile:\t\t'%s'\n", opt_outfile ? outfile : "");
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2367 2368 2369 2370
#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));
2371 2372 2373
  tee_fprintf(stdout, "Client characterset:\t%s\n",
	      default_charset_info->name);
  tee_fprintf(stdout, "Server characterset:\t%s\n", mysql.charset->name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2374
  if (strstr(mysql_get_host_info(&mysql),"TCP/IP") || ! mysql.unix_socket)
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2375
    tee_fprintf(stdout, "TCP port:\t\t%d\n", mysql.port);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2376
  else
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2377
    tee_fprintf(stdout, "UNIX socket:\t\t%s\n", mysql.unix_socket);
2378 2379 2380
  if (mysql.net.compress)
    tee_fprintf(stdout, "Protocol:\t\tCompressed\n");

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2381 2382 2383
  if ((status=mysql_stat(&mysql)) && !mysql_error(&mysql)[0])
  {
    ulong sec;
2384 2385 2386 2387
    char buff[40];
    const char *pos= strchr(status,' ');
    /* print label */
    tee_fprintf(stdout, "%.*s\t\t\t", (int) (pos-status), status);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2388 2389 2390
    if ((status=str2int(pos,10,0,LONG_MAX,(long*) &sec)))
    {
      nice_time((double) sec,buff,0);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2391
      tee_puts(buff, stdout);			/* print nice time */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2392 2393 2394 2395
      while (*status == ' ') status++;		/* to next info */
    }
    if (status)
    {
2396
      tee_putc('\n', stdout);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2397
      tee_puts(status, stdout);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2398 2399 2400 2401 2402
    }
  }
  if (safe_updates)
  {
    vidattr(A_BOLD);
jcole@tetra.spaceapes.com's avatar
jcole@tetra.spaceapes.com committed
2403
    tee_fprintf(stdout, "\nNote that you are running in safe_update_mode:\n");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2404
    vidattr(A_NORMAL);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2405
    tee_fprintf(stdout, "\
jcole@tetra.spaceapes.com's avatar
jcole@tetra.spaceapes.com committed
2406 2407 2408
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\
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2409
Max number of examined row combination in a join is set to: %lu\n\n",
jcole@tetra.spaceapes.com's avatar
jcole@tetra.spaceapes.com committed
2410
select_limit, max_join_size);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2411
  }
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2412
  tee_puts("--------------\n", stdout);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2413 2414 2415 2416 2417 2418 2419
  return 0;
}


static int
put_info(const char *str,INFO_TYPE info_type,uint error)
{
2420
  FILE *file= (info_type == INFO_ERROR ? stderr : stdout);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2421
  static int inited=0;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2422

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2423 2424 2425 2426
  if (status.batch)
  {
    if (info_type == INFO_ERROR)
    {
2427 2428
      (void) fflush(file);
      fprintf(file,"ERROR");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2429
      if (error)
2430
	(void) fprintf(file," %d",error);
2431
      if (status.query_start_line && line_numbers)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2432
      {
2433
	(void) fprintf(file," at line %lu",status.query_start_line);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2434
	if (status.file_name)
2435
	  (void) fprintf(file," in file: '%s'", status.file_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2436
      }
2437 2438
      (void) fprintf(file,": %s\n",str);
      (void) fflush(file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2439 2440 2441 2442
      if (!ignore_errors)
	return 1;
    }
    else if (info_type == INFO_RESULT && verbose > 1)
2443
      tee_puts(str, file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2444
    if (unbuffered)
2445
      fflush(file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458
    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)
    {
2459
      if (!opt_nobeep)
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2460
	putchar('\007');		      	/* This should make a bell */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2461 2462
      vidattr(A_STANDOUT);
      if (error)
2463
        (void) tee_fprintf(file, "ERROR %d: ", error);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2464
      else
2465
        tee_puts("ERROR: ", file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2466 2467 2468
    }
    else
      vidattr(A_BOLD);
2469
    (void) tee_puts(str, file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2470 2471 2472
    vidattr(A_NORMAL);
  }
  if (unbuffered)
2473
    fflush(file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2474 2475 2476
  return info_type == INFO_ERROR ? -1 : 0;
}

jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2477

bk@work.mysql.com's avatar
bk@work.mysql.com committed
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
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));
}


jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2488 2489 2490 2491 2492
void tee_fprintf(FILE *file, const char *fmt, ...)
{
  va_list args;

  va_start(args, fmt);
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2493
  (void) vfprintf(file, fmt, args);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2494 2495 2496
#ifdef OS2
  fflush( file);
#endif
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2497
  if (opt_outfile)
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
2498
    (void) vfprintf(OUTFILE, fmt, args);
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2499 2500 2501 2502 2503 2504 2505
  va_end(args);
}


void tee_fputs(const char *s, FILE *file)
{
  fputs(s, file);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2506 2507 2508
#ifdef OS2
  fflush( file);
#endif
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2509 2510 2511 2512 2513 2514 2515 2516 2517
  if (opt_outfile)
    fputs(s, OUTFILE);
}


void tee_puts(const char *s, FILE *file)
{
  fputs(s, file);
  fputs("\n", file);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2518 2519 2520
#ifdef OS2
  fflush( file);
#endif
jani@prima.mysql.com's avatar
jani@prima.mysql.com committed
2521 2522 2523 2524 2525 2526 2527
  if (opt_outfile)
  {
    fputs(s, OUTFILE);
    fputs("\n", OUTFILE);
  }
}

2528 2529 2530
void tee_putc(int c, FILE *file)
{
  putc(c, file);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
2531 2532 2533
#ifdef OS2
  fflush( file);
#endif
2534 2535 2536 2537
  if (opt_outfile)
    putc(c, OUTFILE);
}

monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2538
#if defined( __WIN__) || defined( OS2) || defined(__NETWARE__)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2539 2540 2541
#include <time.h>
#else
#include <sys/times.h>
2542
#ifdef _SC_CLK_TCK				// For mit-pthreads
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2543 2544 2545
#undef CLOCKS_PER_SEC
#define CLOCKS_PER_SEC (sysconf(_SC_CLK_TCK))
#endif
2546
#endif
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2547 2548 2549

static ulong start_timer(void)
{
monty@mashka.mysql.fi's avatar
monty@mashka.mysql.fi committed
2550
#if defined( __WIN__) || defined( OS2) || defined(__NETWARE__)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604
 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),")");
}

2605 2606
static const char* construct_prompt()
{
2607 2608
  processed_prompt.free();			// Erase the old prompt
  time_t  lclock = time(NULL);			// Get the date struct
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2609
  struct tm *t = localtime(&lclock);
2610 2611

  /* parse thru the settings for the prompt */
2612 2613 2614
  for (char *c = current_prompt; *c ; *c++)
  {
    if (*c != PROMPT_CHAR)
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2615
	processed_prompt.append(*c);
2616 2617
    else
    {
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2618 2619
      switch (*++c) {
      case '\0':
2620
	c--;			// stop it from going beyond if ends with %
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2621 2622 2623 2624 2625
	break;
      case 'c':
	add_int_to_prompt(++prompt_counter);
	break;
      case 'v':
2626 2627 2628 2629
	if (connected)
	  processed_prompt.append(mysql_get_server_info(&mysql));
	else
	  processed_prompt.append("not_connected");
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2630 2631 2632 2633 2634 2635
	break;
      case 'd':
	processed_prompt.append(current_db ? current_db : "(none)");
	break;
      case 'h':
      {
2636 2637
	const char *prompt;
	prompt= connected ? mysql_get_host_info(&mysql) : "not_connected";
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
	if (strstr(prompt, "Localhost"))
	  processed_prompt.append("localhost");
	else
	{
	  const char *end=strcend(prompt,' ');
	  processed_prompt.append(prompt, (uint) (end-prompt));
	}
	break;
      }
      case 'p':
2648 2649 2650 2651 2652 2653 2654
	if (!connected)
	{
	  processed_prompt.append("not_connected");
	  break;
	}
	if (strstr(mysql_get_host_info(&mysql),"TCP/IP") || !
	    mysql.unix_socket)
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2655 2656
	  add_int_to_prompt(mysql.port);
	else
2657 2658 2659 2660
	{
	  char *pos=strrchr(mysql.unix_socket,'/');
	  processed_prompt.append(pos ? pos+1 : mysql.unix_socket);
	}
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
	break;
      case 'U':
	if (!full_username)
	  init_username();
	processed_prompt.append(full_username);
	break;
      case 'u':
	if (!full_username)
	  init_username();
	processed_prompt.append(part_username);
	break;
      case PROMPT_CHAR:
	processed_prompt.append(PROMPT_CHAR);
	break;
      case 'n':
	processed_prompt.append('\n');
	break;
      case ' ':
      case '_':
	processed_prompt.append(' ');
	break;
      case 'R':
2683 2684
	if (t->tm_hour < 10)
	  processed_prompt.append('0');
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2685 2686 2687 2688 2689 2690 2691
	add_int_to_prompt(t->tm_hour);
	break;
      case 'r':
	int getHour;
	getHour = t->tm_hour % 12;
	if (getHour == 0)
	  getHour=12;
2692 2693
	if (getHour < 10)
	  processed_prompt.append('0');
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718
	add_int_to_prompt(getHour);
	break;
      case 'm':
	if (t->tm_min < 10)
	  processed_prompt.append('0');
	add_int_to_prompt(t->tm_min);
	break;
      case 'y':
	int getYear;
	getYear = t->tm_year % 100;
	if (getYear < 10)
	  processed_prompt.append('0');
	add_int_to_prompt(getYear);
	break;
      case 'Y':
	add_int_to_prompt(t->tm_year+1900);
	break;
      case 'D':
	char* dateTime;
	time_t lclock;
	lclock = time(NULL);
	dateTime = ctime(&lclock);
	processed_prompt.append(strtok(dateTime,"\n"));
	break;
      case 's':
2719 2720
	if (t->tm_sec < 10)
	  processed_prompt.append('0');
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
	add_int_to_prompt(t->tm_sec);
	break;
      case 'w':
	processed_prompt.append(day_names[t->tm_wday]);
	break;
      case 'P':
	processed_prompt.append(t->tm_hour < 12 ? "am" : "pm");
	break;
      case 'o':
	add_int_to_prompt(t->tm_mon+1);
	break;
      case 'O':
	processed_prompt.append(month_names[t->tm_mon]);
	break;
      case '\'':
	processed_prompt.append("'");
	break;
      case '"':
	processed_prompt.append('"');
	break;
      case 'S':
	processed_prompt.append(';');
	break;
      case 't':
	processed_prompt.append('\t');
	break;
      default:
	processed_prompt.append(c);
      }
    }
  }
  processed_prompt.append('\0');
  return processed_prompt.ptr();
}

2756 2757 2758

static void add_int_to_prompt(int toadd)
{
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2759 2760 2761 2762 2763
  char buffer[16];
  int10_to_str(toadd,buffer,10);
  processed_prompt.append(buffer);
}

2764 2765
static void init_username()
{
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2766 2767 2768 2769 2770 2771 2772
  my_free(full_username,MYF(MY_ALLOW_ZERO_PTR));
  my_free(part_username,MYF(MY_ALLOW_ZERO_PTR));

  MYSQL_RES *result;
  LINT_INIT(result);
  if (!mysql_query(&mysql,"select USER()") &&
      (result=mysql_use_result(&mysql)))
2773 2774 2775 2776 2777 2778
  {
    MYSQL_ROW cur=mysql_fetch_row(result);
    full_username=my_strdup(cur[0],MYF(MY_WME));
    part_username=my_strdup(strtok(cur[0],"@"),MYF(MY_WME));
    (void) mysql_fetch_row(result);		// Read eof
  }
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2779 2780
}

2781 2782 2783
static int com_prompt(String *buffer, char *line)
{
  char *ptr=strchr(line, ' ');
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2784 2785
  prompt_counter = 0;
  my_free(current_prompt,MYF(MY_ALLOW_ZERO_PTR));
2786 2787
  current_prompt=my_strdup(ptr ? ptr+1 : default_prompt,MYF(MY_WME));
  if (!ptr)
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
2788 2789 2790 2791 2792 2793
    tee_fprintf(stdout, "Returning to default PROMPT of %s\n", default_prompt);
  else
    tee_fprintf(stdout, "PROMPT set to '%s'\n", current_prompt);
  return 0;
}

2794
#ifndef EMBEDDED_LIBRARY
bk@work.mysql.com's avatar
bk@work.mysql.com committed
2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
/* 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));
}
2806
#endif /* EMBEDDED_LIBRARY */