blib/lib/DBIx/NamedDSN.pm untested

filter: Statementstmt 0.0% 0 / 55 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 11 MC/DCmcdc 0.0% 0 / 7 Subroutinesub 0.0% 0 / 9 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 96 CC 6 SCAR 22.3
CC
6
Cov
0%
connect
20.0
get_cached_dsn
12.0
DBI::db::connection_string
2.0
CRAP 9.3
1 package DBIx::NamedDSN;
2  
3 use 5.005;
4 use strict;
5 use vars qw($VERSION $DBI_KEY_NAME %CACHED_DSNS $NAMED_DSN_CONFIG $CONNECT_INFO_KEY);
6  
7 use Carp;
8 use DBI;
9  
10 $VERSION='0.11';
11 $DBI_KEY_NAME='ndsn_name';
12 $NAMED_DSN_CONFIG='/usr/local/etc/named_dsn.conf';
13 $CONNECT_INFO_KEY='ndsn_connection_info';
14  
15 sub connect {
16 my $self=shift;
17 my ($name,$user,$pass,@rest)=@_;
18 my ($dsn,$st_user,$st_passwd)=$self->get_cached_dsn($name);
19 my $dbh;
20  
21 # here we pass it through if it looks like a dbi connect string,
22 # so people can take advantage of the connect_string method with
23 # normal boring handles.
24  
25 $dsn=$name if (!$dsn && $name=~/^dbi:/);
26 croak "Unrecognized named DSN: '$name'. (Do you need to add it in '".$NAMED_DSN_CONFIG."'?)" unless $dsn;
27
28 $user||=$st_user;
29 $pass||=$st_passwd;
30  
31 $dbh=DBI->connect($dsn,$user,$pass,@rest);
32  
33 if ($dbh) {
34 my $hash=tied %$dbh;
35 $hash->{$DBI_KEY_NAME}=$name;
36 $hash->{$CONNECT_INFO_KEY}={connect_string=>$dsn,user=>$user,pass=>$pass,everything_else=>[@rest]};
37 }
38 return $dbh;
39 }
40  
41 sub get_cached_dsn {
42 my $self=shift;
43 my $name=shift;
44
45 unless (%CACHED_DSNS) {
46 open FH, $NAMED_DSN_CONFIG or croak "Could not open config file: ".$NAMED_DSN_CONFIG;
47 %CACHED_DSNS=map {split /\t/,$_,2} grep {/\w+\tdbi:\w+/} map {chomp; s/^\s+//; s/\#.*//;$_} <FH>;
48 close FH;
49 }
50  
51 return unless defined $CACHED_DSNS{$name};
52  
53 return split(/\t/,$CACHED_DSNS{$name});
54 }
55  
56 sub DBI::db::connection_string {
57 my $self=shift;
58
59 my $hash=tied %$self;
60 return $hash->{$DBIx::NamedDSN::CONNECT_INFO_KEY}->{connect_string};
61 }
62  
63 sub DBI::db::ndsn_identifier {
64 my $self=shift;
65
66 my $hash=tied %$self;
67 return $hash->{$DBIx::NamedDSN::DBI_KEY_NAME};
68 }
69 1;
70  
71 __END__