Bot-Cobalt
view release on metacpan or search on metacpan
lib/Bot/Cobalt/Plugin/RDB/Database.pm view on Meta::CPAN
package Bot::Cobalt::Plugin::RDB::Database;
$Bot::Cobalt::Plugin::RDB::Database::VERSION = '0.021003';
## Frontend to managing RDB-style Bot::Cobalt::DB instances
## I regret writing this.
##
## We may have a lot of RDBs.
## This plugin tries to make it easy to operate on them discretely
## with a minimum of angst in the frontend app.
##
## If there is no DB in our RDBDir named 'main' it is initialized.
##
## If an error occurs, the first argument returned will be boolean false.
## The error as a simple string is available via the 'Error' method.
## These values are only 'sort-of' human readable; they're holdovers from
## the previous constant retvals, and typically translated into langset
## RPLs by Plugin::RDB.
##
## Our RDB interfaces typically take RDB names; we map them to paths and
## attempt to switch our ->{CURRENT} Bot::Cobalt::DB object appropriately.
##
## The frontend doesn't have to worry about dbopen/dbclose, which works
## for RDBs because access is almost always a single operation and we
## can afford to open / lock / access / unlock / close every call.
use v5.10;
use strictures 2;
use Carp;
use Bot::Cobalt::DB;
use Bot::Cobalt::Error;
use Bot::Cobalt::Utils qw/ glob_to_re_str /;
use Bot::Cobalt::Plugin::RDB::SearchCache;
use Path::Tiny;
use List::Util qw/shuffle/;
use Time::HiRes;
use Try::Tiny;
sub new {
my $self = {};
my $class = shift;
bless $self, $class;
my %opts = @_;
my $core;
if (ref $opts{core}) {
$core = delete $opts{core};
} else {
require Bot::Cobalt::Core;
$core = Bot::Cobalt::Core->instance;
}
$self->{core} = $core;
my $rdbdir = path(
delete $opts{RDBDir} || croak "new() needs a RDBDir"
);
$self->{RDBDir} = $rdbdir;
$self->{CacheObj} = Bot::Cobalt::Plugin::RDB::SearchCache->new(
MaxKeys => $opts{CacheKeys} // 30,
);
$core->log->debug("Using RDBDir $rdbdir");
unless ($rdbdir->exists) {
$core->log->debug("Did not find RDBDir $rdbdir, attempting mkpath");
$rdbdir->mkpath;
}
unless ($rdbdir->is_dir) {
confess "Found RDBDir $rdbdir but it is not a directory!";
}
unless ( $self->dbexists('main') ) {
$core->log->debug("No main RDB found, creating one");
try {
$self->createdb('main')
} catch {
$core->log->warn("Failed to create 'main' RDB: $_")
};
}
return $self
}
sub dbexists {
my ($self, $rdb) = @_;
$self->path_from_name($rdb)->exists
}
sub path_from_name {
( run in 1.008 second using v1.01-cache-2.11-cpan-39bf76dae61 )