| 1 | package Service::Engine::Data::Mysql; | ||
| 2 | |||
| 3 | use 5.010; | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | use Data::Dumper; | ||
| 7 | |||
| 8 | use Service::Engine; | ||
| 9 | use DBI; | ||
| 10 | |||
| 11 | our $Config; | ||
| 12 | our $Log; | ||
| 13 | |||
| 14 | sub new { | ||
| 15 | |||
| 16 | my ($class,$options) = @_; | ||
| 17 | |||
| 18 | # set some defaults | ||
| 19 | my $attributes = {'handle'=>''}; | ||
| 20 | |||
| 21 | # load options | ||
| 22 | if (ref($options) eq 'HASH') { | ||
| 23 | foreach my $option (keys %{$options}) { | ||
| 24 | $attributes->{$option} = $options->{$option}; | ||
| 25 | } | ||
| 26 | } | ||
| 27 | |||
| 28 | # pull in some Service::Engine globals | ||
| 29 | $Config = $Service::Engine::Config; | ||
| 30 | $Log = $Service::Engine::Log; | ||
| 31 | |||
| 32 | # set some defaults | ||
| 33 | $attributes->{'raise_error'} ||= 0; | ||
| 34 | $attributes->{'port'} ||= '3306'; | ||
| 35 | |||
| 36 | if (!$attributes->{'database'} || !$attributes->{'hostname'} || !$attributes->{'username'} || !$attributes->{'password'}) { | ||
| 37 | $Log->log({msg=>"mysql requires a database, hostname, username and password",level=>1}); | ||
| 38 | } else { | ||
| 39 | my $datasource = 'DBI:mysql:' . $attributes->{'database'} . ':' . $attributes->{'hostname'} . ':' . $attributes->{'port'}; | ||
| 40 | my $db = DBI->connect($datasource, $attributes->{'username'}, $attributes->{'password'},{ RaiseError => $attributes->{'raise_error'}, mysql_enable_utf8mb4 => 1, mysql_auto_reconnect => 1 }); | ||
| 41 | $attributes->{'handle'} = $db; | ||
| 42 | $Log->log({msg=>"creating connection to $datasource",level=>3}); | ||
| 43 | } | ||
| 44 | |||
| 45 | my $self = bless $attributes, $class; | ||
| 46 | |||
| 47 | return $self; | ||
| 48 | |||
| 49 | } | ||
| 50 | |||
| 51 | sub handle { | ||
| 52 | my ($self) = @_; | ||
| 53 | return $self->{'handle'}; | ||
| 54 | } | ||
| 55 | |||
| 56 | sub reconnect { | ||
| 57 | my ($self) = @_; | ||
| 58 | my $datasource = 'DBI:mysql:' . $self->{'database'} . ':' . $self->{'hostname'} . ':' . $self->{'port'}; | ||
| 59 | my $db = DBI->connect($datasource, $self->{'username'}, $self->{'password'},{ RaiseError => $self->{'raise_error'}, mysql_enable_utf8mb4 => 1, mysql_auto_reconnect => 1 }); | ||
| 60 | $Log->log({msg=>"re-connecting to $datasource",level=>3}); | ||
| 61 | $self->{'handle'} = $db; | ||
| 62 | return $self->{'handle'}; | ||
| 63 | } | ||
| 64 | |||
| 65 | 1; |