From fb3ff10b315df432355981453e64f0f6ee9c37be Mon Sep 17 00:00:00 2001 From: Alex 'AdUser' Z Date: Sat, 16 Jun 2018 21:09:21 +1000 Subject: [PATCH] + LDV::DB --- lib/LDV/DB.pm | 70 +++++++++++++++++++++++++++++++++++++++++++++++++++ t/DB.t | 22 ++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 lib/LDV/DB.pm create mode 100644 t/DB.t diff --git a/lib/LDV/DB.pm b/lib/LDV/DB.pm new file mode 100644 index 0000000..c13dc29 --- /dev/null +++ b/lib/LDV/DB.pm @@ -0,0 +1,70 @@ +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; diff --git a/t/DB.t b/t/DB.t new file mode 100644 index 0000000..473239a --- /dev/null +++ b/t/DB.t @@ -0,0 +1,22 @@ +#!/usr/bin/env perl + +use strict; +use warnings; +use utf8; + +use LDV::DB; +use File::Slurp; +use Test::More tests => 2; + +my $hash = read_file('conf/ldv.conf'); +my $config = eval "$hash"; +SKIP: { + skip "Can't load config", 2 unless (ref($config) eq 'HASH'); + + my $ldap = LDV::DB->new($config->{db}); + isa_ok($ldap, "LDV::DB", "LDV::DB->new"); + can_ok($ldap, qw(connect select insert update delete)); + +}; + +exit 0;