App-RecordStream
view release on metacpan - search on metacpan
view release on metacpan or search on metacpan
lib/App/RecordStream/DBHandle.pm view on Meta::CPAN
use App::RecordStream::OptionalRequire 'DBI';
BEGIN { App::RecordStream::OptionalRequire::require_done() }
use Data::Dumper;
use Getopt::Long;
my $MODES = {
'sqlite' => {
'dbfile' => ['=s', 'testDb', 'Local file for database'],
},
'mysql' => {
'host' => ['=s', undef, 'Mysql Host'],
'dbname' => ['=s', undef, 'Database to connect to'],
},
'oracle' => {
'db' => ['=s', undef, 'Database name (tnsname) to connect to'],
},
'pg' => {
'host' => ['=s', undef, 'Hostname to connect to'],
'db' => ['=s', undef, 'Database to connect to'],
},
'main' => {
'type' => ['=s', 'sqlite', 'Type of database to connect to'],
'user' => ['=s', '', 'User to connect as'],
'password' => ['=s', '', 'Password to connect as'],
},
};
my $DESCRIPTIONS = {
'sqlite' => 'A simple local file based db',
'mysql' => 'Connect to a remote mysql database',
'oracle' => 'Connect to a remote Oracle database',
'pg' => 'Connect to a remote PostgreSQL database',
};
my $DISPATCH_TABLE = {
'sqlite' => \&sqlite_dbh,
'mysql' => \&mysql_dbh,
'oracle' => \&oracle_dbh,
'pg' => \&pg_dbh,
};
sub get_dbh {
my $args = shift;
my $options = {};
parse_options($options, 'main', $args);
my $type = $options->{'type'};
parse_options($options, $type, $args);
return $DISPATCH_TABLE->{$type}->($options);
}
sub parse_options {
my $options = shift;
my $mode = shift;
my $args = shift || \@ARGV;
my $spec = get_option_spec($mode, $options);
local @ARGV = @$args;
my $saved_settings = Getopt::Long::Configure();
Getopt::Long::Configure("pass_through");
GetOptions( %$spec );
Getopt::Long::Configure($saved_settings);
set_defaults($mode, $options);
@$args = @ARGV;
}
sub set_defaults {
my $mode = shift;
my $opts = shift;
my $options = $MODES->{$mode};
foreach my $opt ( keys %$options ) {
my $default = @{$options->{$opt}}[1];
if ( (not defined $default) && (!$opts->{$opt}) ) {
die "Must define $opt for type $mode";
}
$opts->{$opt} = $default unless ( exists $opts->{$opt} );
}
}
sub get_option_spec {
my $mode = shift;
my $opts = shift;
my $options = $MODES->{$mode};
my %spec;
foreach my $opt ( keys %$options ) {
my ($modifier) = @{$options->{$opt}};
$spec{$opt . $modifier} = sub { add_opt($opts, @_) };
}
return \%spec;
}
sub mysql_dbh {
my $args = shift;
my $database = $args->{'dbname'};
my $host = $args->{'host'};
my $user = $args->{'user'};
my $password = $args->{'password'};
my $dbh = DBI->connect("DBI:mysql:database=$database;host=$host",
$user,
$password,
{ RaiseError => 1, PrintError => 0 });
return $dbh;
}
sub sqlite_dbh {
view all matches for this distributionview release on metacpan - search on metacpan
( run in 0.759 second using v1.00-cache-2.02-grep-82fe00e-cpan-9e6bc14194b )