Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@kamipo
Last active August 29, 2015 14:03
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamipo/839e8a5b6d12bddba539 to your computer and use it in GitHub Desktop.
Save kamipo/839e8a5b6d12bddba539 to your computer and use it in GitHub Desktop.
package MySQLCasualLog;
use strict;
use warnings;
use utf8;
use DBIx::QueryLog;
use Term::ANSIColor;
use Text::ANSITable;
our $COLOR = "bold red";
{
my $orig_logging = *DBIx::QueryLog::_logging{CODE};
my @explain_cols = qw/id select_type table type possible_keys key key_len ref rows Extra/;
sub explained_logging {
my ($class, $dbh, $ret, $time, $bind_params, $explain) = @_;
my $rows;
my $badquery = 0;
if ($explain) {
$rows = $explain->();
for my $row (@$rows) {
if ($row->{select_type}) {
$row->{select_type} =~ s{
DEPENDENT\sUNION
| DEPENDENT\sSUBQUERY
| UNCACHEABLE\sUNION
| UNCACHEABLE\sSUBQUERY
}{
colored([$COLOR], $&)
}ex
and $badquery++;
}
if ($row->{type}) {
$row->{type} =~ s{
index | ALL
}{
colored([$COLOR], $&)
}ex
and $badquery++;
}
unless ($row->{possible_keys}) {
$row->{possible_keys} = colored([$COLOR], 'NULL');
$badquery++;
}
unless ($row->{key}) {
$row->{key} = colored([$COLOR], 'NULL');
$badquery++;
}
if ($row->{Extra}) {
$row->{Extra} =~ s{
Using\sfilesort
| Using\stemporary
}{
colored([$COLOR], $&)
}exg
and $badquery++;
}
}
}
if ($ENV{BADQUERY_ONLY} and $badquery == 0) {
# nothing badquery
} else {
$explain = $ENV{HIDE_EXPLAIN} ? undef : sub {
my %args = @_;
return $rows unless $args{print};
my $t = Text::ANSITable->new();
$t->border_style('Default::single_ascii');
$t->columns([@explain_cols]);
$t->add_row([map { defined($_) ? $_ : 'NULL' } @{$_}{@explain_cols}]) for @$rows;
$t->draw;
};
my $orig_color = DBIx::QueryLog->color;
DBIx::QueryLog->color($COLOR);
$orig_logging->($class, $dbh, $ret, $time, $bind_params, $explain);
DBIx::QueryLog->color($orig_color);
}
}
no warnings 'redefine';
*DBIx::QueryLog::_logging = \&explained_logging;
}
DBIx::QueryLog->explain(1);
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment