Skip to content

Instantly share code, notes, and snippets.

@Juerd
Forked from Ovid/db-shell.p6
Last active January 22, 2016 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Juerd/92522e8b155c3656fd42 to your computer and use it in GitHub Desktop.
Save Juerd/92522e8b155c3656fd42 to your computer and use it in GitHub Desktop.
A naïve db client in Perl 6
# a rewrite of http://blogs.perl.org/users/ovid/2016/01/a-naive-sql-shell.html in Perl 6
use v6;
use DBIish;
use Linenoise;
use Text::Table::Simple;
my constant HIST-FILE = '.myhist';
my constant HIST-LEN = 100;
my constant ROW-LIMIT = 100;
linenoiseHistoryLoad(HIST-FILE);
linenoiseHistorySetMaxLen(HIST-LEN);
while get-query -> $query {
my (@cols, @rows, $num-rows) := get-cols-and-rows-from-query($query);
say lol2table(@cols, @rows).join("\n");
say "Showing {ROW-LIMIT} out of $num-rows rows" if @rows < $num-rows;
CATCH {
say "Error executing query: $_", Backtrace.new.concise;
}
}
linenoiseHistorySave(HIST-FILE);
sub get-query {
my $query = '';
while linenoise '?- ' -> $line {
return if $line ~~ / \\q \s* $ / {
$query ~= "$line\n";
last if $line ~~ / ';' \s* $ /;
}
$query .= chomp;
linenoiseHistoryAdd($query);
return $query;
}
sub get-cols-and-rows-from-query (Str $query) {
state $dbh = DBIish.connect: 'Pg', :database<...>, :user<...>, :RaiseError;
my $sth = $dbh.prepare($query);
$sth.execute;
my @rows = $sth.allrows(:array-of-hash);
$sth.finish;
my $num-rows = @rows.elems;
my @cols = @rows[0].keys;
@rows .= map: *.values;
@rows .= head(ROW-LIMIT) if @rows > ROW-LIMIT;
return @cols, @rows, $num-rows;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment