mysqlimport.c 21.5 KB
Newer Older
unknown's avatar
unknown committed
1
/* Copyright (C) 2000-2006 MySQL AB
unknown's avatar
unknown committed
2

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

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

unknown's avatar
unknown committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
   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 */

/*
**	   mysqlimport.c  - Imports all given files
**			    into a table(s).
**
**			   *************************
**			   *			   *
**			   * AUTHOR: Monty & Jani  *
**			   * DATE:   June 24, 1997 *
**			   *			   *
**			   *************************
*/
27
#define IMPORT_VERSION "3.7"
unknown's avatar
unknown committed
28

unknown's avatar
unknown committed
29
#include "client_priv.h"
unknown's avatar
unknown committed
30
#include "mysql_version.h"
31
#ifdef HAVE_LIBPTHREAD
32
#include <my_pthread.h>
33
#endif
34

35

36
/* Global Thread counter */
unknown's avatar
unknown committed
37
uint counter;
38
#ifdef HAVE_LIBPTHREAD
39
pthread_mutex_t counter_mutex;
40
pthread_cond_t count_threshhold;
41
#endif
unknown's avatar
unknown committed
42 43 44 45 46 47 48

static void db_error_with_table(MYSQL *mysql, char *table);
static void db_error(MYSQL *mysql);
static char *field_escape(char *to,const char *from,uint length);
static char *add_load_option(char *ptr,const char *object,
			     const char *statement);

unknown's avatar
unknown committed
49
static my_bool	verbose=0,lock_tables=0,ignore_errors=0,opt_delete=0,
50
		replace=0,silent=0,ignore=0,opt_compress=0,
51
                opt_low_priority= 0, tty_password= 0;
52 53
static my_bool debug_info_flag= 0, debug_check_flag= 0;
static uint opt_use_threads=0, opt_local_file=0, my_end_arg= 0;
54
static char	*opt_password=0, *current_user=0,
unknown's avatar
unknown committed
55 56
		*current_host=0, *current_db=0, *fields_terminated=0,
		*lines_terminated=0, *enclosed=0, *opt_enclosed=0,
57
		*escaped=0, *opt_columns=0, 
58
		*default_charset= (char*) MYSQL_DEFAULT_CHARSET_NAME;
unknown's avatar
unknown committed
59
static uint     opt_mysql_port= 0, opt_protocol= 0;
60
static char * opt_mysql_unix_port=0;
61
static longlong opt_ignore_lines= -1;
62
static CHARSET_INFO *charset_info= &my_charset_latin1;
63
#include <sslopt-vars.h>
unknown's avatar
unknown committed
64

65 66 67 68
#ifdef HAVE_SMEM
static char *shared_memory_base_name=0;
#endif

