blib/lib/Morris/Plugin/Log/DBI.pm untested

filter: Statementstmt 0.0% 0 / 37 Branchbran 0.0% 0 / 6 Conditioncond 0.0% 0 / 2 MC/DCmcdc 0.0% 0 / 1 Subroutinesub 0.0% 0 / 5 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 54 CC 4 SCAR 19.1
CC
4
Cov
0%
display_log
12.0
handle_message
6.0
log_message
2.0
CRAP 6.8
1 package Morris::Plugin::Log::DBI;
2 use Moose;
3 use namespace::clean -except => qw(meta);
4  
5 extends 'Morris::Plugin::Log';
6 with 'Morris::Plugin::WithDB';
7  
8 sub handle_message {
9 my ($self, $args) = @_;
10  
11 my $message = $args->{message};
12  
13 # make sure this is from the correct channel
14 if ($self->should_handle_channel($message)) {
15 $self->log_message($args);
16 $self->display_log($args);
17 }
18 }
19  
20 sub display_log {
21 my ($self, $message) = @_;
22 my $dbh = $self->get_dbh();
23  
24 my $body = $message->message;
25  
26 if ($body !~ s/^!log\s*(?:\s+(\d+))?$//) {
27 return;
28 }
29  
30 my $limit = $1 || 10;
31 my $sql = "SELECT message, nickname, created_on FROM log WHERE channel = ? ORDER BY created_on DESC LIMIT $limit";
32 my @binds = ($message->channel);
33  
34 $dbh->exec($sql, @binds, sub {
35 my ($dbh, $rows, $rv) = @_;
36  
37 return unless $rows;
38 my $connection = $self->connection;
39 foreach my $h (reverse @$rows) {
40 $connection->irc_notice({
41 channel => $message->channel,
42 message => sprintf( '[%s] %s: %s',
43 POSIX::strftime('%Y/%m/%d %T', localtime($h->[2])),
44 $h->[1],
45 $h->[0]
46 )
47 });
48 }
49 });
50 }
51  
52 after setup_dbh => sub {
53 my ($self, $dbh) = @_;
54 $dbh->exec(<<EOSQL, \&Morris::_noop_cb);
55 CREATE TABLE IF NOT EXISTS log (
56 id INTEGER AUTO_INCREMENT,
57 channel TEXT NOT NULL,
58 nickname TEXT,
59 username TEXT,
60 hostname TEXT,
61 message TEXT,
62 created_on INTEGER NOT NULL
63 );
64 EOSQL
65 $dbh->exec(<<EOSQL, \&Morris::_noop_cb);
66 CREATE INDEX IF NOT EXISTS log_created_on_idx ON log (created_on)
67 EOSQL
68 $dbh->exec(<<EOSQL, \&Morris::_noop_cb);
69 CREATE INDEX IF NOT EXISTS log_channel_idx ON log (channel)
70 EOSQL
71 };
72  
73 sub log_message {
74 my ($self, $message) = @_;
75  
76 my $dbh = $self->get_dbh();
77 my $sth = $dbh->exec("INSERT INTO log (channel, nickname, username, hostname, message, created_on) VALUES (?, ?, ?, ?, ?, ?)",
78 $message->channel,
79 $message->from->nickname,
80 $message->from->username,
81 $message->from->hostname,
82 $message->message,
83 time(),
84 \&Morris::_noop_cb,
85 );
86 }
87  
88 __PACKAGE__->meta->make_immutable;
89  
90 1;