BeastBB/lib/BeastBB/Database.pm

98 lines
2.7 KiB
Perl

package BeastBB::Database;
use 5.30.3;
use strict;
use warnings;
use Params::ValidationCompiler 'validation_for';
use Types::Standard qw( HashRef Str Int Bool );
use Mojo::Pg;
use Mojo::Pg::Migrations;
{
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 },
max_connections => { type => Int, optional => 1 },
auto_migrate => { type => Bool, default => 1 },
},
);
sub new {
my $class = shift;
my $self = bless {}, $class;
my %params = $validator->(@_);
my $max_connections = $params{max_connections};
my $auto_migrate = $params{auto_migrate};
my $user = $params{user};
my $password = $params{password};
my $dsn = $params{dsn};
$self->{Pg} = Mojo::Pg->new;
$self->Pg->username($user) if defined $user;
$self->Pg->password($password) if defined $password;
$self->Pg->dsn($dsn);
$self->Pg->migrations->from_dir(
Mojo::File::curfile->dirname->child('migrations')->to_string );
$self->Pg->auto_migrate($auto_migrate);
$self->Pg->max_connections($max_connections)
if defined $max_connections;
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;