~drizzle-trunk/drizzle/development

« back to all changes in this revision

Viewing changes to client/drizzleimport.cc

  • Committer: Padraig O'Sullivan
  • Date: 2009-12-17 04:48:59 UTC
  • mto: This revision was merged to the branch mainline in revision 1246.
  • Revision ID: osullivan.padraig@gmail.com-20091217044859-qorpkp4911zypfv3
Added some dtrace probes for tracing the optimizer.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* 
2
 
  Copyright (C) 2010 Vijay Samuel
3
 
  Copyright (C) 2010 Brian Aker
4
 
  Copyright (C) 2000-2006 MySQL AB
5
 
  Copyright (C) 2008-2009 Sun Microsystems, Inc.
6
 
 
7
 
  This program is free software; you can redistribute it and/or modify
8
 
  it under the terms of the GNU General Public License as published by
9
 
  the Free Software Foundation; version 2 of the License.
10
 
 
11
 
  This program is distributed in the hope that it will be useful,
12
 
  but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 
  GNU General Public License for more details.
15
 
 
16
 
  You should have received a copy of the GNU General Public License
17
 
  along with this program; if not, write to the Free Software
18
 
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA */
19
 
 
20
 
#define IMPORT_VERSION "4.0"
 
1
/* Copyright (C) 2000-2006 MySQL AB
 
2
   Copyright (C) 2008-2009 Sun Microsystems, Inc
 
3
 
 
4
   This program is free software; you can redistribute it and/or modify
 
5
   it under the terms of the GNU General Public License as published by
 
6
   the Free Software Foundation; version 2 of the License.
 
7
 
 
8
   This program is distributed in the hope that it will be useful,
 
9
   but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
   GNU General Public License for more details.
 
12
 
 
13
   You should have received a copy of the GNU General Public License
 
14
   along with this program; if not, write to the Free Software
 
15
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
 
16
 
 
17
/*
 
18
**     drizzleimport.c  - Imports all given files
 
19
**          into a table(s).
 
20
**
 
21
**         *************************
 
22
**         *         *
 
23
**         * AUTHOR: Monty & Jani  *
 
24
**         * DATE:   June 24, 1997 *
 
25
**         *         *
 
26
**         *************************
 
27
*/
 
28
#define IMPORT_VERSION "3.7"
21
29
 
22
30
#include "client_priv.h"
23
31
#include <string>
24
 
#include <sstream>
25
 
#include <iostream>
26
 
#include <fstream>
27
 
#include <boost/program_options.hpp>
 
32
 
28
33
#include <pthread.h>
29
34
 
30
35
/* Added this for string translation. */
31
36
#include <drizzled/gettext.h>
32
 
#include <drizzled/configmake.h>
33
37
 
34
 
namespace po= boost::program_options;
35
38
using namespace std;
36
 
using namespace drizzled;
37
39
 
38
 
extern "C" void * worker_thread(void *arg);
 
40
extern "C"
 
41
{
 
42
  bool get_one_option(int optid, const struct my_option *, char *argument);
 
43
  void * worker_thread(void *arg);
 
44
}
39
45
 
40
46
int exitcode= 0;
41
47
 
42
 
const char *program_name= "drizzleimport";
43
 
 
44
48
/* Global Thread counter */
45
49
uint32_t counter;
46
50
pthread_mutex_t counter_mutex;
52
56
static char *add_load_option(char *ptr,const char *object,
53
57
           const char *statement);
54
58
 
55
 
static bool verbose= false, ignore_errors= false,
 
59
static bool verbose= false, lock_tables= false, ignore_errors= false,
56
60
            opt_delete= false, opt_replace= false, silent= false,
57
61
            ignore_unique= false, opt_low_priority= false,
58
 
            use_drizzle_protocol= false, opt_local_file;
 
62
            tty_password= false;
59
63
 
60
 
static uint32_t opt_use_threads;
 
64
static uint32_t opt_use_threads= 0, opt_local_file= 0;
 
65
static char  *opt_password= NULL, *current_user= NULL,
 
66
    *current_host= NULL, *current_db= NULL, *fields_terminated= NULL,
 
67
    *lines_terminated= NULL, *enclosed= NULL, *opt_enclosed= NULL,
 
68
    *escaped= NULL, *opt_columns= NULL;
61
69
static uint32_t opt_drizzle_port= 0;
 
70
static char * opt_drizzle_unix_port= 0;
62
71
static int64_t opt_ignore_lines= -1;
63
72
 
64
 
std::string opt_columns,
65
 
  opt_enclosed,
66
 
  escaped,
67
 
  password,
68
 
  current_db,
69
 
  lines_terminated,
70
 
  current_user,
71
 
  opt_password,
72
 
  enclosed,  
73
 
  current_host,
74
 
  fields_terminated,
75
 
  opt_protocol;
76
 
 
77
 
 
78
 
static int get_options(void)
79
 
{
80
 
 
81
 
  if (! enclosed.empty() && ! opt_enclosed.empty())
 
73
static struct my_option my_long_options[] =
 
74
{
 
75
  {"columns", 'c',
 
76
   "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.",
 
77
   (char**) &opt_columns, (char**) &opt_columns, 0, GET_STR, REQUIRED_ARG, 0, 0, 0,
 
78
   0, 0, 0},
 
79
  {"debug",'#', "Output debug log. Often this is 'd:t:o,filename'.", 0, 0, 0,
 
80
   GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
 
81
  {"delete", 'd', "First delete all rows from table.", (char**) &opt_delete,
 
82
   (char**) &opt_delete, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
 
83
  {"fields-terminated-by", OPT_FTB,
 
84
   "Fields in the textfile are terminated by ...", (char**) &fields_terminated,
 
85
   (char**) &fields_terminated, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
 
86
  {"fields-enclosed-by", OPT_ENC,
 
87
   "Fields in the importfile are enclosed by ...", (char**) &enclosed,
 
88
   (char**) &enclosed, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
 
89
  {"fields-optionally-enclosed-by", OPT_O_ENC,
 
90
   "Fields in the i.file are opt. enclosed by ...", (char**) &opt_enclosed,
 
91
   (char**) &opt_enclosed, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
 
92
  {"fields-escaped-by", OPT_ESC, "Fields in the i.file are escaped by ...",
 
93
   (char**) &escaped, (char**) &escaped, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0,
 
94
   0, 0},
 
95
  {"force", 'f', "Continue even if we get an sql-error.",
 
96
   (char**) &ignore_errors, (char**) &ignore_errors, 0, GET_BOOL, NO_ARG, 0, 0,
 
97
   0, 0, 0, 0},
 
98
  {"help", '?', "Displays this help and exits.", 0, 0, 0, GET_NO_ARG, NO_ARG,
 
99
   0, 0, 0, 0, 0, 0},
 
100
  {"host", 'h', "Connect to host.", (char**) &current_host,
 
101
   (char**) &current_host, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
 
102
  {"ignore", 'i', "If duplicate unique key was found, keep old row.",
 
103
   (char**) &ignore_unique, (char**) &ignore_unique, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
 
104
  {"ignore-lines", OPT_IGN_LINES, "Ignore first n lines of data infile.",
 
105
   (char**) &opt_ignore_lines, (char**) &opt_ignore_lines, 0, GET_LL,
 
106
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
 
107
  {"lines-terminated-by", OPT_LTB, "Lines in the i.file are terminated by ...",
 
108
   (char**) &lines_terminated, (char**) &lines_terminated, 0, GET_STR,
 
109
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
 
110
  {"local", 'L', "Read all files through the client.", (char**) &opt_local_file,
 
111
   (char**) &opt_local_file, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
 
112
  {"lock-tables", 'l', "Lock all tables for write (this disables threads).",
 
113
    (char**) &lock_tables, (char**) &lock_tables, 0, GET_BOOL, NO_ARG,
 
114
    0, 0, 0, 0, 0, 0},
 
115
  {"low-priority", OPT_LOW_PRIORITY,
 
116
   "Use LOW_PRIORITY when updating the table.", (char**) &opt_low_priority,
 
117
   (char**) &opt_low_priority, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
 
118
  {"password", 'P',
 
119
   "Password to use when connecting to server. If password is not given it's asked from the tty.",
 
120
   0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
 
121
  {"port", 'p', "Port number to use for connection or 0 for default to, in "
 
122
   "order of preference, drizzle.cnf, $DRIZZLE_TCP_PORT, "
 
123
   "built-in default (" STRINGIFY_ARG(DRIZZLE_PORT) ").",
 
124
   0, 0, 0, GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
 
125
  {"protocol", OPT_DRIZZLE_PROTOCOL, "The protocol of connection (tcp,socket,pipe,memory).",
 
126
   0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
 
127
  {"replace", 'r', "If duplicate unique key was found, replace old row.",
 
128
   (char**) &opt_replace, (char**) &opt_replace, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
 
129
  {"silent", 's', "Be more silent.", (char**) &silent, (char**) &silent, 0,
 
130
   GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
 
131
  {"socket", 'S', "Socket file to use for connection.",
 
132
   (char**) &opt_drizzle_unix_port, (char**) &opt_drizzle_unix_port, 0, GET_STR,
 
133
   REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
 
134
  {"use-threads", OPT_USE_THREADS,
 
135
   "Load files in parallel. The argument is the number "
 
136
   "of threads to use for loading data.",
 
137
   (char**) &opt_use_threads, (char**) &opt_use_threads, 0,
 
138
   GET_UINT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
 
139
  {"user", 'u', "User for login if not current user.", (char**) &current_user,
 
140
   (char**) &current_user, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
 
141
  {"verbose", 'v', "Print info about the various stages.", (char**) &verbose,
 
142
   (char**) &verbose, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
 
143
  {"version", 'V', "Output version information and exit.", 0, 0, 0, GET_NO_ARG,
 
144
   NO_ARG, 0, 0, 0, 0, 0, 0},
 
145
  { 0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
 
146
};
 
147
 
 
148
 
 
149
static const char *load_default_groups[]= { "drizzleimport","client",0 };
 
150
 
 
151
static void print_version(void)
 
152
{
 
153
  printf("%s  Ver %s Distrib %s, for %s-%s (%s)\n" ,my_progname,
 
154
    IMPORT_VERSION, drizzle_version(),HOST_VENDOR,HOST_OS,HOST_CPU);
 
155
}
 
156
 
 
157
 
 
158
static void usage(void)
 
159
{
 
160
  print_version();
 
161
  puts("Copyright (C) 2008 Drizzle Open Source Development Team");
 
162
  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");
 
163
  printf("\
 
164
Loads tables from text files in various formats.  The base name of the\n\
 
165
text file must be the name of the table that should be used.\n\
 
166
If one uses sockets to connect to the Drizzle server, the server will open and\n\
 
167
read the text file directly. In other cases the client will open the text\n\
 
168
file. The SQL command 'LOAD DATA INFILE' is used to import the rows.\n");
 
169
 
 
170
  printf("\nUsage: %s [OPTIONS] database textfile...",my_progname);
 
171
  print_defaults("drizzle",load_default_groups);
 
172
  my_print_help(my_long_options);
 
173
  my_print_variables(my_long_options);
 
174
}
 
175
 
 
176
bool get_one_option(int optid, const struct my_option *, char *argument)
 
177
{
 
178
  char *endchar= NULL;
 
179
  uint64_t temp_drizzle_port= 0;
 
180
 
 
181
  switch(optid) {
 
182
  case 'p':
 
183
    temp_drizzle_port= (uint64_t) strtoul(argument, &endchar, 10);
 
184
    /* if there is an alpha character this is not a valid port */
 
185
    if (strlen(endchar) != 0)
 
186
    {
 
187
      fprintf(stderr, _("Non-integer value supplied for port.  If you are trying to enter a password please use --password instead.\n"));
 
188
      exit(1);
 
189
    }
 
190
    /* If the port number is > 65535 it is not a valid port
 
191
       This also helps with potential data loss casting unsigned long to a
 
192
       uint32_t. */
 
193
    if ((temp_drizzle_port == 0) || (temp_drizzle_port > 65535))
 
194
    {
 
195
      fprintf(stderr, _("Value supplied for port is not valid.\n"));
 
196
      exit(1);
 
197
    }
 
198
    else
 
199
    {
 
200
      opt_drizzle_port= (uint32_t) temp_drizzle_port;
 
201
    }
 
202
    break;
 
203
  case 'P':
 
204
    if (argument)
 
205
    {
 
206
      char *start=argument;
 
207
      if (opt_password)
 
208
        free(opt_password);
 
209
      opt_password = strdup(argument);
 
210
      if (opt_password == NULL)
 
211
      {
 
212
        fprintf(stderr, "Memory allocation error while copying password. "
 
213
                        "Aborting.\n");
 
214
        exit(ENOMEM);
 
215
      }
 
216
      while (*argument)
 
217
      {
 
218
        /* Overwriting password with 'x' */
 
219
        *argument++= 'x';
 
220
      }
 
221
      if (*start)
 
222
      {
 
223
        /* Cut length of argument */
 
224
        start[1]= 0;
 
225
      }
 
226
      tty_password= 0;
 
227
    }
 
228
    else
 
229
      tty_password= 1;
 
230
    break;
 
231
  case OPT_DRIZZLE_PROTOCOL:
 
232
    break;
 
233
  case 'V': print_version(); exit(0);
 
234
  case 'I':
 
235
  case '?':
 
236
    usage();
 
237
    exit(0);
 
238
  }
 
239
  return 0;
 
240
}
 
241
 
 
242
 
 
243
static int get_options(int *argc, char ***argv)
 
244
{
 
245
  int ho_error;
 
246
 
 
247
  if ((ho_error=handle_options(argc, argv, my_long_options, get_one_option)))
 
248
    exit(ho_error);
 
249
 
 
250
  if (enclosed && opt_enclosed)
82
251
  {
83
252
    fprintf(stderr, "You can't use ..enclosed.. and ..optionally-enclosed.. at the same time.\n");
84
253
    return(1);
88
257
    fprintf(stderr, "You can't use --ignore_unique (-i) and --replace (-r) at the same time.\n");
89
258
    return(1);
90
259
  }
91
 
 
 
260
  if (*argc < 2)
 
261
  {
 
262
    usage();
 
263
    return 1;
 
264
  }
 
265
  current_db= *((*argv)++);
 
266
  (*argc)--;
92
267
  if (tty_password)
93
268
    opt_password=client_get_tty_password(NULL);
94
269
  return(0);
103
278
  drizzle_result_st result;
104
279
  drizzle_return_t ret;
105
280
 
106
 
  internal::fn_format(tablename, filename, "", "", 1 | 2); /* removes path & ext. */
107
 
  if (not opt_local_file)
 
281
  fn_format(tablename, filename, "", "", 1 | 2); /* removes path & ext. */
 
282
  if (!opt_local_file)
108
283
    strcpy(hard_path,filename);
109
284
  else
110
 
    internal::my_load_path(hard_path, filename, NULL); /* filename includes the path */
 
285
    my_load_path(hard_path, filename, NULL); /* filename includes the path */
111
286
 
112
287
  if (opt_delete)
113
288
  {
114
289
    if (verbose)
115
290
      fprintf(stdout, "Deleting the old data from table %s\n", tablename);
116
291
#ifdef HAVE_SNPRINTF
117
 
    snprintf(sql_statement, sizeof(sql_statement), "DELETE FROM %s", tablename);
 
292
    snprintf(sql_statement, FN_REFLEN*16+256, "DELETE FROM %s", tablename);
118
293
#else
119
 
    snprintf(sql_statement, sizeof(sql_statement), "DELETE FROM %s", tablename);
 
294
    sprintf(sql_statement, "DELETE FROM %s", tablename);
120
295
#endif
121
296
    if (drizzle_query_str(con, &result, sql_statement, &ret) == NULL ||
122
297
        ret != DRIZZLE_RETURN_OK)
135
310
      fprintf(stdout, "Loading data from SERVER file: %s into %s\n",
136
311
        hard_path, tablename);
137
312
  }
138
 
  snprintf(sql_statement, sizeof(sql_statement), "LOAD DATA %s %s INFILE '%s'",
 
313
  sprintf(sql_statement, "LOAD DATA %s %s INFILE '%s'",
139
314
    opt_low_priority ? "LOW_PRIORITY" : "",
140
315
    opt_local_file ? "LOCAL" : "", hard_path);
141
316
  end= strchr(sql_statement, '\0');
146
321
 
147
322
  end+= sprintf(end, " INTO TABLE %s", tablename);
148
323
 
149
 
  if (! fields_terminated.empty() || ! enclosed.empty() || ! opt_enclosed.empty() || ! escaped.empty())
 
324
  if (fields_terminated || enclosed || opt_enclosed || escaped)
150
325
      end= strcpy(end, " FIELDS")+7;
151
 
  end= add_load_option(end, (char *)fields_terminated.c_str(), " TERMINATED BY");
152
 
  end= add_load_option(end, (char *)enclosed.c_str(), " ENCLOSED BY");
153
 
  end= add_load_option(end, (char *)opt_enclosed.c_str(),
 
326
  end= add_load_option(end, fields_terminated, " TERMINATED BY");
 
327
  end= add_load_option(end, enclosed, " ENCLOSED BY");
 
328
  end= add_load_option(end, opt_enclosed,
154
329
           " OPTIONALLY ENCLOSED BY");
155
 
  end= add_load_option(end, (char *)escaped.c_str(), " ESCAPED BY");
156
 
  end= add_load_option(end, (char *)lines_terminated.c_str(), " LINES TERMINATED BY");
 
330
  end= add_load_option(end, escaped, " ESCAPED BY");
 
331
  end= add_load_option(end, lines_terminated, " LINES TERMINATED BY");
157
332
  if (opt_ignore_lines >= 0)
158
333
  {
159
334
    end= strcpy(end, " IGNORE ")+8;
162
337
    end= strcpy(end, buffer.str().c_str())+ buffer.str().size();
163
338
    end= strcpy(end, " LINES")+6;
164
339
  }
165
 
  if (! opt_columns.empty())
 
340
  if (opt_columns)
166
341
  {
167
342
    end= strcpy(end, " (")+2;
168
 
    end= strcpy(end, (char *)opt_columns.c_str()+opt_columns.length());
 
343
    end= strcpy(end, opt_columns)+strlen(opt_columns);
169
344
    end= strcpy(end, ")")+1;
170
345
  }
171
346
  *end= '\0';
180
355
  {
181
356
    if (strcmp(drizzle_result_info(&result), ""))
182
357
    {
183
 
      fprintf(stdout, "%s.%s: %s\n", current_db.c_str(), tablename,
 
358
      fprintf(stdout, "%s.%s: %s\n", current_db, tablename,
184
359
        drizzle_result_info(&result));
185
360
    }
186
361
  }
189
364
}
190
365
 
191
366
 
192
 
static drizzle_con_st *db_connect(const string host, const string database,
193
 
                                  const string user, const string passwd)
 
367
static void lock_table(drizzle_con_st *con, int tablecount, char **raw_tablename)
 
368
{
 
369
  string query;
 
370
  int i;
 
371
  char tablename[FN_REFLEN];
 
372
  drizzle_result_st result;
 
373
  drizzle_return_t ret;
 
374
 
 
375
  if (verbose)
 
376
    fprintf(stdout, "Locking tables for write\n");
 
377
  query.append("LOCK TABLES ");
 
378
  for (i=0 ; i < tablecount ; i++)
 
379
  {
 
380
    fn_format(tablename, raw_tablename[i], "", "", 1 | 2);
 
381
    query.append(tablename);
 
382
    query.append(" WRITE,");
 
383
  }
 
384
  if (drizzle_query(con, &result, query.c_str(), query.length()-1,
 
385
                    &ret) == NULL ||
 
386
      ret != DRIZZLE_RETURN_OK)
 
387
  {
 
388
    db_error(con, &result, ret, NULL);
 
389
    /* We shall countinue here, if --force was given */
 
390
    return;
 
391
  }
 
392
  drizzle_result_free(&result);
 
393
}
 
394
 
 
395
 
 
396
static drizzle_con_st *db_connect(char *host, char *database,
 
397
                                  char *user, char *passwd)
194
398
{
195
399
  drizzle_st *drizzle;
196
400
  drizzle_con_st *con;
197
401
  drizzle_return_t ret;
198
402
 
199
403
  if (verbose)
200
 
    fprintf(stdout, "Connecting to %s, using protocol %s...\n", ! host.empty() ? host.c_str() : "localhost", opt_protocol.c_str());
 
404
    fprintf(stdout, "Connecting to %s\n", host ? host : "localhost");
201
405
  if (!(drizzle= drizzle_create(NULL)))
202
406
    return 0;
203
 
  if (!(con= drizzle_con_add_tcp(drizzle,NULL,(char *)host.c_str(),opt_drizzle_port,(char *)user.c_str(),(char *)passwd.c_str(),
204
 
                                 (char *)database.c_str(), use_drizzle_protocol ? DRIZZLE_CON_EXPERIMENTAL : DRIZZLE_CON_MYSQL)))
 
407
  if (!(con= drizzle_con_add_tcp(drizzle,NULL,host,opt_drizzle_port,user,passwd,
 
408
                                 database, DRIZZLE_CON_NONE)))
205
409
  {
206
410
    return 0;
207
411
  }
213
417
  }
214
418
 
215
419
  if (verbose)
216
 
    fprintf(stdout, "Selecting database %s\n", database.c_str());
 
420
    fprintf(stdout, "Selecting database %s\n", database);
217
421
 
218
422
  return con;
219
423
}
220
424
 
221
425
 
222
426
 
223
 
static void db_disconnect(const string host, drizzle_con_st *con)
 
427
static void db_disconnect(char *host, drizzle_con_st *con)
224
428
{
225
429
  if (verbose)
226
 
    fprintf(stdout, "Disconnecting from %s\n", ! host.empty() ? host.c_str() : "localhost");
 
430
    fprintf(stdout, "Disconnecting from %s\n", host ? host : "localhost");
227
431
  drizzle_free(drizzle_con_drizzle(con));
228
432
}
229
433
 
245
449
{
246
450
  if (ret == DRIZZLE_RETURN_ERROR_CODE)
247
451
  {
248
 
    fprintf(stdout, "Error: %d, %s%s%s",
249
 
            drizzle_result_error_code(result),
250
 
            drizzle_result_error(result),
251
 
            table ? ", when using table: " : "", table ? table : "");
 
452
    my_printf_error(0,"Error: %d, %s%s%s", MYF(0),
 
453
                    drizzle_result_error_code(result),
 
454
                    drizzle_result_error(result),
 
455
                    table ? ", when using table: " : "", table ? table : "");
252
456
    drizzle_result_free(result);
253
457
  }
254
458
  else
255
459
  {
256
 
    fprintf(stdout, "Error: %d, %s%s%s", ret, drizzle_con_error(con),
257
 
            table ? ", when using table: " : "", table ? table : "");
 
460
    my_printf_error(0,"Error: %d, %s%s%s", MYF(0), ret, drizzle_con_error(con),
 
461
                    table ? ", when using table: " : "", table ? table : "");
258
462
  }
259
463
 
260
464
  safe_exit(1, con);
314
518
{
315
519
  int error;
316
520
  char *raw_table_name= (char *)arg;
317
 
  drizzle_con_st *con;
 
521
  drizzle_con_st *con= NULL;
 
522
  drizzle_result_st result;
 
523
  drizzle_return_t ret;
318
524
 
319
525
  if (!(con= db_connect(current_host,current_db,current_user,opt_password)))
320
526
  {
321
 
    return 0;
 
527
    goto error;
 
528
  }
 
529
 
 
530
  if (drizzle_query_str(con, &result,
 
531
                        "/*!40101 set @@character_set_database=binary */;",
 
532
                        &ret) == NULL ||
 
533
      ret != DRIZZLE_RETURN_OK)
 
534
  {
 
535
    db_error(con, &result, ret, NULL);
 
536
    /* We shall countinue here, if --force was given */
 
537
    goto error;
322
538
  }
323
539
 
324
540
  /*
325
541
    We are not currently catching the error here.
326
542
  */
327
 
  if ((error= write_to_table(raw_table_name, con)))
328
 
  {
 
543
  if((error= write_to_table(raw_table_name, con)))
329
544
    if (exitcode == 0)
330
 
    {
331
545
      exitcode= error;
332
 
    }
333
 
  }
334
546
 
 
547
error:
335
548
  if (con)
336
 
  {
337
549
    db_disconnect(current_host, con);
338
 
  }
339
550
 
340
551
  pthread_mutex_lock(&counter_mutex);
341
552
  counter--;
342
553
  pthread_cond_signal(&count_threshhold);
343
554
  pthread_mutex_unlock(&counter_mutex);
 
555
  my_thread_end();
344
556
 
345
557
  return 0;
346
558
}
348
560
 
349
561
int main(int argc, char **argv)
350
562
{
351
 
try
352
 
{
353
563
  int error=0;
354
 
 
355
 
  po::options_description commandline_options("Options used only in command line");
356
 
  commandline_options.add_options()
357
 
 
358
 
  ("debug,#", po::value<string>(),
359
 
  "Output debug log. Often this is 'd:t:o,filename'.")
360
 
  ("delete,d", po::value<bool>(&opt_delete)->default_value(false)->zero_tokens(),
361
 
  "First delete all rows from table.")
362
 
  ("help,?", "Displays this help and exits.")
363
 
  ("ignore,i", po::value<bool>(&ignore_unique)->default_value(false)->zero_tokens(),
364
 
  "If duplicate unique key was found, keep old row.")
365
 
  ("low-priority", po::value<bool>(&opt_low_priority)->default_value(false)->zero_tokens(),
366
 
  "Use LOW_PRIORITY when updating the table.")
367
 
  ("replace,r", po::value<bool>(&opt_replace)->default_value(false)->zero_tokens(),
368
 
  "If duplicate unique key was found, replace old row.")
369
 
  ("verbose,v", po::value<bool>(&verbose)->default_value(false)->zero_tokens(),
370
 
  "Print info about the various stages.")
371
 
  ("version,V", "Output version information and exit.")
372
 
  ;
373
 
 
374
 
  po::options_description import_options("Options specific to the drizzleimport");
375
 
  import_options.add_options()
376
 
  ("columns,C", po::value<string>(&opt_columns)->default_value(""),
377
 
  "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.")
378
 
  ("fields-terminated-by", po::value<string>(&fields_terminated)->default_value(""),
379
 
  "Fields in the textfile are terminated by ...")
380
 
  ("fields-enclosed-by", po::value<string>(&enclosed)->default_value(""),
381
 
  "Fields in the importfile are enclosed by ...")
382
 
  ("fields-optionally-enclosed-by", po::value<string>(&opt_enclosed)->default_value(""),
383
 
  "Fields in the i.file are opt. enclosed by ...")
384
 
  ("fields-escaped-by", po::value<string>(&escaped)->default_value(""),
385
 
  "Fields in the i.file are escaped by ...")
386
 
  ("force,f", po::value<bool>(&ignore_errors)->default_value(false)->zero_tokens(),
387
 
  "Continue even if we get an sql-error.")
388
 
  ("ignore-lines", po::value<int64_t>(&opt_ignore_lines)->default_value(0),
389
 
  "Ignore first n lines of data infile.")
390
 
  ("lines-terminated-by", po::value<string>(&lines_terminated)->default_value(""),
391
 
  "Lines in the i.file are terminated by ...")
392
 
  ("local,L", po::value<bool>(&opt_local_file)->default_value(false)->zero_tokens(),
393
 
  "Read all files through the client.")
394
 
  ("silent,s", po::value<bool>(&silent)->default_value(false)->zero_tokens(),
395
 
  "Be more silent.")
396
 
  ("use-threads", po::value<uint32_t>(&opt_use_threads)->default_value(4),
397
 
  "Load files in parallel. The argument is the number of threads to use for loading data (default is 4.")
398
 
  ;
399
 
 
400
 
  po::options_description client_options("Options specific to the client");
401
 
  client_options.add_options()
402
 
  ("host,h", po::value<string>(&current_host)->default_value("localhost"),
403
 
  "Connect to host.")
404
 
  ("password,P", po::value<string>(&password),
405
 
  "Password to use when connecting to server. If password is not given it's asked from the tty." )
406
 
  ("port,p", po::value<uint32_t>(&opt_drizzle_port)->default_value(0),
407
 
  "Port number to use for connection") 
408
 
  ("protocol", po::value<string>(&opt_protocol)->default_value("mysql"),
409
 
  "The protocol of connection (mysql or drizzle).")
410
 
  ("user,u", po::value<string>(&current_user)->default_value(""),
411
 
  "User for login if not current user.")
412
 
  ;
413
 
 
414
 
  po::options_description long_options("Allowed Options");
415
 
  long_options.add(commandline_options).add(import_options).add(client_options);
416
 
 
417
 
  std::string system_config_dir_import(SYSCONFDIR); 
418
 
  system_config_dir_import.append("/drizzle/drizzleimport.cnf");
419
 
 
420
 
  std::string system_config_dir_client(SYSCONFDIR); 
421
 
  system_config_dir_client.append("/drizzle/client.cnf");
422
 
  
423
 
  std::string user_config_dir((getenv("XDG_CONFIG_HOME")? getenv("XDG_CONFIG_HOME"):"~/.config"));
424
 
 
425
 
  if (user_config_dir.compare(0, 2, "~/") == 0)
426
 
  {
427
 
    char *homedir;
428
 
    homedir= getenv("HOME");
429
 
    if (homedir != NULL)
430
 
      user_config_dir.replace(0, 1, homedir);
431
 
  }
432
 
 
433
 
  po::variables_map vm;
434
 
 
435
 
  // Disable allow_guessing
436
 
  int style = po::command_line_style::default_style & ~po::command_line_style::allow_guessing;
437
 
 
438
 
  po::store(po::command_line_parser(argc, argv).options(long_options).
439
 
            style(style).extra_parser(parse_password_arg).run(), vm);
440
 
 
441
 
  std::string user_config_dir_import(user_config_dir);
442
 
  user_config_dir_import.append("/drizzle/drizzleimport.cnf"); 
443
 
 
444
 
  std::string user_config_dir_client(user_config_dir);
445
 
  user_config_dir_client.append("/drizzle/client.cnf");
446
 
 
447
 
  ifstream user_import_ifs(user_config_dir_import.c_str());
448
 
  po::store(parse_config_file(user_import_ifs, import_options), vm);
449
 
 
450
 
  ifstream user_client_ifs(user_config_dir_client.c_str());
451
 
  po::store(parse_config_file(user_client_ifs, client_options), vm);
452
 
 
453
 
  ifstream system_import_ifs(system_config_dir_import.c_str());
454
 
  store(parse_config_file(system_import_ifs, import_options), vm);
455
 
 
456
 
  ifstream system_client_ifs(system_config_dir_client.c_str());
457
 
  po::store(parse_config_file(system_client_ifs, client_options), vm);
458
 
 
459
 
  po::notify(vm);
460
 
  if (vm.count("protocol"))
461
 
  {
462
 
    std::transform(opt_protocol.begin(), opt_protocol.end(),
463
 
      opt_protocol.begin(), ::tolower);
464
 
 
465
 
    if (not opt_protocol.compare("mysql"))
466
 
      use_drizzle_protocol=false;
467
 
    else if (not opt_protocol.compare("drizzle"))
468
 
      use_drizzle_protocol=true;
469
 
    else
470
 
    {
471
 
      cout << _("Error: Unknown protocol") << " '" << opt_protocol << "'" << endl;
472
 
      exit(-1);
473
 
    }
474
 
  }
475
 
 
476
 
  if (vm.count("port"))
477
 
  {
478
 
    
479
 
    /* If the port number is > 65535 it is not a valid port
480
 
       This also helps with potential data loss casting unsigned long to a
481
 
       uint32_t. */
482
 
    if (opt_drizzle_port > 65535)
483
 
    {
484
 
      fprintf(stderr, _("Value supplied for port is not valid.\n"));
485
 
      exit(EXIT_ARGUMENT_INVALID);
486
 
    }
487
 
  }
488
 
 
489
 
  if( vm.count("password") )
490
 
  {
491
 
    if (!opt_password.empty())
492
 
      opt_password.erase();
493
 
    if (password == PASSWORD_SENTINEL)
494
 
    {
495
 
      opt_password= "";
496
 
    }
497
 
    else
498
 
    {
499
 
      opt_password= password;
500
 
      tty_password= false;
501
 
    }
502
 
  }
503
 
  else
504
 
  {
505
 
      tty_password= true;
506
 
  }
507
 
 
508
 
 
509
 
  if (vm.count("version"))
510
 
  {
511
 
    printf("%s  Ver %s Distrib %s, for %s-%s (%s)\n", program_name,
512
 
    IMPORT_VERSION, drizzle_version(),HOST_VENDOR,HOST_OS,HOST_CPU);
513
 
  }
514
 
  
515
 
  if (vm.count("help") || argc < 2)
516
 
  {
517
 
    printf("%s  Ver %s Distrib %s, for %s-%s (%s)\n", program_name,
518
 
    IMPORT_VERSION, drizzle_version(),HOST_VENDOR,HOST_OS,HOST_CPU);
519
 
    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");
520
 
    printf("\
521
 
    Loads tables from text files in various formats.  The base name of the\n\
522
 
    text file must be the name of the table that should be used.\n\
523
 
    If one uses sockets to connect to the Drizzle server, the server will open and\n\
524
 
    read the text file directly. In other cases the client will open the text\n\
525
 
    file. The SQL command 'LOAD DATA INFILE' is used to import the rows.\n");
526
 
 
527
 
    printf("\nUsage: %s [OPTIONS] database textfile...", program_name);
528
 
    cout<<long_options;
529
 
    exit(0);
530
 
  }
531
 
 
532
 
 
533
 
  if (get_options())
534
 
  {
 
564
  char **argv_to_free;
 
565
  MY_INIT(argv[0]);
 
566
 
 
567
  load_defaults("drizzle",load_default_groups,&argc,&argv);
 
568
  /* argv is changed in the program */
 
569
  argv_to_free= argv;
 
570
  if (get_options(&argc, &argv))
 
571
  {
 
572
    free_defaults(argv_to_free);
535
573
    return(1);
536
574
  }
537
 
  
538
 
  current_db= (*argv)++;
539
 
  argc--;
540
575
 
541
 
  if (opt_use_threads)
 
576
#ifdef HAVE_LIBPTHREAD
 
577
  if (opt_use_threads && !lock_tables)
542
578
  {
543
579
    pthread_t mainthread;            /* Thread descriptor */
544
580
    pthread_attr_t attr;          /* Thread attributes */
569
605
        pthread_mutex_lock(&counter_mutex);
570
606
        counter--;
571
607
        pthread_mutex_unlock(&counter_mutex);
572
 
        fprintf(stderr,"%s: Could not create thread\n", program_name);
 
608
        fprintf(stderr,"%s: Could not create thread\n",
 
609
                my_progname);
573
610
      }
574
611
    }
575
612
 
590
627
    pthread_attr_destroy(&attr);
591
628
  }
592
629
  else
 
630
#endif
593
631
  {
594
 
    drizzle_con_st *con;
595
 
 
 
632
    drizzle_con_st *con= 0;
 
633
    drizzle_result_st result;
 
634
    drizzle_return_t ret;
596
635
    if (!(con= db_connect(current_host,current_db,current_user,opt_password)))
597
636
    {
598
 
      return(1);
599
 
    }
600
 
 
 
637
      free_defaults(argv_to_free);
 
638
      return(1);
 
639
    }
 
640
 
 
641
    if (drizzle_query_str(con, &result,
 
642
                          "/*!40101 set @@character_set_database=binary */;",
 
643
                          &ret) == NULL ||
 
644
        ret != DRIZZLE_RETURN_OK)
 
645
    {
 
646
      db_error(con, &result, ret, NULL);
 
647
      /* We shall countinue here, if --force was given */
 
648
      return(1);
 
649
    }
 
650
 
 
651
    drizzle_result_free(&result);
 
652
 
 
653
    if (lock_tables)
 
654
      lock_table(con, argc, argv);
601
655
    for (; *argv != NULL; argv++)
602
656
      if ((error= write_to_table(*argv, con)))
603
657
        if (exitcode == 0)
604
658
          exitcode= error;
605
659
    db_disconnect(current_host, con);
606
660
  }
607
 
  opt_password.empty();
608
 
}
609
 
  catch(exception &err)
610
 
  {
611
 
    cerr<<err.what()<<endl;
612
 
  }
 
661
  free(opt_password);
 
662
  free_defaults(argv_to_free);
 
663
  my_end();
613
664
  return(exitcode);
614
665
}