PgAsync/Pool.pm untested

filter: Statementstmt 0.0% 0 / 63 Branchbran 0.0% 0 / 16 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 93 CC 9 SCAR 31.9
CC
9
Cov
0%
get
42.0
_make_free
20.0
fetch
2.0
CRAP 24.3
1 package Mojolicious::Plugin::PgAsync::Pool;
2 use Mojo::Base -base;
3  
4 use Data::Dumper;
5 use Mojolicious::Plugin::PgAsync::Db;
6  
7 our $VERSION = '0.01';
8  
9 has ioloop => sub { Mojo::IOLoop->singleton };
10 has [qw/ dbi ttl /];
11 has [qw/ db_free /] => sub {[]};
12 has db_pool => sub {{}};
13  
14 our $debug = $ENV{DEBUG_PG};
15  
16  
17 sub get {
18 my $self = shift;
19  
20 my $db = shift @{$self->db_free};
21 say "have free db $db" if $debug && $db;
22 if ($db) {
23 if (my $timer_id = $self->db_pool->{$db}{timer_id}) {
24 say "remove timer $timer_id for $db" if $debug;
25 $self->ioloop->remove($timer_id);
26 }
27  
28 return $db
29 }
30  
31 $db = Mojolicious::Plugin::PgAsync::Db->new
32 ->dbi($self->dbi)
33 ->make_free(sub { $self->_make_free(@_) })
34 ;
35 say "new db $db" if $debug;
36 return $db
37 }
38  
39 sub _make_free {
40 my $self = shift;
41 my $db = shift;
42  
43 unless (grep {$db eq $_} @{$self->db_free}) {
44 push @{$self->db_free}, $db;
45 }
46  
47 my $timer_id; $timer_id = Mojo::IOLoop->timer($self->ttl => sub {
48 my $loop = shift;
49  
50 say "ttl $timer_id for $db" if $debug;
51 $db->disconnect;
52 $self->db_free([grep {$db ne $_} @{$self->db_free}]);
53 delete $self->db_pool->{$db};
54 }
55 );
56  
57 say "set timer $timer_id for $db" if $debug;
58 $self->db_pool->{$db}{timer_id} = $timer_id;
59 }
60  
61 sub fetch {
62 my $self = shift;
63 my $db = shift;
64  
65 $self->db_free([grep {$db ne $_} @{$self->db_free}]);
66  
67 return $db
68 }
69  
70  
71 1
72