| 1 |
#! /usr/bin/env perl |
| 2 |
|
| 3 |
# Copyright (C) 1999-2012 Stefan Hornburg |
| 4 |
|
| 5 |
# Author: Stefan Hornburg (Racke) <[email protected]> |
| 6 |
# Maintainer: Stefan Hornburg (Racke) <[email protected]> |
| 7 |
# Version: 0.19 |
| 8 |
|
| 9 |
# This file is free software; you can redistribute it and/or modify it |
| 10 |
# under the terms of the GNU General Public License as published by the |
| 11 |
# Free Software Foundation; either version 2, or (at your option) any |
| 12 |
# later version. |
| 13 |
|
| 14 |
# This file is distributed in the hope that it will be |
| 15 |
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty |
| 16 |
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 17 |
# General Public License for more details. |
| 18 |
|
| 19 |
# You should have received a copy of the GNU General Public License |
| 20 |
# along with this file; see the file COPYING. If not, write to the Free |
| 21 |
# Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. |
| 22 |
|
| 23 |
use strict; |
| 24 |
use warnings; |
| 25 |
|
| 26 |
use DBIx::Easy; |
| 27 |
use Getopt::Long; |
| 28 |
use Term::ReadKey; |
| 29 |
|
| 30 |
# process commandline parameters |
| 31 |
my %opts; |
| 32 |
$opts{'keys'} = 1; |
| 33 |
my $whandler = $SIG{__WARN__}; |
| 34 |
$SIG{__WARN__} = sub {print STDERR "$0: @_";}; |
| 35 |
unless (GetOptions (\%opts, 'cleanse', 'columns|c=s', |
| 36 |
'file|f=s', 'format=s', 'headline|h', 'insert-only|i', |
| 37 |
'rows=s', 'keys|k=s', |
| 38 |
'map|m=s', 'map-filter=s', 'match-sql=s', 'routine|r=s', |
| 39 |
'skipbadlines', |
| 40 |
'table|t=s', 'update-only|o')) { |
| 41 |
exit 1; |
| 42 |
} |
| 43 |
$SIG{__WARN__} = $whandler; |
| 44 |
|
| 45 |
# sanity checks |
| 46 |
my $format = 'TAB'; |
| 47 |
my %inforef = (); |
| 48 |
my %funcref = (CSV => {get_columns => \&get_columns_csv}, |
| 49 |
TAB => {get_columns => \&get_columns_tab}, |
| 50 |
XLS => {get_columns => \&get_columns_xls}); |
| 51 |
my %mfref = (lc => sub {lc(shift)}); |
| 52 |
my $sep_char = ','; |
| 53 |
my $mfsub; |
| 54 |
|
| 55 |
if ($opts{'cleanse'} || $opts{'headline'}) { |
| 56 |
unless ($opts{'table'}) { |
| 57 |
die ("$0: missing table name\n"); |
| 58 |
} |
| 59 |
} |
| 60 |
if ($opts{'map-filter'}) { |
| 61 |
unless (exists($mfref{$opts{'map-filter'}})) { |
| 62 |
die qq{$0: unknown column name filter "$opts{'map-filter'}"}, "\n"; |
| 63 |
} |
| 64 |
$mfsub = $mfref{$opts{'map-filter'}}; |
| 65 |
} |
| 66 |
|
| 67 |
if ($opts{'format'}) { |
| 68 |
$format = uc($opts{'format'}); |
| 69 |
|
| 70 |
if ($format =~ /^CSV/) { |
| 71 |
$format = 'CSV'; |
| 72 |
if ($') { |
| 73 |
$sep_char = $'; |
| 74 |
$sep_char =~ s/^\s+//; |
| 75 |
$sep_char =~ s/\s+$//; |
| 76 |
} |
| 77 |
eval { |
| 78 |
require Text::CSV_XS; |
| 79 |
}; |
| 80 |
if ($@) { |
| 81 |
die "$0: couldn't load module Text::CSV_XS\n"; |
| 82 |
} |
| 83 |
$inforef{object} = new Text::CSV_XS ({'binary' => 1, 'sep_char' => $sep_char}); |
| 84 |
} elsif ($format eq 'XLS') { |
| 85 |
eval { |
| 86 |
require Spreadsheet::ParseExcel; |
| 87 |
}; |
| 88 |
if ($@) { |
| 89 |
die "$0: couldn't load module Spreadsheet::ParseExcel\n"; |
| 90 |
} |
| 91 |
$inforef{object} = new Spreadsheet::ParseExcel; |
| 92 |
} else { |
| 93 |
die ("$0: unknown format \"" . $opts{'format'} . "\"\n"); |
| 94 |
} |
| 95 |
} |
| 96 |
|
| 97 |
my %fieldmap; |
| 98 |
my $fd_input; |
| 99 |
|
| 100 |
my ($sth, $keyfield, $update, $msg); |
| 101 |
my ($table, $fieldnames, @values, $headline); |
| 102 |
my (@columns, $routine, %colmap); |
| 103 |
my $linebuf = ''; |
| 104 |
|
| 105 |
# whether to consider column |
| 106 |
my $colflag = 1; |
| 107 |
my %usecol; |
| 108 |
# whether to consider rows |
| 109 |
my $rowflag; |
| 110 |
my %userow; |
| 111 |
# current row |
| 112 |
my $currow = 0; |
| 113 |
# input with table as first field may specify start column |
| 114 |
my $startcol; |
| 115 |
# variables for --match-sql option |
| 116 |
my (%matchmap, $matchcol); |
| 117 |
|
| 118 |
if ($opts{'columns'}) { |
| 119 |
$colflag = ! ($opts{'columns'} =~ s/\s*[\!^]//); |
| 120 |
|
| 121 |
# setup positive/negative list for columns |
| 122 |
for (@columns = split(/\s*,\s*/, $opts{'columns'})) { |
| 123 |
$usecol{$_} = $colflag; |
| 124 |
} |
| 125 |
} |
| 126 |
|
| 127 |
if ($opts{'rows'}) { |
| 128 |
my @rows; |
| 129 |
|
| 130 |
$rowflag = ! ($opts{'rows'} =~ s/\s*[^\!]//); |
| 131 |
|
| 132 |
# setup positive/negative list for rows |
| 133 |
for (@rows = split(/\s*,\s*/, $opts{'rows'})) { |
| 134 |
unless (/^\d+$/) { |
| 135 |
die "$0: row number \"$_\" is not numeric\n"; |
| 136 |
} |
| 137 |
$userow{$_} = $rowflag; |
| 138 |
} |
| 139 |
} |
| 140 |
|
| 141 |
if ($opts{'file'}) { |
| 142 |
# read input from file |
| 143 |
require IO::File; |
| 144 |
$fd_input = new IO::File; |
| 145 |
$fd_input->open($opts{'file'}) |
| 146 |
|| die "$0: couldn't open $opts{'file'}: $!\n"; |
| 147 |
} else { |
| 148 |
# read input from standard input |
| 149 |
require IO::Handle; |
| 150 |
$fd_input = new IO::Handle; |
| 151 |
$fd_input->fdopen(fileno(STDIN),'r'); |
| 152 |
} |
| 153 |
|
| 154 |
if ($opts{'map'}) { |
| 155 |
# parse column name mapping |
| 156 |
my ($head, $name); |
| 157 |
foreach (split (/;/, $opts{'map'})) { |
| 158 |
($head, $name) = split /=/; |
| 159 |
$colmap{$head} = $name; |
| 160 |
} |
| 161 |
} |
| 162 |
|
| 163 |
my $csv; |
| 164 |
|
| 165 |
if ($opts{'headline'}) { |
| 166 |
my %hcolmap; |
| 167 |
|
| 168 |
# the first row consists of the column names |
| 169 |
# unless (defined ($headline = <$fd_input>)) { |
| 170 |
# die ("$0: empty input file\n"); |
| 171 |
# } |
| 172 |
my @columns; |
| 173 |
if ($funcref{$format}->{get_columns}(\%inforef, $fd_input,\@columns) <= 0) { |
| 174 |
die "$0: couldn't find headline\n"; |
| 175 |
} |
| 176 |
|
| 177 |
if ($opts{'map-filter'}) { |
| 178 |
@columns = map {$mfsub->($_)} @columns; |
| 179 |
} |
| 180 |
|
| 181 |
# remove whitespace from column names and mark them |
| 182 |
map {s/^\s+//; s/\s+$//; $hcolmap{$_} = 1;} @columns; |
| 183 |
|
| 184 |
if ($opts{'map'}) { |
| 185 |
my @newcolumns; |
| 186 |
|
| 187 |
# filter column names |
| 188 |
foreach (@columns) { |
| 189 |
if (exists $colmap{$_}) { |
| 190 |
push (@newcolumns, $colmap{$_}); |
| 191 |
$hcolmap{$colmap{$_}} = 1; |
| 192 |
} else { |
| 193 |
push (@newcolumns, $_); |
| 194 |
} |
| 195 |
} |
| 196 |
@columns = @newcolumns; |
| 197 |
} |
| 198 |
|
| 199 |
# add any other columns explicitly selected |
| 200 |
for (sort (keys %usecol)) { |
| 201 |
next if $hcolmap{$_}; |
| 202 |
next unless exists $usecol{$_}; |
| 203 |
next unless $usecol{$_}; |
| 204 |
push (@columns, $_); |
| 205 |
} |
| 206 |
|
| 207 |
# fixed table name |
| 208 |
$table = $opts{'table'}; |
| 209 |
$fieldmap{$table} = \@columns; |
| 210 |
} |
| 211 |
|
| 212 |
if ($opts{'routine'}) { |
| 213 |
# read Perl subroutine for filtering the input |
| 214 |
$routine = eval $opts{'routine'}; |
| 215 |
|
| 216 |
if ($@) { |
| 217 |
die "$0: invalid filter routine: $@: \n"; |
| 218 |
} |
| 219 |
|
| 220 |
if (ref($routine) ne 'CODE') { |
| 221 |
die "$0: invalid filter routine\n"; |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
if ($opts{'table'}) { |
| 226 |
# set fixed table name |
| 227 |
$table = $opts{'table'}; |
| 228 |
# use defined columns |
| 229 |
if (! $opts{'headline'} && $opts{'columns'}) { |
| 230 |
$fieldmap{$table} = \@columns; |
| 231 |
} |
| 232 |
} |
| 233 |
|
| 234 |
my $dbif; |
| 235 |
my $pwdused = 0; |
| 236 |
|
| 237 |
my ($driver, $database, $user) = @ARGV; |
| 238 |
|
| 239 |
$dbif = new DBIx::Easy ($driver, $database, $user); |
| 240 |
|
| 241 |
# handler for DBI error messages and missing password |
| 242 |
$dbif -> install_handler (\&fatal); |
| 243 |
|
| 244 |
# we need to explicitly establish the connection |
| 245 |
# for the case that a password is needed |
| 246 |
$dbif -> connect; |
| 247 |
|
| 248 |
my (@keys, @cleansekeys, %cleansemap, $numkeysleft, %recmap, @names); |
| 249 |
|
| 250 |
if ($opts{'cleanse'}) { |
| 251 |
# determine column names |
| 252 |
@names = &column_names ($dbif, $table); |
| 253 |
$fieldnames = \@names; |
| 254 |
|
| 255 |
# determine keys |
| 256 |
%cleansemap = &key_names ($dbif, $table, $opts{'keys'}, 1); |
| 257 |
@cleansekeys = sort (keys %cleansemap); |
| 258 |
|
| 259 |
# get records |
| 260 |
my ($row, $href, $i); |
| 261 |
|
| 262 |
$sth = $dbif -> process ('SELECT ' . join(', ', @cleansekeys) |
| 263 |
. " FROM $table"); |
| 264 |
|
| 265 |
while ($row = $sth -> fetch()) { |
| 266 |
# build chain of all keys but the last |
| 267 |
$href = \%recmap; |
| 268 |
for ($i = 0; $i < $#cleansekeys; $i++) { |
| 269 |
unless (exists $href->{$$row[$i]}) { |
| 270 |
$href->{$$row[$i]} = {}; |
| 271 |
} |
| 272 |
$href = $href->{$$row[$i]}; |
| 273 |
} |
| 274 |
# stop if key kombination occurs multiple |
| 275 |
if (exists $href->{$$row[$i]}) { |
| 276 |
die "$0: duplicate key: ", join (",", @$row), "\n"; |
| 277 |
} |
| 278 |
# record last key |
| 279 |
if (defined $$row[$i]) { |
| 280 |
$href->{$$row[$i]} = 1; |
| 281 |
} else { |
| 282 |
$href->{$$row[$i]} = ''; |
| 283 |
} |
| 284 |
} |
| 285 |
} |
| 286 |
|
| 287 |
if ($opts{'match-sql'}) { |
| 288 |
unless ($opts{'match-sql'} =~ /^(.*?):\{(.*?)\}$/) { |
| 289 |
die "$0: invalid format for option --match-sql: $opts{'match-sql'}\n"; |
| 290 |
} |
| 291 |
$matchcol = $1; |
| 292 |
$sth = $dbif -> process ($2); |
| 293 |
|
| 294 |
my $row; |
| 295 |
while ($row = $sth->fetch()) { |
| 296 |
$matchmap{$$row[0]} = 1; |
| 297 |
} |
| 298 |
} |
| 299 |
|
| 300 |
my $gcsub = $funcref{$format}->{get_columns}; |
| 301 |
|
| 302 |
MAIN: while ($gcsub->(\%inforef, $fd_input, \@columns)) { |
| 303 |
my (@data); |
| 304 |
|
| 305 |
if ($opts{'headline'} || $opts{'table'}) { |
| 306 |
# table name already known |
| 307 |
@values = @columns; |
| 308 |
} else { |
| 309 |
# table name is the first column |
| 310 |
if ($format eq 'TAB') { |
| 311 |
($table, @values) = split /\t/; |
| 312 |
} elsif ($format eq 'CSV') { |
| 313 |
next unless csv_parseline ($csv, \$linebuf, $_, [$table, @values]); |
| 314 |
} |
| 315 |
|
| 316 |
# extract optional start column parameter |
| 317 |
if ($table =~ /(.+?)\.(.+)/) { |
| 318 |
$table = $1; $startcol = $2; |
| 319 |
|
| 320 |
unless ($startcol =~ /^\d+$/) { |
| 321 |
$msg = "$0: $.: start column not a number: \"" |
| 322 |
. $startcol . "\"\n"; |
| 323 |
if ($opts{'skipbadlines'}) { |
| 324 |
warn ($msg); |
| 325 |
next; |
| 326 |
} else { |
| 327 |
die ($msg); |
| 328 |
} |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
# sanity check on the table name |
| 333 |
if ($table =~ /\s/) { |
| 334 |
warn ("$0: $.: skipping record (\"$table\" not accepted as table name)\n"); |
| 335 |
next; |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
# check for row ex/inclusion |
| 340 |
$currow++; |
| 341 |
if (defined $rowflag) { |
| 342 |
if ($rowflag && ! exists $userow{$currow}) { |
| 343 |
# print "Skipping row $currow due to inclusion\n"; |
| 344 |
next; |
| 345 |
} |
| 346 |
if (! $rowflag && exists $userow{$currow}) { |
| 347 |
# print "Skipping row $currow due to exclusion\n"; |
| 348 |
next; |
| 349 |
} |
| 350 |
} |
| 351 |
|
| 352 |
# determine column names |
| 353 |
@names = &column_names ($dbif, $table, $startcol); |
| 354 |
$fieldnames = \@names; |
| 355 |
|
| 356 |
if ($opts{'routine'}) { |
| 357 |
# filter input first |
| 358 |
next unless filter_input ($routine, $table, $fieldnames, \@values); |
| 359 |
} |
| 360 |
|
| 361 |
# filter out non-matching rows |
| 362 |
MATCHSQL: { |
| 363 |
if ($opts{'match-sql'}) { |
| 364 |
for (my $i = 0; $i < @$fieldnames; $i++) { |
| 365 |
if ($$fieldnames[$i] eq $matchcol) { |
| 366 |
last MATCHSQL if $matchmap{$values[$i]}; |
| 367 |
print "Not accepted record @values\n"; |
| 368 |
next MAIN; |
| 369 |
} |
| 370 |
} |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
# sanity checks on input data |
| 375 |
my $typeref = $dbif -> typemap ($table); |
| 376 |
my $sizeref = $dbif -> sizemap ($table); |
| 377 |
|
| 378 |
for (my $i = 0; $i <= $#$fieldnames; $i++) { |
| 379 |
# check for column exclusion |
| 380 |
if (keys %usecol) { |
| 381 |
# note: we do not check the actual value !! |
| 382 |
if ($colflag && ! exists $usecol{$$fieldnames[$i]}) { |
| 383 |
next; |
| 384 |
} |
| 385 |
if (! $colflag && exists $usecol{$$fieldnames[$i]}) { |
| 386 |
next; |
| 387 |
} |
| 388 |
} |
| 389 |
# expand newlines and tabulators |
| 390 |
if (defined $values[$i]) { |
| 391 |
$values[$i] =~ s/\\n/\n/g; |
| 392 |
$values[$i] =~ s/\\t/\t/g; |
| 393 |
} |
| 394 |
|
| 395 |
# check if input exceeds column capacity |
| 396 |
unless (exists $$typeref{$$fieldnames[$i]}) { |
| 397 |
warn ("$0: No type information for column $$fieldnames[$i] found\n"); |
| 398 |
next; |
| 399 |
} |
| 400 |
unless (exists $$sizeref{$$fieldnames[$i]}) { |
| 401 |
warn ("$0: No size information for column $$fieldnames[$i] found\n"); |
| 402 |
next; |
| 403 |
} |
| 404 |
if ($$typeref{$$fieldnames[$i]} == DBI::SQL_CHAR) { |
| 405 |
if (defined $values[$i]) { |
| 406 |
if (length($values[$i]) > $$sizeref{$$fieldnames[$i]}) { |
| 407 |
warn (prefix() . "Data for field $$fieldnames[$i] truncated: $values[$i]\n"); |
| 408 |
$values[$i] = substr($values[$i], 0, |
| 409 |
$$sizeref{$$fieldnames[$i]}); |
| 410 |
} |
| 411 |
} else { |
| 412 |
# avoid insertion of NULL values |
| 413 |
$values[$i] = ''; |
| 414 |
} |
| 415 |
} elsif ($$typeref{$$fieldnames[$i]} == DBI::SQL_VARCHAR) { |
| 416 |
if (defined $values[$i]) { |
| 417 |
if (length($values[$i]) > $$sizeref{$$fieldnames[$i]}) { |
| 418 |
warn (prefix() . "Data for field $$fieldnames[$i] truncated: $values[$i]\n"); |
| 419 |
$values[$i] = substr($values[$i], 0, |
| 420 |
$$sizeref{$$fieldnames[$i]}); |
| 421 |
} |
| 422 |
} else { |
| 423 |
# avoid insertion of NULL values |
| 424 |
$values[$i] = ''; |
| 425 |
} |
| 426 |
} |
| 427 |
# push (@data, $$fieldnames[$i], $values[$i]); |
| 428 |
} |
| 429 |
|
| 430 |
# check if record exists |
| 431 |
my %keymap = &key_names ($dbif, $table, $opts{'keys'}, 1); |
| 432 |
@keys = (keys(%keymap)); |
| 433 |
my @terms = map {$_ . ' = ' . $dbif->quote($values[$keymap{$_}])} |
| 434 |
(@keys); |
| 435 |
$sth = $dbif -> process ('SELECT ' . join(', ', @keys) |
| 436 |
. " FROM $table WHERE " |
| 437 |
. join (' AND ', @terms)); |
| 438 |
while ($sth -> fetch) {} |
| 439 |
|
| 440 |
if ($sth -> rows () > 1) { |
| 441 |
$" = ', '; |
| 442 |
die ("$0: duplicate key(s) @keys in table $table\n"); |
| 443 |
} |
| 444 |
|
| 445 |
$update = $sth -> rows (); |
| 446 |
$sth -> finish (); |
| 447 |
|
| 448 |
# generate SQL statement |
| 449 |
for (my $i = 0; $i <= $#$fieldnames; $i++) { |
| 450 |
# check for column exclusion |
| 451 |
if (keys %usecol) { |
| 452 |
# note: we do not check the actual value !! |
| 453 |
if ($colflag && ! exists $usecol{$$fieldnames[$i]}) { |
| 454 |
next; |
| 455 |
} |
| 456 |
if (! $colflag && exists $usecol{$$fieldnames[$i]}) { |
| 457 |
next; |
| 458 |
} |
| 459 |
} |
| 460 |
# expand newlines |
| 461 |
if (defined $values[$i]) { |
| 462 |
$values[$i] =~ s/\\n/\n/g; |
| 463 |
} |
| 464 |
push (@data, $$fieldnames[$i], $values[$i]); |
| 465 |
} |
| 466 |
|
| 467 |
if ($update) { |
| 468 |
if ($opts{'insert-only'}) { |
| 469 |
# print "SKIP UPDATING $.\n"; |
| 470 |
next; |
| 471 |
} |
| 472 |
# print "UPDATING $.\n"; |
| 473 |
$dbif -> update ($table, join (' AND ', @terms), @data); |
| 474 |
} else { |
| 475 |
if ($opts{'update-only'}) { |
| 476 |
# print "SKIP INSERTING $.\n"; |
| 477 |
next; |
| 478 |
} |
| 479 |
# print "INSERTING $.\n"; |
| 480 |
$dbif -> insert ($table, @data); |
| 481 |
} |
| 482 |
|
| 483 |
if ($opts{'cleanse'} && $update) { |
| 484 |
my ($href, $i); |
| 485 |
|
| 486 |
# now unregister key combination |
| 487 |
$href = \%recmap; |
| 488 |
# Mysql strips trailing blanks from VARCHAR fields, so we do |
| 489 |
if ($dbif->{DRIVER} eq 'mysql') { |
| 490 |
for ($i = 0; $i < @cleansekeys; $i++) { |
| 491 |
if ($$typeref{$cleansekeys[$i]} |
| 492 |
== DBI::SQL_VARCHAR) { |
| 493 |
$values[$cleansemap{$cleansekeys[$i]}] =~ s/\s+$//; |
| 494 |
} |
| 495 |
} |
| 496 |
} |
| 497 |
# data from input file may exceed column capacity |
| 498 |
for ($i = 0; $i < @cleansekeys; $i++) { |
| 499 |
if ($$typeref{$cleansekeys[$i]} == DBI::SQL_CHAR) { |
| 500 |
$values[$cleansemap{$cleansekeys[$i]}] |
| 501 |
= substr($values[$cleansemap{$cleansekeys[$i]}], |
| 502 |
0,$$sizeref{$cleansekeys[$i]}); |
| 503 |
} |
| 504 |
} |
| 505 |
for ($i = 0; $i < $#cleansekeys; $i++) { |
| 506 |
unless (exists $href->{$values[$cleansemap{$cleansekeys[$i]}]}) { |
| 507 |
die ("$0: internal error: key $cleansekeys[$i] not found: ", |
| 508 |
join (",", @values), "\n"); |
| 509 |
} |
| 510 |
$href = $href->{$values[$cleansemap{$cleansekeys[$i]}]}; |
| 511 |
} |
| 512 |
|
| 513 |
unless (exists $href->{$values[$cleansemap{$cleansekeys[$i]}]}) { |
| 514 |
die ("$0: internal error: key $cleansekeys[$i] not found: ", |
| 515 |
join (",", @values), "\n"); |
| 516 |
} |
| 517 |
if ($href->{$values[$cleansemap{$cleansekeys[$i]}]} == 0) { |
| 518 |
my $j = 0; |
| 519 |
warn (prefix () . "duplicate key(s) in input: ", |
| 520 |
join (", ", map {"$_ = \"" . $values[$cleansemap{$cleansekeys[$j++]}] . "\""} @cleansekeys) . "\n"); |
| 521 |
} |
| 522 |
$href->{$values[$cleansemap{$cleansekeys[$i]}]} = 0; |
| 523 |
} |
| 524 |
} |
| 525 |
|
| 526 |
if ($opts{'cleanse'} && ! $opts{'insert-only'}) { |
| 527 |
my $href; |
| 528 |
|
| 529 |
# now start to eliminate old records |
| 530 |
$href = \%recmap; |
| 531 |
|
| 532 |
my @keylist = keys %recmap; |
| 533 |
my (@tmpkeys, @reckeys, $thiskey, $keyval, @conds); |
| 534 |
|
| 535 |
for (keys %recmap) { |
| 536 |
push (@reckeys, [$recmap{$_}, $_]); |
| 537 |
} |
| 538 |
|
| 539 |
for (my $i = 1; $i < @cleansekeys; $i++) { |
| 540 |
@tmpkeys = @reckeys; |
| 541 |
undef @reckeys; |
| 542 |
for $thiskey (@tmpkeys) { |
| 543 |
$href = shift @$thiskey; |
| 544 |
for (keys %$href) { |
| 545 |
push (@reckeys, [$href->{$_}, @$thiskey, $_]); |
| 546 |
} |
| 547 |
} |
| 548 |
} |
| 549 |
for (@reckeys) { |
| 550 |
undef @conds; |
| 551 |
|
| 552 |
# finally delete the record |
| 553 |
next unless shift (@$_); |
| 554 |
|
| 555 |
for (my $i = 0; $i < @cleansekeys; $i++) { |
| 556 |
push (@conds, $cleansekeys[$i] . ' = ' . $dbif->quote ($_->[$i])); |
| 557 |
} |
| 558 |
|
| 559 |
$dbif -> process ("DELETE FROM $table WHERE " . join (' AND ', @conds)); |
| 560 |
} |
| 561 |
} |
| 562 |
|
| 563 |
if (length $linebuf) { |
| 564 |
if ($opts{'skipbadlines'}) { |
| 565 |
warn ("$0: unexpected EOF"); |
| 566 |
} else { |
| 567 |
die ("$0: unexpected EOF"); |
| 568 |
} |
| 569 |
} |
| 570 |
|
| 571 |
undef $dbif; |
| 572 |
|
| 573 |
if ($opts{'file'}) { |
| 574 |
$fd_input->close; |
| 575 |
} |
| 576 |
|
| 577 |
# ---------------------------------------- |
| 578 |
# FUNCTION: get_columns_tab IREF FD COLREF |
| 579 |
# |
| 580 |
# Get columns from a tab separated file. |
| 581 |
# ---------------------------------------- |
| 582 |
|
| 583 |
sub get_columns_tab { |
| 584 |
my ($iref, $fd, $colref) = @_; |
| 585 |
my $line; |
| 586 |
|
| 587 |
while (defined ($line = <$fd>)) { |
| 588 |
# skip empty/blank/comment lines |
| 589 |
next if $line =~ /^\#/; next if $line =~ /^\s*$/; |
| 590 |
# remove newlines and carriage returns |
| 591 |
chomp ($line); |
| 592 |
$line =~ s/\r$//; |
| 593 |
|
| 594 |
@$colref = split (/\t/, $line); |
| 595 |
return @$colref; |
| 596 |
} |
| 597 |
} |
| 598 |
|
| 599 |
# ---------------------------------------- |
| 600 |
# FUNCTION: get_columns_csv IREF FD COLREF |
| 601 |
# |
| 602 |
# Get columns from a CSV file. |
| 603 |
# ---------------------------------------- |
| 604 |
|
| 605 |
sub get_columns_csv { |
| 606 |
my ($iref, $fd, $colref) = @_; |
| 607 |
my ($line, $buffer); |
| 608 |
|
| 609 |
unless ($iref->{parser}) { |
| 610 |
$iref->{parser} = Text::CSV_XS->new ({'binary' => 1, 'sep_char' => ','}); |
| 611 |
} |
| 612 |
|
| 613 |
while (defined ($line = <$fd>)) { |
| 614 |
if ($iref->{parser}->parse($line)) { |
| 615 |
# csv line completed, delete buffer |
| 616 |
@$colref = $iref->{parser}->fields(); |
| 617 |
$buffer = ''; |
| 618 |
return @$colref; |
| 619 |
} |
| 620 |
|
| 621 |
if (($line =~ tr/"/"/) % 2) { |
| 622 |
# odd number of quotes, try again with next line |
| 623 |
$buffer = $line; |
| 624 |
} else { |
| 625 |
$msg = "$0: $.: line not in CSV format: " . $iref->{parser}->error_input() . "\n"; |
| 626 |
die ($msg); |
| 627 |
} |
| 628 |
} |
| 629 |
} |
| 630 |
|
| 631 |
# ---------------------------------------- |
| 632 |
# FUNCTION: get_columns_xls IREF FD COLREF |
| 633 |
# |
| 634 |
# Get columns from a XLS spreadsheet. |
| 635 |
# ---------------------------------------- |
| 636 |
|
| 637 |
sub get_columns_xls { |
| 638 |
my ($iref, $fd, $colref) = @_; |
| 639 |
|
| 640 |
unless ($iref->{workbook}) { |
| 641 |
# parse the spreadsheet once |
| 642 |
$iref->{workbook} = $iref->{object}->Parse($fd); |
| 643 |
unless ($iref->{workbook}) { |
| 644 |
die "$0: couldn't parse spreadsheet\n"; |
| 645 |
} |
| 646 |
$iref->{worksheet} = $iref->{workbook}->{Worksheet}[0]; |
| 647 |
$iref->{row} = 0; |
| 648 |
} |
| 649 |
|
| 650 |
if ($iref->{row} <= $iref->{worksheet}->{MaxRow}) { |
| 651 |
@$colref = map {defined $_ ? $_->{Val} : undef} |
| 652 |
@{$iref->{worksheet}->{Cells}[$iref->{row}++]}; |
| 653 |
return @$colref; |
| 654 |
} |
| 655 |
} |
| 656 |
|
| 657 |
# ------------------------------------------------- |
| 658 |
# FUNCTION: column_names DBIF TABLE [START] |
| 659 |
# |
| 660 |
# Returns array with column names from table TABLE |
| 661 |
# using database connection DBIF. |
| 662 |
# Optional parameter START specifies column where |
| 663 |
# the array should start with. |
| 664 |
# ------------------------------------------------- |
| 665 |
|
| 666 |
sub column_names ($$) { |
| 667 |
my ($dbif, $table, $start) = @_; |
| 668 |
my ($names, $sth); |
| 669 |
|
| 670 |
$start = 0 unless $start; |
| 671 |
|
| 672 |
if (exists $fieldmap{$table}) { |
| 673 |
$names = $fieldmap{$table}; |
| 674 |
} else { |
| 675 |
$sth = $dbif -> process ("SELECT * FROM $table WHERE 0 = 1"); |
| 676 |
$names = $fieldmap{$table} = $sth -> {NAME}; |
| 677 |
$sth -> finish (); |
| 678 |
} |
| 679 |
|
| 680 |
@$names[$start .. $#$names]; |
| 681 |
} |
| 682 |
|
| 683 |
# -------------------------------------------------- |
| 684 |
# FUNCTION: key_names DBIF TABLE KEYSPEC [HASH] |
| 685 |
# |
| 686 |
# Returns array with key names for table TABLE. |
| 687 |
# Database connection DBIF may be used to |
| 688 |
# retrieve necessary information. |
| 689 |
# KEYSPEC contains desired keys, either a numeric |
| 690 |
# value or a comma-separated list of keys. |
| 691 |
# If HASH is set, a mapping between key name |
| 692 |
# and position is returned. |
| 693 |
# -------------------------------------------------- |
| 694 |
|
| 695 |
sub key_names () { |
| 696 |
my ($dbif, $table, $keyspec, $hash) = @_; |
| 697 |
|
| 698 |
my ($numkeysleft, $i); |
| 699 |
my @columns = column_names ($dbif, $table); |
| 700 |
my (@keys, %kmap); |
| 701 |
|
| 702 |
$keyspec =~ s/^\s+//; $keyspec =~ s/\s+$//; |
| 703 |
|
| 704 |
if ($keyspec =~ /^\d+$/) { |
| 705 |
# |
| 706 |
# passed keys are numeric, figure out the names |
| 707 |
# |
| 708 |
|
| 709 |
$numkeysleft = $keyspec; |
| 710 |
|
| 711 |
for ($i = 0; $i < $numkeysleft && $i < @columns; $i++) { |
| 712 |
if (keys %usecol) { |
| 713 |
# note: we do not check the actual value !! |
| 714 |
if ($colflag && ! exists $usecol{$columns[$i]}) { |
| 715 |
$numkeysleft++; |
| 716 |
next; |
| 717 |
} |
| 718 |
if (! $colflag && exists $usecol{$columns[$i]}) { |
| 719 |
$numkeysleft++; |
| 720 |
next; |
| 721 |
} |
| 722 |
} |
| 723 |
if ($hash) { |
| 724 |
$kmap{$columns[$i]} = $i; |
| 725 |
} else { |
| 726 |
push (@keys, $columns[$i]); |
| 727 |
} |
| 728 |
} |
| 729 |
} else { |
| 730 |
# |
| 731 |
# key names are passed explicitly |
| 732 |
# |
| 733 |
|
| 734 |
my %colmap; |
| 735 |
|
| 736 |
for ($i = 0; $i < @columns; $i++) { |
| 737 |
$colmap{$columns[$i]} = $i; |
| 738 |
} |
| 739 |
|
| 740 |
for (split (/\s*,\s*/, $keyspec)) { |
| 741 |
# sanity check |
| 742 |
unless (exists $colmap{$_}) { |
| 743 |
die "$0: key \"$_\" appears not in column list\n"; |
| 744 |
} |
| 745 |
|
| 746 |
if ($hash) { |
| 747 |
$kmap{$_} = $colmap{$_}; |
| 748 |
} else { |
| 749 |
push (@keys, $_); |
| 750 |
} |
| 751 |
} |
| 752 |
} |
| 753 |
|
| 754 |
return $hash ? %kmap : @keys; |
| 755 |
} |
| 756 |
|
| 757 |
# --------------------------------------------------------- |
| 758 |
# FUNCTION: filter_input ROUTINE TABLE FIELDNAMES VALREF |
| 759 |
# |
| 760 |
# Filters data input with ROUTINE. Produces first a mapping |
| 761 |
# between FIELDNAMES and the data pointed to by VALREF |
| 762 |
# and passes the table name TABLE and the mapping to the |
| 763 |
# ROUTINE. |
| 764 |
# --------------------------------------------------------- |
| 765 |
|
| 766 |
sub filter_input { |
| 767 |
my ($routine, $table, $fieldnames, $valref) = @_; |
| 768 |
my (%colmap, $ret); |
| 769 |
|
| 770 |
# produce mapping |
| 771 |
for (my $i = 0; $i <= $#$fieldnames; $i++) { |
| 772 |
$colmap{$$fieldnames[$i]} = $$valref[$i]; |
| 773 |
} |
| 774 |
|
| 775 |
# apply filter routine |
| 776 |
$ret = &$routine ($table, \%colmap); |
| 777 |
|
| 778 |
# write new values |
| 779 |
for (my $i = 0; $i <= $#$fieldnames; $i++) { |
| 780 |
$$valref[$i] = $colmap{$$fieldnames[$i]}; |
| 781 |
} |
| 782 |
|
| 783 |
$ret; |
| 784 |
} |
| 785 |
|
| 786 |
# ------------------------------------ |
| 787 |
# FUNCTION: prefix |
| 788 |
# |
| 789 |
# Generates prefix for error messages. |
| 790 |
# ------------------------------------ |
| 791 |
|
| 792 |
sub prefix { |
| 793 |
my @frags = ($0); |
| 794 |
|
| 795 |
if ($.) { |
| 796 |
if ($opts{'file'}) { |
| 797 |
push (@frags, $opts{'file'}); |
| 798 |
} |
| 799 |
push (@frags, $.); |
| 800 |
} |
| 801 |
join (': ', @frags, ''); |
| 802 |
} |
| 803 |
|
| 804 |
# ----------------------------------- |
| 805 |
# FUNCTION: fatal |
| 806 |
# |
| 807 |
# Error handler called by DBIx::Easy. |
| 808 |
# ----------------------------------- |
| 809 |
|
| 810 |
sub fatal { |
| 811 |
my ($statement, $err, $msg) = @_; |
| 812 |
my $pwd; |
| 813 |
my $prefix = prefix (); |
| 814 |
|
| 815 |
if ($dbif->is_auth_error ($err)) { |
| 816 |
unless ($pwdused) { |
| 817 |
print "We need a password.\n"; |
| 818 |
$pwd = querypwd(); |
| 819 |
$pwdused = 1; |
| 820 |
|
| 821 |
# retry the connection |
| 822 |
if (length ($pwd)) { |
| 823 |
$dbif = new DBIx::Easy ($driver, $database, $user, $pwd); |
| 824 |
$dbif -> install_handler (\&fatal); |
| 825 |
$dbif -> connect (); |
| 826 |
return; |
| 827 |
} else { |
| 828 |
die ("$prefix$statement: $msg\n"); |
| 829 |
} |
| 830 |
} |
| 831 |
} |
| 832 |
die ("$prefix$statement: $msg\n"); |
| 833 |
} |
| 834 |
|
| 835 |
# ---------------------------- |
| 836 |
# FUNCTION: querypwd |
| 837 |
# |
| 838 |
# Queries user for a password. |
| 839 |
# ---------------------------- |
| 840 |
|
| 841 |
sub querypwd () { |
| 842 |
my $pwd; |
| 843 |
|
| 844 |
print "Password: "; |
| 845 |
ReadMode ('noecho'); # turn echo off |
| 846 |
$pwd = ReadLine (0); |
| 847 |
ReadMode ('restore'); # restore terminal |
| 848 |
print "\n"; |
| 849 |
chomp ($pwd); |
| 850 |
$pwd; |
| 851 |
} |
| 852 |
|
| 853 |
# script documentation (POD style) |
| 854 |
|
| 855 |
=head1 NAME |
| 856 |
|
| 857 |
dbs_update - Update SQL Databases |
| 858 |
|
| 859 |
=head1 DESCRIPTION |
| 860 |
|
| 861 |
dbs_update is an utility to update SQL databases from text files. |
| 862 |
|
| 863 |
=head2 FORMAT OF THE TEXT FILES |
| 864 |
|
| 865 |
dbs_update assumes that each line of the input contains a data record |
| 866 |
and that the field within the records are separated by tabulators. |
| 867 |
You can tell dbs_update about the input format with the B<--format> |
| 868 |
option. |
| 869 |
|
| 870 |
The first field of the data record is used as table specification. |
| 871 |
These consists of the table name and optionally the index of starting |
| 872 |
column, separated by a dot. |
| 873 |
|
| 874 |
Alternatively dbs_update can read the column names from the first line |
| 875 |
of input (see the B<-h>/B<--headline> option). These can even be aliases |
| 876 |
for the real column names (see the B<-m>/B<--map> option). |
| 877 |
|
| 878 |
=head1 COMMAND LINE PARAMETERS |
| 879 |
|
| 880 |
Required command line parameters are the DBI driver |
| 881 |
(C<Pg> for Postgres or C<mysql> for MySQL) |
| 882 |
and the database name. The third parameter is optionally |
| 883 |
and specifies the database user and/or the host where the |
| 884 |
database resides (C<racke>, C<[email protected]> or C<@linuxia.de>). |
| 885 |
|
| 886 |
=head1 OPTIONS |
| 887 |
|
| 888 |
=head2 B<--cleanse> |
| 889 |
|
| 890 |
I<Removes> all records which remain unaffected from the update |
| 891 |
process. The same result as deleting all records from the table |
| 892 |
first and then running dbs_update, but the table is not empty |
| 893 |
in the meantime. |
| 894 |
|
| 895 |
=head2 B<-c> I<COLUMN,COLUMN,...>, B<--columns>=I<COLUMN,COLUMN,...> |
| 896 |
|
| 897 |
Update only the table columns given by the I<COLUMN> parameters. |
| 898 |
To exclude columns from the update prepend C<!> or C<^> to the |
| 899 |
parameters. |
| 900 |
|
| 901 |
=head2 B<--rows>=I<ROW,ROW,...> |
| 902 |
|
| 903 |
Update only the input rows given by the I<ROW> parameters. |
| 904 |
The first row is 1 where headlines doesn't count. |
| 905 |
To exclude rows from the update prepend C<!> or C<^> to the |
| 906 |
parameters. |
| 907 |
|
| 908 |
=head2 B<-f> I<FILE>, B<--file>=I<FILE> |
| 909 |
|
| 910 |
Reads records from file I<FILE> instead of from standard input. |
| 911 |
|
| 912 |
=head2 B<--format>=I<FORMAT[SEPCHAR]> |
| 913 |
|
| 914 |
Assumes I<FORMAT> as format for the input. Only B<CSV> can be |
| 915 |
specified for now, default is B<TAB>. The default field |
| 916 |
separator for B<CSV> is a comma, you may change this by |
| 917 |
appending the separator to the format. |
| 918 |
|
| 919 |
=head2 B<-h>, B<--headline> |
| 920 |
|
| 921 |
Reads the column names from the first line of the input instead |
| 922 |
of dedicting them from the database layout. Requires the |
| 923 |
B<-t/--table> option. |
| 924 |
|
| 925 |
=head2 B<-i>, B<--insert-only> |
| 926 |
|
| 927 |
Insert new database entries only, skip others. |
| 928 |
|
| 929 |
=head2 B<-k> I<COUNT>, B<-k> I<KEY,KEY,...>, B<--keys>=I<COUNT>, B<--keys>=I<KEY,KEY,...> |
| 930 |
|
| 931 |
Specifies the keys for the table(s) either as the number of columns |
| 932 |
used as keys or by specifying them explicitly as comma separated |
| 933 |
arguments to the option. |
| 934 |
This is used for the detection of existing records. |
| 935 |
|
| 936 |
=head2 B<-m> I<ALIASDEF>, B<--map>=I<ALIASDEF> |
| 937 |
|
| 938 |
Maps the names found in the first line of input to the actual column |
| 939 |
names in the database. The alias and the column name are separated |
| 940 |
with C<=> signs and the different entries are separated by C<;> signs, |
| 941 |
e.g. C<Art-No.=code;Short Description=shortdescr'>. |
| 942 |
|
| 943 |
=head2 B<--map-filter>=I<FILTER> |
| 944 |
|
| 945 |
Applies a filter to the column names read from the input file. |
| 946 |
Currently there is only the C<lc> filter available. |
| 947 |
|
| 948 |
=head2 B<--match-sql>=I<FIELD:{STATEMENT}> |
| 949 |
|
| 950 |
Updates only records where the value of the column I<FIELD> is in |
| 951 |
the result set of the SQL statement I<STATEMENT>, |
| 952 |
e.g. C<category:{select distinct name from categories}>. |
| 953 |
|
| 954 |
=head2 B<-o>, B<--update-only> |
| 955 |
|
| 956 |
Updates existing database entries only, stops if it detects |
| 957 |
new ones. |
| 958 |
|
| 959 |
=head2 B<-r> I<ROUTINE>, B<--routine>=I<ROUTINE> |
| 960 |
|
| 961 |
Applies I<ROUTINE> to any data record. I<ROUTINE> must be a subroutine. |
| 962 |
dbs_update passes the table name and a hash reference to this subroutine. |
| 963 |
The keys of the hash are the column names and the values are the |
| 964 |
corresponding field values. If the return value of I<ROUTINE> is not |
| 965 |
a truth value, the data record will be skipped. |
| 966 |
|
| 967 |
C<sub {my ($table, $valref) = @_; |
| 968 |
unless (defined $$valref{country} && $$valref{country} !~ /\S/) { |
| 969 |
$$valref{country} = "Germany"; |
| 970 |
} |
| 971 |
1; |
| 972 |
}> |
| 973 |
|
| 974 |
=head2 B<--skipbadlines> |
| 975 |
|
| 976 |
Lines not matching the assumed format are ignored. Without this |
| 977 |
option, dbs_update simply stops. |
| 978 |
|
| 979 |
=head2 B<-t> I<TABLE>, B<--table>=I<TABLE> |
| 980 |
|
| 981 |
Uses I<TABLE> as table name for all records instead of the |
| 982 |
first field name. |
| 983 |
|
| 984 |
=head1 AUTHOR |
| 985 |
|
| 986 |
Stefan Hornburg (Racke), [email protected] |
| 987 |
|
| 988 |
=head1 SEE ALSO |
| 989 |
|
| 990 |
perl(1), DBIx::Easy(3) |
| 991 |
|
| 992 |
=cut |