Skip to content

Instantly share code, notes, and snippets.

@agramajo
Created April 15, 2015 14:14
Show Gist options
  • Save agramajo/7268a5432c0e9ad3ff9a to your computer and use it in GitHub Desktop.
Save agramajo/7268a5432c0e9ad3ff9a to your computer and use it in GitHub Desktop.
optimize mysql tables
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