Created
April 15, 2015 14:14
-
-
Save agramajo/7268a5432c0e9ad3ff9a to your computer and use it in GitHub Desktop.
optimize mysql tables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use vars qw/ $f /; | |
use DBI; | |
my $fix = $f || 0; | |
my $dbname = $ARGV[0] || "mysql"; | |
my $dbuser = $ARGV[1] || "root"; | |
my $dbpass = $ARGV[2] || "pass"; | |
my $dbhost = $ARGV[3] || "localhost"; | |
my $socket = ""; | |
my $dsn = "DBI:mysql:database=$dbname;host=$dbhost;mysql_socket=$socket"; | |
my $dbh = DBI->connect($dsn, $dbuser, $dbpass); | |
my $sth = $dbh->prepare('show databases'); | |
$sth->execute(); | |
my @dbases; | |
while(my @vec = $sth->fetchrow_array()) { | |
push @dbases, $vec[0]; | |
} | |
foreach my $db (@dbases) { | |
print "database: $db\n"; | |
my $sth = $dbh->prepare('SHOW TABLE STATUS FROM ' . $db); | |
$sth->execute(); | |
my @to_optimize; | |
while(my $hash = $sth->fetchrow_hashref()) { | |
if ($hash->{'Data_free'} > 0) { | |
print "\t $hash->{'Name'} table needs optimization\n"; | |
push @to_optimize, $hash->{'Name'}; | |
} | |
} | |
foreach my $tbl (@to_optimize) { | |
$dbh->do('OPTIMIZE TABLE ' . $db . "." . $tbl) if $fix; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment