Last active
January 22, 2016 16:10
-
-
Save Ovid/43c131642b82f202d977 to your computer and use it in GitHub Desktop.
A naïve db client in Perl 6
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
# 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; | |
} |
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
Line 34 the { should be a ; fairly sure