mysqldump.c 43.7 KB
Newer Older
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1
/* Copyright (C) 2000 MySQL AB
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.
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.
12

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

/* mysqldump.c  - Dump a tables contents and format to an ASCII file
**
** The author's original notes follow :-
**
21 22 23 24 25 26 27 28 29 30 31 32 33
** AUTHOR: Igor Romanenko (igor@frog.kiev.ua)
** DATE:   December 3, 1994
** WARRANTY: None, expressed, impressed, implied
**	    or other
** STATUS: Public domain
** Adapted and optimized for MySQL by
** Michael Widenius, Sinisa Milivojevic, Jani Tolonen
** -w --where added 9/10/98 by Jim Faucette
** slave code by David Saez Padros <david@ols.es>
** master/autocommit code by Brian Aker <brian@tangent.org>
** SSL by
** Andrei Errapart <andreie@no.spam.ee>
** Tnu Samuel  <tonu@please.do.not.remove.this.spam.ee>
34 35
** XML by Gary Huntress <ghuntress@mediaone.net> 10/10/01, cleaned up
** and adapted to mysqldump 05/11/01 by Jani Tolonen
36
** Added --single-transaction option 06/06/2002 by Peter Zaitsev
37
*/
bk@work.mysql.com's avatar
bk@work.mysql.com committed
38

39
#define DUMP_VERSION "9.07"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
40

41
#include <my_global.h>
bk@work.mysql.com's avatar
bk@work.mysql.com committed
42 43 44 45
#include <my_sys.h>
#include <m_string.h>
#include <m_ctype.h>

46
#include "client_priv.h"
bk@work.mysql.com's avatar
bk@work.mysql.com committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
#include "mysql.h"
#include "mysql_version.h"
#include "mysqld_error.h"

/* Exit codes */

#define EX_USAGE 1
#define EX_MYSQLERR 2
#define EX_CONSCHECK 3
#define EX_EOM 4

/* index into 'show fields from table' */

#define SHOW_FIELDNAME  0
#define SHOW_TYPE  1
#define SHOW_NULL  2
#define SHOW_DEFAULT  4
#define SHOW_EXTRA  5
#define QUOTE_CHAR	'`'

67 68 69
/* Size of buffer for dump's select query */
#define QUERY_LENGTH 1536

bk@work.mysql.com's avatar
bk@work.mysql.com committed
70 71 72 73 74 75 76 77
static char *add_load_option(char *ptr, const char *object,
			     const char *statement);

static char *field_escape(char *to,const char *from,uint length);
static my_bool  verbose=0,tFlag=0,cFlag=0,dFlag=0,quick=0, extended_insert = 0,
		lock_tables=0,ignore_errors=0,flush_logs=0,replace=0,
		ignore=0,opt_drop=0,opt_keywords=0,opt_lock=0,opt_compress=0,
                opt_delayed=0,create_options=0,opt_quoted=0,opt_databases=0,
78
	        opt_alldbs=0,opt_create_db=0,opt_first_slave=0,
79
                opt_autocommit=0,opt_master_data,opt_disable_keys=0,opt_xml=0,
80
                tty_password=0,opt_single_transaction=0;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
81
static MYSQL  mysql_connection,*sock=0;
82
static char  insert_pat[12 * 1024],*opt_password=0,*current_user=0,
bk@work.mysql.com's avatar
bk@work.mysql.com committed
83 84 85 86 87 88 89 90
             *current_host=0,*path=0,*fields_terminated=0,
             *lines_terminated=0, *enclosed=0, *opt_enclosed=0, *escaped=0,
             *where=0, *default_charset;
static uint     opt_mysql_port=0;
static my_string opt_mysql_unix_port=0;
static int   first_error=0;
extern ulong net_buffer_length;
static DYNAMIC_STRING extended_row;
91
#include <sslopt-vars.h>
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
92
FILE  *md_result_file;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
93

