Created
June 14, 2013 15:28
-
-
Save mfontani/5782744 to your computer and use it in GitHub Desktop.
Beautify DBIC_TRACE=1 dumped SQL to a human readable format which doesn't suck
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
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use SQL::Beautify; | |
use 5.010_001; | |
# Whether or not to replace "?" in the given SQL with the | |
# values contained at the end of the SQL, a la: | |
# SELECT foo FROM bar WHERE baz = ? ORDER BY foo DESC: 'barbaz' | |
# becomes: | |
# SELECT foo FROM bar WHERE baz = 'barbaz' ORDER BY foo DESC | |
# and then gets beautified to: | |
# SELECT | |
# foo | |
# FROM | |
# bar | |
# WHERE | |
# baz = 'barbaz' | |
# ORDER BY | |
# foo DESC | |
my $replace_placeholders = shift; | |
my $input = do { local $/ = undef; <>; }; | |
$input = replace_placeholders($input) | |
if $replace_placeholders; | |
my $sql = SQL::Beautify->new; | |
$sql->query($input); | |
my $nice_sql = $sql->beautify; | |
print $nice_sql; | |
sub replace_placeholders { | |
my $input = shift; | |
if ($input =~ /(?<strip>: (?<values>('[^']+',? ?)+))\s*$/s) { | |
my ($strip, $values) = @+{qw<strip values>}; | |
my @values = split(', ', $values); | |
my $i = index($input, $strip); | |
substr($input, $i, length $strip) = ''; | |
for my $value (@values) { | |
my $i = index($input, '?'); | |
substr($input, $i, 1) = $value; | |
} | |
} | |
return $input; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment