1#!perl
2
3use DBI;
4use Getopt::Std;
5use strict;
6
7use constant PROMPT          => 'pgsql.PP> ';
8use constant WELCOME_MESSAGE => "Welcome to the DBD::PgPP monitor. Type 'quit' for quit pgsql.PP.\n";
9use constant QUIT_MESSAGE    => "Bye\n";
10
11
12my %option;
13getopts '?vh:u:dP:', \%option;
14my $database = shift;
15show_version() if $option{v};
16show_usage()   if $option{'?'} || ! defined $database;
17$option{u} ||= $ENV{USER};
18$option{P} ||= 5432;
19
20my $password;
21system 'stty -echo';
22print 'Enter password: ';
23chomp($password = <STDIN>);
24system 'stty echo';
25print "\n";
26
27my $dbh;
28eval {
29	$dbh = DBI->connect(
30		"dbi:PgPP:database=$database;hostname=$option{h};port=$option{P};debug=$option{d}",
31		$option{u}, $password, {
32			RaiseError => 1, PrintError => 0
33	});
34};
35die $@ if $@;
36
37print WELCOME_MESSAGE;
38print PROMPT;
39while (my $query = <>) {
40	chomp $query;
41	last if $query =~ /^(?:q(?:uit)?|exit|logout|logoff)$/i;
42	if ($query !~ /^\s*$/) {
43		eval {
44			my $sth = $dbh->prepare($query);
45			my $rc = $sth->execute;
46			if ($query =~ /select /i) {
47				while (my $row = $sth->fetch) {
48					printf "%s\n", join ', ', @$row;
49				}
50			}
51			elsif ($query =~ /insert /i) {
52				printf "insert %d records. last index: %d\n",
53					$sth->rows, $dbh->{pgpp_insertid};
54			}
55			else {
56				printf "update %d records.\n",
57					$sth->rows;
58			}
59		};
60		if ($@) {
61			print $dbh->errstr, "\n";
62		}
63	}
64	print PROMPT;
65}
66
67print QUIT_MESSAGE;
68$dbh->disconnect;
69exit;
70
71
72sub show_usage
73{
74	die <<__USAGE__;
75Usage: pgsql.pl [-?vd] [-h HOSTNAME] [-u USER] DATABASE
76
77  -?   Display this help and exit.
78  -h   Connect to host.
79  -d   Show Debug information.
80  -u   User for login if not current user.
81  -v   Output version information and exit.
82
83  Example:
84    % pgsql.pl -u root mydatabase
85__USAGE__
86}
87
88sub show_version
89{
90	die <<__VERSION__;
91$0  Ver $DBI::PgPP::VERSION
92__VERSION__
93}
94
95__END__
96