Created
January 10, 2012 14:04
-
-
Save mix3/1589242 to your computer and use it in GitHub Desktop.
Dancer::Plugin::Teng
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package Dancer::Plugin::Teng; | |
BEGIN { | |
$Dancer::Plugin::Teng::VERSION = '0.1'; | |
} | |
use strict; | |
use warnings; | |
use Dancer::Plugin; | |
use DBI; | |
use Teng; | |
use Teng::Schema::Loader; | |
my $schemas = {}; | |
register teng => sub { | |
my $name = shift; | |
my $cfg = plugin_setting; | |
if (not defined $name) { | |
($name) = keys %$cfg or die "No schemas are configured"; | |
} | |
if ($schemas->{$name}) { | |
my $dbh = $schemas->{$name}->dbh; | |
if (!$dbh->ping) { | |
$dbh->disconnect; | |
delete $schemas->{$name}; | |
} else { | |
return $schemas->{$name}; | |
} | |
} | |
#return $schemas->{$name} if $schemas->{$name}; | |
my $options = $cfg->{$name} or die "The schema $name is not configured"; | |
my @conn_info = $options->{connect_info} | |
? @{$options->{connect_info}} | |
: @$options{qw(dsn user pass options)}; | |
# pckg should be deprecated | |
my $schema_class = $options->{schema_class} || $options->{pckg}; | |
if ($schema_class) { | |
$schema_class =~ s/-/::/g; | |
eval "use $schema_class"; | |
if ( my $err = $@ ) { | |
die "error while loading $schema_class : $err"; | |
} | |
$schemas->{$name} = $schema_class->connect({ | |
connect_info => \@conn_info, | |
on_connect_do => $options->{on_connect_do}, | |
}); | |
} else { | |
my $dbh = DBI->connect(@conn_info); | |
my $schema = Teng::Schema::Loader->load( | |
dbh => $dbh, | |
namespace => 'MyAPP::DB', | |
); | |
$schemas->{$name} = Teng->new( | |
connect_info => \@conn_info, | |
on_connect_do => $options->{on_connect_do}, | |
schema => $schema, | |
); | |
} | |
return $schemas->{$name}; | |
}; | |
register_plugin; | |
1; | |
__END__ | |
plugins: | |
Teng: | |
conn1: | |
dsn: dbi:mysql:database=db1;host=localhost | |
user: root | |
pass: | |
options: | |
RaiseError: 1 | |
PrintError: 0 | |
AutoCommit: 1 | |
on_connect_do: ["SET NAMES utf8"] | |
conn2: | |
dsn: dbi:mysql:database=db2;host=localhost | |
user: root | |
pass: | |
options: | |
RaiseError: 1 | |
PrintError: 0 | |
AutoCommit: 1 | |
on_connect_do: ["SET NAMES utf8"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment