ShellKit/DBI.pm untested

filter: Statementstmt 0.0% 0 / 65 Branchbran 0.0% 0 / 20 Conditioncond 0.0% 0 / 15 MC/DCmcdc 0.0% 0 / 9 Subroutinesub 0.0% 0 / 14 Podpod 0.0% 0 / 10 totaltotal 0.0% 0 / 133 CC 11 SCAR 25.2
CC
11
Cov
0%
dbi_do
30.0
dbi_connect
20.0
dbi_fetch
12.0
CRAP 12.4
1 package Term::ShellKit::DBI;
2  
3 require Term::ShellKit;
4 use DBI;
5 use Data::ShowTable;
6  
7 ######################################################################
8  
9 use vars qw( $Connection );
10  
11 sub dbi_connect {
12 if ( ! scalar @_ ) {
13 $_[0] ||= &{ $Term::ShellKit::SubReadLine }( "DBI connect string: " );
14 $_[1] ||= &{ $Term::ShellKit::SubReadLine }( "DBI user name: " ) if ( $_[0] );
15 $_[2] ||= &{ $Term::ShellKit::SubReadLine }( "DBI password: " ) if ( $_[1] );
16 }
17 $_[3] ||= { RaiseError => 1 };
18
19 $Connection = DBI->connect( @_ );
20 }
21  
22 ########################################################################
23  
24 sub dbi_execute {
25 my $sql = shift;
26 dbi_connect() unless $Connection;
27
28 my $count = ( $sql =~ tr[?][?] );
29 my @params;
30 my $p_i = 1;
31 foreach ( 1 .. $count ) {
32 push @params, &{ $Term::ShellKit::SubReadLine }( "Parameter $p_i: " );
33 $p_i ++;
34 }
35
36 my $sth = $Connection->prepare_cached( $sql );
37 my $rv = $sth->execute(@params);
38 $sth, $rv;
39 }
40  
41 sub dbi_do ($) {
42 my $sql = shift;
43 my ($sth, $rv) = dbi_execute( $sql );
44 $sth->finish;
45 defined($rv) ? "Query affected ". ($rv < 0 ? 'unknown number of rows' : $rv < 1 ? 'no rows' : $rv < 2 ? '1 row' : ( $rv + 0) . " rows") : "Query failed";
46 }
47  
48 sub dbi_fetch ($) {
49 my $sql = shift;
50 my ($sth, $rv) = dbi_execute( $sql );
51 my $cols = $sth->{'NAME'};
52 my $types = eval { $sth->{'TYPE'} } || [ ( 'varchar' ) x $#$cols ];
53 my $lengths = eval { $sth->{'PRECISION'} } || [ ( 32 ) x $#$cols ];
54 my $rows = $sth->fetchall_arrayref( {} );
55 $sth->finish;
56
57 my $i = 0;
58 ShowBoxTable(
59 $cols,
60 $types,
61 $lengths,
62 sub {
63 if ( shift ) { $i = 0; return 1 }
64 my $row = $rows->[ $i++ ];
65 return unless $row;
66 map $row->{$_}, @$cols
67 }
68 );
69 return;
70 }
71  
72 ########################################################################
73  
74 sub select ($) { dbi_fetch( "select $_[0]" ) }
75 sub update ($) { dbi_do( "update $_[0]" ) }
76 sub insert ($) { dbi_do( "insert $_[0]" ) }
77 sub delete ($) { dbi_do( "delete $_[0]" ) }
78 sub create ($) { dbi_do( "create $_[0]" ) }
79 sub drop ($) { dbi_do( "drop $_[0]" ) }
80  
81 ########################################################################
82  
83 1;
84  
85 __END__