mysqldump.c 69.1 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000 MySQL AB
unknown's avatar
unknown committed
2

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

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

unknown's avatar
unknown committed
13 14 15 16 17 18 19 20
   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 :-
**
unknown's avatar
unknown committed
21 22 23 24 25 26 27 28 29 30 31 32
** 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>
33
** Tõnu Samuel  <tonu@please.do.not.remove.this.spam.ee>
unknown's avatar
unknown committed
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
unknown's avatar
unknown committed
37
** 10 Jun 2003: SET NAMES and --no-set-names by Alexander Barkov
unknown's avatar
unknown committed
38
*/
unknown's avatar
unknown committed
39

40
#define DUMP_VERSION "10.8"
unknown's avatar
unknown committed
41

unknown's avatar
unknown committed
42
#include <my_global.h>
unknown's avatar
unknown committed
43 44 45 46
#include <my_sys.h>
#include <m_string.h>
#include <m_ctype.h>

47
#include "client_priv.h"
unknown's avatar
unknown committed
48 49 50 51 52 53 54 55 56 57
#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
58
#define EX_EOF 5 /* ferror for output file was got */
unknown's avatar
unknown committed
59 60 61 62 63 64 65 66 67

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

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

unknown's avatar
unknown committed
71 72
static char *add_load_option(char *ptr, const char *object,
			     const char *statement);
73 74
static ulong find_set(TYPELIB *lib, const char *x, uint length,
		      char **err_pos, uint *err_len);
unknown's avatar
unknown committed
75 76

static char *field_escape(char *to,const char *from,uint length);
77 78 79 80
static my_bool  verbose=0,tFlag=0,cFlag=0,dFlag=0,quick= 1, extended_insert= 1,
		lock_tables=1,ignore_errors=0,flush_logs=0,replace=0,
		ignore=0,opt_drop=1,opt_keywords=0,opt_lock=1,opt_compress=0,
                opt_delayed=0,create_options=1,opt_quoted=0,opt_databases=0,
81
                opt_alldbs=0,opt_create_db=0,opt_first_slave=0,opt_set_charset,
unknown's avatar
unknown committed
82 83
		opt_autocommit=0,opt_master_data,opt_disable_keys=1,opt_xml=0,
		opt_delete_master_logs=0, tty_password=0,
84 85
		opt_single_transaction=0, opt_comments= 0, opt_compact= 0,
		opt_hex_blob=0;
86
static ulong opt_max_allowed_packet, opt_net_buffer_length;
unknown's avatar
unknown committed
87
static MYSQL mysql_connection,*sock=0;
88
static char  insert_pat[12 * 1024],*opt_password=0,*current_user=0,
unknown's avatar
unknown committed
89 90
             *current_host=0,*path=0,*fields_terminated=0,
             *lines_terminated=0, *enclosed=0, *opt_enclosed=0, *escaped=0,
unknown's avatar
unknown committed
91
             *where=0,
92
             *opt_compatible_mode_str= 0,
93
             *err_ptr= 0;
94
static char compatible_mode_normal_str[255];
95 96
static ulong opt_compatible_mode= 0;
static uint     opt_mysql_port= 0, err_len= 0;
unknown's avatar
unknown committed
97 98 99
static my_string opt_mysql_unix_port=0;
static int   first_error=0;
static DYNAMIC_STRING extended_row;
100
#include <sslopt-vars.h>
unknown's avatar
unknown committed
101
FILE  *md_result_file;
102 103 104
#ifdef HAVE_SMEM
static char *shared_memory_base_name=0;
#endif
105
static uint opt_protocol= 0;
unknown's avatar
unknown committed
106
static char *default_charset= (char*) MYSQL_UNIVERSAL_CLIENT_CHARSET;
107
static CHARSET_INFO *charset_info= &my_charset_latin1;
unknown's avatar
unknown committed
108
const char *default_dbug_option="d:t:o,/tmp/mysqldump.trace";
unknown's avatar
unknown committed
109 110
/* do we met VIEWs during tables scaning */
my_bool was_views= 0;
111 112 113 114

const char *compatible_mode_names[]=
{
  "MYSQL323", "MYSQL40", "POSTGRESQL", "ORACLE", "MSSQL", "DB2",
115 116
  "MAXDB", "NO_KEY_OPTIONS", "NO_TABLE_OPTIONS", "NO_FIELD_OPTIONS",
  "ANSI",
117 118
  NullS
};
119 120 121 122 123 124 125 126 127
#define MASK_ANSI_QUOTES \
(\
 (1<<2)  | /* POSTGRESQL */\
 (1<<3)  | /* ORACLE     */\
 (1<<4)  | /* MSSQL      */\
 (1<<5)  | /* DB2        */\
 (1<<6)  | /* MAXDB      */\
 (1<<10)   /* ANSI       */\
)
128
TYPELIB compatible_mode_typelib= {array_elements(compatible_mode_names) - 1,
unknown's avatar
unknown committed
129
				  "", compatible_mode_names, NULL};
130

unknown's avatar
unknown committed
131

132
static struct my_option my_long_options[] =
unknown's avatar
unknown committed
133
{
134 135 136
  {"all", 'a', "Deprecated. Use --create-options instead.",
   (gptr*) &create_options, (gptr*) &create_options, 0, GET_BOOL, NO_ARG, 1,
   0, 0, 0, 0, 0},
137 138 139 140 141
  {"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},
  {"add-drop-table", OPT_DROP, "Add a 'drop table' before each create.",
142
   (gptr*) &opt_drop, (gptr*) &opt_drop, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0,
143 144
   0},
  {"add-locks", OPT_LOCKS, "Add locks around insert statements.",
145
   (gptr*) &opt_lock, (gptr*) &opt_lock, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0,
146 147 148 149 150
   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,
151
   "Directory where character sets are.", (gptr*) &charsets_dir,
152
   (gptr*) &charsets_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
153
  {"compatible", OPT_COMPATIBLE,
unknown's avatar
unknown committed
154
   "Change the dump to be compatible with a given mode. By default tables are dumped in a format optimized for MySQL. Legal modes are: ansi, mysql323, mysql40, postgresql, oracle, mssql, db2, maxdb, no_key_options, no_table_options, no_field_options. One can use several modes separated by commas. Note: Requires MySQL server version 4.1.0 or higher. This option is ignored with earlier server versions.",
155 156
   (gptr*) &opt_compatible_mode_str, (gptr*) &opt_compatible_mode_str, 0,
   GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
157 158 159 160
  {"compact", OPT_COMPACT,
   "Give less verbose output (useful for debugging). Disables structure comments and header/footer constructs.  Enables options --skip-add-drop-table --no-set-names --skip-disable-keys --skip-lock-tables",
   (gptr*) &opt_compact, (gptr*) &opt_compact, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
   0, 0},
161 162
  {"complete-insert", 'c', "Use complete insert statements.", (gptr*) &cFlag,
   (gptr*) &cFlag, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
163 164 165
  {"compress", 'C', "Use compression in server/client protocol.",
   (gptr*) &opt_compress, (gptr*) &opt_compress, 0, GET_BOOL, NO_ARG, 0, 0, 0,
   0, 0, 0},
unknown's avatar
unknown committed
166 167 168 169
  {"create-options", OPT_CREATE_OPTIONS,
   "Include all MySQL specific create options.",
   (gptr*) &create_options, (gptr*) &create_options, 0, GET_BOOL, NO_ARG, 1,
   0, 0, 0, 0, 0},
170 171 172 173
  {"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},
unknown's avatar
unknown committed
174 175 176 177 178 179 180
#ifdef DBUG_OFF
  {"debug", '#', "This is a non-debug version. Catch this and exit",
   0,0, 0, GET_DISABLED, OPT_ARG, 0, 0, 0, 0, 0, 0},
#else
  {"debug", '#', "Output debug log", (gptr*) &default_dbug_option,
   (gptr*) &default_dbug_option, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
#endif
181 182 183 184 185 186
  {"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},
unknown's avatar
unknown committed
187
  {"delete-master-logs", OPT_DELETE_MASTER_LOGS,
unknown's avatar
unknown committed
188
   "Delete logs on master after backup. This automatically enables --first-slave.",
unknown's avatar
unknown committed
189
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
190 191
  {"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,
192
   (gptr*) &opt_disable_keys, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0},
193 194 195
  {"extended-insert", 'e',
   "Allows utilization of the new, much faster INSERT syntax.",
   (gptr*) &extended_insert, (gptr*) &extended_insert, 0, GET_BOOL, NO_ARG,
196
   1, 0, 0, 0, 0, 0},
197 198 199 200 201 202 203 204 205 206
  {"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 ...",
unknown's avatar
unknown committed
207
   (gptr*) &escaped, (gptr*) &escaped, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
208 209 210
  {"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},
unknown's avatar
unknown committed
211 212 213 214
  {"flush-logs", 'F', "Flush logs file in server before starting dump. "
    "Note that if you dump many databases at once (using the option "
    "--databases= or --all-databases), the logs will be flushed for "
    "each database dumped.",
215 216 217 218 219 220 221 222
   (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,
223
   (gptr*) &current_host, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
224 225 226 227
  {"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,
228
   (gptr*) &lock_tables, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0},
229
  {"master-data", OPT_MASTER_DATA,
unknown's avatar
unknown committed
230
   "This causes the master position and filename to be appended to your output. This automatically enables --first-slave.",
231 232 233 234 235
   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},
236 237
  {"single-transaction", OPT_TRANSACTION,
   "Dump all tables in single transaction to get consistent snapshot. Mutually exclusive with --lock-tables.",
238
   (gptr*) &opt_single_transaction, (gptr*) &opt_single_transaction, 0,
239
   GET_BOOL, NO_ARG,  0, 0, 0, 0, 0, 0},
240
  {"no-create-db", 'n',
241
   "'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.}.",
242 243 244
   (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.",
245 246 247
   (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},
unknown's avatar
unknown committed
248
  {"no-set-names", 'N',
249
   "Deprecated. Use --skip-set-charset instead.",
250 251
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"set-charset", OPT_SET_CHARSET,
unknown's avatar
unknown committed
252
   "Add 'SET NAMES default_character_set' to the output. Enabled by default; suppress with --skip-set-charset.",
253 254
   (gptr*) &opt_set_charset, (gptr*) &opt_set_charset, 0, GET_BOOL, NO_ARG, 1,
   0, 0, 0, 0, 0},
255
  {"set-variable", 'O',
unknown's avatar
unknown committed
256
   "Change the value of a variable. Please note that this option is deprecated; you can set variables directly with --variable-name=value.",
257 258
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"opt", OPT_OPTIMIZE,
259
   "Same as --add-drop-table, --add-locks, --create-options, --quick, --extended-insert, --lock-tables, --set-charset, and --disable-keys. Enabled by default, disable with --skip-opt.",
260 261 262 263
   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},
unknown's avatar
unknown committed
264
#ifdef __WIN__
265
  {"pipe", 'W', "Use named pipes to connect to server.", 0, 0, 0, GET_NO_ARG,
266
   NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
267
#endif
268 269 270
  {"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},
271
  {"protocol", OPT_MYSQL_PROTOCOL, "The protocol of connection (tcp,socket,pipe,memory).",
272
   0, 0, 0, GET_STR,  REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
273
  {"quick", 'q', "Don't buffer query, dump directly to stdout.",
274
   (gptr*) &quick, (gptr*) &quick, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0},
275
  {"quote-names",'Q', "Quote table and column names with backticks (`).",
276
   (gptr*) &opt_quoted, (gptr*) &opt_quoted, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0,
277 278
   0, 0},
  {"result-file", 'r',
unknown's avatar
unknown committed
279
   "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).",
unknown's avatar
unknown committed
280
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
281
#ifdef HAVE_SMEM
282
  {"shared-memory-base-name", OPT_SHARED_MEMORY_BASE_NAME,
283
   "Base name of shared memory.", (gptr*) &shared_memory_base_name, (gptr*) &shared_memory_base_name,
284 285
   0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#endif
286
  {"skip-opt", OPT_SKIP_OPTIMIZATION,
287
   "Disable --opt. Disables --add-drop-table, --add-locks, --create-options, --quick, --extended-insert, --lock-tables, --set-charset, and --disable-keys.",
288
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
289 290 291
  {"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},
292
#include <sslopt-longopts.h>
293 294 295 296 297
  {"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},
unknown's avatar
unknown committed
298
#ifndef DONT_ALLOW_USER_CHANGE
299 300 301
  {"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},
unknown's avatar
unknown committed
302
#endif
303 304 305 306 307 308 309 310
  {"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},
311
  {"max_allowed_packet", OPT_MAX_ALLOWED_PACKET, "",
312
    (gptr*) &opt_max_allowed_packet, (gptr*) &opt_max_allowed_packet, 0,
313 314
    GET_ULONG, REQUIRED_ARG, 24*1024*1024, 4096, 
   (longlong) 2L*1024L*1024L*1024L, MALLOC_OVERHEAD, 1024, 0},
315
  {"net_buffer_length", OPT_NET_BUFFER_LENGTH, "",
316
    (gptr*) &opt_net_buffer_length, (gptr*) &opt_net_buffer_length, 0,
317
    GET_ULONG, REQUIRED_ARG, 1024*1024L-1025, 4096, 16*1024L*1024L,
unknown's avatar
merge  
unknown committed
318
    MALLOC_OVERHEAD-1024, 1024, 0},
319 320 321
  {"comments", 'i', "Write additional information.",
   (gptr*) &opt_comments, (gptr*) &opt_comments, 0, GET_BOOL, NO_ARG,
   1, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
322
  {"hex-blob", OPT_HEXBLOB, "Dump BLOBs in HEX.",
323
   (gptr*) &opt_hex_blob, (gptr*) &opt_hex_blob, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
324
  {0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
unknown's avatar
unknown committed
325 326 327 328 329
};

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

static void safe_exit(int error);
330
static void write_header(FILE *sql_file, char *db_name);
unknown's avatar
unknown committed
331 332 333 334 335 336 337 338
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();
unknown's avatar
unknown committed
339
static char *quote_name(const char *name, char *buff, my_bool force);
340
static const char *check_if_ignore_table(const char *table_name);
unknown's avatar
unknown committed
341 342
static my_bool getViewStructure(char *table, char* db);
static my_bool dump_all_views_in_db(char *database);
343

unknown's avatar
unknown committed
344
#include <help_start.h>
unknown's avatar
unknown committed
345

346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
/*
  exit with message if ferror(file)
  
  SYNOPSIS
    check_io()
    file	- checked file
*/

void check_io(FILE *file)
{
  if (ferror(file))
  {
    fprintf(stderr, "%s: Got errno %d on write\n", my_progname, errno);
    safe_exit(EX_EOF);
  }
}

unknown's avatar
unknown committed
363 364 365
static void print_version(void)
{
  printf("%s  Ver %s Distrib %s, for %s (%s)\n",my_progname,DUMP_VERSION,
unknown's avatar
unknown committed
366 367
         MYSQL_SERVER_VERSION,SYSTEM_TYPE,MACHINE_TYPE);
  NETWARE_SET_SCREEN_MODE(1);
unknown's avatar
unknown committed
368 369 370
} /* print_version */


371 372 373 374 375 376
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);
unknown's avatar
unknown committed
377
  NETWARE_SET_SCREEN_MODE(1);
378 379
}

unknown's avatar
unknown committed
380

unknown's avatar
unknown committed
381 382 383 384 385 386
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");
387
  short_usage_sub();
unknown's avatar
unknown committed
388
  print_defaults("my",load_default_groups);
389 390
  my_print_help(my_long_options);
  my_print_variables(my_long_options);
unknown's avatar
unknown committed
391 392 393
} /* usage */


394 395 396 397 398 399
static void short_usage(void)
{
  short_usage_sub();
  printf("For more options, use %s --help\n", my_progname);
}

unknown's avatar
unknown committed
400 401
#include <help_end.h>

402

403
static void write_header(FILE *sql_file, char *db_name)
unknown's avatar
unknown committed
404
{
unknown's avatar
unknown committed
405
  if (opt_xml)
unknown's avatar
unknown committed
406
  {
407 408
    fputs("<?xml version=\"1.0\"?>\n", sql_file);
    fputs("<mysqldump>\n", sql_file);
409
    check_io(sql_file);
unknown's avatar
unknown committed
410
  }
unknown's avatar
unknown committed
411
  else if (!opt_compact)
unknown's avatar
unknown committed
412
  {
unknown's avatar
unknown committed
413 414 415 416 417 418 419 420 421 422 423
    if (opt_comments)
    {
      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));
    }
424
    if (opt_set_charset)
unknown's avatar
unknown committed
425 426 427 428 429
      fprintf(sql_file,
"\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;"
"\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;"
"\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;"
"\n/*!40101 SET NAMES %s */;\n",default_charset);
430 431 432
    if (!path)
    {
      fprintf(md_result_file,"\
433 434 435
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;\n\
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;\n\
");
436 437
    }
    fprintf(sql_file,
unknown's avatar
Merge  
unknown committed
438 439 440
	    "/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=\"%s%s%s\" */;\n",
	    path?"":"NO_AUTO_VALUE_ON_ZERO",compatible_mode_normal_str[0]==0?"":",",
	    compatible_mode_normal_str);
441
    check_io(sql_file);
unknown's avatar
unknown committed
442
  }
443
} /* write_header */
unknown's avatar
unknown committed
444

445

unknown's avatar
unknown committed
446 447 448
static void write_footer(FILE *sql_file)
{
  if (opt_xml)
449
  {
unknown's avatar
unknown committed
450
    fputs("</mysqldump>\n", sql_file);
451 452
    check_io(sql_file);
  }
unknown's avatar
unknown committed
453
  else if (!opt_compact)
454
  {
455 456 457 458
    fprintf(sql_file,"\n/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;\n");
    if (!path)
    {
      fprintf(md_result_file,"\
459
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;\n\
unknown's avatar
unknown committed
460
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;\n");
461
    }
462
    if (opt_set_charset)
463
      fprintf(sql_file,
unknown's avatar
unknown committed
464 465 466
"/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n"
"/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n"
"/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n");
unknown's avatar
unknown committed
467
    fputs("\n", sql_file);
468
    check_io(sql_file);
469
  }
unknown's avatar
unknown committed
470
} /* write_footer */
unknown's avatar
unknown committed
471

472

unknown's avatar
unknown committed
473

474 475 476
static my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
	       char *argument)
unknown's avatar
unknown committed
477
{
unknown's avatar
unknown committed
478
  switch (optid) {
479 480 481 482
  case OPT_MASTER_DATA:
    opt_master_data=1;
    opt_first_slave=1;
    break;
unknown's avatar
unknown committed
483 484 485 486
  case OPT_DELETE_MASTER_LOGS:
    opt_delete_master_logs=1;
    opt_first_slave=1;
    break;
487 488 489 490 491 492 493 494 495
  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 */
496
      tty_password= 0;
497 498 499 500 501
    }
    else
      tty_password=1;
    break;
  case 'r':
unknown's avatar
unknown committed
502
    if (!(md_result_file = my_fopen(argument, O_WRONLY | FILE_BINARY,
503 504 505 506
				    MYF(MY_WME))))
      exit(1);
    break;
  case 'W':
unknown's avatar
unknown committed
507
#ifdef __WIN__
508
    opt_protocol = MYSQL_PROTOCOL_PIPE;
unknown's avatar
unknown committed
509
#endif
510
    break;
511 512 513
  case 'N':
    opt_set_charset= 0;
    break;
514 515 516 517
  case 'T':
    opt_disable_keys=0;
    break;
  case '#':
unknown's avatar
unknown committed
518
    DBUG_PUSH(argument ? argument : default_dbug_option);
519
    break;
520
#include <sslopt-case.h>
521 522 523
  case 'V': print_version(); exit(0);
  case 'X':
    opt_xml = 1;
524 525
    extended_insert= opt_drop= opt_lock= 
      opt_disable_keys= opt_autocommit= opt_create_db= 0;
526 527 528 529 530 531
    break;
  case 'I':
  case '?':
    usage();
    exit(0);
  case (int) OPT_OPTIMIZE:
532
    extended_insert= opt_drop= opt_lock= quick= create_options=
533
      opt_disable_keys= lock_tables= opt_set_charset= 1;
534
    if (opt_single_transaction) lock_tables=0;
535
    break;
536 537
  case (int) OPT_SKIP_OPTIMIZATION:
    extended_insert= opt_drop= opt_lock= quick= create_options=
unknown's avatar
unknown committed
538
      opt_disable_keys= lock_tables= opt_set_charset= 0;
539
    break;
unknown's avatar
unknown committed
540 541 542 543
  case (int) OPT_COMPACT:
  if (opt_compact)
  {
    opt_comments= opt_drop= opt_disable_keys= opt_lock= 0;
544
    opt_set_charset= 0;
unknown's avatar
unknown committed
545
  }
546 547 548
  case (int) OPT_TABLES:
    opt_databases=0;
    break;
549 550 551
  case (int) OPT_COMPATIBLE:
    {  
      char buff[255];
552 553 554
      char *end= compatible_mode_normal_str;
      int i;
      ulong mode;
555 556

      opt_quoted= 1;
557
      opt_set_charset= 0;
558 559 560 561 562 563 564 565 566 567
      opt_compatible_mode_str= argument;
      opt_compatible_mode= find_set(&compatible_mode_typelib,
				    argument, strlen(argument),
				    &err_ptr, &err_len);
      if (err_len)
      {
	strmake(buff, err_ptr, min(sizeof(buff), err_len));
	fprintf(stderr, "Invalid mode to --compatible: %s\n", buff);
	exit(1);
      }
568 569
#if !defined(DBUG_OFF)
      {
unknown's avatar
unknown committed
570
	uint size_for_sql_mode= 0;
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
	const char **ptr;
	for (ptr= compatible_mode_names; *ptr; ptr++)
	  size_for_sql_mode+= strlen(*ptr);
	size_for_sql_mode+= sizeof(compatible_mode_names)-1;
	DBUG_ASSERT(sizeof(compatible_mode_normal_str)>=size_for_sql_mode);
      }
#endif
      mode= opt_compatible_mode;
      for (i= 0, mode= opt_compatible_mode; mode; mode>>= 1, i++)
      {
	if (mode & 1)
	{
	  end= strmov(end, compatible_mode_names[i]);
	  end= strmov(end, ",");
	}
      }
      if (end!=compatible_mode_normal_str)
	end[-1]= 0;
589 590 591
      break;
    }
  case (int) OPT_MYSQL_PROTOCOL:
592
    {
593
      if ((opt_protocol= find_type(argument, &sql_protocol_typelib,0)) <= 0)
594 595 596 597 598
      {
	fprintf(stderr, "Unknown option to protocol: %s\n", argument);
	exit(1);
      }
      break;
599
    }
unknown's avatar
unknown committed
600
  }
601 602 603 604 605 606
  return 0;
}

static int get_options(int *argc, char ***argv)
{
  int ho_error;
607 608 609 610
  MYSQL_PARAMETERS *mysql_params= mysql_get_parameters();

  opt_max_allowed_packet= *mysql_params->p_max_allowed_packet;
  opt_net_buffer_length= *mysql_params->p_net_buffer_length;
611 612 613 614

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

615
  if ((ho_error=handle_options(argc, argv, my_long_options, get_one_option)))
616
    exit(ho_error);
617

618 619 620
  *mysql_params->p_max_allowed_packet= opt_max_allowed_packet;
  *mysql_params->p_net_buffer_length= opt_net_buffer_length;

unknown's avatar
unknown committed
621 622 623 624 625
  if (opt_delayed)
    opt_lock=0;				/* Can't have lock with delayed */
  if (!path && (enclosed || opt_enclosed || escaped || lines_terminated ||
		fields_terminated))
  {
626 627
    fprintf(stderr,
	    "%s: You must use option --tab with --fields-...\n", my_progname);
unknown's avatar
unknown committed
628 629
    return(1);
  }
630 631
  if (opt_single_transaction)
    lock_tables= 0;
unknown's avatar
unknown committed
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
  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);
  }
649 650
  if (strcmp(default_charset, charset_info->csname) &&
      !(charset_info= get_charset_by_csname(default_charset, 
651
  					    MY_CS_PRIMARY, MYF(MY_WME))))
652
    exit(1);
unknown's avatar
unknown committed
653 654
  if ((*argc < 1 && !opt_alldbs) || (*argc > 0 && opt_alldbs))
  {
655
    short_usage();
unknown's avatar
unknown committed
656 657 658
    return 1;
  }
  if (tty_password)
659
    opt_password=get_tty_password(NullS);
unknown's avatar
unknown committed
660 661 662 663 664 665 666 667 668 669
  return(0);
} /* get_options */


/*
** DBerror -- prints mysql error message and exits the program.
*/
static void DBerror(MYSQL *mysql, const char *when)
{
  DBUG_ENTER("DBerror");
unknown's avatar
unknown committed
670
  my_printf_error(0,"Got error: %d: %s %s", MYF(0),
unknown's avatar
unknown committed
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
		  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)
{
696
  char buff[20+FN_REFLEN];
unknown's avatar
unknown committed
697 698 699
  DBUG_ENTER("dbConnect");
  if (verbose)
  {
700
    fprintf(stderr, "-- Connecting to %s...\n", host ? host : "localhost");
unknown's avatar
unknown committed
701 702 703 704 705 706 707
  }
  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,
708
		  opt_ssl_capath, opt_ssl_cipher);
709 710 711 712 713 714
#endif
  if (opt_protocol)
    mysql_options(&mysql_connection,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
#ifdef HAVE_SMEM
  if (shared_memory_base_name)
    mysql_options(&mysql_connection,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
unknown's avatar
unknown committed
715
#endif
716
  mysql_options(&mysql_connection, MYSQL_SET_CHARSET_NAME, default_charset);
unknown's avatar
unknown committed
717 718 719 720 721 722 723
  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;
  }
724 725 726 727 728 729 730 731 732 733
  sprintf(buff, "/*!40100 SET @@SQL_MODE=\"%s\" */",
	  compatible_mode_normal_str);
  if (mysql_query(sock, buff))
  {
    fprintf(stderr, "%s: Can't set the compatible mode %s (error %s)\n",
	    my_progname, compatible_mode_normal_str, mysql_error(sock));
    mysql_close(sock);
    safe_exit(EX_MYSQLERR);
    return 1;
  }
unknown's avatar
unknown committed
734 735 736 737 738 739 740 741 742 743
  return 0;
} /* dbConnect */


/*
** dbDisconnect -- disconnects from the host.
*/
static void dbDisconnect(char *host)
{
  if (verbose)
744
    fprintf(stderr, "-- Disconnecting from %s...\n", host ? host : "localhost");
unknown's avatar
unknown committed
745 746 747 748 749 750 751 752 753 754 755 756 757
  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 */
  }
unknown's avatar
unknown committed
758
  mysql_real_escape_string(&mysql_connection, tmp, pos, length);
unknown's avatar
unknown committed
759 760 761
  fputc('\'', file);
  fputs(tmp, file);
  fputc('\'', file);
762
  check_io(file);
unknown's avatar
unknown committed
763 764 765 766 767 768 769 770 771
  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++)
772
    if (!my_isvar(charset_info,*str) && *str != '$')
unknown's avatar
unknown committed
773 774 775 776 777
      return 1;
#endif
  return 0;
} /* test_if_special_chars */

unknown's avatar
unknown committed
778

unknown's avatar
unknown committed
779

unknown's avatar
unknown committed
780
static char *quote_name(const char *name, char *buff, my_bool force)
unknown's avatar
unknown committed
781
{
unknown's avatar
unknown committed
782
  char *to= buff;
783 784
  char qtype= (opt_compatible_mode & MASK_ANSI_QUOTES) ? '\"' : '`';

unknown's avatar
unknown committed
785 786
  if (!force && !opt_quoted && !test_if_special_chars(name))
    return (char*) name;
787
  *to++= qtype;
unknown's avatar
unknown committed
788 789
  while (*name)
  {
790 791
    if (*name == qtype)
      *to++= qtype;
unknown's avatar
unknown committed
792 793
    *to++= *name++;
  }
794 795
  to[0]= qtype;
  to[1]= 0;
unknown's avatar
unknown committed
796 797 798 799
  return buff;
} /* quote_name */


800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816

static char *quote_for_like(const char *name, char *buff)
{
  char *to= buff;
  *to++= '\'';
  while (*name)
  {
    if (*name == '\'' || *name == '_' || *name == '\\' || *name == '%')
      *to++= '\\';
    *to++= *name++;
  }
  to[0]= '\'';
  to[1]= 0;
  return buff;
}


817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
/*
  Quote and print a string.
  
  SYNOPSIS
    print_quoted_xml()
    output	- output file
    str		- string to print
    len		- its length
    
  DESCRIPTION
    Quote '<' '>' '&' '\"' singns and print a string to the xml_file.
*/

static void print_quoted_xml(FILE *xml_file, const char *str, ulong len)
{
  const char *end;
  
  for (end= str + len; str != end; str++)
  {
    switch (*str) {
    case '<':
      fputs("&lt;", xml_file);
      break;
    case '>':
      fputs("&gt;", xml_file);
      break;
    case '&':
      fputs("&amp;", xml_file);
      break;
    case '\"':
      fputs("&quot;", xml_file);
      break;
    default:
      fputc(*str, xml_file);
      break;
    }
  }
854
  check_io(xml_file);
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
}


/*
  Print xml tag with one attribute.
  
  SYNOPSIS
    print_xml_tag1()
    xml_file	- output file
    sbeg	- line beginning
    stag_atr	- tag and attribute
    sval	- value of attribute
    send	- line ending
    
  DESCRIPTION
    Print tag with one attribute to the xml_file. Format is:
      sbeg<stag_atr="sval">send
  NOTE
    sval MUST be a NULL terminated string.
    sval string will be qouted before output.
*/

static void print_xml_tag1(FILE * xml_file, const char* sbeg,
			   const char* stag_atr, const char* sval,
			   const char* send)
{
  fputs(sbeg, xml_file);
  fputs("<", xml_file);
  fputs(stag_atr, xml_file);
  fputs("\"", xml_file);
  print_quoted_xml(xml_file, sval, strlen(sval));
  fputs("\">", xml_file);
  fputs(send, xml_file);
888
  check_io(xml_file);
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
}


/*
  Print xml tag with many attributes.

  SYNOPSIS
    print_xml_row()
    xml_file	- output file
    row_name	- xml tag name
    tableRes	- query result
    row		- result row
    
  DESCRIPTION
    Print tag with many attribute to the xml_file. Format is:
      \t\t<row_name Atr1="Val1" Atr2="Val2"... />
  NOTE
    All atributes and values will be quoted before output.
*/

static void print_xml_row(FILE *xml_file, const char *row_name,
			  MYSQL_RES *tableRes, MYSQL_ROW *row)
911 912 913 914 915 916
{
  uint i;
  MYSQL_FIELD *field;
  ulong *lengths= mysql_fetch_lengths(tableRes);
  
  fprintf(xml_file, "\t\t<%s", row_name);
917
  check_io(xml_file);
918 919 920
  mysql_field_seek(tableRes, 0);
  for (i= 0; (field= mysql_fetch_field(tableRes)); i++)
  {
921
    if ((*row)[i])
922
    {
unknown's avatar
unknown committed
923
      fputc(' ', xml_file);
924
      print_quoted_xml(xml_file, field->name, field->name_length);
925 926
      fputs("=\"", xml_file);
      print_quoted_xml(xml_file, (*row)[i], lengths[i]);
unknown's avatar
unknown committed
927
      fputc('"', xml_file);
928
      check_io(xml_file);
929 930 931
    }
  }
  fputs(" />\n", xml_file);
932
  check_io(xml_file);
933 934
}

unknown's avatar
unknown committed
935
/*
unknown's avatar
unknown committed
936 937 938 939 940
  getStructure -- retrievs database structure, prints out corresponding
  CREATE statement and fills out insert_pat.

  RETURN
    number of fields in table, 0 if error
unknown's avatar
unknown committed
941
*/
unknown's avatar
unknown committed
942

unknown's avatar
unknown committed
943 944 945 946 947 948
static uint getTableStructure(char *table, char* db)
{
  MYSQL_RES  *tableRes;
  MYSQL_ROW  row;
  my_bool    init=0;
  uint       numFields;
unknown's avatar
unknown committed
949
  char	     *strpos, *result_table, *opt_quoted_table;
unknown's avatar
unknown committed
950
  const char *delayed;
unknown's avatar
unknown committed
951 952
  char	     name_buff[NAME_LEN+3],table_buff[NAME_LEN*2+3];
  char	     table_buff2[NAME_LEN*2+3];
unknown's avatar
unknown committed
953
  FILE       *sql_file = md_result_file;
unknown's avatar
unknown committed
954 955 956 957 958
  DBUG_ENTER("getTableStructure");

  delayed= opt_delayed ? " DELAYED " : "";

  if (verbose)
959
    fprintf(stderr, "-- Retrieving table structure for table %s...\n", table);
unknown's avatar
unknown committed
960

unknown's avatar
unknown committed
961 962
  sprintf(insert_pat,"SET OPTION SQL_QUOTE_SHOW_CREATE=%d",
	  (opt_quoted || opt_keywords));
unknown's avatar
unknown committed
963
  if (!create_options)
unknown's avatar
unknown committed
964
    strmov(strend(insert_pat), "/*!40102 ,SQL_MODE=concat(@@sql_mode, _utf8 ',NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS') */");
unknown's avatar
unknown committed
965

unknown's avatar
unknown committed
966 967
  result_table=     quote_name(table, table_buff, 1);
  opt_quoted_table= quote_name(table, table_buff2, 0);
968
  if (!opt_xml && !mysql_query(sock,insert_pat))
unknown's avatar
unknown committed
969
  {
970 971
    /* using SHOW CREATE statement */
    if (!tFlag)
unknown's avatar
unknown committed
972
    {
973 974
      /* Make an sql-file, if path was given iow. option -T was given */
      char buff[20+FN_REFLEN];
unknown's avatar
unknown committed
975
      MYSQL_FIELD *field;
976

unknown's avatar
unknown committed
977
      sprintf(buff,"show create table %s", result_table);
978
      if (mysql_query(sock, buff))
unknown's avatar
unknown committed
979
      {
unknown's avatar
unknown committed
980 981
        fprintf(stderr, "%s: Can't get CREATE TABLE for table %s (%s)\n",
		      my_progname, result_table, mysql_error(sock));
982 983
        safe_exit(EX_MYSQLERR);
        DBUG_RETURN(0);
unknown's avatar
unknown committed
984 985
      }

986 987 988
      if (path)
      {
        char filename[FN_REFLEN], tmp_path[FN_REFLEN];
989
        convert_dirname(tmp_path,path,NullS);
990
        sql_file= my_fopen(fn_format(filename, table, tmp_path, ".sql", 4),
991
				 O_WRONLY, MYF(MY_WME));
992 993
        if (!sql_file)			/* If file couldn't be opened */
        {
unknown's avatar
unknown committed
994 995
	  safe_exit(EX_MYSQLERR);
	  DBUG_RETURN(0);
996
        }
997
        write_header(sql_file, db);
998
      }
999
      if (!opt_xml && opt_comments)
1000
      {
unknown's avatar
unknown committed
1001
        fprintf(sql_file, "\n--\n-- Table structure for table %s\n--\n\n",
unknown's avatar
unknown committed
1002
		result_table);
1003 1004
	check_io(sql_file);
      }
1005
      if (opt_drop)
1006
      {
unknown's avatar
unknown committed
1007
        fprintf(sql_file, "DROP TABLE IF EXISTS %s;\n", opt_quoted_table);
1008 1009
	check_io(sql_file);
      }
1010

unknown's avatar
unknown committed
1011 1012 1013 1014 1015 1016 1017
      tableRes= mysql_store_result(sock);
      field= mysql_fetch_field_direct(tableRes, 0);
      if (strcmp(field->name, "View") == 0)
      {
        if (verbose)
          fprintf(stderr, "-- It's a view, skipped\n");
        was_views= 1;
unknown's avatar
unknown committed
1018
        DBUG_RETURN(0);
unknown's avatar
unknown committed
1019 1020
      }
      row= mysql_fetch_row(tableRes);
1021
      fprintf(sql_file, "%s;\n", row[1]);
1022
      check_io(sql_file);
1023 1024
      mysql_free_result(tableRes);
    }
unknown's avatar
unknown committed
1025
    sprintf(insert_pat,"show fields from %s", result_table);
1026
    if (mysql_query(sock,insert_pat) || !(tableRes=mysql_store_result(sock)))
unknown's avatar
unknown committed
1027
    {
unknown's avatar
unknown committed
1028 1029
      fprintf(stderr, "%s: Can't get info about table: %s\nerror: %s\n",
	      my_progname, result_table, mysql_error(sock));
1030 1031
      if (path)
	my_fclose(sql_file, MYF(MY_WME));
1032 1033
      safe_exit(EX_MYSQLERR);
      DBUG_RETURN(0);
unknown's avatar
unknown committed
1034
    }
1035

unknown's avatar
unknown committed
1036
    if (cFlag)
unknown's avatar
unknown committed
1037
      sprintf(insert_pat, "INSERT %sINTO %s (", delayed, opt_quoted_table);
1038
    else
unknown's avatar
unknown committed
1039
    {
unknown's avatar
unknown committed
1040 1041
      sprintf(insert_pat, "INSERT %sINTO %s VALUES ", delayed,
	      opt_quoted_table);
1042 1043 1044 1045 1046 1047 1048 1049
      if (!extended_insert)
        strcat(insert_pat,"(");
    }

    strpos=strend(insert_pat);
    while ((row=mysql_fetch_row(tableRes)))
    {
      if (init)
unknown's avatar
unknown committed
1050
      {
1051
        if (cFlag)
1052
	  strpos=strmov(strpos,", ");
unknown's avatar
unknown committed
1053
      }
1054 1055
      init=1;
      if (cFlag)
unknown's avatar
unknown committed
1056
        strpos=strmov(strpos,quote_name(row[SHOW_FIELDNAME], name_buff, 0));
unknown's avatar
unknown committed
1057
    }
1058 1059
    numFields = (uint) mysql_num_rows(tableRes);
    mysql_free_result(tableRes);
unknown's avatar
unknown committed
1060
  }
1061
  else
unknown's avatar
unknown committed
1062
  {
unknown's avatar
unknown committed
1063 1064 1065 1066
    if (verbose)
      fprintf(stderr,
              "%s: Warning: Can't set SQL_QUOTE_SHOW_CREATE option (%s)\n",
              my_progname, mysql_error(sock));
1067

unknown's avatar
unknown committed
1068
    sprintf(insert_pat,"show fields from %s", result_table);
1069
    if (mysql_query(sock,insert_pat) || !(tableRes=mysql_store_result(sock)))
unknown's avatar
unknown committed
1070
    {
unknown's avatar
unknown committed
1071 1072
      fprintf(stderr, "%s: Can't get info about table: %s\nerror: %s\n",
		    my_progname, result_table, mysql_error(sock));
unknown's avatar
unknown committed
1073 1074 1075 1076
      safe_exit(EX_MYSQLERR);
      DBUG_RETURN(0);
    }

1077 1078
    /* Make an sql-file, if path was given iow. option -T was given */
    if (!tFlag)
unknown's avatar
unknown committed
1079
    {
1080
      if (path)
unknown's avatar
unknown committed
1081
      {
1082
        char filename[FN_REFLEN], tmp_path[FN_REFLEN];
1083
        convert_dirname(tmp_path,path,NullS);
1084 1085 1086 1087
        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 */
        {
1088 1089
	  safe_exit(EX_MYSQLERR);
	  DBUG_RETURN(0);
1090
        }
1091
        write_header(sql_file, db);
unknown's avatar
unknown committed
1092
      }
1093
      if (!opt_xml && opt_comments)
unknown's avatar
unknown committed
1094 1095
	fprintf(sql_file, "\n--\n-- Table structure for table %s\n--\n\n",
		result_table);
1096
      if (opt_drop)
1097
        fprintf(sql_file, "DROP TABLE IF EXISTS %s;\n",result_table);
1098 1099 1100
      if (!opt_xml)
	fprintf(sql_file, "CREATE TABLE %s (\n", result_table);
      else
1101
        print_xml_tag1(sql_file, "\t", "table_structure name=", table, "\n");
1102
      check_io(sql_file);
1103 1104
    }
    if (cFlag)
1105
      sprintf(insert_pat, "INSERT %sINTO %s (", delayed, result_table);
1106 1107
    else
    {
1108
      sprintf(insert_pat, "INSERT %sINTO %s VALUES ", delayed, result_table);
1109 1110
      if (!extended_insert)
        strcat(insert_pat,"(");
unknown's avatar
unknown committed
1111
    }
1112 1113

    strpos=strend(insert_pat);
unknown's avatar
unknown committed
1114 1115
    while ((row=mysql_fetch_row(tableRes)))
    {
1116 1117
      ulong *lengths=mysql_fetch_lengths(tableRes);
      if (init)
unknown's avatar
unknown committed
1118
      {
1119
        if (!opt_xml && !tFlag)
1120
	{
1121
	  fputs(",\n",sql_file);
1122 1123
	  check_io(sql_file);
	}
1124
        if (cFlag)
1125
	  strpos=strmov(strpos,", ");
1126 1127 1128
      }
      init=1;
      if (cFlag)
unknown's avatar
unknown committed
1129
        strpos=strmov(strpos,quote_name(row[SHOW_FIELDNAME], name_buff, 0));
1130 1131
      if (!tFlag)
      {
1132 1133 1134 1135 1136 1137
	if (opt_xml)
	{
	  print_xml_row(sql_file, "field", tableRes, &row);
	  continue;
	}
	
1138
        if (opt_keywords)
1139
	  fprintf(sql_file, "  %s.%s %s", result_table,
unknown's avatar
unknown committed
1140 1141
		  quote_name(row[SHOW_FIELDNAME],name_buff, 0),
		  row[SHOW_TYPE]);
1142
        else
unknown's avatar
unknown committed
1143
	  fprintf(sql_file, "  %s %s", quote_name(row[SHOW_FIELDNAME],
unknown's avatar
unknown committed
1144 1145
						  name_buff, 0),
		  row[SHOW_TYPE]);
1146 1147
        if (row[SHOW_DEFAULT])
        {
unknown's avatar
unknown committed
1148
	  fputs(" DEFAULT ", sql_file);
unknown's avatar
unknown committed
1149
	  unescape(sql_file, row[SHOW_DEFAULT], lengths[SHOW_DEFAULT]);
1150 1151
        }
        if (!row[SHOW_NULL][0])
unknown's avatar
unknown committed
1152
	  fputs(" NOT NULL", sql_file);
1153
        if (row[SHOW_EXTRA][0])
unknown's avatar
unknown committed
1154
	  fprintf(sql_file, " %s",row[SHOW_EXTRA]);
1155
	check_io(sql_file);
unknown's avatar
unknown committed
1156 1157
      }
    }
1158 1159 1160
    numFields = (uint) mysql_num_rows(tableRes);
    mysql_free_result(tableRes);
    if (!tFlag)
unknown's avatar
unknown committed
1161
    {
1162 1163 1164
      /* Make an sql-file, if path was given iow. option -T was given */
      char buff[20+FN_REFLEN];
      uint keynr,primary_key;
unknown's avatar
unknown committed
1165
      sprintf(buff,"show keys from %s", result_table);
unknown's avatar
unknown committed
1166 1167
      if (mysql_query(sock, buff))
      {
unknown's avatar
unknown committed
1168 1169 1170 1171 1172 1173
        if (mysql_errno(sock) == ER_WRONG_OBJECT)
        {
          /* it is VIEW */
          fputs("\t\t<options Comment=\"view\" />\n", sql_file);
          goto continue_xml;
        }
unknown's avatar
unknown committed
1174 1175
        fprintf(stderr, "%s: Can't get keys for table %s (%s)\n",
		my_progname, result_table, mysql_error(sock));
1176
        if (path)
unknown's avatar
unknown committed
1177
	  my_fclose(sql_file, MYF(MY_WME));
1178 1179
        safe_exit(EX_MYSQLERR);
        DBUG_RETURN(0);
unknown's avatar
unknown committed
1180
      }
1181 1182 1183 1184 1185 1186

      tableRes=mysql_store_result(sock);
      /* Find first which key is primary key */
      keynr=0;
      primary_key=INT_MAX;
      while ((row=mysql_fetch_row(tableRes)))
unknown's avatar
unknown committed
1187
      {
1188 1189
        if (atoi(row[3]) == 1)
        {
unknown's avatar
unknown committed
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
	  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;
	  }
1200
        }
unknown's avatar
unknown committed
1201
      }
1202 1203 1204 1205
      mysql_data_seek(tableRes,0);
      keynr=0;
      while ((row=mysql_fetch_row(tableRes)))
      {
1206 1207 1208 1209 1210 1211
	if (opt_xml)
	{
	  print_xml_row(sql_file, "key", tableRes, &row);
	  continue;
	}
        
1212 1213
        if (atoi(row[3]) == 1)
        {
unknown's avatar
unknown committed
1214 1215 1216 1217
	  if (keynr++)
	    putc(')', sql_file);
	  if (atoi(row[1]))       /* Test if duplicate key */
	    /* Duplicate allowed */
unknown's avatar
unknown committed
1218
	    fprintf(sql_file, ",\n  KEY %s (",quote_name(row[2],name_buff,0));
unknown's avatar
unknown committed
1219 1220 1221
	  else if (keynr == primary_key)
	    fputs(",\n  PRIMARY KEY (",sql_file); /* First UNIQUE is primary */
	  else
unknown's avatar
unknown committed
1222 1223
	    fprintf(sql_file, ",\n  UNIQUE %s (",quote_name(row[2],name_buff,
							    0));
1224 1225
        }
        else
unknown's avatar
unknown committed
1226
	  putc(',', sql_file);
unknown's avatar
unknown committed
1227
        fputs(quote_name(row[4], name_buff, 0), sql_file);
1228
        if (row[7])
unknown's avatar
unknown committed
1229
	  fprintf(sql_file, " (%s)",row[7]);      /* Sub key */
1230
	check_io(sql_file);
1231
      }
1232 1233 1234 1235 1236
      if (!opt_xml)
      {
	if (keynr)
	  putc(')', sql_file);
	fputs("\n)",sql_file);
1237
	check_io(sql_file);
1238
      }
1239 1240 1241

      /* Get MySQL specific create options */
      if (create_options)
unknown's avatar
unknown committed
1242
      {
1243 1244 1245
	char show_name_buff[FN_REFLEN];
        sprintf(buff,"show table status like %s",
		quote_for_like(table, show_name_buff));
1246 1247
        if (mysql_query(sock, buff))
        {
unknown's avatar
unknown committed
1248 1249 1250 1251
	  if (mysql_errno(sock) != ER_PARSE_ERROR)
	  {					/* If old MySQL version */
	    if (verbose)
	      fprintf(stderr,
unknown's avatar
unknown committed
1252 1253
		      "-- Warning: Couldn't get status information for table %s (%s)\n",
		      result_table,mysql_error(sock));
unknown's avatar
unknown committed
1254
	  }
1255 1256
        }
        else if (!(tableRes=mysql_store_result(sock)) ||
unknown's avatar
unknown committed
1257
		 !(row=mysql_fetch_row(tableRes)))
1258
        {
unknown's avatar
unknown committed
1259
	  fprintf(stderr,
unknown's avatar
unknown committed
1260 1261
		  "Error: Couldn't read status information for table %s (%s)\n",
		  result_table,mysql_error(sock));
1262 1263 1264
        }
        else
        {
1265 1266 1267 1268 1269 1270 1271
	  if (opt_xml)
	  {
	    print_xml_row(sql_file, "options", tableRes, &row);
	  }
	  else
	  {
	    fputs("/*!",sql_file);
unknown's avatar
unknown committed
1272
	    print_value(sql_file,tableRes,row,"engine=","Engine",0);
1273 1274 1275
	    print_value(sql_file,tableRes,row,"","Create_options",0);
	    print_value(sql_file,tableRes,row,"comment=","Comment",1);
	    fputs(" */",sql_file);
1276
	    check_io(sql_file);
1277
	  }
1278 1279
        }
        mysql_free_result(tableRes);		/* Is always safe to free */
unknown's avatar
unknown committed
1280
      }
unknown's avatar
unknown committed
1281
continue_xml:
1282 1283 1284 1285
      if (!opt_xml)
	fputs(";\n", sql_file);
      else
	fputs("\t</table_structure>\n", sql_file);
1286
      check_io(sql_file);
unknown's avatar
unknown committed
1287 1288 1289 1290 1291 1292 1293 1294
    }
  }
  if (cFlag)
  {
    strpos=strmov(strpos,") VALUES ");
    if (!extended_insert)
      strpos=strmov(strpos,"(");
  }
1295
  if (sql_file != md_result_file)
1296 1297 1298
  {
    fputs("\n", sql_file);
    write_footer(sql_file);
1299
    my_fclose(sql_file, MYF(MY_WME));
1300
  }
unknown's avatar
unknown committed
1301 1302 1303 1304 1305 1306 1307 1308 1309
  DBUG_RETURN(numFields);
} /* getTableStructure */


static char *add_load_option(char *ptr,const char *object,
			     const char *statement)
{
  if (object)
  {
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
    /* 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++= '\'';
    }
unknown's avatar
unknown committed
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
  }
  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 */


1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
static char *alloc_query_str(ulong size)
{
  char *query;

  if (!(query= (char*) my_malloc(size, MYF(MY_WME))))
  {
    ignore_errors= 0;   			/* Fatal error */
    safe_exit(EX_MYSQLERR);			/* Force exit */
  }
  return query;
}

unknown's avatar
unknown committed
1368 1369 1370 1371 1372
/*
** dumpTable saves database contents as a series of INSERT statements.
*/
static void dumpTable(uint numFields, char *table)
{
1373
  char query_buf[QUERY_LENGTH], *end, buff[256],table_buff[NAME_LEN+3];
unknown's avatar
unknown committed
1374
  char *result_table, table_buff2[NAME_LEN*2+3], *opt_quoted_table;
1375
  char *query= query_buf;
unknown's avatar
unknown committed
1376
  MYSQL_RES	*res;
unknown's avatar
unknown committed
1377 1378
  MYSQL_FIELD	*field;
  MYSQL_ROW	row;
unknown's avatar
unknown committed
1379
  ulong		rownr, row_break, total_length, init_length;
1380
  const char    *table_type;
1381
  int error= 0;
unknown's avatar
unknown committed
1382

unknown's avatar
unknown committed
1383 1384
  result_table= quote_name(table,table_buff, 1);
  opt_quoted_table= quote_name(table, table_buff2, 0);
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397

  /* Check table type */
  if ((table_type= check_if_ignore_table(table)))
  {
    if (verbose)
      fprintf(stderr,
	      "-- Skipping data for table '%s' because it's of type %s\n",
	      table, table_type);
    return;
  }

  if (verbose)
    fprintf(stderr, "-- Sending SELECT query...\n");
unknown's avatar
unknown committed
1398 1399 1400
  if (path)
  {
    char filename[FN_REFLEN], tmp_path[FN_REFLEN];
1401
    convert_dirname(tmp_path,path,NullS);
unknown's avatar
unknown committed
1402 1403 1404 1405 1406
    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);
1407 1408
    sprintf(query, "SELECT /*!40001 SQL_NO_CACHE */ * INTO OUTFILE '%s'",
	    filename);
unknown's avatar
unknown committed
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423
    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';

unknown's avatar
unknown committed
1424
    sprintf(buff," FROM %s", result_table);
unknown's avatar
unknown committed
1425 1426
    end= strmov(end,buff);
    if (where)
1427 1428 1429 1430 1431
    {
      query= alloc_query_str((ulong) (strlen(where) + (end - query) + 10));
      end= strxmov(query, query_buf, " WHERE ", where, NullS);
    }
    if (mysql_real_query(sock, query, (uint) (end - query)))
unknown's avatar
unknown committed
1432 1433 1434 1435 1436 1437 1438
    {
      DBerror(sock, "when executing 'SELECT INTO OUTFILE'");
      return;
    }
  }
  else
  {
1439
    if (!opt_xml && opt_comments)
1440
    {
unknown's avatar
unknown committed
1441 1442
      fprintf(md_result_file,"\n--\n-- Dumping data for table %s\n--\n",
	      result_table);
1443 1444
      check_io(md_result_file);
    }
1445
    sprintf(query, "SELECT /*!40001 SQL_NO_CACHE */ * FROM %s",
unknown's avatar
unknown committed
1446
	    result_table);
unknown's avatar
unknown committed
1447 1448
    if (where)
    {
1449
      if (!opt_xml && opt_comments)
1450
      {
unknown's avatar
unknown committed
1451
	fprintf(md_result_file,"-- WHERE:  %s\n",where);
1452 1453
	check_io(md_result_file);
      }
1454 1455
      query= alloc_query_str((ulong) (strlen(where) + strlen(query) + 10));
      strxmov(query, query_buf, " WHERE ", where, NullS);
unknown's avatar
unknown committed
1456
    }
unknown's avatar
unknown committed
1457
    if (!opt_xml && !opt_compact)
1458
    {
unknown's avatar
merge  
unknown committed
1459
      fputs("\n", md_result_file);
1460 1461
      check_io(md_result_file);
    }
unknown's avatar
unknown committed
1462 1463 1464
    if (mysql_query(sock, query))
    {
      DBerror(sock, "when retrieving data from server");
1465 1466
      error= EX_CONSCHECK;
      goto err;
unknown's avatar
unknown committed
1467 1468 1469 1470 1471 1472 1473 1474
    }
    if (quick)
      res=mysql_use_result(sock);
    else
      res=mysql_store_result(sock);
    if (!res)
    {
      DBerror(sock, "when retrieving data from server");
1475 1476
      error= EX_CONSCHECK;
      goto err;
unknown's avatar
unknown committed
1477 1478
    }
    if (verbose)
1479
      fprintf(stderr, "-- Retrieving rows...\n");
unknown's avatar
unknown committed
1480 1481
    if (mysql_num_fields(res) != numFields)
    {
unknown's avatar
unknown committed
1482 1483
      fprintf(stderr,"%s: Error in field count for table: %s !  Aborting.\n",
	      my_progname, result_table);
1484 1485
      error= EX_CONSCHECK;
      goto err;
unknown's avatar
unknown committed
1486 1487
    }

unknown's avatar
merge  
unknown committed
1488
    if (opt_disable_keys)
1489
    {
unknown's avatar
unknown committed
1490
      fprintf(md_result_file, "\n/*!40000 ALTER TABLE %s DISABLE KEYS */;\n",
unknown's avatar
unknown committed
1491
	      opt_quoted_table);
1492 1493
      check_io(md_result_file);
    }
unknown's avatar
unknown committed
1494
    if (opt_lock)
1495
    {
unknown's avatar
unknown committed
1496
      fprintf(md_result_file,"LOCK TABLES %s WRITE;\n", opt_quoted_table);
1497 1498
      check_io(md_result_file);
    }
unknown's avatar
unknown committed
1499

1500
    total_length= opt_net_buffer_length;		/* Force row break */
unknown's avatar
unknown committed
1501 1502
    row_break=0;
    rownr=0;
unknown's avatar
unknown committed
1503
    init_length=(uint) strlen(insert_pat)+4;
unknown's avatar
unknown committed
1504
    if (opt_xml)
1505
      print_xml_tag1(md_result_file, "\t", "table_data name=", table, "\n");
unknown's avatar
unknown committed
1506

unknown's avatar
unknown committed
1507
    if (opt_autocommit)
1508
    {
unknown's avatar
unknown committed
1509
      fprintf(md_result_file, "set autocommit=0;\n");
1510 1511
      check_io(md_result_file);
    }
unknown's avatar
unknown committed
1512

unknown's avatar
unknown committed
1513 1514 1515 1516 1517
    while ((row=mysql_fetch_row(res)))
    {
      uint i;
      ulong *lengths=mysql_fetch_lengths(res);
      rownr++;
unknown's avatar
unknown committed
1518
      if (!extended_insert && !opt_xml)
1519
      {
unknown's avatar
unknown committed
1520
	fputs(insert_pat,md_result_file);
1521 1522
	check_io(md_result_file);
      }
unknown's avatar
unknown committed
1523 1524
      mysql_field_seek(res,0);

unknown's avatar
merge  
unknown committed
1525
      if (opt_xml)
1526
      {
1527
        fputs("\t<row>\n", md_result_file);
1528 1529
	check_io(md_result_file);
      }
unknown's avatar
merge  
unknown committed
1530

unknown's avatar
unknown committed
1531 1532
      for (i = 0; i < mysql_num_fields(res); i++)
      {
1533
        int is_blob;
unknown's avatar
unknown committed
1534 1535
	if (!(field = mysql_fetch_field(res)))
	{
unknown's avatar
unknown committed
1536 1537
	  sprintf(query,"%s: Not enough fields from table %s! Aborting.\n",
		  my_progname, result_table);
unknown's avatar
unknown committed
1538
	  fputs(query,stderr);
1539 1540
	  error= EX_CONSCHECK;
	  goto err;
unknown's avatar
unknown committed
1541
	}
1542 1543 1544 1545
	
	/*
	   63 is my_charset_bin. If charsetnr is not 63,
	   we have not a BLOB but a TEXT column. 
unknown's avatar
unknown committed
1546
	   we'll dump in hex only BLOB columns.
1547 1548
	*/
        is_blob= (opt_hex_blob && field->charsetnr == 63 &&
1549 1550 1551 1552 1553 1554 1555
                  (field->type == MYSQL_TYPE_STRING ||
                   field->type == MYSQL_TYPE_VAR_STRING ||
                   field->type == MYSQL_TYPE_VARCHAR ||
                   field->type == MYSQL_TYPE_BLOB ||
                   field->type == MYSQL_TYPE_LONG_BLOB ||
                   field->type == MYSQL_TYPE_MEDIUM_BLOB ||
                   field->type == MYSQL_TYPE_TINY_BLOB)) ? 1 : 0;
1556
	if (extended_insert)
unknown's avatar
unknown committed
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
	{
	  ulong length = lengths[i];
	  if (i == 0)
	    dynstr_set(&extended_row,"(");
	  else
	    dynstr_append(&extended_row,",");

	  if (row[i])
	  {
	    if (length)
	    {
1568
	      if (!IS_NUM_FIELD(field))
unknown's avatar
unknown committed
1569
	      {
unknown's avatar
unknown committed
1570 1571 1572 1573 1574 1575 1576
	        /*
	          "length * 2 + 2" is OK for both HEX and non-HEX modes:
	          - In HEX mode we need exactly 2 bytes per character
	          plus 2 bytes for '0x' prefix.
	          - In non-HEX mode we need up to 2 bytes per character,
	          plus 2 bytes for leading and trailing '\'' characters.
	        */
unknown's avatar
unknown committed
1577 1578 1579
		if (dynstr_realloc(&extended_row,length * 2+2))
		{
		  fputs("Aborting dump (out of memory)",stderr);
1580 1581
		  error= EX_EOM;
		  goto err;
unknown's avatar
unknown committed
1582
		}
1583 1584 1585
                if (opt_hex_blob && is_blob)
                {
                  dynstr_append(&extended_row, "0x");
unknown's avatar
unknown committed
1586 1587 1588 1589
                  extended_row.length+= mysql_hex_string(extended_row.str + 
                                                         extended_row.length,
                                                         row[i], length);
                  extended_row.str[extended_row.length]= '\0';
1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600
                }
                else
                {
                  dynstr_append(&extended_row,"'");
                  extended_row.length +=
                  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,"'");
                }
unknown's avatar
unknown committed
1601 1602
	      }
	      else
1603
	      {
unknown's avatar
unknown committed
1604
		/* change any strings ("inf", "-inf", "nan") into NULL */
1605
		char *ptr = row[i];
unknown's avatar
unknown committed
1606 1607
		if (my_isalpha(charset_info, *ptr) || (*ptr == '-' &&
		    my_isalpha(charset_info, ptr[1])))
unknown's avatar
unknown committed
1608 1609 1610 1611 1612 1613
		  dynstr_append(&extended_row, "NULL");
		else
		{
		  if (field->type == FIELD_TYPE_DECIMAL)
		  {
		    /* add " signs around */
unknown's avatar
unknown committed
1614
		    dynstr_append(&extended_row, "'");
unknown's avatar
unknown committed
1615
		    dynstr_append(&extended_row, ptr);
unknown's avatar
unknown committed
1616
		    dynstr_append(&extended_row, "'");
unknown's avatar
unknown committed
1617 1618 1619 1620
		  }
		  else
		    dynstr_append(&extended_row, ptr);
		}
1621
	      }
unknown's avatar
unknown committed
1622 1623
	    }
	    else
unknown's avatar
unknown committed
1624
	      dynstr_append(&extended_row,"''");
unknown's avatar
unknown committed
1625 1626 1627 1628
	  }
	  else if (dynstr_append(&extended_row,"NULL"))
	  {
	    fputs("Aborting dump (out of memory)",stderr);
1629 1630
	    error= EX_EOM;
	    goto err;
unknown's avatar
unknown committed
1631 1632 1633 1634
	  }
	}
	else
	{
unknown's avatar
unknown committed
1635
	  if (i && !opt_xml)
1636
	  {
unknown's avatar
unknown committed
1637
	    fputc(',', md_result_file);
1638 1639
	    check_io(md_result_file);
	  }
unknown's avatar
unknown committed
1640 1641
	  if (row[i])
	  {
1642
	    if (!IS_NUM_FIELD(field))
1643
	    {
unknown's avatar
unknown committed
1644
	      if (opt_xml)
1645
	      {
1646 1647
	        print_xml_tag1(md_result_file, "\t\t", "field name=",
			      field->name, "");
1648 1649 1650
		print_quoted_xml(md_result_file, row[i], lengths[i]);
		fputs("</field>\n", md_result_file);
	      }
1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664
	      else if (opt_hex_blob && is_blob)
              { /* sakaik got this idea. */
                ulong counter;
                char xx[4];
                unsigned char *ptr= row[i];
                fputs("0x", md_result_file);
                for (counter = 0; counter < lengths[i]; counter++)
                {
                  sprintf(xx, "%02X", ptr[counter]);
                  fputs(xx, md_result_file);
                }
              }
              else
                unescape(md_result_file, row[i], lengths[i]);
unknown's avatar
unknown committed
1665
	    }
unknown's avatar
unknown committed
1666
	    else
1667
	    {
unknown's avatar
unknown committed
1668
	      /* change any strings ("inf", "-inf", "nan") into NULL */
1669
	      char *ptr = row[i];
unknown's avatar
unknown committed
1670
	      if (opt_xml)
1671
	      {
1672 1673
	        print_xml_tag1(md_result_file, "\t\t", "field name=",
			       field->name, "");
1674 1675 1676 1677
		fputs(!my_isalpha(charset_info, *ptr) ? ptr: "NULL",
		      md_result_file);
		fputs("</field>\n", md_result_file);
	      }
unknown's avatar
unknown committed
1678 1679 1680 1681
	      else if (my_isalpha(charset_info, *ptr) ||
		       (*ptr == '-' && my_isalpha(charset_info, ptr[1])))
	        fputs("NULL", md_result_file);
	      else if (field->type == FIELD_TYPE_DECIMAL)
unknown's avatar
unknown committed
1682 1683
	      {
		/* add " signs around */
unknown's avatar
unknown committed
1684
		fputc('\'', md_result_file);
unknown's avatar
unknown committed
1685
		fputs(ptr, md_result_file);
unknown's avatar
unknown committed
1686
		fputc('\'', md_result_file);
unknown's avatar
unknown committed
1687
	      }
unknown's avatar
unknown committed
1688
	      else
unknown's avatar
unknown committed
1689
		fputs(ptr, md_result_file);
1690
	    }
unknown's avatar
unknown committed
1691
	  }
1692 1693
	  else
            fputs("NULL", md_result_file);
unknown's avatar
Merge  
unknown committed
1694
          check_io(md_result_file);
unknown's avatar
unknown committed
1695 1696 1697
	}
      }

unknown's avatar
merge  
unknown committed
1698
      if (opt_xml)
1699
      {
1700
        fputs("\t</row>\n", md_result_file);
1701 1702
	check_io(md_result_file);
      }
unknown's avatar
merge  
unknown committed
1703

1704
      if (extended_insert)
unknown's avatar
unknown committed
1705 1706 1707 1708
      {
	ulong row_length;
	dynstr_append(&extended_row,")");
        row_length = 2 + extended_row.length;
1709
        if (total_length + row_length < opt_net_buffer_length)
unknown's avatar
unknown committed
1710 1711
        {
	  total_length += row_length;
unknown's avatar
unknown committed
1712 1713
	  fputc(',',md_result_file);		/* Always row break */
	  fputs(extended_row.str,md_result_file);
unknown's avatar
unknown committed
1714 1715 1716
	}
        else
        {
1717
	  if (row_break)
unknown's avatar
unknown committed
1718
	    fputs(";\n", md_result_file);
unknown's avatar
unknown committed
1719
	  row_break=1;				/* This is first row */
unknown's avatar
unknown committed
1720

1721 1722
          fputs(insert_pat,md_result_file);
          fputs(extended_row.str,md_result_file);
unknown's avatar
unknown committed
1723 1724
	  total_length = row_length+init_length;
        }
1725
	check_io(md_result_file);
unknown's avatar
unknown committed
1726
      }
unknown's avatar
unknown committed
1727
      else if (!opt_xml)
1728
      {
unknown's avatar
unknown committed
1729
	fputs(");\n", md_result_file);
1730 1731
	check_io(md_result_file);
      }
unknown's avatar
unknown committed
1732
    }
unknown's avatar
unknown committed
1733

unknown's avatar
unknown committed
1734
    /* XML - close table tag and supress regular output */
unknown's avatar
unknown committed
1735
    if (opt_xml)
1736
	fputs("\t</table_data>\n", md_result_file);
unknown's avatar
unknown committed
1737
    else if (extended_insert && row_break)
unknown's avatar
unknown committed
1738 1739
      fputs(";\n", md_result_file);		/* If not empty table */
    fflush(md_result_file);
1740
    check_io(md_result_file);
unknown's avatar
unknown committed
1741 1742
    if (mysql_errno(sock))
    {
unknown's avatar
unknown committed
1743
      sprintf(query,"%s: Error %d: %s when dumping table %s at row: %ld\n",
unknown's avatar
unknown committed
1744 1745 1746
	      my_progname,
	      mysql_errno(sock),
	      mysql_error(sock),
unknown's avatar
unknown committed
1747
	      result_table,
unknown's avatar
unknown committed
1748 1749
	      rownr);
      fputs(query,stderr);
1750 1751
      error= EX_CONSCHECK;
      goto err;
unknown's avatar
unknown committed
1752 1753
    }
    if (opt_lock)
1754
    {
unknown's avatar
unknown committed
1755
      fputs("UNLOCK TABLES;\n", md_result_file);
1756 1757
      check_io(md_result_file);
    }
unknown's avatar
merge  
unknown committed
1758
    if (opt_disable_keys)
1759
    {
unknown's avatar
merge  
unknown committed
1760
      fprintf(md_result_file,"/*!40000 ALTER TABLE %s ENABLE KEYS */;\n",
unknown's avatar
unknown committed
1761
	      opt_quoted_table);
1762 1763
      check_io(md_result_file);
    }
unknown's avatar
unknown committed
1764
    if (opt_autocommit)
1765
    {
unknown's avatar
unknown committed
1766
      fprintf(md_result_file, "commit;\n");
1767 1768
      check_io(md_result_file);
    }
1769
    mysql_free_result(res);
1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
    if (query != query_buf)
      my_free(query, MYF(MY_ALLOW_ZERO_PTR));
  } 
  return;

err:
  if (query != query_buf)
    my_free(query, MYF(MY_ALLOW_ZERO_PTR));
  safe_exit(error);
  return;
unknown's avatar
unknown committed
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
} /* dumpTable */


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]);
unknown's avatar
unknown committed
1795

unknown's avatar
unknown committed
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
  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;
  }
unknown's avatar
unknown committed
1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
  if (was_views)
  {
    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_views_in_db(row[0]))
        result=1;
    }
  }
unknown's avatar
unknown committed
1840 1841 1842 1843 1844 1845 1846 1847
  return result;
}
/* dump_all_databases */


static int dump_databases(char **db_names)
{
  int result=0;
unknown's avatar
unknown committed
1848 1849
  char **db;
  for (db= db_names ; *db ; db++)
1850
  {
unknown's avatar
unknown committed
1851
    if (dump_all_tables_in_db(*db))
unknown's avatar
unknown committed
1852 1853
      result=1;
  }
unknown's avatar
unknown committed
1854 1855 1856 1857 1858 1859 1860 1861
  if (!result && was_views)
  {
    for (db= db_names ; *db ; db++)
    {
      if (dump_all_views_in_db(*db))
        result=1;
    }
  }
unknown's avatar
unknown committed
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872
  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 */
  }
unknown's avatar
unknown committed
1873
  if (!path && !opt_xml)
unknown's avatar
unknown committed
1874 1875 1876
  {
    if (opt_databases || opt_alldbs)
    {
unknown's avatar
unknown committed
1877
      /*
unknown's avatar
unknown committed
1878
	length of table name * 2 (if name contains quotes), 2 quotes and 0
unknown's avatar
unknown committed
1879
      */
unknown's avatar
unknown committed
1880 1881
      char quoted_database_buf[64*2+3];
      char *qdatabase= quote_name(database,quoted_database_buf,opt_quoted);
1882
      if (opt_comments)
1883
      {
unknown's avatar
unknown committed
1884
	fprintf(md_result_file,"\n--\n-- Current Database: %s\n--\n", qdatabase);
1885 1886
	check_io(md_result_file);
      }
unknown's avatar
unknown committed
1887
      if (!opt_create_db)
1888
      {
unknown's avatar
unknown committed
1889
        char qbuf[256];
1890 1891
        MYSQL_ROW row;
        MYSQL_RES *dbinfo;
1892

unknown's avatar
unknown committed
1893
        sprintf(qbuf,"SHOW CREATE DATABASE WITH IF NOT EXISTS %s",
unknown's avatar
unknown committed
1894
		qdatabase);
1895

1896 1897 1898
        if (mysql_query(sock, qbuf) || !(dbinfo = mysql_store_result(sock)))
        {
          /* Old server version, dump generic CREATE DATABASE */
1899
	  fprintf(md_result_file,
unknown's avatar
unknown committed
1900 1901
		  "\nCREATE DATABASE /*!32312 IF NOT EXISTS*/ %s;\n",
		  qdatabase);
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
	}
	else
        {
	  row = mysql_fetch_row(dbinfo);
	  if (row[1])
	  {
	    fprintf(md_result_file,"\n%s;\n",row[1]);
          }
	}
      }
unknown's avatar
unknown committed
1912
      fprintf(md_result_file,"\nUSE %s;\n", qdatabase);
1913
      check_io(md_result_file);
unknown's avatar
unknown committed
1914 1915
    }
  }
unknown's avatar
unknown committed
1916 1917
  if (extended_insert && init_dynamic_string(&extended_row, "", 1024, 1024))
    exit(EX_EOM);
unknown's avatar
unknown committed
1918 1919 1920 1921
  return 0;
} /* init_dumping */


unknown's avatar
unknown committed
1922

unknown's avatar
unknown committed
1923 1924 1925 1926
static int dump_all_tables_in_db(char *database)
{
  char *table;
  uint numrows;
unknown's avatar
unknown committed
1927
  char table_buff[NAME_LEN*2+3];
unknown's avatar
unknown committed
1928 1929 1930

  if (init_dumping(database))
    return 1;
unknown's avatar
unknown committed
1931
  if (opt_xml)
1932
    print_xml_tag1(md_result_file, "", "database name=", database, "\n");
unknown's avatar
unknown committed
1933 1934 1935 1936 1937 1938
  if (lock_tables)
  {
    DYNAMIC_STRING query;
    init_dynamic_string(&query, "LOCK TABLES ", 256, 1024);
    for (numrows=0 ; (table = getTableName(1)) ; numrows++)
    {
unknown's avatar
unknown committed
1939
      dynstr_append(&query, quote_name(table, table_buff, 1));
unknown's avatar
unknown committed
1940 1941 1942
      dynstr_append(&query, " READ /*!32311 LOCAL */,");
    }
    if (numrows && mysql_real_query(sock, query.str, query.length-1))
unknown's avatar
unknown committed
1943
      DBerror(sock, "when using LOCK TABLES");
unknown's avatar
unknown committed
1944 1945 1946 1947 1948 1949
            /* We shall continue here, if --force was given */
    dynstr_free(&query);
  }
  if (flush_logs)
  {
    if (mysql_refresh(sock, REFRESH_LOG))
unknown's avatar
unknown committed
1950
      DBerror(sock, "when doing refresh");
unknown's avatar
unknown committed
1951 1952 1953 1954 1955 1956 1957 1958
           /* We shall continue here, if --force was given */
  }
  while ((table = getTableName(0)))
  {
    numrows = getTableStructure(table, database);
    if (!dFlag && numrows > 0)
      dumpTable(numrows,table);
  }
unknown's avatar
unknown committed
1959
  if (opt_xml)
1960
  {
1961
    fputs("</database>\n", md_result_file);
1962 1963
    check_io(md_result_file);
  }
unknown's avatar
unknown committed
1964
  if (lock_tables)
1965
    mysql_query(sock,"UNLOCK TABLES");
unknown's avatar
unknown committed
1966 1967 1968
  return 0;
} /* dump_all_tables_in_db */

unknown's avatar
unknown committed
1969 1970
/*
   dump structure of views of database
unknown's avatar
unknown committed
1971

unknown's avatar
unknown committed
1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 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 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021
   SYNOPSIS
     dump_all_views_in_db()
     database  database name

  RETURN
    0 OK
    1 ERROR
*/

static my_bool dump_all_views_in_db(char *database)
{
  char *table;
  uint numrows;
  char table_buff[NAME_LEN*2+3];

  if (init_dumping(database))
    return 1;
  if (opt_xml)
    print_xml_tag1(md_result_file, "", "database name=", database, "\n");
  if (lock_tables)
  {
    DYNAMIC_STRING query;
    init_dynamic_string(&query, "LOCK TABLES ", 256, 1024);
    for (numrows= 0 ; (table= getTableName(1)); numrows++)
    {
      dynstr_append(&query, quote_name(table, table_buff, 1));
      dynstr_append(&query, " READ /*!32311 LOCAL */,");
    }
    if (numrows && mysql_real_query(sock, query.str, query.length-1))
      DBerror(sock, "when using LOCK TABLES");
            /* We shall continue here, if --force was given */
    dynstr_free(&query);
  }
  if (flush_logs)
  {
    if (mysql_refresh(sock, REFRESH_LOG))
      DBerror(sock, "when doing refresh");
           /* We shall continue here, if --force was given */
  }
  while ((table= getTableName(0)))
     getViewStructure(table, database);
  if (opt_xml)
  {
    fputs("</database>\n", md_result_file);
    check_io(md_result_file);
  }
  if (lock_tables)
    mysql_query(sock,"UNLOCK TABLES");
  return 0;
} /* dump_all_tables_in_db */
unknown's avatar
unknown committed
2022 2023 2024 2025

static int dump_selected_tables(char *db, char **table_names, int tables)
{
  uint numrows;
unknown's avatar
unknown committed
2026
  int i;
unknown's avatar
unknown committed
2027
  char table_buff[NAME_LEN*+3];
unknown's avatar
unknown committed
2028 2029 2030 2031 2032 2033 2034 2035 2036 2037

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

    init_dynamic_string(&query, "LOCK TABLES ", 256, 1024);
    for (i=0 ; i < tables ; i++)
    {
unknown's avatar
unknown committed
2038
      dynstr_append(&query, quote_name(table_names[i], table_buff, 1));
unknown's avatar
unknown committed
2039 2040 2041
      dynstr_append(&query, " READ /*!32311 LOCAL */,");
    }
    if (mysql_real_query(sock, query.str, query.length-1))
unknown's avatar
unknown committed
2042
      DBerror(sock, "when doing LOCK TABLES");
unknown's avatar
unknown committed
2043 2044 2045 2046 2047 2048
       /* We shall countinue here, if --force was given */
    dynstr_free(&query);
  }
  if (flush_logs)
  {
    if (mysql_refresh(sock, REFRESH_LOG))
unknown's avatar
unknown committed
2049
      DBerror(sock, "when doing refresh");
unknown's avatar
unknown committed
2050 2051
     /* We shall countinue here, if --force was given */
  }
unknown's avatar
unknown committed
2052
  if (opt_xml)
2053
    print_xml_tag1(md_result_file, "", "database name=", db, "\n");
unknown's avatar
unknown committed
2054
  for (i=0 ; i < tables ; i++)
unknown's avatar
unknown committed
2055
  {
unknown's avatar
unknown committed
2056
    numrows = getTableStructure(table_names[i], db);
unknown's avatar
unknown committed
2057
    if (!dFlag && numrows > 0)
unknown's avatar
unknown committed
2058 2059 2060 2061 2062 2063
      dumpTable(numrows, table_names[i]);
  }
  if (was_views)
  {
    for (i=0 ; i < tables ; i++)
      getViewStructure(table_names[i], db);
unknown's avatar
unknown committed
2064
  }
unknown's avatar
unknown committed
2065
  if (opt_xml)
2066
  {
2067
    fputs("</database>\n", md_result_file);
2068 2069
    check_io(md_result_file);
  }
unknown's avatar
unknown committed
2070
  if (lock_tables)
unknown's avatar
unknown committed
2071
    mysql_query(sock,"UNLOCK TABLES");
unknown's avatar
unknown committed
2072 2073 2074 2075
  return 0;
} /* dump_selected_tables */


2076 2077 2078 2079 2080 2081 2082 2083 2084

static ulong find_set(TYPELIB *lib, const char *x, uint length,
		      char **err_pos, uint *err_len)
{
  const char *end= x + length;
  ulong found= 0;
  uint find;
  char buff[255];

2085
  *err_pos= 0;                  /* No error yet */
2086
  while (end > x && my_isspace(charset_info, end[-1]))
2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
    end--;

  *err_len= 0;
  if (x != end)
  {
    const char *start= x;
    for (;;)
    {
      const char *pos= start;
      uint var_len;

      for (; pos != end && *pos != ','; pos++) ;
      var_len= (uint) (pos - start);
      strmake(buff, start, min(sizeof(buff), var_len));
      find= find_type(buff, lib, var_len);
      if (!find)
      {
        *err_pos= (char*) start;
        *err_len= var_len;
      }
      else
        found|= ((longlong) 1 << (find - 1));
      if (pos == end)
        break;
      start= pos + 1;
    }
  }
  return found;
}


unknown's avatar
unknown committed
2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
/* 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)
unknown's avatar
unknown committed
2135
	  unescape(file,row[0],(uint) strlen(row[0]));
unknown's avatar
unknown committed
2136 2137
	else
	  fputs(row[0], file);
2138
	check_io(file);
unknown's avatar
unknown committed
2139 2140 2141 2142 2143 2144 2145 2146
	return;
      }
    }
  }
  return;					/* This shouldn't happen */
} /* print_value */


2147 2148 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 2189 2190 2191 2192 2193
/*
  Check if we the table is one of the table types that should be ignored:
  MRG_ISAM, MRG_MYISAM

  SYNOPSIS
    check_if_ignore_table()
    table_name			Table name to check

  GLOBAL VARIABLES
    sock			MySQL socket
    verbose			Write warning messages

  RETURN
    0	Table should be backuped
    #	Type of table (that should be skipped)
*/

static const char *check_if_ignore_table(const char *table_name)
{
  char buff[FN_REFLEN+80], show_name_buff[FN_REFLEN];
  MYSQL_RES *res;
  MYSQL_ROW row;
  const char *result= 0;

  sprintf(buff,"show table status like %s",
	  quote_for_like(table_name, show_name_buff));
  if (mysql_query(sock, buff))
  {
    if (mysql_errno(sock) != ER_PARSE_ERROR)
    {					/* If old MySQL version */
      if (verbose)
	fprintf(stderr,
		"-- Warning: Couldn't get status information for table %s (%s)\n",
		table_name,mysql_error(sock));
      return 0;					/* assume table is ok */
    }
  }
  if (!(res= mysql_store_result(sock)) ||
      !(row= mysql_fetch_row(res)))
  {
    fprintf(stderr,
	    "Error: Couldn't read status information for table %s (%s)\n",
	    table_name, mysql_error(sock));
    if (res)
      mysql_free_result(res);
    return 0;					/* assume table is ok */
  }
unknown's avatar
unknown committed
2194 2195 2196 2197 2198 2199 2200 2201
  if (!(row[1]))
      result= "VIEW";
  else
  {
    if (strcmp(row[1], (result= "MRG_MyISAM")) &&
        strcmp(row[1], (result= "MRG_ISAM")))
      result= 0;
  }
2202 2203 2204 2205 2206
  mysql_free_result(res);  
  return result;
}


unknown's avatar
unknown committed
2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
/*
  Getting VIEW structure

  SYNOPSIS
    getViewStructure()
    table   view name
    db      db name

  RETURN
    0 OK
    1 ERROR
*/

static my_bool getViewStructure(char *table, char* db)
{
  MYSQL_RES  *tableRes;
  MYSQL_ROW  row;
  MYSQL_FIELD *field;
  char	     *result_table, *opt_quoted_table;
  char	     table_buff[NAME_LEN*2+3];
  char	     table_buff2[NAME_LEN*2+3];
  char       buff[20+FN_REFLEN];
  FILE       *sql_file = md_result_file;
  DBUG_ENTER("getViewStructure");

  if (tFlag)
    DBUG_RETURN(0);

  if (verbose)
    fprintf(stderr, "-- Retrieving view structure for table %s...\n", table);

  sprintf(insert_pat,"SET OPTION SQL_QUOTE_SHOW_CREATE=%d",
	  (opt_quoted || opt_keywords));
  result_table=     quote_name(table, table_buff, 1);
  opt_quoted_table= quote_name(table, table_buff2, 0);

  sprintf(buff,"show create table %s", result_table);
  if (mysql_query(sock, buff))
  {
    fprintf(stderr, "%s: Can't get CREATE TABLE for view %s (%s)\n",
            my_progname, result_table, mysql_error(sock));
    safe_exit(EX_MYSQLERR);
    DBUG_RETURN(0);
  }

  if (path)
  {
    char filename[FN_REFLEN], tmp_path[FN_REFLEN];
    convert_dirname(tmp_path,path,NullS);
    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 */
    {
      safe_exit(EX_MYSQLERR);
      DBUG_RETURN(1);
    }
    write_header(sql_file, db);
  }
  tableRes= mysql_store_result(sock);
  field= mysql_fetch_field_direct(tableRes, 0);
  if (strcmp(field->name, "View") != 0)
  {
    if (verbose)
      fprintf(stderr, "-- It's base table, skipped\n");
unknown's avatar
unknown committed
2271
    DBUG_RETURN(0);
unknown's avatar
unknown committed
2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300
  }

  if (!opt_xml && opt_comments)
  {
    fprintf(sql_file, "\n--\n-- View structure for view %s\n--\n\n",
            result_table);
    check_io(sql_file);
  }
  if (opt_drop)
  {
    fprintf(sql_file, "DROP VIEW IF EXISTS %s;\n", opt_quoted_table);
    check_io(sql_file);
  }

  row= mysql_fetch_row(tableRes);
  fprintf(sql_file, "%s;\n", row[1]);
  check_io(sql_file);
  mysql_free_result(tableRes);

  if (sql_file != md_result_file)
  {
    fputs("\n", sql_file);
    write_footer(sql_file);
    my_fclose(sql_file, MYF(MY_WME));
  }
  DBUG_RETURN(0);
}


unknown's avatar
unknown committed
2301 2302
int main(int argc, char **argv)
{
unknown's avatar
unknown committed
2303 2304
  MYSQL_ROW row;
  MYSQL_RES *master;
2305
  compatible_mode_normal_str[0]= 0;
unknown's avatar
unknown committed
2306

unknown's avatar
unknown committed
2307 2308 2309 2310 2311 2312
  MY_INIT(argv[0]);
  if (get_options(&argc, &argv))
  {
    my_end(0);
    exit(EX_USAGE);
  }
2313
  if (dbConnect(current_host, current_user, opt_password))
unknown's avatar
unknown committed
2314 2315
    exit(EX_MYSQLERR);
  if (!path)
2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328
    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);
    }
  }
2329
  else if (opt_single_transaction)
2330 2331 2332
  {
    /* There is no sense to start transaction if all tables are locked */ 
    if (mysql_query(sock, "BEGIN"))
2333
    {
2334
      my_printf_error(0, "Error: Couldn't execute 'BEGIN': %s",
2335
                        MYF(0), mysql_error(sock));
2336 2337 2338 2339
      my_end(0);
      return(first_error);
    }    
  }
unknown's avatar
unknown committed
2340 2341 2342
  if (opt_alldbs)
    dump_all_databases();
  else if (argc > 1 && !opt_databases)
2343 2344
  {
    /* Only one database and selected table(s) */
unknown's avatar
unknown committed
2345
    dump_selected_tables(*argv, (argv + 1), (argc - 1));
2346
  }
unknown's avatar
unknown committed
2347
  else
2348 2349
  {
    /* One or more databases, all tables */
unknown's avatar
unknown committed
2350
    dump_databases(argv);
2351
  }
unknown's avatar
unknown committed
2352 2353 2354

  if (opt_first_slave)
  {
2355 2356 2357 2358 2359
    if (opt_delete_master_logs && mysql_query(sock, "FLUSH MASTER"))
    {
      my_printf_error(0, "Error: Couldn't execute 'FLUSH MASTER': %s",
		      MYF(0), mysql_error(sock));
    }
unknown's avatar
unknown committed
2360 2361 2362 2363 2364 2365
    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));
2366
      else
unknown's avatar
unknown committed
2367 2368
      {
	row = mysql_fetch_row(master);
unknown's avatar
unknown committed
2369
	if (row && row[0] && row[1])
2370
	{
2371 2372 2373
	  if (opt_comments)
	    fprintf(md_result_file,
		    "\n--\n-- Position to start replication from\n--\n\n");
unknown's avatar
unknown committed
2374
	  fprintf(md_result_file,
unknown's avatar
unknown committed
2375 2376
		  "CHANGE MASTER TO MASTER_LOG_FILE='%s', \
MASTER_LOG_POS=%s ;\n",row[0],row[1]); 
2377
	  check_io(md_result_file);
unknown's avatar
unknown committed
2378 2379 2380 2381
	}
	mysql_free_result(master);
      }
    }
unknown's avatar
unknown committed
2382 2383 2384 2385
    if (mysql_query(sock, "UNLOCK TABLES"))
      my_printf_error(0, "Error: Couldn't execute 'UNLOCK TABLES': %s",
		      MYF(0), mysql_error(sock));
  }
2386
  else if (opt_single_transaction) /* Just to make it beautiful enough */
2387 2388 2389
#ifdef HAVE_SMEM
  my_free(shared_memory_base_name,MYF(MY_ALLOW_ZERO_PTR));
#endif
2390
  {
2391
    /*
2392 2393
      In case we were locking all tables, we did not start transaction
      so there is no need to commit it.
2394 2395
    */

2396 2397 2398 2399
    /* 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",
2400 2401
	      MYF(0), mysql_error(sock));
    }
2402
  }
unknown's avatar
unknown committed
2403
  dbDisconnect(current_host);
2404 2405
  if (!path)
    write_footer(md_result_file);
unknown's avatar
unknown committed
2406 2407
  if (md_result_file != stdout)
    my_fclose(md_result_file, MYF(0));
2408
  my_free(opt_password, MYF(MY_ALLOW_ZERO_PTR));
2409
  if (extended_insert)
unknown's avatar
unknown committed
2410 2411 2412 2413
    dynstr_free(&extended_row);
  my_end(0);
  return(first_error);
} /* main */