69
static struct my_option my_long_options[] =
unknown's avatar
unknown committed
70
{
unknown's avatar
unknown committed
71
#ifdef __NETWARE__
72
  {"autoclose", OPT_AUTO_CLOSE, "Auto close the screen on exit for Netware.",
unknown's avatar
unknown committed
73 74
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
#endif
75
  {"character-sets-dir", OPT_CHARSETS_DIR,
76 77
   "Directory where character sets are.", (uchar**) &charsets_dir,
   (uchar**) &charsets_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
78
  {"default-character-set", OPT_DEFAULT_CHARSET,
79 80
   "Set the default character set.", (uchar**) &default_charset,
   (uchar**) &default_charset, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
81 82
  {"columns", 'c',
   "Use only these columns to import the data to. Give the column names in a comma separated list. This is same as giving columns to LOAD DATA INFILE.",
83
   (uchar**) &opt_columns, (uchar**) &opt_columns, 0, GET_STR, REQUIRED_ARG, 0, 0, 0,
84 85
   0, 0, 0},
  {"compress", 'C', "Use compression in server/client protocol.",
86
   (uchar**) &opt_compress, (uchar**) &opt_compress, 0, GET_BOOL, NO_ARG, 0, 0, 0,
87
   0, 0, 0},
88 89
  {"debug",'#', "Output debug log. Often this is 'd:t:o,filename'.", 0, 0, 0,
   GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
90
  {"debug-check", OPT_DEBUG_CHECK, "Check memory and open file usage at exit.",
91 92 93 94 95
   (uchar**) &debug_check_flag, (uchar**) &debug_check_flag, 0,
   GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"debug-info", OPT_DEBUG_INFO, "Print some debug info at exit.",
   (uchar**) &debug_info_flag, (uchar**) &debug_info_flag,
   0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
96 97
  {"delete", 'd', "First delete all rows from table.", (uchar**) &opt_delete,
   (uchar**) &opt_delete, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
98
  {"fields-terminated-by", OPT_FTB,
99 100
   "Fields in the textfile are terminated by ...", (uchar**) &fields_terminated,
   (uchar**) &fields_terminated, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
101
  {"fields-enclosed-by", OPT_ENC,
102 103
   "Fields in the importfile are enclosed by ...", (uchar**) &enclosed,
   (uchar**) &enclosed, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
104
  {"fields-optionally-enclosed-by", OPT_O_ENC,
105 106
   "Fields in the i.file are opt. enclosed by ...", (uchar**) &opt_enclosed,
   (uchar**) &opt_enclosed, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
107
  {"fields-escaped-by", OPT_ESC, "Fields in the i.file are escaped by ...",
108
   (uchar**) &escaped, (uchar**) &escaped, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0,
109 110
   0, 0},
  {"force", 'f', "Continue even if we get an sql-error.",
111
   (uchar**) &ignore_errors, (uchar**) &ignore_errors, 0, GET_BOOL, NO_ARG, 0, 0,
112 113 114
   0, 0, 0, 0},
  {"help", '?', "Displays this help and exits.", 0, 0, 0, GET_NO_ARG, NO_ARG,
   0, 0, 0, 0, 0, 0},
115 116
  {"host", 'h', "Connect to host.", (uchar**) &current_host,
   (uchar**) &current_host, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
117
  {"ignore", 'i', "If duplicate unique key was found, keep old row.",
118
   (uchar**) &ignore, (uchar**) &ignore, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
119
  {"ignore-lines", OPT_IGN_LINES, "Ignore first n lines of data infile.",
120
   (uchar**) &opt_ignore_lines, (uchar**) &opt_ignore_lines, 0, GET_LL,
121
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
122
  {"lines-terminated-by", OPT_LTB, "Lines in the i.file are terminated by ...",
123
   (uchar**) &lines_terminated, (uchar**) &lines_terminated, 0, GET_STR,
124
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
125 126
  {"local", 'L', "Read all files through the client.", (uchar**) &opt_local_file,
   (uchar**) &opt_local_file, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
127
  {"lock-tables", 'l', "Lock all tables for write (this disables threads).",
128
    (uchar**) &lock_tables, (uchar**) &lock_tables, 0, GET_BOOL, NO_ARG, 
129
    0, 0, 0, 0, 0, 0},
130
  {"low-priority", OPT_LOW_PRIORITY,
131 132
   "Use LOW_PRIORITY when updating the table.", (uchar**) &opt_low_priority,
   (uchar**) &opt_low_priority, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
133 134 135
  {"password", 'p',
   "Password to use when connecting to server. If password is not given it's asked from the tty.",
   0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
136
#ifdef __WIN__
137 138
  {"pipe", 'W', "Use named pipes to connect to server.", 0, 0, 0, GET_NO_ARG,
   NO_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
139
#endif
140 141 142 143 144 145
  {"port", 'P', "Port number to use for connection or 0 for default to, in "
   "order of preference, my.cnf, $MYSQL_TCP_PORT, "
#if MYSQL_PORT_DEFAULT == 0
   "/etc/services, "
#endif
   "built-in default (" STRINGIFY_ARG(MYSQL_PORT) ").",
146
   (uchar**) &opt_mysql_port,
147
   (uchar**) &opt_mysql_port, 0, GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0,
148
   0},
149
  {"protocol", OPT_MYSQL_PROTOCOL, "The protocol of connection (tcp,socket,pipe,memory).",
150
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
151
  {"replace", 'r', "If duplicate unique key was found, replace old row.",
152
   (uchar**) &replace, (uchar**) &replace, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
153
#ifdef HAVE_SMEM
154
  {"shared-memory-base-name", OPT_SHARED_MEMORY_BASE_NAME,
155
   "Base name of shared memory.", (uchar**) &shared_memory_base_name, (uchar**) &shared_memory_base_name,
156 157
   0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#endif
158
  {"silent", 's', "Be more silent.", (uchar**) &silent, (uchar**) &silent, 0,
159 160
   GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"socket", 'S', "Socket file to use for connection.",
161
   (uchar**) &opt_mysql_unix_port, (uchar**) &opt_mysql_unix_port, 0, GET_STR,
162
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
163
#include <sslopt-longopts.h>
164
  {"use-threads", OPT_USE_THREADS,
unknown's avatar
unknown committed
165 166
   "Load files in parallel. The argument is the number "
   "of threads to use for loading data.",
167
   (uchar**) &opt_use_threads, (uchar**) &opt_use_threads, 0, 
unknown's avatar
unknown committed
168
   GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
169
#ifndef DONT_ALLOW_USER_CHANGE
170 171
  {"user", 'u', "User for login if not current user.", (uchar**) &current_user,
   (uchar**) &current_user, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
172
#endif
173 174
  {"verbose", 'v', "Print info about the various stages.", (uchar**) &verbose,
   (uchar**) &verbose, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
175 176 177
  {"version", 'V', "Output version information and exit.", 0, 0, 0, GET_NO_ARG,
   NO_ARG, 0, 0, 0, 0, 0, 0},
  { 0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
unknown's avatar
unknown committed
178 179 180 181 182
};


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

unknown's avatar
unknown committed
183 184
#include <help_start.h>

unknown's avatar
unknown committed
185 186 187 188
static void print_version(void)
{
  printf("%s  Ver %s Distrib %s, for %s (%s)\n" ,my_progname,
	  IMPORT_VERSION, MYSQL_SERVER_VERSION,SYSTEM_TYPE,MACHINE_TYPE);
unknown's avatar
unknown committed
189
  NETWARE_SET_SCREEN_MODE(1);
unknown's avatar
unknown committed
190 191 192 193 194 195
}


static void usage(void)
{
  print_version();
196
  puts("Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.");
unknown's avatar
unknown committed
197 198 199 200 201 202 203 204 205 206
  puts("This software comes with ABSOLUTELY NO WARRANTY. This is free software,\nand you are welcome to modify and redistribute it under the GPL license\n");
  printf("\
Loads tables from text files in various formats.  The base name of the\n\
text file must be the name of the table that should be used.\n\
If one uses sockets to connect to the MySQL server, the server will open and\n\
read the text file directly. In other cases the client will open the text\n\
file. The SQL command 'LOAD DATA INFILE' is used to import the rows.\n");

  printf("\nUsage: %s [OPTIONS] database textfile...",my_progname);
  print_defaults("my",load_default_groups);
207 208
  my_print_help(my_long_options);
  my_print_variables(my_long_options);
unknown's avatar
unknown committed
209 210
}

unknown's avatar
unknown committed
211
#include <help_end.h>
unknown's avatar
unknown committed
212

213 214 215 216 217
static my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
	       char *argument)
{
  switch(optid) {
unknown's avatar
unknown committed
218 219 220 221 222
#ifdef __NETWARE__
  case OPT_AUTO_CLOSE:
    setscreenmode(SCR_AUTOCLOSE_ON_EXIT);
    break;
#endif
223
  case 'p':
224
    if (argument == disabled_my_option)
225
      argument= (char*) "";			/* Don't require password */
226 227 228 229 230 231 232 233
    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 */
234
      tty_password= 0;
235 236 237 238
    }
    else
      tty_password= 1;
    break;
unknown's avatar
unknown committed
239
#ifdef __WIN__
240
  case 'W':
241
    opt_protocol = MYSQL_PROTOCOL_PIPE;
242 243
    opt_local_file=1;
    break;
unknown's avatar
unknown committed
244
#endif
245
  case OPT_MYSQL_PROTOCOL:
246 247
    opt_protocol= find_type_or_exit(argument, &sql_protocol_typelib,
                                    opt->name);
248
    break;
249 250
  case '#':
    DBUG_PUSH(argument ? argument : "d:t:o");
251
    debug_check_flag= 1;
252
    break;
253
#include <sslopt-case.h>
254 255 256 257 258 259 260 261 262 263 264 265 266 267
  case 'V': print_version(); exit(0);
  case 'I':
  case '?':
    usage();
    exit(0);
  }
  return 0;
}


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

268
  if ((ho_error=handle_options(argc, argv, my_long_options, get_one_option)))
269
    exit(ho_error);
270 271 272 273
  if (debug_info_flag)
    my_end_arg= MY_CHECK_ERROR | MY_GIVE_INFO;
  if (debug_check_flag)
    my_end_arg= MY_CHECK_ERROR;
274

unknown's avatar
unknown committed
275 276 277 278 279 280 281 282 283 284
  if (enclosed && opt_enclosed)
  {
    fprintf(stderr, "You can't use ..enclosed.. and ..optionally-enclosed.. at the same time.\n");
    return(1);
  }
  if (replace && ignore)
  {
    fprintf(stderr, "You can't use --ignore (-i) and --replace (-r) at the same time.\n");
    return(1);
  }
285 286
  if (strcmp(default_charset, charset_info->csname) &&
      !(charset_info= get_charset_by_csname(default_charset,
287
  					    MY_CS_PRIMARY, MYF(MY_WME))))
288
    exit(1);
unknown's avatar
unknown committed
289 290 291 292 293 294 295 296
  if (*argc < 2)
  {
    usage();
    return 1;
  }
  current_db= *((*argv)++);
  (*argc)--;
  if (tty_password)
297
    opt_password=get_tty_password(NullS);
unknown's avatar
unknown committed
298 299 300 301 302
  return(0);
}



303
static int write_to_table(char *filename, MYSQL *mysql)
unknown's avatar
unknown committed
304 305
{
  char tablename[FN_REFLEN], hard_path[FN_REFLEN],
306 307
       escaped_name[FN_REFLEN * 2 + 1],
       sql_statement[FN_REFLEN*16+256], *end, *pos;
unknown's avatar
unknown committed
308 309 310 311
  DBUG_ENTER("write_to_table");
  DBUG_PRINT("enter",("filename: %s",filename));

  fn_format(tablename, filename, "", "", 1 | 2); /* removes path & ext. */
312
  if (!opt_local_file)
unknown's avatar
unknown committed
313 314 315 316
    strmov(hard_path,filename);
  else
    my_load_path(hard_path, filename, NULL); /* filename includes the path */

unknown's avatar
unknown committed
317
  if (opt_delete)
unknown's avatar
unknown committed
318 319 320
  {
    if (verbose)
      fprintf(stdout, "Deleting the old data from table %s\n", tablename);
unknown's avatar
unknown committed
321
#ifdef HAVE_SNPRINTF
322
    snprintf(sql_statement, FN_REFLEN*16+256, "DELETE FROM %s", tablename);
unknown's avatar
unknown committed
323 324 325
#else
    sprintf(sql_statement, "DELETE FROM %s", tablename);
#endif
326
    if (mysql_query(mysql, sql_statement))
unknown's avatar
unknown committed
327
    {
328
      db_error_with_table(mysql, tablename);
unknown's avatar
unknown committed
329 330 331 332 333 334
      DBUG_RETURN(1);
    }
  }
  to_unix_path(hard_path);
  if (verbose)
  {
335
    if (opt_local_file)
unknown's avatar
unknown committed
336 337 338 339 340 341
      fprintf(stdout, "Loading data from LOCAL file: %s into %s\n",
	      hard_path, tablename);
    else
      fprintf(stdout, "Loading data from SERVER file: %s into %s\n",
	      hard_path, tablename);
  }
342 343
  mysql_real_escape_string(mysql, escaped_name, hard_path,
                           (unsigned long) strlen(hard_path));
unknown's avatar
unknown committed
344 345
  sprintf(sql_statement, "LOAD DATA %s %s INFILE '%s'",
	  opt_low_priority ? "LOW_PRIORITY" : "",
346
	  opt_local_file ? "LOCAL" : "", escaped_name);
unknown's avatar
unknown committed
347 348 349 350 351
  end= strend(sql_statement);
  if (replace)
    end= strmov(end, " REPLACE");
  if (ignore)
    end= strmov(end, " IGNORE");
352 353 354 355 356 357 358 359 360
  end= strmov(end, " INTO TABLE `");
  /* Turn any ` into `` in table name. */
  for (pos= tablename; *pos; pos++)
  {
    if (*pos == '`')
      *end++= '`';
    *end++= *pos;
  }
  end= strmov(end, "`");
unknown's avatar
unknown committed
361

unknown's avatar
unknown committed
362 363 364 365 366 367 368 369
  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");
370 371 372
  if (opt_ignore_lines >= 0)
    end= strmov(longlong10_to_str(opt_ignore_lines, 
				  strmov(end, " IGNORE "),10), " LINES");
unknown's avatar
unknown committed
373 374 375 376
  if (opt_columns)
    end= strmov(strmov(strmov(end, " ("), opt_columns), ")");
  *end= '\0';

377
  if (mysql_query(mysql, sql_statement))
unknown's avatar
unknown committed
378
  {
379
    db_error_with_table(mysql, tablename);
unknown's avatar
unknown committed
380 381 382 383
    DBUG_RETURN(1);
  }
  if (!silent)
  {
384
    if (mysql_info(mysql)) /* If NULL-pointer, print nothing */
unknown's avatar
unknown committed
385 386
    {
      fprintf(stdout, "%s.%s: %s\n", current_db, tablename,
387
	      mysql_info(mysql));
unknown's avatar
unknown committed
388 389 390 391 392 393 394
    }
  }
  DBUG_RETURN(0);
}



395
static void lock_table(MYSQL *mysql, int tablecount, char **raw_tablename)
unknown's avatar
unknown committed
396 397 398 399 400 401 402 403 404 405 406 407 408 409
{
  DYNAMIC_STRING query;
  int i;
  char tablename[FN_REFLEN];

  if (verbose)
    fprintf(stdout, "Locking tables for write\n");
  init_dynamic_string(&query, "LOCK TABLES ", 256, 1024);
  for (i=0 ; i < tablecount ; i++)
  {
    fn_format(tablename, raw_tablename[i], "", "", 1 | 2);
    dynstr_append(&query, tablename);
    dynstr_append(&query, " WRITE,");
  }
410 411
  if (mysql_real_query(mysql, query.str, query.length-1))
    db_error(mysql); /* We shall countinue here, if --force was given */
unknown's avatar
unknown committed
412 413 414 415 416
}




unknown's avatar
unknown committed
417
static MYSQL *db_connect(char *host, char *database,
418
                         char *user, char *passwd)
unknown's avatar
unknown committed
419
{
unknown's avatar
unknown committed
420
  MYSQL *mysql;
unknown's avatar
unknown committed
421 422
  if (verbose)
    fprintf(stdout, "Connecting to %s\n", host ? host : "localhost");
423 424
  if (!(mysql= mysql_init(NULL)))
    return 0;
unknown's avatar
unknown committed
425
  if (opt_compress)
426
    mysql_options(mysql,MYSQL_OPT_COMPRESS,NullS);
unknown's avatar
merge  
unknown committed
427
  if (opt_local_file)
428
    mysql_options(mysql,MYSQL_OPT_LOCAL_INFILE,
unknown's avatar
merge  
unknown committed
429
		  (char*) &opt_local_file);
unknown's avatar
unknown committed
430 431
#ifdef HAVE_OPENSSL
  if (opt_use_ssl)
432
    mysql_ssl_set(mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
433
		  opt_ssl_capath, opt_ssl_cipher);
434
  mysql_options(mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT,
435
                (char*)&opt_ssl_verify_server_cert);
436 437
#endif
  if (opt_protocol)
438
    mysql_options(mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol);
439 440
#ifdef HAVE_SMEM
  if (shared_memory_base_name)
441
    mysql_options(mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
unknown's avatar
unknown committed
442
#endif
443 444 445
  if (!(mysql_real_connect(mysql,host,user,passwd,
                           database,opt_mysql_port,opt_mysql_unix_port,
                           0)))
unknown's avatar
unknown committed
446 447
  {
    ignore_errors=0;	  /* NO RETURN FROM db_error */
448
    db_error(mysql);
unknown's avatar
unknown committed
449
  }
450
  mysql->reconnect= 0;
unknown's avatar
unknown committed
451 452
  if (verbose)
    fprintf(stdout, "Selecting database %s\n", database);
453
  if (mysql_select_db(mysql, database))
unknown's avatar
unknown committed
454 455
  {
    ignore_errors=0;
456
    db_error(mysql);
unknown's avatar
unknown committed
457
  }
458
  return mysql;
unknown's avatar
unknown committed
459 460 461 462
}



463
static void db_disconnect(char *host, MYSQL *mysql)
unknown's avatar
unknown committed
464 465 466
{
  if (verbose)
    fprintf(stdout, "Disconnecting from %s\n", host ? host : "localhost");
467
  mysql_close(mysql);
unknown's avatar
unknown committed
468 469 470 471
}



472
static void safe_exit(int error, MYSQL *mysql)
unknown's avatar
unknown committed
473 474 475
{
  if (ignore_errors)
    return;
476 477
  if (mysql)
    mysql_close(mysql);
unknown's avatar
unknown committed
478 479 480 481 482 483 484
  exit(error);
}



static void db_error_with_table(MYSQL *mysql, char *table)
{
485 486
  my_printf_error(0,"Error: %d, %s, when using table: %s",
		  MYF(0), mysql_errno(mysql), mysql_error(mysql), table);
unknown's avatar
unknown committed
487 488 489 490 491 492 493
  safe_exit(1, mysql);
}



static void db_error(MYSQL *mysql)
{
494
  my_printf_error(0,"Error: %d %s", MYF(0), mysql_errno(mysql), mysql_error(mysql));
unknown's avatar
unknown committed
495 496 497 498
  safe_exit(1, mysql);
}


499 500
static char *add_load_option(char *ptr, const char *object,
			     const char *statement)
unknown's avatar
unknown committed
501 502 503
{
  if (object)
  {
504 505 506 507 508 509 510 511 512 513
    /* 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
514 515 516 517 518 519 520 521 522 523
  }
  return ptr;
}

/*
** 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.
*/ 
unknown's avatar
unknown committed
524

unknown's avatar
unknown committed
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
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 dublicate of "'" for MySQL */
      end_backslashes=0;
    }
  }
  /* Add missing backslashes if user has specified odd number of backs.*/
  if (end_backslashes)
    *to++= '\\';          
  return to;
}
unknown's avatar
unknown committed
547

548
int exitcode= 0;
unknown's avatar
unknown committed
549

550
#ifdef HAVE_LIBPTHREAD
unknown's avatar
unknown committed
551
pthread_handler_t worker_thread(void *arg)
552
{
553
  int error;
unknown's avatar
unknown committed
554
  char *raw_table_name= (char *)arg;
555 556 557 558 559
  MYSQL *mysql= 0;

  if (mysql_thread_init())
    goto error;
  
560
  if (!(mysql= db_connect(current_host,current_db,current_user,opt_password)))
561 562 563 564
  {
    goto error;
  }

565
  if (mysql_query(mysql, "/*!40101 set @@character_set_database=binary */;"))
566
  {
567
    db_error(mysql); /* We shall countinue here, if --force was given */
568 569 570
    goto error;
  }

571 572 573
  /*
    We are not currently catching the error here.
  */
574 575 576
  if((error= write_to_table(raw_table_name, mysql)))
    if (exitcode == 0)
      exitcode= error;
577 578

error:
579 580
  if (mysql)
    db_disconnect(current_host, mysql);
581

582
  pthread_mutex_lock(&counter_mutex);
583
  counter--;
584
  pthread_cond_signal(&count_threshhold);
585
  pthread_mutex_unlock(&counter_mutex);
586 587
  my_thread_end();

unknown's avatar
unknown committed
588
  return 0;
589
}
590
#endif
591

unknown's avatar
unknown committed
592 593 594

int main(int argc, char **argv)
{
595
  int error=0;
unknown's avatar
unknown committed
596 597 598 599 600 601 602
  char **argv_to_free;
  MY_INIT(argv[0]);

  load_defaults("my",load_default_groups,&argc,&argv);
  /* argv is changed in the program */
  argv_to_free= argv;
  if (get_options(&argc, &argv))
603 604
  {
    free_defaults(argv_to_free);
unknown's avatar
unknown committed
605
    return(1);
606
  }
unknown's avatar
unknown committed
607

608
#ifdef HAVE_LIBPTHREAD
609
  if (opt_use_threads && !lock_tables)
unknown's avatar
unknown committed
610
  {
611 612
    pthread_t mainthread;            /* Thread descriptor */
    pthread_attr_t attr;          /* Thread attributes */
613 614 615 616
    pthread_attr_init(&attr);
    pthread_attr_setdetachstate(&attr,
                                PTHREAD_CREATE_DETACHED);

617
    VOID(pthread_mutex_init(&counter_mutex, NULL));
618
    VOID(pthread_cond_init(&count_threshhold, NULL));
619

620
    for (counter= 0; *argv != NULL; argv++) /* Loop through tables */
621
    {
622 623
      pthread_mutex_lock(&counter_mutex);
      while (counter == opt_use_threads)
624
      {
625 626 627 628
        struct timespec abstime;

        set_timespec(abstime, 3);
        pthread_cond_timedwait(&count_threshhold, &counter_mutex, &abstime);
629
      }
630
      /* Before exiting the lock we set ourselves up for the next thread */
631
      counter++;
632
      pthread_mutex_unlock(&counter_mutex);
633
      /* now create the thread */
unknown's avatar
unknown committed
634
      if (pthread_create(&mainthread, &attr, worker_thread, 
635 636
                         (void *)*argv) != 0)
      {
637
        pthread_mutex_lock(&counter_mutex);
638
        counter--;
639
        pthread_mutex_unlock(&counter_mutex);
640 641 642 643 644 645 646 647
        fprintf(stderr,"%s: Could not create thread\n",
                my_progname);
      }
    }

    /*
      We loop until we know that all children have cleaned up.
    */
648 649
    pthread_mutex_lock(&counter_mutex);
    while (counter)
650
    {
651 652 653 654
      struct timespec abstime;

      set_timespec(abstime, 3);
      pthread_cond_timedwait(&count_threshhold, &counter_mutex, &abstime);
655
    }
656
    pthread_mutex_unlock(&counter_mutex);
657
    VOID(pthread_mutex_destroy(&counter_mutex));
658 659
    VOID(pthread_cond_destroy(&count_threshhold));
    pthread_attr_destroy(&attr);
unknown's avatar
unknown committed
660
  }
661
  else
662
#endif
663
  {
unknown's avatar
unknown committed
664
    MYSQL *mysql= 0;
665
    if (!(mysql= db_connect(current_host,current_db,current_user,opt_password)))
666 667 668 669
    {
      free_defaults(argv_to_free);
      return(1); /* purecov: deadcode */
    }
unknown's avatar
unknown committed
670

671
    if (mysql_query(mysql, "/*!40101 set @@character_set_database=binary */;"))
672
    {
673
      db_error(mysql); /* We shall countinue here, if --force was given */
674 675 676 677
      return(1);
    }

    if (lock_tables)
678
      lock_table(mysql, argc, argv);
679
    for (; *argv != NULL; argv++)
680
      if ((error= write_to_table(*argv, mysql)))
681
        if (exitcode == 0)
682
          exitcode= error;
683
    db_disconnect(current_host, mysql);
684
  }
685
  my_free(opt_password,MYF(MY_ALLOW_ZERO_PTR));
686 687 688
#ifdef HAVE_SMEM
  my_free(shared_memory_base_name,MYF(MY_ALLOW_ZERO_PTR));
#endif
unknown's avatar
unknown committed
689
  free_defaults(argv_to_free);
690
  my_end(my_end_arg);
unknown's avatar
unknown committed
691 692
  return(exitcode);
}