Skip to content

Instantly share code, notes, and snippets.

@Ovid
Last active January 22, 2016 10:04
Show Gist options
  • Save Ovid/ac863b28ef9c2251cf0c to your computer and use it in GitHub Desktop.
Save Ovid/ac863b28ef9c2251cf0c to your computer and use it in GitHub Desktop.
A Naïve SQL Client
#!/usr/bin/env perl
use warnings;
use 5.18.0;
use Term::ReadLine;
use Term::ReadKey;
use Try::Tiny;
use Text::Table;
use Term::ANSIColor;
use DBI;
my $dbh = DBI->connect(...)
my $LIMIT = 100;
my $term = Term::ReadLine->new('Naïve SQL Shell');
my $query = '';
while (1) {
$query .= $term->readline("?- ") . "\n";
exit if $query =~ /\\q*$/i; # immediate exit on \q
next unless $query =~ /;\s*$/;
$term->addhistory($query);
try {
my $results = $dbh->selectall_arrayref($query);
my $truncated = 0;
if ( @$results > $LIMIT ) {
$truncated = @$results;
@$results = @{$results}[ 0 .. $LIMIT - 1 ];
}
my $table = Text::Table->new;
$table->load(@$results);
print $table;
say STDERR "Showing $LIMIT out of $truncated results" if $truncated;
}
catch {
say colored( ['red on_bright_yellow'], "Query failed: $_" );
};
$query = '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment