#!/usr/bin/perl #myrestore: a tool to restore data dumped by mybackup #by Marc Swanson #please note that this is not blob column safe. To restore #your blob column types, you'd need to use the "load_file" #string command on the contents of your blob field. #I'll modify this code when I get the chance. Anyone wishing #to include the mod is welcome and encouraged to send me the source :) use DBI; my $dbuser = "root"; my $dbpass = ""; if($#ARGV < 0) { useage(); } my $base_dir = $ARGV[0]; if(!-d $base_dir) { die "given database directory [$base_dir] does not seem to exist.\n"; } if($base_dir =~ /^(.*?)\/$/) { $base_dir = $1; #strip trailing slash } my @dbnames; if($#ARGV >= 1) { for(my $i=1;$i<=$#ARGV;$i++) { my $db_arg = $ARGV[$i]; if(!-d "$base_dir/$db_arg") { die "The specified database: [$db_arg] does not exist.\n"; } push(@dbnames,$db_arg); } } sub useage { print "Usage: myrestore mybackup_directory_name [dbname1] [dbname2] [dbname...]\n"; exit; } $dbh = DBI->connect("dbi:mysql:dbname=mysql", $dbuser, $dbpass) || die "Could not connect to database: $DBI::errstr"; opendir DIR, "$base_dir" or die "could not open $base_dir for read: $!\n"; while(defined ($dbname = readdir(DIR))) { if(-d "$base_dir/$dbname") { #this should be the name of a database if($#dbnames >= 0) { #check to make sure this db is in our list my $found = 0; for(my $i=0;$i<@dbnames;$i++) { if($dbnames[$i] eq $dbname) { $found = 1; last; } } if($found == 0) { next; } } print "Processing database: $dbname\n"; opendir DBDIR, "$base_dir/$dbname" or die "could not open $base_dir/$dbname for read: $!\n"; while(defined ($file = readdir(DBDIR))) { if($file =~ /(\S+)\.txt/ && -e "$base_dir/$dbname/$1.sql") { #this appears to be a valid db import file $tablename = $1; print "\tProcessing table: $tablename\n"; $query = "load data local infile '$base_dir/$dbname/$file' " . 'ignore into table ' . $dbname . '.' . $tablename . ' fields terminated by \'\t\' enclosed by \'"\''; $dbh->do($query); } } closedir(DBDIR); } } closedir(DIR); $dbh->disconnect()