Skip to content

Instantly share code, notes, and snippets.

@Ovid
Last active January 22, 2016 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ovid/43c131642b82f202d977 to your computer and use it in GitHub Desktop.
Save Ovid/43c131642b82f202d977 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 my $query = get-query() {
my (@cols,@rows,$num-rows) := get-cols-and-rows-from-query($query);
say lol2table(@cols,@rows).join("\n");
if @rows.elems != $num-rows {
say "Showing {ROW-LIMIT} out of $num-rows rows";
}
CATCH {
default {
say "Error executing query: $_", Backtrace.new.concise;
}
}
$query = '';
}
linenoiseHistorySave(HIST-FILE);
sub get-query () {
my $query = '';
while my $line = linenoise '?- ' {
return if $line ~~ / \\q \s* $ / {
$query ~= $line ~ "\n";
last if $line ~~ / ';' \s* $ /;
}
$query = $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 @cols = @rows.[0].keys;
@rows = @rows.map: {.values};
my $num-rows = @rows.elems;
if @rows > ROW-LIMIT {
@rows = @rows[^ROW-LIMIT];
}
return @cols, @rows, $num-rows;
}
@con-mo8
Copy link

con-mo8 commented Jan 22, 2016

Line 34 the { should be a ; fairly sure

@dakkar
Copy link

dakkar commented Jan 22, 2016

line 52: you seem to be depending on @rows[*].values always returning things in the same order as @rows[0].keys; while this is certainly guaranteed for @rows[0], I see no reason why it should work for the other hashes.
Maybe:

@rows = @rows.map: { .{@cols} };

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment