89 lines
2.2 KiB
Perl
89 lines
2.2 KiB
Perl
package BeastBB::Database;
|
|
|
|
use 5.30.3;
|
|
|
|
use strict;
|
|
use warnings;
|
|
|
|
use Params::ValidationCompiler 'validation_for';
|
|
use Types::Standard qw( HashRef Str );
|
|
|
|
use Mojo::Pg;
|
|
|
|
{
|
|
my $validator = validation_for(
|
|
params => { config => { type => HashRef } },
|
|
);
|
|
|
|
sub NewFromConfig {
|
|
my $class = shift;
|
|
my %params = $validator->(@_);
|
|
my $config = $params{config};
|
|
$config = {%$config};
|
|
my $user = delete $config->{user};
|
|
my $password = delete $config->{password};
|
|
my %other_params = %$config;
|
|
return $class->new(
|
|
( ( defined $user ) ? ( user => $user ) : () ),
|
|
( ( defined $password ) ? ( password => $password ) : () ),
|
|
dsn => 'dbi:Pg:' . (
|
|
join ';',
|
|
(
|
|
map {
|
|
"$_="
|
|
. $class->_SingleQuoteString( $other_params{$_} )
|
|
} keys %other_params
|
|
)
|
|
)
|
|
);
|
|
}
|
|
}
|
|
|
|
{
|
|
my $validator = validation_for(
|
|
params => {
|
|
user => { type => Str, default => '' },
|
|
password => { type => Str, default => '' },
|
|
dsn => { type => Str },
|
|
},
|
|
);
|
|
|
|
sub new {
|
|
my $class = shift;
|
|
my $self = bless {}, $class;
|
|
$self->{Pg} = Mojo::Pg->new;
|
|
my %params = $validator->(@_);
|
|
my $user = $params{user};
|
|
my $password = $params{password};
|
|
my $dsn = $params{dsn};
|
|
$self->Pg->username($user) if defined $user;
|
|
$self->Pg->password($password) if defined $password;
|
|
$self->Pg->dsn($dsn);
|
|
return $self;
|
|
}
|
|
}
|
|
|
|
{
|
|
my $validator = validation_for(
|
|
params => [ { type => Str->where('$_ !~ /\'/') } ],
|
|
);
|
|
|
|
sub _SingleQuoteString {
|
|
my $self = shift;
|
|
my @params = $validator->(@_);
|
|
my $string_to_single_quote = $params[0];
|
|
return "'${string_to_single_quote}'";
|
|
}
|
|
}
|
|
|
|
sub Pg {
|
|
my $self = shift;
|
|
return $self->{Pg};
|
|
}
|
|
|
|
sub DB {
|
|
my $self = shift;
|
|
return $self->Pg->db;
|
|
}
|
|
1;
|