| 1 | # POD documentation - main docs before the code | ||
| 2 | |||
| 3 | =head1 NAME | ||
| 4 | |||
| 5 | GenOO::DB::Connector - Connector to database object, with features | ||
| 6 | |||
| 7 | =head1 SYNOPSIS | ||
| 8 | |||
| 9 | # Initializes a connection to a user provided database through perl DBI | ||
| 10 | my $dbconn = GenOO::DB::Connector->new({ | ||
| 11 | driver => undef, | ||
| 12 | host => undef, | ||
| 13 | database => undef, | ||
| 14 | user => undef, | ||
| 15 | port => undef, | ||
| 16 | }); | ||
| 17 | |||
| 18 | =head1 DESCRIPTION | ||
| 19 | |||
| 20 | Not provided yet | ||
| 21 | |||
| 22 | =head1 EXAMPLES | ||
| 23 | |||
| 24 | # Get the DBI handle | ||
| 25 | my $dbh = $dbconn->handle; | ||
| 26 | $dbh->do("CREATE TABLE foo") | ||
| 27 | |||
| 28 | =cut | ||
| 29 | |||
| 30 | # Let the code begin... | ||
| 31 | |||
| 32 | package GenOO::Data::DB::Connector; | ||
| 33 | $GenOO::Data::DB::Connector::VERSION = '1.5.0'; | ||
| 34 | use Moose; | ||
| 35 | use namespace::autoclean; | ||
| 36 | |||
| 37 | use DBI; | ||
| 38 | |||
| 39 | has 'driver' => (isa => 'Str', is => 'ro', required => 1); | ||
| 40 | has 'host' => (isa => 'Str', is => 'ro', required => 1); | ||
| 41 | has 'database' => (isa => 'Str', is => 'ro', required => 1); | ||
| 42 | has 'user' => (isa => 'Str', is => 'ro'); | ||
| 43 | has 'password' => (isa => 'Str', is => 'ro'); | ||
| 44 | has 'port' => (isa => 'Int', is => 'ro', builder => '_default_port'); | ||
| 45 | has 'handle' => (is => 'ro', writer => '_set_handle'); | ||
| 46 | has 'extra' => (is => 'rw'); | ||
| 47 | |||
| 48 | sub BUILD { | ||
| 49 | my $self = shift; | ||
| 50 | |||
| 51 | my $dbh = DBI->connect( | ||
| 52 | 'DBI:'.$self->driver.':database='.$self->database.';'. | ||
| 53 | 'host='.$self->host.';'. | ||
| 54 | 'port='.$self->port.';', | ||
| 55 | $self->user, | ||
| 56 | $self->password | ||
| 57 | ) or die "Can't connect to mysql database: $DBI::errstr\n"; | ||
| 58 | |||
| 59 | $self->_set_handle($dbh); | ||
| 60 | } | ||
| 61 | |||
| 62 | ####################################################################### | ||
| 63 | ######################## Interface Methods ######################## | ||
| 64 | ####################################################################### | ||
| 65 | sub disconnect() { | ||
| 66 | my ($self) = @_; | ||
| 67 | $self->handle->disconnect; | ||
| 68 | } | ||
| 69 | |||
| 70 | ####################################################################### | ||
| 71 | ######################### Private methods ########################## | ||
| 72 | ####################################################################### | ||
| 73 | sub _default_port { | ||
| 74 | return '3306'; | ||
| 75 | } | ||
| 76 | |||
| 77 | __PACKAGE__->meta->make_immutable; | ||
| 78 | 1; |