| 1 | |||
| 2 | package DBIx::Romani::Connection::Factory; | ||
| 3 | |||
| 4 | use DBIx::Romani::Connection; | ||
| 5 | use DBI; | ||
| 6 | use strict; | ||
| 7 | |||
| 8 | sub new | ||
| 9 | { | ||
| 10 | my $class = shift; | ||
| 11 | my $args = shift; | ||
| 12 | |||
| 13 | my $dbh; | ||
| 14 | my $dsn; | ||
| 15 | my $username; | ||
| 16 | my $password; | ||
| 17 | my $driver; | ||
| 18 | |||
| 19 | if ( ref($args) eq 'HASH' ) | ||
| 20 | { | ||
| 21 | $dbh = $args->{dbh}; | ||
| 22 | $dsn = $args->{dsn}; | ||
| 23 | $username = $args->{username}; | ||
| 24 | $password = $args->{password}; | ||
| 25 | $driver = $args->{driver}; | ||
| 26 | } | ||
| 27 | |||
| 28 | if ( not defined $dbh and not defined $dsn ) | ||
| 29 | { | ||
| 30 | # Programmer error | ||
| 31 | die "Must defined either a dsn or dbh"; | ||
| 32 | } | ||
| 33 | if ( defined $dsn and defined $dbh ) | ||
| 34 | { | ||
| 35 | # Programmer error | ||
| 36 | die "Cannot defined both a dsn and dbh"; | ||
| 37 | } | ||
| 38 | if ( not defined $driver ) | ||
| 39 | { | ||
| 40 | # Programmer error | ||
| 41 | die "Must define the connection driver"; | ||
| 42 | } | ||
| 43 | |||
| 44 | my $self = { | ||
| 45 | dbh => $dbh, | ||
| 46 | dsn => $dsn, | ||
| 47 | username => $username, | ||
| 48 | password => $password, | ||
| 49 | driver => $driver | ||
| 50 | }; | ||
| 51 | |||
| 52 | bless $self, $class; | ||
| 53 | return $self; | ||
| 54 | } | ||
| 55 | |||
| 56 | sub create | ||
| 57 | { | ||
| 58 | my $self = shift; | ||
| 59 | |||
| 60 | my $conn; | ||
| 61 | |||
| 62 | if ( $self->{dbh} ) | ||
| 63 | { | ||
| 64 | $conn = DBIx::Romani::Connection->new({ dbh => $self->{dbh}, driver => $self->{driver}, disconnect => 0 }); | ||
| 65 | } | ||
| 66 | else | ||
| 67 | { | ||
| 68 | my $dbh = DBI->connect( $self->{dsn}, $self->{username}, $self->{password} ); | ||
| 69 | $conn = DBIx::Romani::Connection->new({ dbh => $dbh, driver => $self->{driver}, disconnect => 1 }); | ||
| 70 | } | ||
| 71 | |||
| 72 | return $conn; | ||
| 73 | } | ||
| 74 | |||
| 75 | sub DESTROY | ||
| 76 | { | ||
| 77 | my $self = shift; | ||
| 78 | |||
| 79 | if ( $self->{dbh} ) | ||
| 80 | { | ||
| 81 | $self->{dbh}->disconnect(); | ||
| 82 | $self->{dbh} = undef; | ||
| 83 | } | ||
| 84 | } | ||
| 85 | |||
| 86 | 1; | ||
| 87 |