You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

70 lines
1.9 KiB

package LDV::DB;
use strict;
use warnings;
use utf8;
use DBIx::Simple;
use SQL::Abstract;
sub new {
my ($class, $conf) = @_;
my $self = {
dsn => undef,
user => undef,
pass => undef,
opts => { RaiseError => 1, AutoCommit => 1 },
};
die "DB: config should be hashref\n"
unless ref($conf) eq 'HASH';
die "DB: database type should be set\n"
unless $conf->{type};
foreach my $key (qw(user pass)) {
next unless $conf->{$key};
$self->{$key} = $conf->{$key};
}
if ($conf->{type} eq 'sqlite3') {
die "DB: Path to database file should be set for sqlite3\n"
unless $conf->{file};
$self->{dsn} = sprintf 'dbi:SQLite:dbname=%s', $conf->{file};
$self->{opts}->{sqlite_see_if_its_a_number} = 1;
$self->{opts}->{sqlite_unicode} = 1;
} elsif ($conf->{type} eq 'mysql') {
die "DB: database name should be set for mysql\n"
unless $conf->{file};
$self->{dsn} = sprintf 'dbi:mysql:dbname=%s', $conf->{name};
$self->{dsn} .= sprintf ';host=%s', $conf->{host}
if $conf->{host};
$self->{opts}->{mysql_enable_utf8} = 1;
} elsif ($conf->{type} eq 'pgsql') {
die "DB: database name should be set for pgsql\n"
unless $conf->{file};
$self->{dsn} = sprintf 'dbi:Pg:dbname=%s', $conf->{name};
$self->{dsn} .= sprintf ';host=%s', $conf->{host}
if $conf->{host};
$self->{opts}->{pg_enable_utf8} = 1;
} else {
die "DB: unsupported database type\n";
}
bless($self, $class);
}
sub connect {
my ($self) = @_;
$self->{dbh} = DBIx::Simple->new($self->{dsn}, $self->{user}, $self->{pass}, $self->{opts});
}
# proxy methods
sub select { shift->{dbh}->select(@_); }
sub insert { shift->{dbh}->insert(@_); }
sub update { shift->{dbh}->update(@_); }
sub delete { shift->{dbh}->delete(@_); }
sub query { shift->{dbh}->query(@_); }
# for connection keepalive
sub ping { shift->{dbh}->query('SELECT 1'); }
1;