94
static struct my_option my_long_options[] =
bk@work.mysql.com's avatar
bk@work.mysql.com committed
95
{
96 97 98 99
  {"all-databases", 'A',
   "Dump all the databases. This will be same as --databases with all databases selected.",
   (gptr*) &opt_alldbs, (gptr*) &opt_alldbs, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
   0, 0},
100 101 102
  {"all", 'a', "Include all MySQL specific create options.",
   (gptr*) &create_options, (gptr*) &create_options, 0, GET_BOOL, NO_ARG, 0,
   0, 0, 0, 0, 0},
103 104 105 106 107 108 109 110 111 112 113 114
  {"add-drop-table", OPT_DROP, "Add a 'drop table' before each create.",
   (gptr*) &opt_drop, (gptr*) &opt_drop, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0,
   0},
  {"add-locks", OPT_LOCKS, "Add locks around insert statements.",
   (gptr*) &opt_lock, (gptr*) &opt_lock, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0,
   0},
  {"allow-keywords", OPT_KEYWORDS,
   "Allow creation of column names that are keywords.", (gptr*) &opt_keywords,
   (gptr*) &opt_keywords, 0, GET_BOOL, 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},
115 116
  {"complete-insert", 'c', "Use complete insert statements.", (gptr*) &cFlag,
   (gptr*) &cFlag, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
  {"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},
  {"databases", 'B',
   "To dump several databases. Note the difference in usage; In this case no tables are given. All name arguments are regarded as databasenames. 'USE db_name;' will be included in the output.",
   (gptr*) &opt_databases, (gptr*) &opt_databases, 0, GET_BOOL, NO_ARG, 0, 0,
   0, 0, 0, 0},
  {"debug", '#', "Output debug log. Often this is 'd:t:o,filename'.",
   0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
  {"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},
  {"delayed-insert", OPT_DELAYED, "Insert rows with INSERT DELAYED.",
   (gptr*) &opt_delayed, (gptr*) &opt_delayed, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
   0, 0},
  {"disable-keys", 'K',
   "'/*!40000 ALTER TABLE tb_name DISABLE KEYS */; and '/*!40000 ALTER TABLE tb_name ENABLE KEYS */; will be put in the output.", (gptr*) &opt_disable_keys,
   (gptr*) &opt_disable_keys, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"extended-insert", 'e',
   "Allows utilization of the new, much faster INSERT syntax.",
   (gptr*) &extended_insert, (gptr*) &extended_insert, 0, GET_BOOL, NO_ARG,
   0, 0, 0, 0, 0, 0},
  {"fields-terminated-by", OPT_FTB,
   "Fields in the textfile are terminated by ...", (gptr*) &fields_terminated,
   (gptr*) &fields_terminated, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"fields-enclosed-by", OPT_ENC,
   "Fields in the importfile are enclosed by ...", (gptr*) &enclosed,
   (gptr*) &enclosed, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0 ,0, 0},
  {"fields-optionally-enclosed-by", OPT_O_ENC,
   "Fields in the i.file are opt. enclosed by ...", (gptr*) &opt_enclosed,
   (gptr*) &opt_enclosed, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0 ,0, 0},
  {"fields-escaped-by", OPT_ESC, "Fields in the i.file are escaped by ...",
   (gptr*) &escaped, (gptr*) &escaped, 0, GET_STR, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"first-slave", 'x', "Locks all tables across all databases.",
   (gptr*) &opt_first_slave, (gptr*) &opt_first_slave, 0, GET_BOOL, NO_ARG,
   0, 0, 0, 0, 0, 0},
  {"flush-logs", 'F', "Flush logs file in server before starting dump.",
   (gptr*) &flush_logs, (gptr*) &flush_logs, 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},
  {"help", '?', "Display this help message and exit.", 0, 0, 0, GET_NO_ARG,
   NO_ARG, 0, 0, 0, 0, 0, 0},
  {"host", 'h', "Connect to host.", (gptr*) &current_host,
162
   (gptr*) &current_host, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
163 164 165 166 167 168 169 170 171 172 173 174
  {"lines-terminated-by", OPT_LTB, "Lines in the i.file are terminated by ...",
   (gptr*) &lines_terminated, (gptr*) &lines_terminated, 0, GET_STR,
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"lock-tables", 'l', "Lock all tables for read.", (gptr*) &lock_tables,
   (gptr*) &lock_tables, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"master-data", OPT_MASTER_DATA,
   "This will cause the master position and filename to be appended to your output. This will automagically enable --first-slave.",
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"no-autocommit", OPT_AUTOCOMMIT,
   "Wrap tables with autocommit/commit statements.",
   (gptr*) &opt_autocommit, (gptr*) &opt_autocommit, 0, GET_BOOL, NO_ARG,
   0, 0, 0, 0, 0, 0},
175 176 177 178
  {"single-transaction", OPT_TRANSACTION,
   "Dump all tables in single transaction to get consistent snapshot. Mutually exclusive with --lock-tables.",
   (gptr*) &opt_single_transaction, (gptr*) &opt_single_transaction, 0, GET_BOOL, NO_ARG,
   0, 0, 0, 0, 0, 0},   
179 180 181 182 183
  {"no-create-db", 'n',
   "'CREATE DATABASE /*!32312 IF NOT EXISTS*/ db_name;' will not be put in the output. The above line will be added otherwise, if --databases or --all-databases option was given.}",
   (gptr*) &opt_create_db, (gptr*) &opt_create_db, 0, GET_BOOL, NO_ARG, 0, 0,
   0, 0, 0, 0},
  {"no-create-info", 't', "Don't write table creation info.",
184 185 186
   (gptr*) &tFlag, (gptr*) &tFlag, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"no-data", 'd', "No row information.", (gptr*) &dFlag, (gptr*) &dFlag, 0,
   GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
187
  {"set-variable", 'O',
188
   "Change the value of a variable. Please note that this option is deprecated; you can set variables directly with --variable-name=value.",
189 190 191 192 193 194 195
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"opt", OPT_OPTIMIZE,
   "Same as --add-drop-table --add-locks --all --quick --extended-insert --lock-tables --disable-keys",
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"password", 'p',
   "Password to use when connecting to server. If password is not given it's solicited on 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
196
#ifdef __WIN__
197 198
  {"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
199
#endif
200 201 202
  {"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},
203 204 205 206 207 208
  {"quick", 'q', "Don't buffer query, dump directly to stdout.",
   (gptr*) &quick, (gptr*) &quick, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"quote-names",'Q', "Quote table and column names with a `",
   (gptr*) &opt_quoted, (gptr*) &opt_quoted, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
   0, 0},
  {"result-file", 'r',
serg@sergbook.mysql.com's avatar
serg@sergbook.mysql.com committed
209
   "Direct output to a given file. This option should be used in MSDOS, because it prevents new line '\\n' from being converted to '\\r\\n' (carriage return + line feed).",
210
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
211 212 213
  {"socket", 'S', "Socket file to use for connection.",
   (gptr*) &opt_mysql_unix_port, (gptr*) &opt_mysql_unix_port, 0, GET_STR,
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
214
#include <sslopt-longopts.h>
215 216 217 218 219
  {"tab",'T',
   "Creates tab separated textfile for each table to given path. (creates .sql and .txt files). NOTE: This only works if mysqldump is run on the same machine as the mysqld daemon.",
   (gptr*) &path, (gptr*) &path, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"tables", OPT_TABLES, "Overrides option --databases (-B).",
   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
220
#ifndef DONT_ALLOW_USER_CHANGE
221 222 223
  {"user", 'u', "User for login if not current user.",
   (gptr*) &current_user, (gptr*) &current_user, 0, GET_STR, REQUIRED_ARG,
   0, 0, 0, 0, 0, 0},
bk@work.mysql.com's avatar
bk@work.mysql.com committed
224
#endif
225 226 227 228 229 230 231 232
  {"verbose", 'v', "Print info about the various stages.",
   (gptr*) &verbose, (gptr*) &verbose, 0, GET_BOOL, 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},
  {"where", 'w', "Dump only selected records; QUOTES mandatory!",
   (gptr*) &where, (gptr*) &where, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"xml", 'X', "Dump a database as well formed XML.", 0, 0, 0, GET_NO_ARG,
   NO_ARG, 0, 0, 0, 0, 0, 0},
233
  {"max_allowed_packet", OPT_MAX_ALLOWED_PACKET, "",
234
    (gptr*) &max_allowed_packet, (gptr*) &max_allowed_packet, 0,
235
    GET_ULONG, REQUIRED_ARG, 24*1024*1024, 4096, 1024*1024L*1024L,
236
    MALLOC_OVERHEAD, 1024, 0},
237
  {"net_buffer_length", OPT_NET_BUFFER_LENGTH, "",
238
    (gptr*) &net_buffer_length, (gptr*) &net_buffer_length, 0,
239
    GET_ULONG, REQUIRED_ARG, 1024*1024L-1025, 4096, 16*1024L*1024L,
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
240
    MALLOC_OVERHEAD-1024, 1024, 0},
241
  {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
242 243 244 245 246
};

static const char *load_default_groups[]= { "mysqldump","client",0 };

static void safe_exit(int error);
247
static void write_header(FILE *sql_file, char *db_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
248 249 250 251 252 253 254 255 256
static void print_value(FILE *file, MYSQL_RES  *result, MYSQL_ROW row,
			const char *prefix,const char *name,
			int string_value);
static int dump_selected_tables(char *db, char **table_names, int tables);
static int dump_all_tables_in_db(char *db);
static int init_dumping(char *);
static int dump_databases(char **);
static int dump_all_databases();
static char *quote_name(char *name, char *buff);
257
static void print_quoted_xml(FILE *output, char *fname, char *str, uint len);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
258 259 260 261 262 263 264 265

static void print_version(void)
{
  printf("%s  Ver %s Distrib %s, for %s (%s)\n",my_progname,DUMP_VERSION,
   MYSQL_SERVER_VERSION,SYSTEM_TYPE,MACHINE_TYPE);
} /* print_version */


266 267 268 269 270 271 272 273
static void short_usage_sub(void)
{
  printf("Usage: %s [OPTIONS] database [tables]\n", my_progname);
  printf("OR     %s [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]\n",
	 my_progname);
  printf("OR     %s [OPTIONS] --all-databases [OPTIONS]\n", my_progname);
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
274 275 276 277 278 279
static void usage(void)
{
  print_version();
  puts("By Igor Romanenko, Monty, Jani & Sinisa");
  puts("This software comes with ABSOLUTELY NO WARRANTY. This is free software,\nand you are welcome to modify and redistribute it under the GPL license\n");
  puts("Dumping definition and data mysql database or table");
280
  short_usage_sub();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
281
  print_defaults("my",load_default_groups);
282 283
  my_print_help(my_long_options);
  my_print_variables(my_long_options);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
284 285 286
} /* usage */


287 288 289 290 291 292 293
static void short_usage(void)
{
  short_usage_sub();
  printf("For more options, use %s --help\n", my_progname);
}


294
static void write_header(FILE *sql_file, char *db_name)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
295
{
296 297 298 299 300 301 302 303 304 305 306 307
  if (opt_xml)
    fprintf(sql_file,"<?xml version=\"1.0\"?>\n");
  else
  {
    fprintf(sql_file, "-- MySQL dump %s\n--\n", DUMP_VERSION);
    fprintf(sql_file, "-- Host: %s    Database: %s\n",
	    current_host ? current_host : "localhost", db_name ? db_name : "");
    fputs("---------------------------------------------------------\n",
	  sql_file);
    fprintf(sql_file, "-- Server version\t%s\n",
	    mysql_get_server_info(&mysql_connection));
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
308
  return;
309
} /* write_header */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
310 311


312 313 314
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
315
{
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
  switch(optid) {
  case OPT_MASTER_DATA:
    opt_master_data=1;
    opt_first_slave=1;
    break;
  case 'p':
    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;				/* Cut length of argument */
    }
    else
      tty_password=1;
    break;
  case 'r':
    if (!(md_result_file = my_fopen(argument, O_WRONLY | O_BINARY,
				    MYF(MY_WME))))
      exit(1);
    break;
  case 'W':
bk@work.mysql.com's avatar
bk@work.mysql.com committed
340
#ifdef __WIN__
341
    opt_mysql_unix_port=MYSQL_NAMEDPIPE;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
342
#endif
343 344 345 346 347 348 349
    break;
  case 'T':
    opt_disable_keys=0;
    break;
  case '#':
    DBUG_PUSH(argument ? argument : "d:t:o");
    break;
350
#include <sslopt-case.h>
351 352 353 354 355 356 357 358 359 360
  case 'V': print_version(); exit(0);
  case 'X':
    opt_xml = 1;
    opt_disable_keys=0;
    break;
  case 'I':
  case '?':
    usage();
    exit(0);
  case (int) OPT_OPTIMIZE:
361 362 363
    extended_insert=opt_drop=opt_lock=quick=create_options=opt_disable_keys=
    lock_tables=1;
    if (opt_single_transaction) lock_tables=0;
364 365 366 367
    break;
  case (int) OPT_TABLES:
    opt_databases=0;
    break;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
368
  }
369 370 371 372 373 374 375 376 377 378 379 380
  return 0;
}


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

  md_result_file= stdout;
  load_defaults("my",load_default_groups,argc,argv);

  if ((ho_error=handle_options(argc, argv, my_long_options, get_one_option)))
381
    exit(ho_error);
382

bk@work.mysql.com's avatar
bk@work.mysql.com committed
383 384 385 386 387
  if (opt_delayed)
    opt_lock=0;				/* Can't have lock with delayed */
  if (!path && (enclosed || opt_enclosed || escaped || lines_terminated ||
		fields_terminated))
  {
388 389
    fprintf(stderr,
	    "%s: You must use option --tab with --fields-...\n", my_progname);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
390 391
    return(1);
  }
392 393 394 395 396 397
  
  if (opt_single_transaction && lock_tables) 
  {
    fprintf(stderr, "%s: You can't use --lock-tables and --single-transaction at the same time.\n", my_progname);
    return(1);    
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422

  if (enclosed && opt_enclosed)
  {
    fprintf(stderr, "%s: You can't use ..enclosed.. and ..optionally-enclosed.. at the same time.\n", my_progname);
    return(1);
  }
  if (replace && ignore)
  {
    fprintf(stderr, "%s: You can't use --ignore (-i) and --replace (-r) at the same time.\n",my_progname);
    return(1);
  }
  if ((opt_databases || opt_alldbs) && path)
  {
    fprintf(stderr,
	    "%s: --databases or --all-databases can't be used with --tab.\n",
	    my_progname);
    return(1);
  }
  if (default_charset)
  {
    if (set_default_charset_by_name(default_charset, MYF(MY_WME)))
      exit(1);
  }
  if ((*argc < 1 && !opt_alldbs) || (*argc > 0 && opt_alldbs))
  {
423
    short_usage();
bk@work.mysql.com's avatar
bk@work.mysql.com committed
424 425 426
    return 1;
  }
  if (tty_password)
427
    opt_password=get_tty_password(NullS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
428 429 430 431 432 433 434 435 436 437
  return(0);
} /* get_options */


/*
** DBerror -- prints mysql error message and exits the program.
*/
static void DBerror(MYSQL *mysql, const char *when)
{
  DBUG_ENTER("DBerror");
438
  my_printf_error(0,"Got error: %d: %s %s", MYF(0),
bk@work.mysql.com's avatar
bk@work.mysql.com committed
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
		  mysql_errno(mysql), mysql_error(mysql), when);
  safe_exit(EX_MYSQLERR);
  DBUG_VOID_RETURN;
} /* DBerror */


static void safe_exit(int error)
{
  if (!first_error)
    first_error= error;
  if (ignore_errors)
    return;
  if (sock)
    mysql_close(sock);
  exit(error);
}
/* safe_exit */


/*
** dbConnect -- connects to the host and selects DB.
**        Also checks whether the tablename is a valid table name.
*/
static int dbConnect(char *host, char *user,char *passwd)
{
  DBUG_ENTER("dbConnect");
  if (verbose)
  {
467
    fprintf(stderr, "-- Connecting to %s...\n", host ? host : "localhost");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
468 469 470 471 472 473 474
  }
  mysql_init(&mysql_connection);
  if (opt_compress)
    mysql_options(&mysql_connection,MYSQL_OPT_COMPRESS,NullS);
#ifdef HAVE_OPENSSL
  if (opt_use_ssl)
    mysql_ssl_set(&mysql_connection, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
475
		  opt_ssl_capath, opt_ssl_cipher);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
#endif
  if (!(sock= mysql_real_connect(&mysql_connection,host,user,passwd,
         NULL,opt_mysql_port,opt_mysql_unix_port,
         0)))
  {
    DBerror(&mysql_connection, "when trying to connect");
    return 1;
  }
  return 0;
} /* dbConnect */


/*
** dbDisconnect -- disconnects from the host.
*/
static void dbDisconnect(char *host)
{
  if (verbose)
494
    fprintf(stderr, "-- Disconnecting from %s...\n", host ? host : "localhost");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
495 496 497 498 499 500 501 502 503 504 505 506 507
  mysql_close(sock);
} /* dbDisconnect */


static void unescape(FILE *file,char *pos,uint length)
{
  char *tmp;
  DBUG_ENTER("unescape");
  if (!(tmp=(char*) my_malloc(length*2+1, MYF(MY_WME))))
  {
    ignore_errors=0;				/* Fatal error */
    safe_exit(EX_MYSQLERR);			/* Force exit */
  }
508
  mysql_real_escape_string(&mysql_connection, tmp, pos, length);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
509 510 511 512 513 514 515 516 517 518 519 520
  fputc('\'', file);
  fputs(tmp, file);
  fputc('\'', file);
  my_free(tmp, MYF(MY_WME));
  DBUG_VOID_RETURN;
} /* unescape */


static my_bool test_if_special_chars(const char *str)
{
#if MYSQL_VERSION_ID >= 32300
  for ( ; *str ; str++)
521
    if (!my_isvar(system_charset_info,*str) && *str != '$')
bk@work.mysql.com's avatar
bk@work.mysql.com committed
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
      return 1;
#endif
  return 0;
} /* test_if_special_chars */

static char *quote_name(char *name, char *buff)
{
  char *end;
  if (!opt_quoted && !test_if_special_chars(name))
    return name;
  buff[0]=QUOTE_CHAR;
  end=strmov(buff+1,name);
  end[0]=QUOTE_CHAR;
  end[1]=0;
  return buff;
} /* quote_name */


/*
** getStructure -- retrievs database structure, prints out corresponding
**       CREATE statement and fills out insert_pat.
** Return values:  number of fields in table, 0 if error
*/
static uint getTableStructure(char *table, char* db)
{
  MYSQL_RES  *tableRes;
  MYSQL_ROW  row;
  my_bool    init=0;
  uint       numFields;
551
  char	     *strpos, *table_name;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
552
  const char *delayed;
553
  char	     name_buff[NAME_LEN+3],table_buff[NAME_LEN+3];
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
554
  FILE       *sql_file = md_result_file;
bk@work.mysql.com's avatar
bk@work.mysql.com committed
555 556 557 558 559
  DBUG_ENTER("getTableStructure");

  delayed= opt_delayed ? " DELAYED " : "";

  if (verbose)
560
    fprintf(stderr, "-- Retrieving table structure for table %s...\n", table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
561

562
  sprintf(insert_pat,"SET OPTION SQL_QUOTE_SHOW_CREATE=%d", opt_quoted);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
563
  table_name=quote_name(table,table_buff);
serg@serg.mysql.com's avatar
serg@serg.mysql.com committed
564
  if (!mysql_query(sock,insert_pat))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
565
  {
566 567
    /* using SHOW CREATE statement */
    if (!tFlag)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
568
    {
569 570 571
      /* Make an sql-file, if path was given iow. option -T was given */
      char buff[20+FN_REFLEN];

jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
572
      sprintf(buff,"show create table `%s`",table);
573
      if (mysql_query(sock, buff))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
574
      {
575
        fprintf(stderr, "%s: Can't get CREATE TABLE for table '%s' (%s)\n",
576
		      my_progname, table, mysql_error(sock));
577 578
        safe_exit(EX_MYSQLERR);
        DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
579 580
      }

581 582 583
      if (path)
      {
        char filename[FN_REFLEN], tmp_path[FN_REFLEN];
584
        convert_dirname(tmp_path,path,NullS);
585
        sql_file= my_fopen(fn_format(filename, table, tmp_path, ".sql", 4),
586
				 O_WRONLY, MYF(MY_WME));
587 588
        if (!sql_file)			/* If file couldn't be opened */
        {
589 590
	  safe_exit(EX_MYSQLERR);
	  DBUG_RETURN(0);
591
        }
592
        write_header(sql_file, db);
593
      }
594 595 596
      if (!opt_xml)
	fprintf(sql_file, "\n--\n-- Table structure for table '%s'\n--\n\n",
		table);
597 598 599 600 601
      if (opt_drop)
        fprintf(sql_file, "DROP TABLE IF EXISTS %s;\n",table_name);

      tableRes=mysql_store_result(sock);
      row=mysql_fetch_row(tableRes);
602 603
      if (!opt_xml)
	fprintf(sql_file, "%s;\n", row[1]);
604 605 606 607
      mysql_free_result(tableRes);
    }
    sprintf(insert_pat,"show fields from %s",table_name);
    if (mysql_query(sock,insert_pat) || !(tableRes=mysql_store_result(sock)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
608
    {
609
      fprintf(stderr, "%s: Can't get info about table: '%s'\nerror: %s\n",
610
		    my_progname, table, mysql_error(sock));
611 612
      if (path)
	my_fclose(sql_file, MYF(MY_WME));
613 614
      safe_exit(EX_MYSQLERR);
      DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
615
    }
616

bk@work.mysql.com's avatar
bk@work.mysql.com committed
617
    if (cFlag)
618 619
      sprintf(insert_pat, "INSERT %sINTO %s (", delayed, table_name);
    else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
620
    {
621 622 623 624 625 626 627 628 629
      sprintf(insert_pat, "INSERT %sINTO %s VALUES ", delayed, table_name);
      if (!extended_insert)
        strcat(insert_pat,"(");
    }

    strpos=strend(insert_pat);
    while ((row=mysql_fetch_row(tableRes)))
    {
      if (init)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
630
      {
631
        if (cFlag)
632
	  strpos=strmov(strpos,", ");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
633
      }
634 635 636
      init=1;
      if (cFlag)
        strpos=strmov(strpos,quote_name(row[SHOW_FIELDNAME],name_buff));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
637
    }
638 639
    numFields = (uint) mysql_num_rows(tableRes);
    mysql_free_result(tableRes);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
640
  }
641
  else
bk@work.mysql.com's avatar
bk@work.mysql.com committed
642
  {
643 644 645 646 647
  /*  fprintf(stderr, "%s: Can't set SQL_QUOTE_SHOW_CREATE option (%s)\n",
      my_progname, mysql_error(sock)); */

    sprintf(insert_pat,"show fields from %s",table_name);
    if (mysql_query(sock,insert_pat) || !(tableRes=mysql_store_result(sock)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
648
    {
649 650
      fprintf(stderr, "%s: Can't get info about table: '%s'\nerror: %s\n",
		    my_progname, table, mysql_error(sock));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
651 652 653 654
      safe_exit(EX_MYSQLERR);
      DBUG_RETURN(0);
    }

655 656
    /* Make an sql-file, if path was given iow. option -T was given */
    if (!tFlag)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
657
    {
658
      if (path)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
659
      {
660
        char filename[FN_REFLEN], tmp_path[FN_REFLEN];
661
        convert_dirname(tmp_path,path,NullS);
662 663 664 665
        sql_file= my_fopen(fn_format(filename, table, tmp_path, ".sql", 4),
				 O_WRONLY, MYF(MY_WME));
        if (!sql_file)			/* If file couldn't be opened */
        {
666 667
	  safe_exit(EX_MYSQLERR);
	  DBUG_RETURN(0);
668
        }
669
        write_header(sql_file, db);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
670
      }
671 672 673
      if (!opt_xml)
	fprintf(sql_file, "\n--\n-- Table structure for table '%s'\n--\n\n",
		table);
674 675 676 677 678 679 680 681 682 683 684
      if (opt_drop)
        fprintf(sql_file, "DROP TABLE IF EXISTS %s;\n",table_name);
      fprintf(sql_file, "CREATE TABLE %s (\n", table_name);
    }
    if (cFlag)
      sprintf(insert_pat, "INSERT %sINTO %s (", delayed, table_name);
    else
    {
      sprintf(insert_pat, "INSERT %sINTO %s VALUES ", delayed, table_name);
      if (!extended_insert)
        strcat(insert_pat,"(");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
685
    }
686 687

    strpos=strend(insert_pat);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
688 689
    while ((row=mysql_fetch_row(tableRes)))
    {
690 691
      ulong *lengths=mysql_fetch_lengths(tableRes);
      if (init)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
692
      {
693
        if (!tFlag)
694
	  fputs(",\n",sql_file);
695
        if (cFlag)
696
	  strpos=strmov(strpos,", ");
697 698 699 700 701 702 703
      }
      init=1;
      if (cFlag)
        strpos=strmov(strpos,quote_name(row[SHOW_FIELDNAME],name_buff));
      if (!tFlag)
      {
        if (opt_keywords)
704
	  fprintf(sql_file, "  %s.%s %s", table_name,
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
705
	  quote_name(row[SHOW_FIELDNAME],name_buff), row[SHOW_TYPE]);
706
        else
707 708
	  fprintf(sql_file, "  %s %s", quote_name(row[SHOW_FIELDNAME],
						  name_buff), row[SHOW_TYPE]);
709 710
        if (row[SHOW_DEFAULT])
        {
711
	  fputs(" DEFAULT ", sql_file);
712
	  unescape(sql_file, row[SHOW_DEFAULT], lengths[SHOW_DEFAULT]);
713 714
        }
        if (!row[SHOW_NULL][0])
715
	  fputs(" NOT NULL", sql_file);
716
        if (row[SHOW_EXTRA][0])
717
	  fprintf(sql_file, " %s",row[SHOW_EXTRA]);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
718 719
      }
    }
720 721 722
    numFields = (uint) mysql_num_rows(tableRes);
    mysql_free_result(tableRes);
    if (!tFlag)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
723
    {
724 725 726 727
      /* Make an sql-file, if path was given iow. option -T was given */
      char buff[20+FN_REFLEN];
      uint keynr,primary_key;
      sprintf(buff,"show keys from %s",table_name);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
728 729
      if (mysql_query(sock, buff))
      {
730
        fprintf(stderr, "%s: Can't get keys for table '%s' (%s)\n",
731
		my_progname, table, mysql_error(sock));
732
        if (path)
733
	  my_fclose(sql_file, MYF(MY_WME));
734 735
        safe_exit(EX_MYSQLERR);
        DBUG_RETURN(0);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
736
      }
737 738 739 740 741 742

      tableRes=mysql_store_result(sock);
      /* Find first which key is primary key */
      keynr=0;
      primary_key=INT_MAX;
      while ((row=mysql_fetch_row(tableRes)))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
743
      {
744 745
        if (atoi(row[3]) == 1)
        {
746 747 748 749 750 751 752 753 754 755
	  keynr++;
#ifdef FORCE_PRIMARY_KEY
	  if (atoi(row[1]) == 0 && primary_key == INT_MAX)
	    primary_key=keynr;
#endif
	  if (!strcmp(row[2],"PRIMARY"))
	  {
	    primary_key=keynr;
	    break;
	  }
756
        }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
757
      }
758 759 760 761 762 763
      mysql_data_seek(tableRes,0);
      keynr=0;
      while ((row=mysql_fetch_row(tableRes)))
      {
        if (atoi(row[3]) == 1)
        {
764 765 766 767 768 769 770 771 772
	  if (keynr++)
	    putc(')', sql_file);
	  if (atoi(row[1]))       /* Test if duplicate key */
	    /* Duplicate allowed */
	    fprintf(sql_file, ",\n  KEY %s (",quote_name(row[2],name_buff));
	  else if (keynr == primary_key)
	    fputs(",\n  PRIMARY KEY (",sql_file); /* First UNIQUE is primary */
	  else
	    fprintf(sql_file, ",\n  UNIQUE %s (",quote_name(row[2],name_buff));
773 774
        }
        else
775
	  putc(',', sql_file);
776 777
        fputs(quote_name(row[4],name_buff), sql_file);
        if (row[7])
778
	  fprintf(sql_file, " (%s)",row[7]);      /* Sub key */
779 780 781 782 783 784 785
      }
      if (keynr)
        putc(')', sql_file);
      fputs("\n)",sql_file);

      /* Get MySQL specific create options */
      if (create_options)
bk@work.mysql.com's avatar
bk@work.mysql.com committed
786
      {
787 788 789
        sprintf(buff,"show table status like '%s'",table);
        if (mysql_query(sock, buff))
        {
790 791 792 793
	  if (mysql_errno(sock) != ER_PARSE_ERROR)
	  {					/* If old MySQL version */
	    if (verbose)
	      fprintf(stderr,
794
		      "-- Warning: Couldn't get status information for table '%s' (%s)\n",
795 796
		      table,mysql_error(sock));
	  }
797 798
        }
        else if (!(tableRes=mysql_store_result(sock)) ||
799
		 !(row=mysql_fetch_row(tableRes)))
800
        {
801 802 803
	  fprintf(stderr,
		  "Error: Couldn't read status information for table '%s' (%s)\n",
		  table,mysql_error(sock));
804 805 806
        }
        else
        {
807 808 809 810 811
	  fputs("/*!",sql_file);
	  print_value(sql_file,tableRes,row,"type=","Type",0);
	  print_value(sql_file,tableRes,row,"","Create_options",0);
	  print_value(sql_file,tableRes,row,"comment=","Comment",1);
	  fputs(" */",sql_file);
812 813
        }
        mysql_free_result(tableRes);		/* Is always safe to free */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
814
      }
815
      fputs(";\n", sql_file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
816 817 818 819 820 821 822 823
    }
  }
  if (cFlag)
  {
    strpos=strmov(strpos,") VALUES ");
    if (!extended_insert)
      strpos=strmov(strpos,"(");
  }
824 825
  if (sql_file != md_result_file)
    my_fclose(sql_file, MYF(MY_WME));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
826 827 828 829 830 831 832 833 834
  DBUG_RETURN(numFields);
} /* getTableStructure */


static char *add_load_option(char *ptr,const char *object,
			     const char *statement)
{
  if (object)
  {
835 836 837 838 839 840 841 842 843 844
    /* Don't escape hex constants */
    if (object[0] == '0' && (object[1] == 'x' || object[1] == 'X'))
      ptr= strxmov(ptr," ",statement," ",object,NullS);
    else
    {
      /* char constant; escape */
      ptr= strxmov(ptr," ",statement," '",NullS);
      ptr= field_escape(ptr,object,(uint) strlen(object));
      *ptr++= '\'';
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
845 846 847 848 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
  }
  return ptr;
} /* add_load_option */


/*
** Allow the user to specify field terminator strings like:
** "'", "\", "\\" (escaped backslash), "\t" (tab), "\n" (newline)
** This is done by doubleing ' and add a end -\ if needed to avoid
** syntax errors from the SQL parser.
*/

static char *field_escape(char *to,const char *from,uint length)
{
  const char *end;
  uint end_backslashes=0;

  for (end= from+length; from != end; from++)
  {
    *to++= *from;
    if (*from == '\\')
      end_backslashes^=1;    /* find odd number of backslashes */
    else
    {
      if (*from == '\'' && !end_backslashes)
	*to++= *from;      /* We want a duplicate of "'" for MySQL */
      end_backslashes=0;
    }
  }
  /* Add missing backslashes if user has specified odd number of backs.*/
  if (end_backslashes)
    *to++= '\\';
  return to;
} /* field_escape */


/*
** dumpTable saves database contents as a series of INSERT statements.
*/
static void dumpTable(uint numFields, char *table)
{
886
  char query[QUERY_LENGTH], *end, buff[256],table_buff[NAME_LEN+3];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
887 888 889 890 891 892
  MYSQL_RES	*res;
  MYSQL_FIELD  *field;
  MYSQL_ROW    row;
  ulong		rownr, row_break, total_length, init_length;

  if (verbose)
893
    fprintf(stderr, "-- Sending SELECT query...\n");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
894 895 896
  if (path)
  {
    char filename[FN_REFLEN], tmp_path[FN_REFLEN];
897
    convert_dirname(tmp_path,path,NullS);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
898 899 900 901 902
    my_load_path(tmp_path, tmp_path, NULL);
    fn_format(filename, table, tmp_path, ".txt", 4);
    my_delete(filename, MYF(0)); /* 'INTO OUTFILE' doesn't work, if
				    filename wasn't deleted */
    to_unix_path(filename);
903 904
    sprintf(query, "SELECT /*!40001 SQL_NO_CACHE */ * INTO OUTFILE '%s'",
	    filename);
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
    end= strend(query);
    if (replace)
      end= strmov(end, " REPLACE");
    if (ignore)
      end= strmov(end, " IGNORE");

    if (fields_terminated || enclosed || opt_enclosed || escaped)
      end= strmov(end, " FIELDS");
    end= add_load_option(end, fields_terminated, " TERMINATED BY");
    end= add_load_option(end, enclosed, " ENCLOSED BY");
    end= add_load_option(end, opt_enclosed, " OPTIONALLY ENCLOSED BY");
    end= add_load_option(end, escaped, " ESCAPED BY");
    end= add_load_option(end, lines_terminated, " LINES TERMINATED BY");
    *end= '\0';

920
    sprintf(buff," FROM %s",quote_name(table,table_buff));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
921 922 923 924 925 926 927 928 929 930 931
    end= strmov(end,buff);
    if (where)
      end= strxmov(end, " WHERE ",where,NullS);
    if (mysql_query(sock, query))
    {
      DBerror(sock, "when executing 'SELECT INTO OUTFILE'");
      return;
    }
  }
  else
  {
932 933 934
    if (!opt_xml)
      fprintf(md_result_file,"\n--\n-- Dumping data for table '%s'\n--\n",
	      table);
935 936
    sprintf(query, "SELECT /*!40001 SQL_NO_CACHE */ * FROM %s",
	    quote_name(table,table_buff));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
937 938
    if (where)
    {
939 940
      if (!opt_xml)
	fprintf(md_result_file,"-- WHERE:  %s\n",where);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
941 942
      strxmov(strend(query), " WHERE ",where,NullS);
    }
943
    if (!opt_xml)
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
944
      fputs("\n", md_result_file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
    if (mysql_query(sock, query))
    {
      DBerror(sock, "when retrieving data from server");
      return;
    }
    if (quick)
      res=mysql_use_result(sock);
    else
      res=mysql_store_result(sock);
    if (!res)
    {
      DBerror(sock, "when retrieving data from server");
      return;
    }
    if (verbose)
960
      fprintf(stderr, "-- Retrieving rows...\n");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
961 962 963 964 965 966 967 968
    if (mysql_num_fields(res) != numFields)
    {
      fprintf(stderr,"%s: Error in field count for table: '%s' !  Aborting.\n",
	      my_progname,table);
      safe_exit(EX_CONSCHECK);
      return;
    }

jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
969 970 971
    if (opt_disable_keys)
      fprintf(md_result_file,"/*!40000 ALTER TABLE %s DISABLE KEYS */;\n",
	      quote_name(table, table_buff));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
972
    if (opt_lock)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
973
      fprintf(md_result_file,"LOCK TABLES %s WRITE;\n",
974
	      quote_name(table,table_buff));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
975 976 977 978

    total_length=net_buffer_length;		/* Force row break */
    row_break=0;
    rownr=0;
979
    init_length=(uint) strlen(insert_pat)+4;
980 981
    if (opt_xml)
      fprintf(md_result_file, "\t<%s>\n", table);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
982

983 984 985
    if (opt_autocommit)
      fprintf(md_result_file, "set autocommit=0;\n");

bk@work.mysql.com's avatar
bk@work.mysql.com committed
986 987 988 989 990
    while ((row=mysql_fetch_row(res)))
    {
      uint i;
      ulong *lengths=mysql_fetch_lengths(res);
      rownr++;
991
      if (!extended_insert && !opt_xml)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
992
	fputs(insert_pat,md_result_file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
993 994
      mysql_field_seek(res,0);

jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
995 996 997
      if (opt_xml)
        fprintf(md_result_file, "\t<row>\n");

bk@work.mysql.com's avatar
bk@work.mysql.com committed
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
      for (i = 0; i < mysql_num_fields(res); i++)
      {
	if (!(field = mysql_fetch_field(res)))
	{
	  sprintf(query,"%s: Not enough fields from table '%s'! Aborting.\n",
		  my_progname,table);
	  fputs(query,stderr);
	  safe_exit(EX_CONSCHECK);
	  return;
	}
	if (extended_insert)
	{
	  ulong length = lengths[i];
	  if (i == 0)
	    dynstr_set(&extended_row,"(");
	  else
	    dynstr_append(&extended_row,",");

	  if (row[i])
	  {
	    if (length)
	    {
1020
	      if (!IS_NUM_FIELD(field))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1021 1022 1023 1024 1025 1026 1027
	      {
		if (dynstr_realloc(&extended_row,length * 2+2))
		{
		  fputs("Aborting dump (out of memory)",stderr);
		  safe_exit(EX_EOM);
		}
		dynstr_append(&extended_row,"\'");
1028
		extended_row.length +=
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1029 1030 1031 1032 1033 1034
		  mysql_real_escape_string(&mysql_connection,
					   &extended_row.str[extended_row.length],row[i],length);
		extended_row.str[extended_row.length]='\0';
		dynstr_append(&extended_row,"\'");
	      }
	      else
1035 1036 1037 1038
	      {
		/* change any strings ("inf","nan",..) into NULL */
		char *ptr = row[i];
		dynstr_append(&extended_row,
1039 1040
			      (!my_isalpha(system_charset_info,*ptr)) ? 
			      ptr : "NULL");
1041
	      }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
	    }
	    else
	      dynstr_append(&extended_row,"\'\'");
	  }
	  else if (dynstr_append(&extended_row,"NULL"))
	  {
	    fputs("Aborting dump (out of memory)",stderr);
	    safe_exit(EX_EOM);
	  }
	}
	else
	{
1054 1055
	  if (i && !opt_xml)
	    fputc(',', md_result_file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1056 1057
	  if (row[i])
	  {
1058
	    if (!IS_NUM_FIELD(field))
1059
	    {
1060 1061 1062 1063 1064
	      if (opt_xml)
		print_quoted_xml(md_result_file, field->name, row[i],
				 lengths[i]);
	      else
		unescape(md_result_file, row[i], lengths[i]);
1065
	    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1066
	    else
1067 1068 1069
	    {
	      /* change any strings ("inf","nan",..) into NULL */
	      char *ptr = row[i];
1070 1071
	      if (opt_xml)
		fprintf(md_result_file, "\t\t<%s>%s</%s>\n",
1072 1073
			field->name,
			!my_isalpha(system_charset_info,*ptr) ?ptr: "NULL",field->name);
1074
	      else
1075 1076
		fputs((!my_isalpha(system_charset_info,*ptr)) ? 
		       ptr : "NULL", md_result_file);
1077
	    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1078 1079 1080
	  }
	  else
	  {
1081 1082 1083 1084 1085
	    if (opt_xml)
	      fprintf(md_result_file, "\t\t<%s>%s</%s>\n",
		      field->name, "NULL", field->name);
	    else
	      fputs("NULL", md_result_file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1086 1087 1088 1089
	  }
	}
      }

jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
1090 1091 1092
      if (opt_xml)
        fprintf(md_result_file, "\t</row>\n");

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1093 1094 1095 1096 1097 1098 1099 1100
      if (extended_insert)
      {
	ulong row_length;
	dynstr_append(&extended_row,")");
        row_length = 2 + extended_row.length;
        if (total_length + row_length < net_buffer_length)
        {
	  total_length += row_length;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1101 1102
	  fputc(',',md_result_file);		/* Always row break */
	  fputs(extended_row.str,md_result_file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1103 1104 1105
	}
        else
        {
1106
	  if (row_break && !opt_xml)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1107
	    fputs(";\n", md_result_file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1108
	  row_break=1;				/* This is first row */
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1109

1110 1111 1112 1113 1114
	  if (!opt_xml)
	  {
	    fputs(insert_pat,md_result_file);
	    fputs(extended_row.str,md_result_file);
	  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1115 1116 1117
	  total_length = row_length+init_length;
        }
      }
1118
      else if (!opt_xml)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1119
	fputs(");\n", md_result_file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1120
    }
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1121

1122
    /* XML - close table tag and supress regular output */
1123
    if (opt_xml)
1124
	fprintf(md_result_file, "\t</%s>\n", table);
1125
    else if (extended_insert && row_break)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1126 1127
      fputs(";\n", md_result_file);		/* If not empty table */
    fflush(md_result_file);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
    if (mysql_errno(sock))
    {
      sprintf(query,"%s: Error %d: %s when dumping table '%s' at row: %ld\n",
	      my_progname,
	      mysql_errno(sock),
	      mysql_error(sock),
	      table,
	      rownr);
      fputs(query,stderr);
      safe_exit(EX_CONSCHECK);
      return;
    }
    if (opt_lock)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1141
      fputs("UNLOCK TABLES;\n", md_result_file);
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
1142 1143 1144
    if (opt_disable_keys)
      fprintf(md_result_file,"/*!40000 ALTER TABLE %s ENABLE KEYS */;\n",
	      quote_name(table,table_buff));
1145 1146
    if (opt_autocommit)
      fprintf(md_result_file, "commit;\n");
1147
    mysql_free_result(res);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1148 1149 1150 1151
  }
} /* dumpTable */


1152 1153 1154
static void print_quoted_xml(FILE *output, char *fname, char *str, uint len)
{
  const char *end;
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1155

1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
  fprintf(output, "\t\t<%s>", fname);
  for (end = str + len; str != end; str++)
  {
    if (*str == '<')
      fputs("&lt;", output);
    else if (*str == '>')
      fputs("&gt;", output);
    else if (*str == '&')
      fputs("&amp;", output);
    else if (*str == '\"')
      fputs("&quot;", output);
    else
      fputc(*str, output);
  }
jani@hynda.mysql.fi's avatar
merge  
jani@hynda.mysql.fi committed
1170
  fprintf(output, "</%s>\n", fname);
1171 1172
}

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
static char *getTableName(int reset)
{
  static MYSQL_RES *res = NULL;
  MYSQL_ROW    row;

  if (!res)
  {
    if (!(res = mysql_list_tables(sock,NullS)))
      return(NULL);
  }
  if ((row = mysql_fetch_row(res)))
    return((char*) row[0]);
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1185

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
  if (reset)
    mysql_data_seek(res,0);      /* We want to read again */
  else
  {
    mysql_free_result(res);
    res = NULL;
  }
  return(NULL);
} /* getTableName */


static int dump_all_databases()
{
  MYSQL_ROW row;
  MYSQL_RES *tableres;
  int result=0;

  if (mysql_query(sock, "SHOW DATABASES") ||
      !(tableres = mysql_store_result(sock)))
  {
    my_printf_error(0, "Error: Couldn't execute 'SHOW DATABASES': %s",
		    MYF(0), mysql_error(sock));
    return 1;
  }
  while ((row = mysql_fetch_row(tableres)))
  {
    if (dump_all_tables_in_db(row[0]))
      result=1;
  }
  return result;
}
/* dump_all_databases */


static int dump_databases(char **db_names)
{
  int result=0;
  for ( ; *db_names ; db_names++)
1224
  {
1225
    /* XML edit - add database element */
1226 1227
    if (opt_xml)
      fprintf(md_result_file, "<%s>\n", *db_names);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1228 1229
    if (dump_all_tables_in_db(*db_names))
      result=1;
1230 1231
    if (opt_xml)
      fprintf(md_result_file, "</%s>\n", *db_names);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
  }
  return result;
} /* dump_databases */


static int init_dumping(char *database)
{
  if (mysql_select_db(sock, database))
  {
    DBerror(sock, "when selecting the database");
    return 1;			/* If --force */
  }
  if (!path)
  {
    if (opt_databases || opt_alldbs)
    {
1248
      fprintf(md_result_file,"\n--\n-- Current Database: %s\n--\n", database);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1249
      if (!opt_create_db)
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1250
	fprintf(md_result_file,"\nCREATE DATABASE /*!32312 IF NOT EXISTS*/ %s;\n",
1251
		database);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1252
      fprintf(md_result_file,"\nUSE %s;\n", database);
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265
    }
  }
  if (extended_insert)
    if (init_dynamic_string(&extended_row, "", 1024, 1024))
      exit(EX_EOM);
  return 0;
} /* init_dumping */


static int dump_all_tables_in_db(char *database)
{
  char *table;
  uint numrows;
1266
  char table_buff[NAME_LEN+3];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1267 1268 1269 1270 1271 1272 1273 1274 1275

  if (init_dumping(database))
    return 1;
  if (lock_tables)
  {
    DYNAMIC_STRING query;
    init_dynamic_string(&query, "LOCK TABLES ", 256, 1024);
    for (numrows=0 ; (table = getTableName(1)) ; numrows++)
    {
1276
      dynstr_append(&query, quote_name(table, table_buff));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1277 1278 1279
      dynstr_append(&query, " READ /*!32311 LOCAL */,");
    }
    if (numrows && mysql_real_query(sock, query.str, query.length-1))
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1280
      DBerror(sock, "when using LOCK TABLES");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1281 1282 1283 1284 1285 1286
            /* We shall continue here, if --force was given */
    dynstr_free(&query);
  }
  if (flush_logs)
  {
    if (mysql_refresh(sock, REFRESH_LOG))
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1287
      DBerror(sock, "when doing refresh");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
           /* We shall continue here, if --force was given */
  }
  while ((table = getTableName(0)))
  {
    numrows = getTableStructure(table, database);
    if (!dFlag && numrows > 0)
      dumpTable(numrows,table);
  }
  if (lock_tables)
    mysql_query(sock,"UNLOCK_TABLES");
  return 0;
} /* dump_all_tables_in_db */



static int dump_selected_tables(char *db, char **table_names, int tables)
{
  uint numrows;
1306
  char table_buff[NAME_LEN+3];
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317

  if (init_dumping(db))
    return 1;
  if (lock_tables)
  {
    DYNAMIC_STRING query;
    int i;

    init_dynamic_string(&query, "LOCK TABLES ", 256, 1024);
    for (i=0 ; i < tables ; i++)
    {
1318
      dynstr_append(&query, quote_name(table_names[i], table_buff));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1319 1320 1321
      dynstr_append(&query, " READ /*!32311 LOCAL */,");
    }
    if (mysql_real_query(sock, query.str, query.length-1))
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1322
      DBerror(sock, "when doing LOCK TABLES");
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1323 1324 1325 1326 1327 1328
       /* We shall countinue here, if --force was given */
    dynstr_free(&query);
  }
  if (flush_logs)
  {
    if (mysql_refresh(sock, REFRESH_LOG))
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1329
      DBerror(sock, "when doing refresh");
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 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
     /* We shall countinue here, if --force was given */
  }
  for (; tables > 0 ; tables-- , table_names++)
  {
    numrows = getTableStructure(*table_names, db);
    if (!dFlag && numrows > 0)
      dumpTable(numrows, *table_names);
  }
  if (lock_tables)
    mysql_query(sock,"UNLOCK_TABLES");
  return 0;
} /* dump_selected_tables */


/* Print a value with a prefix on file */
static void print_value(FILE *file, MYSQL_RES  *result, MYSQL_ROW row,
			const char *prefix, const char *name,
			int string_value)
{
  MYSQL_FIELD	*field;
  mysql_field_seek(result, 0);

  for ( ; (field = mysql_fetch_field(result)) ; row++)
  {
    if (!strcmp(field->name,name))
    {
      if (row[0] && row[0][0] && strcmp(row[0],"0")) /* Skip default */
      {
	fputc(' ',file);
	fputs(prefix, file);
	if (string_value)
1361
	  unescape(file,row[0],(uint) strlen(row[0]));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
	else
	  fputs(row[0], file);
	return;
      }
    }
  }
  return;					/* This shouldn't happen */
} /* print_value */


int main(int argc, char **argv)
{
1374 1375 1376
  MYSQL_ROW row;
  MYSQL_RES *master;

bk@work.mysql.com's avatar
bk@work.mysql.com committed
1377 1378 1379 1380 1381 1382
  MY_INIT(argv[0]);
  if (get_options(&argc, &argv))
  {
    my_end(0);
    exit(EX_USAGE);
  }
1383
  if (dbConnect(current_host, current_user, opt_password))
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1384 1385
    exit(EX_MYSQLERR);
  if (!path)
1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
    write_header(md_result_file, *argv);

  if (opt_first_slave)
  {
    lock_tables=0;				/* No other locks needed */
    if (mysql_query(sock, "FLUSH TABLES WITH READ LOCK"))
    {
      my_printf_error(0, "Error: Couldn't execute 'FLUSH TABLES WITH READ LOCK': %s",
                      MYF(0), mysql_error(sock));
      my_end(0);
      return(first_error);
    }
  }
1399
  else if (opt_single_transaction)
1400 1401 1402
  {
    /* There is no sense to start transaction if all tables are locked */ 
    if (mysql_query(sock, "BEGIN"))
1403
    {
1404
      my_printf_error(0, "Error: Couldn't execute 'BEGIN': %s",
1405
                        MYF(0), mysql_error(sock));
1406 1407 1408 1409
      my_end(0);
      return(first_error);
    }    
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1410 1411 1412
  if (opt_alldbs)
    dump_all_databases();
  else if (argc > 1 && !opt_databases)
1413 1414
  {
    /* Only one database and selected table(s) */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1415
    dump_selected_tables(*argv, (argv + 1), (argc - 1));
1416
  }
monty@donna.mysql.com's avatar
monty@donna.mysql.com committed
1417
  else
1418 1419
  {
    /* One or more databases, all tables */
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1420
    dump_databases(argv);
1421
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1422 1423 1424

  if (opt_first_slave)
  {
1425 1426 1427 1428 1429 1430
    if (opt_master_data)
    {
      if (mysql_query(sock, "SHOW MASTER STATUS") ||
	  !(master = mysql_store_result(sock)))
	my_printf_error(0, "Error: Couldn't execute 'SHOW MASTER STATUS': %s",
			MYF(0), mysql_error(sock));
1431
      else
1432 1433
      {
	row = mysql_fetch_row(master);
1434 1435
	if (row[0] && row[1])
	{
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445
	  fprintf(md_result_file,
		  "\n--\n-- Position to start replication from\n--\n\n");
	  fprintf(md_result_file,
		  "CHANGE MASTER TO MASTER_LOG_FILE='%s' ;\n", row[0]);
	  fprintf(md_result_file, "CHANGE MASTER TO MASTER_LOG_POS=%s ;\n",
		  row[1]);
	}
	mysql_free_result(master);
      }
    }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1446 1447 1448 1449 1450 1451 1452
    if (mysql_query(sock, "FLUSH MASTER"))
      my_printf_error(0, "Error: Couldn't execute 'FLUSH MASTER': %s",
		      MYF(0), mysql_error(sock));
    if (mysql_query(sock, "UNLOCK TABLES"))
      my_printf_error(0, "Error: Couldn't execute 'UNLOCK TABLES': %s",
		      MYF(0), mysql_error(sock));
  }
1453 1454
  else if (opt_single_transaction) /* Just to make it beautiful enough */
  {
1455
    /*
1456 1457
      In case we were locking all tables, we did not start transaction
      so there is no need to commit it.
1458 1459
    */

1460 1461 1462 1463 1464 1465 1466
    /* This should just free locks as we did not change anything */
    if (mysql_query(sock, "COMMIT"))
    {
      my_printf_error(0, "Error: Couldn't execute 'COMMIT': %s",
  	      MYF(0), mysql_error(sock));
    }		      
  }
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1467
  dbDisconnect(current_host);
monty@hundin.mysql.fi's avatar
monty@hundin.mysql.fi committed
1468 1469 1470
  fputs("\n", md_result_file);
  if (md_result_file != stdout)
    my_fclose(md_result_file, MYF(0));
1471
  my_free(opt_password, MYF(MY_ALLOW_ZERO_PTR));
bk@work.mysql.com's avatar
bk@work.mysql.com committed
1472 1473 1474 1475 1476
  if (extended_insert)
    dynstr_free(&extended_row);
  my_end(0);
  return(first_error);
} /* main */