-
-
Save Juerd/92522e8b155c3656fd42 to your computer and use it in GitHub Desktop.
A naïve db client in Perl 6
This file contains hidden or 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 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