summaryrefslogtreecommitdiff
path: root/sql-bench/copy-db.sh
blob: 245aa4e79b6160563bb50c843cb7ac8ead6303e0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
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
#!@PERL@
# Copyright (C) 2000 MySQL AB & MySQL Finland AB & TCX DataKonsult AB
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
# MA 02111-1307, USA
#
# start initialition
#

$VER = "1.0";

use Getopt::Long;
use DBI;

$max_row_length=500000;		# Don't create bigger SQL rows that this
$opt_lock=1;			# lock tables

chomp($pwd = `pwd`); $pwd = "." if ($pwd eq '');

require "$pwd/server-cfg" || die "Can't read Configuration file: $!\n";

$|=1;

$opt_from_server= $opt_to_server= "mysql";
$opt_from_host= $opt_to_host=     "localhost";
$opt_from_db= $opt_to_db=         "test";
$opt_from_user=$opt_from_password=$opt_to_user=$opt_to_password="";
$opt_help=$opt_verbose=$opt_debug=0;


GetOptions("from-server=s","to-server=s","from-host=s","to-host=s","from-db=s",
	   "to-db=s", "help", "verbose","debug") || usage();

usage() if ($opt_help || 
	    ($opt_from_server eq $opt_to_server && 
	     $opt_from_db eq $opt_to_db &&
	     $opt_from_host eq $opt_to_host));

####
#### Usage
####


sub usage
{
  print <<EOF;

$0 version $VER by Monty

 Copies tables between two database servers. If the destination table doesn\'t
 exist it\'s autoamticly created.  If the destination table exists, it
 should be compatible with the source table.

 Because DBI doesn\'t provide full information about the columns in a table,
 some columns may not have optimal types in a create tables.  Any created
 tables will also not have any keys!

  Usage: $0 [options] tables...

  Options:
  --help         Show this help and exit
  --from-server	  Source server			(Default: $opt_from_server)
  --from-host     Source hostname		(Default: $opt_from_host)
  --from-db       Source database name		(Default: $opt_from_db)
  --from-user	  Source user			(Default: $opt_from_password)
  --from-password Source password		(Default: $opt_from_password)
  --to-server     Destination server		(Default: $opt_to_server)
  --to-host       Destination hostname		(Default: $opt_to_host)
  --to-db         Destination database name	(Default: $opt_to_db)
  --to-user	  Destination user		(Default: $opt_to_user)
  --to-password	  Destination password		(Default: $opt_to_password)
  --verbose	  Be more verbose

  If you the server names ends with _ODBC, then this program will connect
  through ODBC instead of using a native driver.
EOF
   exit(0);
}

####
#### Connect
####

$from_server=get_server($opt_from_server,$opt_from_host,$opt_from_db);
$to_server=get_server($opt_to_server,$opt_to_host,$opt_to_db);

$opt_user=$opt_from_user; $opt_password=$opt_from_password;
print "- connecting to SQL servers\n" if ($opt_verbose);
$from_dbh=$from_server->connect() || die "Can't connect to source server $opt_from_server on host $opt_from_host using db $opt_from_db";
$opt_user=$opt_to_user; $opt_password=$opt_to_password;
$to_dbh=$to_server->connect() || die "Can't connect to source server $opt_to_server on host $opt_to_host using db $opt_to_db";

####
#### Copy data
####

foreach $table (@ARGV)
{

  print "- querying $table\n" if ($opt_verbose);
  $sth=$from_dbh->prepare("select * from $table") || die "Can't prepare query to get $table; $DBI::errstr";
  $sth->execute || die "Can't execute query to get data from $table; $DBI::errstr";

  if (!table_exists($to_server,$to_dbh,$table))
  {
    print "- creating $table\n" if ($opt_verbose);
    $table_def=get_table_definition($from_server,$from_dbh,$sth);
    do_many($to_dbh,$to_server->create($table,$table_def,[]));
  }
  if ($opt_lock && $to_server->{'lock_tables'})
  {
    print "- locking $table\n" if ($opt_verbose);
    $to_dbh->do("lock tables $table WRITE");
  }

  $columns=$sth->{NUM_OF_FIELDS};
  $columns_to_quote=get_columns_to_quote($sth);
  $multi_value_insert=$sth->{'multi_value_insert'};
  $query="insert into $table values"; $result="";

  print "- copying $table\n" if ($opt_verbose);
  while (($row = $sth->fetchrow_arrayref))
  {
    $tmp="(";
    for ($i=0 ; $i < $columns ; $i++)
    {
      if ($columns_to_quote->[$i])
      {
	$tmp.= $to_dbh->quote($row->[$i]) . ",";
      }
      else
      {
	$tmp.= $row->[$i] . ",";	
      }
    }
    substr($tmp,-1)=")";		# Remove last ','
    if ($multi_value_insert)
    {
      $to_dbh->do($query . $tmp) || die "Can't insert row: $DBI::errstr";
    }
    elsif (length($result)+length($tmp) >= $max_row_length && $result)
    {
      $to_dbh->do($query . $result) || die "Can't insert row: $DBI::errstr";
      $result="";
    }
    elsif (length($result))
    {
      $result.= ",$tmp";
    }
    else
    {
      $result=$tmp;
    }
  }
  if (length($result))
  {
    $to_dbh->do($query . $result) || die "Can't insert row: $DBI::errstr";
  }
  if ($opt_lock && $to_server->{'lock_tables'})
  {
    $to_dbh->do("unlock tables");
  }
}


sub get_table_definition
{
  my ($server,$dbh,$sth)=@_;
  my ($i,$names,$types,$scale,$precision,$nullable,@res);

  $names=$sth->{NAME};
  $types=$sth->{TYPE};
  $nullable=$sth->{NULLABLE};
  if (0)
  {
    # The following doesn't yet work
    $scale=$sth->{SCALE};
    $precision=$sth->{PRECISION};
  }
  else
  {
    my (@tmp);
    @tmp= (undef()) x $sth->{NUM_OF_FIELDS};
    $precision= $scale= \@tmp;
  }
  for ($i = 0; $i < $sth->{NUM_OF_FIELDS} ; $i++)
  {
    push(@res,$names->[$i] . " " .
	 odbc_to_sql($server,$types->[$i],$precision->[$i],$scale->[$i]) .
	 ($nullable->[$i] ? "" : " NOT NULL"));
  }
  return \@res;
}


sub odbc_to_sql
{
  my ($server,$type,$precision,$scale)=@_;

  if ($type == DBI::SQL_CHAR())
  {
    return defined($precision) ? "char($precision)" : "varchar(255)";
  }

  if ($type == DBI::SQL_NUMERIC())
  {
    $precision=15 if (!defined($precision));
    $scale=6 if (!defined($scale));
    return "numeric($precision,$scale)";
  }
  if ($type == DBI::SQL_DECIMAL())
  {
    $precision=15 if (!defined($precision));
    $scale=6 if (!defined($scale));
    return "decimal($precision,$scale)";
  }
  if ($type == DBI::SQL_INTEGER())
  {
    return "integer" if (!defined($precision));
    return "integer($precision)";
  }
  if ($type == DBI::SQL_SMALLINT())
  {
    return "smallint" if (!defined($precision));
    return "smallint($precision)";
  }
  if ($type == DBI::SQL_FLOAT())
  {
    $precision=12 if (!defined($precision));
    $scale=2 if (!defined($scale));
    return "float($precision,$scale)";
  }
  if ($type == DBI::SQL_REAL())
  {
    $precision=12 if (!defined($precision));
    $scale=2 if (!defined($scale));
    return "float($precision,$scale)";
  }
  if ($type == DBI::SQL_DOUBLE())
  {
    $precision=22 if (!defined($precision));
    $scale=2 if (!defined($scale));
    return "double($precision,$scale)";
  }
  if ($type == DBI::SQL_VARCHAR())
  {
    $precision=255 if (!defined($precision));
    return "varchar($precision)";
  }
  return "date"				if ($type == DBI::SQL_DATE());
  return "time"				if ($type == DBI::SQL_TIME());
  return "timestamp"			if ($type == DBI::SQL_TIMESTAMP());
  return $server->{'text'}		if ($type == DBI::SQL_LONGVARCHAR());
  return $server->{'blob'}		if ($type == DBI::SQL_LONGVARBINARY());
  if ($type == DBI::SQL_BIGINT())
  {
    return "bigint" if (!defined($precision));
    return "bigint($precision)";
  }
  if ($type == DBI::SQL_TINYINT())
  {
    return "tinyint" if (!defined($precision));
    return "tinyint($precision)";
  }
  die "Can't covert type '$type' to a ODBC type\n";
}

#
# return an array with 1 for all coumns that we have to quote
#
					      
sub get_columns_to_quote($sth)
{
  my ($sth)=@_;
  my ($i,@res,$type,$tmp);

  @res=();
  for ($i = 0; $i < $sth->{NUM_OF_FIELDS} ; $i++)
  {
    $type=$sth->{TYPE}->[$i];
    $tmp=1;			# String by default
    if ($type == DBI::SQL_NUMERIC()	|| $type == DBI::SQL_DECIMAL() ||
	$type == DBI::SQL_INTEGER()	|| $type == DBI::SQL_SMALLINT() ||
	$type == DBI::SQL_SMALLINT()	|| $type == DBI::SQL_FLOAT() ||
	$type == DBI::SQL_REAL() 	|| $type == DBI::SQL_DOUBLE() ||
	$type == DBI::SQL_BIGINT()	|| $type == DBI::SQL_TINYINT())
    {
      $tmp=0;
    }
    push (@res,$tmp);
  }
  return \@res;
}

#
# Check if table exists;  Return 1 if table exists
#

sub table_exists
{
  my ($server,$dbh,$table)=@_;
  if ($server->{'limits'}->{'group_functions'})
  {
    return !safe_query($dbh,"select count(*) from $table");
  }
  if ($server->{'limits'}->{'limit'})
  {
    return !safe_query($dbh,"select * from $table limit 1");
  }
  die "Don't know how to check if table '$table' exists in destination server\n";
}


#
# execute query;  return 0 if query is ok
#

sub safe_query
{
  my ($dbh,$query)=@_;
  my ($sth);

  print "query: $query\n" if ($opt_debug);
  if (!($sth= $dbh->prepare($query)))
  {
    print "error: $DBI::errstr\n" if ($opt_debug);
    return 1;
  }
  if (!$sth->execute)
  {
    print "error: $DBI::errstr\n" if ($opt_debug);
    return 1
  }
  while ($sth->fetchrow_arrayref)
  {
  }
  $sth->finish;
  undef($sth);
  return 0;
}

#
# execute an array of queries
#

sub do_many
{
  my ($dbh,@statements)=@_;
  my ($statement,$sth);

  foreach $statement (@statements)
  {
    print "query: $statement\n" if ($opt_debug);
    if (!($sth=$dbh->do($statement)))
    {
      die "Can't execute command '$statement'\nError: $DBI::errstr\n";
    }
  }
}