Sunteți pe pagina 1din 2

#!

/usr/bin/perl -w

use strict;
use warnings;

use Data::Dumper;

# take the total time to do the job


my $home_dir = $ENV{'HOME'};

# Use less -niSFX as the default config


my $is_config_present = 0;
my $pager_command = 'less -niSFX';

my @regexes;
my $config_file = "$home_dir/.mysmartpager";
my $tee_file = "$home_dir/.mysqltee";

if ( -e "$config_file" ) {
$is_config_present = 1;
open( CONFIG, "<$config_file" );
while ( <CONFIG> ) {
chomp; # no newline
s/#.*//xm; # no comments
s/^\s+//xm; # no leading white
s/\s+$//xm; # no trailing white
next unless length; # anything left?
my ( $command, $regex )
= split( /\=/, $_, 2 ); # command = regex model
$command =~ s/\s+$//xm;
$regex =~ s/^\s+//xm;

if ( $regex ) {
push @regexes,
{ 'regex' => $regex, 'command' => $command };
}
}
}

my $input = '';
while ( <> ) {
$input .= $_;
}

# Write the complete input to a temp file, always helps


open PAGER_LOG, '>/tmp/mysql_pager.log';
print PAGER_LOG "$input\n";
close PAGER_LOG;

# This is to fool mysql client that smartpager has finished the job and will
resume to
# tee-ing the data to the $tee_file.
exit if fork;

# Child process should sleep for a small time giving mysql client enough time to
write to
# tee_file
sleep(1);
print "\n";

# Get the mysql command from tee file


# CAUTION: In case you are using a custom prompt,change this code. I'm too lazy to
write code for automation.
my $mysql_command = `grep '^mysql>' $tee_file | tail -n 1`;
$mysql_command =~ s/^mysql>//xm;

# Pass and test the command against all the regular expressions one by one and
stop when it matches
if ( $is_config_present ) {
foreach my $regex ( @regexes ) {
if ( $mysql_command =~ /$regex->{'regex'}/xmi ) {
$pager_command = $regex->{'command'};
last;
}
}
}

eval {
local $SIG{'__WARN__'};
system "$pager_command /tmp/mysql_pager.log 2>/dev/null";
};

# truncate the tee file. this will optimize grep :)


system "echo '' > $tee_file";

S-ar putea să vă placă și