Skip to content

Instantly share code, notes, and snippets.

@kamichidu
Created August 7, 2013 23:25
Show Gist options
  • Save kamichidu/6179929 to your computer and use it in GitHub Desktop.
Save kamichidu/6179929 to your computer and use it in GitHub Desktop.
use 5.010;
use utf8;
use strict;
use warnings;
use Carp qw/croak cluck/;
use IPC::Open2;
use Time::HiRes qw/gettimeofday tv_interval/;
use Data::Dumper;
use Devel::Peek;
use Encode qw/decode/;
use constant {
term_encoding => 'utf8',
db_host => 'localhost',
db_port => 5432,
db_username => 'postgres',
db_dbname => 'test',
};
local $|= 1;
binmode STDIN => ':encoding(' . term_encoding . ')';
binmode STDOUT => ':encoding(' . term_encoding . ')';
sub measure(&@)
{
my ($code_ref, @args)= @_;
my $start_time= [gettimeofday];
my @result= $code_ref->(@args);
my $end_time= [gettimeofday];
return (
tv_interval($start_time, $end_time),
@result,
);
}
sub read_until(*$)
{
my ($in, $eoq)= @_;
my @result;
while(my $line= <$in>)
{
last if $line ~~ $eoq;
push @result, $line;
}
chomp @result;
my $buffer= join "\n", @result;
$buffer= decode term_encoding, $buffer;
@result= split /\n/, $buffer;
return @result;
}
sub new_table_info($)
{
my ($line)= @_;
return unless $line;
my @elms= split /\|/, $line;
$_=~ s/^\s+|\s+$//mg for @elms;
return {
schema => $elms[0],
name => $elms[1],
type => $elms[2],
owner => $elms[3],
size => $elms[4],
comment => $elms[5],
};
}
my ($pout, $pin);
open2 $pout, $pin, 'psql', '--host', db_host, '--port', db_port, '--username', db_username, '--dbname', db_dbname, '--no-password' or die $!;
say $pin '\encoding ', term_encoding;
say $pin '\t on';
say $pin '\echo ---end-of-query---';
read_until $pout, qr/^---end-of-query---$/m;
my ($interval, @tinfos);
($interval, @tinfos)= measure {
say $pin '\dS+';
say $pin '\echo ---end-of-query---';
my @tables= read_until $pout, qr/^---end-of-query---$/m;
@tinfos= map { new_table_info($_); } @tables;
@tinfos= grep { $_->{schema} eq 'public' } @tinfos;
};
say $interval;
{
local $Data::Dumper::Purity= 1;
say Data::Dumper::Dumper @tinfos;
}
Dump $_ for @tinfos;
say $_->{comment} for @tinfos;
say $pin '\q';
close $pout or die $!;
close $pin or die $!;
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment