DEV Community

Query Filter
Query Filter

Posted on

perl5

!/usr/bin/perl

use strict;
use warnings;

my $sql = '';
{
local $/;
if (-t STDIN) {
my $file = shift @ARGV or die "Usage: $0 \n";
open my $fh, '<', $file or die "Cannot open $file: $!";
$sql = <$fh>;
close $fh;
} else {
$sql = ;
}
}

my @keywords = (
'SELECT', 'FROM', 'WHERE', 'GROUP BY', 'HAVING', 'ORDER BY', 'UNION',
'JOIN', 'LEFT JOIN', 'RIGHT JOIN', 'INNER JOIN', 'OUTER JOIN',
'AND', 'OR', 'ON', 'INTO', 'VALUES', 'SET', 'WHEN', 'ELSE', 'END'
);

$sql =~ s/[\r\n]+/ /g;
$sql =~ s/\s+/ /g;

foreach my $kw (@keywords) {
my $pattern = quotemeta($kw);
$sql =~ s/\b$pattern\b/\n$kw/ig;
}

foreach my $kw (@keywords) {
my $lc = lc($kw);
$sql =~ s/\b$lc\b/\U$kw\E/ig;
}

my @lines = split /\n+/, $sql;
my $indent = 0;
my @out;

foreach my $line (@lines) {
my $opens = ($line =~ tr/(//) || 0;
my $closes = ($line =~ tr/)//) || 0;

$indent-- if $closes > $opens;
push @out, ('    ' x ($indent > 0 ? $indent : 0)) . $line;
$indent++ if $opens > $closes;
$indent = 0 if $indent < 0;
Enter fullscreen mode Exit fullscreen mode

}

for my $line (@out) {
$line =~ s/^\s+//;
$line =~ s/\s+$//;
}

print join("\n", @out), "\n";

Top comments (0)