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

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 21 22 23 24 25 26 27
   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 *
**			   *			   *
**			   *************************
*/
28
#define IMPORT_VERSION "3.5"
unknown's avatar
unknown committed
29

unknown's avatar
unknown committed
30
#include "client_priv.h"
unknown's avatar
unknown committed
31
#include "mysql_version.h"
32
#undef SAFE_MUTEX
33 34
#include <my_pthread.h>

35

36 37
/* Global Thread counter */
int counter= 0;
38
pthread_mutex_t counter_mutex;
unknown's avatar
unknown committed
39 40 41 42 43 44 45

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

63 64 65 66
#ifdef HAVE_SMEM
static char *shared_memory_base_name=0;
#endif

67
static struct my_option my_long_options[] =
unknown's avatar
unknown committed
68
{
unknown's avatar
unknown committed
69
#ifdef __NETWARE__
70
  {"autoclose", OPT_AUTO_CLOSE, "Auto close the screen on exit for Netware.",
unknown's avatar
unknown committed
71 72
   0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
#endif
73
  {"character-sets-dir", OPT_CHARSETS_DIR,
74
   "Directory where character sets are.", (gptr*) &charsets_dir,
75 76 77 78 79 80 81 82 83 84 85
   (gptr*) &charsets_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"default-character-set", OPT_DEFAULT_CHARSET,
   "Set the default character set.", (gptr*) &default_charset,
   (gptr*) &default_charset, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"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.",
   (gptr*) &opt_columns, (gptr*) &opt_columns, 0, GET_STR, REQUIRED_ARG, 0, 0, 0,
   0, 0, 0},
  {"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},
86 87
  {"debug",'#', "Output debug log. Often this is 'd:t:o,filename'.", 0, 0, 0,
   GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
  {"delete", 'd', "First delete all rows from table.", (gptr*) &opt_delete,
   (gptr*) &opt_delete, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"fields-terminated-by", OPT_FTB,
   "Fields in the textfile are terminated by ...", (gptr*) &fields_terminated,
   (gptr*) &fields_terminated, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"fields-enclosed-by", OPT_ENC,
   "Fields in the importfile are enclosed by ...", (gptr*) &enclosed,
   (gptr*) &enclosed, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"fields-optionally-enclosed-by", OPT_O_ENC,
   "Fields in the i.file are opt. enclosed by ...", (gptr*) &opt_enclosed,
   (gptr*) &opt_enclosed, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"fields-escaped-by", OPT_ESC, "Fields in the i.file are escaped by ...",
   (gptr*) &escaped, (gptr*) &escaped, 0, GET_STR, REQUIRED_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", '?', "Displays this help and exits.", 0, 0, 0, GET_NO_ARG, NO_ARG,
   0, 0, 0, 0, 0, 0},
  {"host", 'h', "Connect to host.", (gptr*) &current_host,
   (gptr*) &current_host, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
  {"ignore", 'i', "If duplicate unique key was found, keep old row.",
   (gptr*) &ignore, (gptr*) &ignore, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
111
  {"ignore-lines", OPT_IGN_LINES, "Ignore first n lines of data infile.",
112
   (gptr*) &opt_ignore_lines, (gptr*) &opt_ignore_lines, 0, GET_LL,
113
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
114 115 116
  {"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},
117
  {"local", 'L', "Read all files through the client.", (gptr*) &opt_local_file,
118
   (gptr*) &opt_local_file, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
119 120 121
  {"lock-tables", 'l', "Lock all tables for write (this disables threads).",
    (gptr*) &lock_tables, (gptr*) &lock_tables, 0, GET_BOOL, NO_ARG, 
    0, 0, 0, 0, 0, 0},
122
  {"low-priority", OPT_LOW_PRIORITY,
123
   "Use LOW_PRIORITY when updating the table.", (gptr*) &opt_low_priority,
124 125 126 127
   (gptr*) &opt_low_priority, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"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
128
#ifdef __WIN__
129 130
  {"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
131
#endif
132
  {"port", 'P', "Port number to use for connection.", (gptr*) &opt_mysql_port,
133
   (gptr*) &opt_mysql_port, 0, GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0,
134
   0},
135
  {"protocol", OPT_MYSQL_PROTOCOL, "The protocol of connection (tcp,socket,pipe,memory).",
136
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
137 138
  {"replace", 'r', "If duplicate unique key was found, replace old row.",
   (gptr*) &replace, (gptr*) &replace, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
139
#ifdef HAVE_SMEM
140
  {"shared-memory-base-name", OPT_SHARED_MEMORY_BASE_NAME,
141
   "Base name of shared memory.", (gptr*) &shared_memory_base_name, (gptr*) &shared_memory_base_name,
142 143
   0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#endif
144 145 146 147 148
  {"silent", 's', "Be more silent.", (gptr*) &silent, (gptr*) &silent, 0,
   GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
  {"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},
149
#include <sslopt-longopts.h>
150 151 152 153 154
  {"use-threads", OPT_USE_THREADS,
    "Parrelize the loading of files. Requires an arguement for the number \
      threads to use for loading of data.",
      (gptr*) &opt_use_threads, (gptr*) &opt_use_threads, 0, 
      GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
unknown's avatar
unknown committed
155
#ifndef DONT_ALLOW_USER_CHANGE
156 157
  {"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
158
#endif
159 160 161 162 163
  {"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},
  { 0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
unknown's avatar
unknown committed
164 165 166 167 168
};


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

unknown's avatar
unknown committed
169 170
#include <help_start.h>

unknown's avatar
unknown committed
171 172 173 174
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
175
  NETWARE_SET_SCREEN_MODE(1);
unknown's avatar
unknown committed
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
}


static void usage(void)
{
  print_version();
  puts("Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB");
  puts("This software comes with ABSOLUTELY NO WARRANTY. This is free software,\nand you are welcome to modify and redistribute it under the GPL license\n");
  printf("\
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);
193 194
  my_print_help(my_long_options);
  my_print_variables(my_long_options);
unknown's avatar
unknown committed
195 196
}

unknown's avatar
unknown committed
197
#include <help_end.h>
unknown's avatar
unknown committed
198

199 200 201 202 203
static my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
	       char *argument)
{
  switch(optid) {
unknown's avatar
unknown committed
204 205 206 207 208
#ifdef __NETWARE__
  case OPT_AUTO_CLOSE:
    setscreenmode(SCR_AUTOCLOSE_ON_EXIT);
    break;
#endif
209 210 211 212 213 214 215 216 217
  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 */
218
      tty_password= 0;
219 220 221 222
    }
    else
      tty_password= 1;
    break;
unknown's avatar
unknown committed
223
#ifdef __WIN__
224
  case 'W':
225
    opt_protocol = MYSQL_PROTOCOL_PIPE;
226 227
    opt_local_file=1;
    break;
unknown's avatar
unknown committed
228
#endif
229 230
  case OPT_MYSQL_PROTOCOL:
  {
231
    if ((opt_protocol= find_type(argument, &sql_protocol_typelib,0)) <= 0)
232 233 234 235 236 237
    {
      fprintf(stderr, "Unknown option to protocol: %s\n", argument);
      exit(1);
    }
    break;
  }
238 239 240
  case '#':
    DBUG_PUSH(argument ? argument : "d:t:o");
    break;
241
#include <sslopt-case.h>
242 243 244 245 246 247 248 249 250 251 252 253 254 255
  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;

256
  if ((ho_error=handle_options(argc, argv, my_long_options, get_one_option)))
257 258
    exit(ho_error);

unknown's avatar
unknown committed
259 260 261 262 263 264 265 266 267 268
  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);
  }
269 270
  if (strcmp(default_charset, charset_info->csname) &&
      !(charset_info= get_charset_by_csname(default_charset,
271
  					    MY_CS_PRIMARY, MYF(MY_WME))))
272
    exit(1);
unknown's avatar
unknown committed
273 274 275 276 277 278 279 280
  if (*argc < 2)
  {
    usage();
    return 1;
  }
  current_db= *((*argv)++);
  (*argc)--;
  if (tty_password)
281
    opt_password=get_tty_password(NullS);
unknown's avatar
unknown committed
282 283 284 285 286 287 288 289
  return(0);
}



static int write_to_table(char *filename, MYSQL *sock)
{
  char tablename[FN_REFLEN], hard_path[FN_REFLEN],
290
       sql_statement[FN_REFLEN*16+256], *end;
unknown's avatar
unknown committed
291 292 293 294
  DBUG_ENTER("write_to_table");
  DBUG_PRINT("enter",("filename: %s",filename));

  fn_format(tablename, filename, "", "", 1 | 2); /* removes path & ext. */
295
  if (! opt_local_file)
unknown's avatar
unknown committed
296 297 298 299
    strmov(hard_path,filename);
  else
    my_load_path(hard_path, filename, NULL); /* filename includes the path */

unknown's avatar
unknown committed
300
  if (opt_delete)
unknown's avatar
unknown committed
301 302 303
  {
    if (verbose)
      fprintf(stdout, "Deleting the old data from table %s\n", tablename);
304
    snprintf(sql_statement, FN_REFLEN*16+256, "DELETE FROM %s", tablename);
unknown's avatar
unknown committed
305 306 307 308 309 310 311 312 313
    if (mysql_query(sock, sql_statement))
    {
      db_error_with_table(sock, tablename);
      DBUG_RETURN(1);
    }
  }
  to_unix_path(hard_path);
  if (verbose)
  {
314
    if (opt_local_file)
unknown's avatar
unknown committed
315 316 317 318 319 320 321 322
      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);
  }
  sprintf(sql_statement, "LOAD DATA %s %s INFILE '%s'",
	  opt_low_priority ? "LOW_PRIORITY" : "",
323
	  opt_local_file ? "LOCAL" : "", hard_path);
unknown's avatar
unknown committed
324 325 326 327 328 329
  end= strend(sql_statement);
  if (replace)
    end= strmov(end, " REPLACE");
  if (ignore)
    end= strmov(end, " IGNORE");
  end= strmov(strmov(end, " INTO TABLE "), tablename);
unknown's avatar
unknown committed
330

unknown's avatar
unknown committed
331 332 333 334 335 336 337 338
  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");
339 340 341
  if (opt_ignore_lines >= 0)
    end= strmov(longlong10_to_str(opt_ignore_lines, 
				  strmov(end, " IGNORE "),10), " LINES");
unknown's avatar
unknown committed
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
  if (opt_columns)
    end= strmov(strmov(strmov(end, " ("), opt_columns), ")");
  *end= '\0';

  if (mysql_query(sock, sql_statement))
  {
    db_error_with_table(sock, tablename);
    DBUG_RETURN(1);
  }
  if (!silent)
  {
    if (mysql_info(sock)) /* If NULL-pointer, print nothing */
    {
      fprintf(stdout, "%s.%s: %s\n", current_db, tablename,
	      mysql_info(sock));
    }
  }
  DBUG_RETURN(0);
}



static void lock_table(MYSQL *sock, int tablecount, char **raw_tablename)
{
  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,");
  }
  if (mysql_real_query(sock, query.str, query.length-1))
    db_error(sock); /* We shall countinue here, if --force was given */
}




static MYSQL *db_connect(char *host, char *database, char *user, char *passwd)
{
  MYSQL *sock;
  if (verbose)
    fprintf(stdout, "Connecting to %s\n", host ? host : "localhost");
  mysql_init(&mysql_connection);
  if (opt_compress)
    mysql_options(&mysql_connection,MYSQL_OPT_COMPRESS,NullS);
unknown's avatar
merge  
unknown committed
394 395 396
  if (opt_local_file)
    mysql_options(&mysql_connection,MYSQL_OPT_LOCAL_INFILE,
		  (char*) &opt_local_file);
unknown's avatar
unknown committed
397 398 399
#ifdef HAVE_OPENSSL
  if (opt_use_ssl)
    mysql_ssl_set(&mysql_connection, opt_ssl_key, opt_ssl_cert, opt_ssl_ca,
400
		  opt_ssl_capath, opt_ssl_cipher);
401 402 403 404 405 406
#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
407 408 409 410 411 412 413 414
#endif
  if (!(sock= mysql_real_connect(&mysql_connection,host,user,passwd,
				 database,opt_mysql_port,opt_mysql_unix_port,
				 0)))
  {
    ignore_errors=0;	  /* NO RETURN FROM db_error */
    db_error(&mysql_connection);
  }
415
  mysql_connection.reconnect= 0;
unknown's avatar
unknown committed
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
  if (verbose)
    fprintf(stdout, "Selecting database %s\n", database);
  if (mysql_select_db(sock, database))
  {
    ignore_errors=0;
    db_error(&mysql_connection);
  }
  return sock;
}



static void db_disconnect(char *host, MYSQL *sock)
{
  if (verbose)
    fprintf(stdout, "Disconnecting from %s\n", host ? host : "localhost");
  mysql_close(sock);
}



static void safe_exit(int error, MYSQL *sock)
{
  if (ignore_errors)
    return;
  if (sock)
    mysql_close(sock);
  exit(error);
}



static void db_error_with_table(MYSQL *mysql, char *table)
{
  my_printf_error(0,"Error: %s, when using table: %s",
		  MYF(0), mysql_error(mysql), table);
  safe_exit(1, mysql);
}



static void db_error(MYSQL *mysql)
{
  my_printf_error(0,"Error: %s", MYF(0), mysql_error(mysql));
  safe_exit(1, mysql);
}


464 465
static char *add_load_option(char *ptr, const char *object,
			     const char *statement)
unknown's avatar
unknown committed
466 467 468
{
  if (object)
  {
469 470 471 472 473 474 475 476 477 478
    /* 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
479 480 481 482 483 484 485 486 487 488
  }
  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
489

unknown's avatar
unknown committed
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511
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
512

unknown's avatar
unknown committed
513

514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
int
worker_thread(char *raw_table_name)
{
  MYSQL *sock= 0;
  if (!(sock= db_connect(current_host,current_db,current_user,opt_password)))
  {
    goto error;
  }

  if (mysql_query(sock, "set @@character_set_database=binary;"))
  {
    db_error(sock); /* We shall countinue here, if --force was given */
    goto error;
  }

  /*
    We should do something about the error
  */
  write_to_table(raw_table_name, sock);

error:
  if (sock)
    db_disconnect(current_host, sock);

538
  pthread_mutex_lock(&counter_mutex);
539
  counter--;
540
  pthread_mutex_unlock(&counter_mutex);
541 542 543
  return 0;
}

unknown's avatar
unknown committed
544 545 546 547 548 549 550 551 552 553 554

int main(int argc, char **argv)
{
  int exitcode=0, error=0;
  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))
555 556
  {
    free_defaults(argv_to_free);
unknown's avatar
unknown committed
557
    return(1);
558
  }
unknown's avatar
unknown committed
559

560
  if (opt_use_threads && !lock_tables)
unknown's avatar
unknown committed
561
  {
562 563
    pthread_t mainthread;            /* Thread descriptor */
    pthread_attr_t attr;          /* Thread attributes */
564
    VOID(pthread_mutex_init(&counter_mutex, NULL));
565 566 567 568 569 570 571 572 573 574 575 576 577 578

    for (; *argv != NULL; argv++) // Loop through tables
    {
      /*
        If we hit thread count limit we loop until some threads exit.
        We sleep for a second, so that we don't chew up a lot of 
        CPU in the loop.
      */
sanity_label:
      if (counter == opt_use_threads)
      {
        sleep(1);
        goto sanity_label;
      }
579
      pthread_mutex_lock(&counter_mutex);
580
      counter++;
581
      pthread_mutex_unlock(&counter_mutex);
582 583 584 585 586 587 588 589
      pthread_attr_init(&attr);
      pthread_attr_setdetachstate(&attr,
                                   PTHREAD_CREATE_DETACHED);

      /* now create the thread */
      if (pthread_create(&mainthread, &attr, (void *)worker_thread, 
                         (void *)*argv) != 0)
      {
590
        pthread_mutex_lock(&counter_mutex);
591
        counter--;
592
        pthread_mutex_unlock(&counter_mutex);
593 594 595 596 597 598 599 600 601 602 603 604 605 606
        fprintf(stderr,"%s: Could not create thread\n",
                my_progname);
      }
    }

    /*
      We loop until we know that all children have cleaned up.
    */
loop_label:
    if (counter)
    {
      sleep(1);
      goto loop_label;
    }
607
    VOID(pthread_mutex_destroy(&counter_mutex));
unknown's avatar
unknown committed
608
  }
609 610 611 612 613 614 615 616
  else
  {
    MYSQL *sock= 0;
    if (!(sock= db_connect(current_host,current_db,current_user,opt_password)))
    {
      free_defaults(argv_to_free);
      return(1); /* purecov: deadcode */
    }
unknown's avatar
unknown committed
617

618 619 620 621 622 623 624 625 626 627 628 629 630 631
    if (mysql_query(sock, "set @@character_set_database=binary;"))
    {
      db_error(sock); /* We shall countinue here, if --force was given */
      return(1);
    }

    if (lock_tables)
      lock_table(sock, argc, argv);
    for (; *argv != NULL; argv++)
      if ((error=write_to_table(*argv, sock)))
        if (exitcode == 0)
          exitcode = error;
    db_disconnect(current_host, sock);
  }
632
  my_free(opt_password,MYF(MY_ALLOW_ZERO_PTR));
633 634 635
#ifdef HAVE_SMEM
  my_free(shared_memory_base_name,MYF(MY_ALLOW_ZERO_PTR));
#endif
unknown's avatar
unknown committed
636 637 638 639
  free_defaults(argv_to_free);
  my_end(0);
  return(exitcode);
}